# LobCopyInput.java

    /*
    ** Module   : LobCopyInput.java
    ** Abstract : Input value to a converted COPY-LOB statement.
    **
    ** Copyright (c) 2019-2022, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ---------------------------------------Description---------------------------------------
    ** 001 ECF 20190510 Created initial version.
    ** 002 ECF 20190628 Implemented COPY-LOB runtime.
    ** 003 CA  20191203 Fixed overlay and unknown COPY-LOB related bugs.
    ** 004 MED 20200331 Fix length and validation for offset/length.
    ** 005 OM  20210328 Improved copy lob engine and validations.
    **     EVL 20220405 Abstract method validateOffset is now moved to base interface.
    **     EVL 20220408 Added error emission for attempt to copy non-zero size binary data to clob.
    **     EVL 20220720 Re-enabled copy binary source to clob in validate() method.  The error previously emitted
    **                  is related to the ability to convert binary source to text and for some internal code
    **                  pages can produce the error.  But this checking should be done in other class (I18nOps).
    */

    /*
    ** This program is free software: you can redistribute it and/or modify
    ** it under the terms of the GNU Affero General Public License as
    ** published by the Free Software Foundation, either version 3 of the
    ** License, or (at your option) any later version.
    **
    ** This program is distributed in the hope that it will be useful,
    ** but WITHOUT ANY WARRANTY; without even the implied warranty of
    ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    ** GNU Affero General Public License for more details.
    **
    ** You may find a copy of the GNU Affero GPL version 3 at the following
    ** location: https://www.gnu.org/licenses/agpl-3.0.en.html
    **
    ** Additional terms under GNU Affero GPL version 3 section 7:
    **
    **   Under Section 7 of the GNU Affero GPL version 3, the following additional
    **   terms apply to the works covered under the License.  These additional terms
    **   are non-permissive additional terms allowed under Section 7 of the GNU
    **   Affero GPL version 3 and may not be removed by you.
    **
    **   0. Attribution Requirement.
    **
    **     You must preserve all legal notices or author attributions in the covered
    **     work or Appropriate Legal Notices displayed by works containing the covered
    **     work.  You may not remove from the covered work any author or developer
    **     credit already included within the covered work.
    **
    **   1. No License To Use Trademarks.
    **
    **     This license does not grant any license or rights to use the trademarks
    **     Golden Code, FWD, any Golden Code or FWD logo, or any other trademarks
    **     of Golden Code Development Corporation. You are not authorized to use the
    **     name Golden Code, FWD, or the names of any author or contributor, for
    **     publicity purposes without written authorization.
    **
    **   2. No Misrepresentation of Affiliation.
    **
    **     You may not represent yourself as Golden Code Development Corporation or FWD.
    **
    **     You may not represent yourself for publicity purposes as associated with
    **     Golden Code Development Corporation, FWD, or any author or contributor to
    **     the covered work, without written authorization.
    **
    **   3. No Misrepresentation of Source or Origin.
    **
    **     You may not represent the covered work as solely your work.  All modified
    **     versions of the covered work must be marked in a reasonable way to make it
    **     clear that the modified work is not originating from Golden Code Development
    **     Corporation or FWD.  All modified versions must contain the notices of
    **     attribution required in this license.
    */

    package com.goldencode.p2j.util;

    /**
     * Abstract base class for an object that can be the input value to a converted COPY-LOB statement.
     */
    public abstract class LobCopyInput
    implements LobCopyParameter
    {
       /** Offset (in bytes or characters) at which to start reading content for the copy */
       NumberType offset = null;

       /** Number of bytes or characters to read; zero means all */
       private NumberType length = null;

       /**
        * Set the starting offset at which to read content; corresponds with the STARTING AT option.
        *
        * @param   offset
        *          Starting offset.
        *
        * @return  This object instance, to allow method chaining.
        */
       public LobCopyInput offset(NumberType offset)
       {
          this.offset = offset;

          return this;
       }

       /**
        * Set the starting offset at which to read content; corresponds with the STARTING AT option.
        *
        * @param   offset
        *          Starting offset.
        *
        * @return  This object instance, to allow method chaining.
        */
       public LobCopyInput offset(int offset)
       {
          this.offset = new integer(offset);

          return this;
       }

       /**
        * Set the length of the content to read; corresponds with the FOR option.
        *
        * @param   length
        *          Length of content to read.
        *
        * @return  This object instance, to allow method chaining.
        */
       public LobCopyInput length(NumberType length)
       {
          this.length = length;

          return this;
       }

       /**
        * Set the length of the content to read; corresponds with the FOR option.
        *
        * @param   length
        *          Length of content to read.
        *
        * @return  This object instance, to allow method chaining.
        */
       public LobCopyInput length(int length)
       {
          this.length = new integer(length);

          return this;
       }

       /**
        * Validate this parameter. The following parameters are checked: offset,
        *
        * @param   targetType
        *          The type of the target object. The error messages are different in some cases.
        *
        * @return  {@code true} if validation did not encounter any issue and {@code false} otherwise, when in
        *          NO-ERROR mode and the {@code ErrorConditionException} is not thrown.
        *
        * @throws  ErrorConditionException
        *          if the parameter fails validation and silent error mode is not active.
        */
       @Override
       public boolean validate(int targetType)
       {
          long vOffset = 0;
          long size = getSize();
          int objectType = getObjectType();
          boolean isFile = (objectType == TYPE_FILE);

          if (offset != null)
          {
             vOffset = offset.longValue();

             // the [offset] is allowed to be the at most the next-after last character, in which case the "read"
             // value from the source is the empty string.
             if (vOffset > size + 1)
             {
                if (isFile)
                {
                   if (targetType == TYPE_FILE)
                   {
                      ErrorManager.recordOrThrowError(11331,
                                                      Long.toString(vOffset),
                                                      Long.toString(getSize()),
                                                      ((SourceLobFile) this).getFileName());
                      // File offset  is greater than size of file  for file ''. (11331)
                      return false;
                   }
                   else if (targetType == TYPE_LONGCHAR || targetType == TYPE_MEMPTR)
                   {
                      ErrorManager.recordOrThrowError(11329,
                                                      Long.toString(vOffset),
                                                      Long.toString(getSize()),
                                                      ((SourceLobFile) this).getFileName());
                      // File offset  is greater than size of file  for file ''. (11329)
                      return false;
                   }
                   else
                   {
                      ErrorManager.recordOrThrowError(11279,
                                                      Long.toString(vOffset),
                                                      Long.toString(size),
                                                      ((SourceLobFile) this).getFileName());
                      // File offset <number> is greater than size of file <number> for file '<file-name>' (11279)
                      return false;
                   }
                }
                else if (targetType == TYPE_FILE)
                {
                   // in case the target is a FILE the and the offset is greater than the sources' size,
                   // the length (aka FOR option) is ignored
                   return true;
                }
                else
                {
                   ErrorManager.recordOrThrowError(11334);
                   // Offset supplied for source large object is greater than object size. (11334)
                   return false;
                }
             }
          }

          long vLen = 0;
          if (length != null)
          {
             if (length.isUnknown() || length.intValue() < 0)
             {
                ErrorManager.recordOrThrowError(11344);
                // Unknown or invalid length specified in COPY-LOB statement. (11344)
                return false;
             }
             vLen = length.longValue();

             long toProcess = size - vOffset + 1;
             if (vLen > toProcess)
             {
                if (isFile)
                {
                   if (targetType == TYPE_LONGCHAR || targetType == TYPE_MEMPTR)
                   {
                      ErrorManager.recordOrThrowError(11330,
                                                      Long.toString(vOffset),
                                                      Long.toString(vLen),
                                                      Long.toString(size),
                                                      ((SourceLobFile) this).getFileName());
                      // File offset  plus copy length  is greater than size of file  for ''. (11330)
                      return false;
                   }
                   else if (targetType != TYPE_FILE)
                   {
                      ErrorManager.recordOrThrowError(14500, Long.toString(vOffset), Long.toString(vLen));
                      // Source file does not contain sufficient data starting at  to copy  bytes (14500)
                      return false;
                   }
                   else
                   {
                      // in this case, just process the available data
                      length.assign(toProcess);
                   }
                }
                else if (objectType == TYPE_LONGCHAR || objectType == TYPE_MEMPTR)
                {
                   if (targetType == TYPE_FILE)
                   {
                      ErrorManager.recordOrThrowError(11295);
                      // Attempt to access past end of MEMPTR during COPY-LOB (11295)
                   }
                   else
                   {
                      ErrorManager.recordOrThrowError(11305,
                                                      Long.toString(vOffset),
                                                      Long.toString(size),
                                                      Long.toString(size));
                      // Cannot copy large object starting at <offset> for <len> bytes when object size is <size>. (11305)
                   }
                   return false;
                }
                else
                {
                   if (targetType == LobCopyParameter.TYPE_FILE)
                   {
                      System.out.println("?"); // what happens in case of FILE?
                   }
                   else
                   {
                      ErrorManager.recordOrThrowError(11305,
                                                      Long.toString(vOffset),
                                                      Long.toString(size),
                                                      Long.toString(size));
                      // Cannot copy large object starting at <offset> for <len> bytes when object size is <size>. (11305)
                      return false;
                   }
                }
             }
          }

          int len = getLength();
          int off = getOffset(); // zero-based

          // NOTE: if the target is a file, the a larger value for [length] works, but the resulting file will
          //       reflect the size of the source
          if (off + len > size && targetType != TYPE_FILE)
          {
             ErrorManager.recordOrThrowError(11305,
                                             Integer.toString(off),
                                             Integer.toString(len),
                                             Long.toString(size));
             // Cannot copy large object starting at <offset> for <len> bytes when object size is <size>. (11305)
             return false;
          }

          if (objectType == TYPE_BLOB && size == 0 && targetType == TYPE_CLOB)
          {
             // not an error, but since there is no data to copy, just abort the mission
             return false;
          }

          // everything seems fine now
          return true;
       }

       /**
        * Get the starting offset (in bytes or characters) for the source content.
        *
        * @return  Zero-based offset at which to start reading.
        */
       protected int getOffset()
       {
          if (offset == null)
          {
             return 0;
          }

          return offset.isUnknown() ? 0 : offset.intValue() - 1;
       }

       /**
        * Get the length of data to read (in bytes or characters) from the source content.
        *
        * @return  Length of data to read. Negative value indicates length was specified, but was
        *          unknown value. If length is {@code null} (i.e., the original statement had no
        *          FOR option, the size of the source data is returned).
        */
       protected int getLength()
       {
          if (length == null)
          {
             return getSize() - getOffset();
          }

          return length.isUnknown() ? 0 : length.intValue();
       }

       /**
        * Get the size of the object to be copied.
        *
        * @return  Size of object, in bytes or characters, as appropriate to the object type.
        */
       protected abstract int getSize();

       /**
        * Read the content of the backing LOB from the starting offset up to the length and return
        * it as a string using the given encoding.
        *
        * @param   charsetName
        *          Name of the character set to be used to encode the read string. If {@code null},
        *          the default charset will be used.
        *
        * @return  The data as described above.
        */
       protected abstract String readString(String charsetName);

       /**
        * Read the content of the backing LOB from the starting offset up to the length and return
        * it as a byte buffer.
        * <p>
        * Note that the returned buffer must not be modified, as it could either be a copy of the LOB's data or
        * its real backing data.
        *
        * @return  The data as described above.
        */
       protected abstract byte[] readBytes();
    }