# SourceLob.java

    /*
    ** Module   : SourceLob.java
    ** Abstract : Source parameter of a converted COPY-LOB statement.
    **
    ** Copyright (c) 2019-2023, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ---------------------------------------Description---------------------------------------
    ** 001 ECF 20190510 Created initial version.
    ** 002 ECF 20190628 Implemented COPY-LOB runtime.
    ** 003 CA  20191119 unknown values are allowed as source lob.
    ** 004 CA  20191203 Fixed overlay and unknown COPY-LOB related bugs.
    ** 005 CA  20200427 I18nOps.convmap2Java uses uppercase keys.
    ** 006 OM  20210328 Improved copy lob engine and validations.
    ** 007 HC  20230118 Eliminated some of the uses of String.toUpperCase and/or String.toLowerCase
    **                  for performance.
    */

    /*
    ** 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;

    import java.io.*;

    /**
     * Concrete implementation of a converted COPY-LOB source parameter, corresponding with the
     * {@code FROM [ OBJECT ] source-lob} phrase.
     */
    public class SourceLob
    extends LobCopyInput
    {
       /** Large object which is the source of the copy operation */
       private final LargeObject lob;

       /**
        * Constructor which takes a LOB.
        *
        * @param   lob
        *          Large object which is the source of the copy operation.
        */
       public SourceLob(LargeObject lob)
       {
          this.lob = lob;
       }

       /**
        * Constructor which takes an object that is expected to be a LOB. Intended to handle the
        * converted POLY case.
        *
        * @param   lob
        *          Large object which is the source of the copy operation.
        *
        * @throws  ConditionException
        *          if {@code lob} is not an instance of @LargeObject@.
        */
       public SourceLob(Object lob)
       {
          this(LobCopy.assertParameterType(lob));
       }

       /**
        * Checks if the optional offset is valid.
        *
        * @param   targetType
        *          The type of the target object. The error messages are different in some cases.
        *
        * @return  {@code true} if the optional offset is valid.
        */
       @Override
       public boolean validateOffset(int targetType)
       {
          if (offset != null)
          {
             if (offset.isUnknown() || offset.intValue() <= 0)
             {
                ErrorManager.recordOrThrowError(11332);
                // Invalid offset specified in COPY-LOB statement. (11332)
                return false;
             }

             int objectType = getObjectType();
             if (getSize() < offset.longValue())
             {
                if (objectType == TYPE_LONGCHAR || objectType == TYPE_MEMPTR)
                {
                   return true; // this is not an error, an empty string will be returned/used
                }

                if (targetType == TYPE_FILE)
                {
                   ErrorManager.recordOrThrowError(11265);
                   // Attempt to access blob beyond its end. (11265)
                }
                else
                {
                   // NOTE: sometimes 11332 is thrown instead for: (targetType == MEMPTR && objectType == CLOB)

                   ErrorManager.recordOrThrowError(11334);
                   // Offset supplied for source large object is greater than object size. (11334)
                }
             }
          }

          return true;
       }

       /**
        * Indicate whether this object is a valid large object data type. It is possible to pass a
        * POLY which is not a valid LOB type as a COPY-LOB parameter, and this error must be
        * determined at runtime.
        *
        * @return  {@code true} if valid, else {@code false}. The default implementation assumes
        *          validity; implementors which must handle runtime type verification must override
        *          this method.
        */
       @Override
       public boolean isLargeObject()
       {
          return lob != null;
       }

       /**
        * Obtain the type of the object wrapped by this parameter
        *
        * @return  The numerical id of a type declared as one of the TYPE static constants from
        *          {@code LobCopyParameter} interface.
        */
       @Override
       public int getObjectType()
       {
          return (lob instanceof clob) ? TYPE_CLOB : // must be checked first
                 (lob instanceof blob) ? TYPE_BLOB :
                 (lob instanceof memptr) ? TYPE_MEMPTR :
                 (lob instanceof longchar) ? TYPE_LONGCHAR : TYPE_UNKNOWN;
       }

       /**
        * Indicate whether the large object represented by this parameter natively represents
        * encoded character data, as opposed to binary data.
        *
        * @return  {@code true} if character data; {@code false} if binary data.
        */
       @Override
       public boolean isCharacterData()
       {
          return lob != null && lob.isCharacterData();
       }

       /**
        * Get the size of the object to be copied.
        *
        * @return  Size of object, in bytes or characters, as appropriate to the object type.
        */
       @Override
       protected int getSize()
       {
          // cast is ok; max 4GL LOB size fits in integer
          return (int) lob.lengthOf();
       }

       /**
        * Get the code page of this parameter, if any.
        *
        * @return  4GL code page name or {@code null} if parameter represents non-character data.
        */
       @Override
       public String getCodePage()
       {
          return LobCopy.getLobDefaultCodePage(lob);
       }

       /**
        * 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   codePage
        *          Name of the 4GL code page to be used to encode the read string. If {@code null},
        *          the large object's explicit code page (if any) will be used. If none, the value
        *          of {@code -cpinternal} will be used.
        *
        * @return  The data as described above.
        */
       @Override
       protected String readString(String codePage)
       {
          // NOTE: this implementation is wasteful in the case that the entire content of the LOB
          //       is not needed, in that we encode the entire byte array into a String, then pluck out
          //       the substring we are interested in. However, I'm not sure how else to do this to ensure
          //       we are getting the proper character offset and length, since the number of bytes per
          //       character can vary by charset.

          if (isLargeObject() && lob.isUnknown())
          {
             return isCharacterData() ? null : "";
          }

          long size = lob.lengthOf();
          String all;
          if (codePage != null && I18nOps.isSupported(codePage))
          {
             String charset = I18nOps.convmap2Java.get(codePage);

             try
             {
                byte[] data = lob.asByteArray(0, size);
                if (!I18nOps.prevalidateData(data, 0, data.length, codePage))
                {
                   ErrorManager.recordOrThrowError(12008, codePage.toUpperCase(), "");
                   // Invalid character code found in data for codepage  (12008)
                   return ""; // if ever
                }
                all = new String(data, charset);
             }
             catch (UnsupportedEncodingException exc)
             {
                ErrorManager.recordOrThrowError(12008);
                // Invalid character code found in data for codepage  (12008)

                return null;
             }
          }
          else
          {
             byte[] data = lob.asByteArray(0, size);
             if (!I18nOps.prevalidateData(data, 0, data.length, codePage))
             {
                String cp = (codePage == null) ? I18nOps._getCPInternal() : codePage.toUpperCase();
                ErrorManager.recordOrThrowError(12008, cp, "");
                // Invalid character code found in data for codepage  (12008)
                return ""; // if ever
             }
             all = new String(data);
          }

          int off = getOffset();
          int len = getLength();

          if (off == 0 && len == size)
          {
             return all;
          }

          // in case of LONGCHAR it is legal to 'read' off the available data; the result is the empty string
          if (off >= size)
          {
             return "";
          }

          // adjust the length overflow: 'read' all remaining data from the input LOB
          if (off + len > size)
          {
             return all.substring(off);
          }

          return all.substring(off, off + len);
       }

       /**
        * 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.
        */
       @Override
       protected byte[] readBytes()
       {
          int off = getOffset();
          int len = getLength();

          return lob.asByteArray(off, len);
       }
    }