# SourceData.java

    /*
    ** Module   : SourceData.java
    ** Abstract : Describes an external source from which data is read into a buffer.
    **
    ** Copyright (c) 2017-2023, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ---------------------------------------Description---------------------------------------
    ** 001 ECF 20170820 Created initial version.
    ** 002 ECF 20171008 Implemented file as an output resource.
    ** 003 ECF 20190120 Added implementation for c'tor which accepts longchar.
    ** 004 OM  20190327 Renamed to SourceData to avoid conflicts with DataSet source.
    ** 005 CA  20200503 Added c'tor to read data from a JsonObject instance (stubbed).
    ** 006 OM  20201120 Implementing Closeable interface. Lazily open the file stream.
    **     OM  20210120 Added full type support, including validation and error handling.
    **     OM  20210825 Added support methods for READ-JSON methods.
    ** 007 IAS 20230325 Changed type of 15357/13184 message from Error to Warning.
    ** 008 CA  20230907 Added support for X-Document source.  X-Noderef is not yet supported.
    ** 009 SP  20240606 Error 4065 must not set ERROR-STATUS:ERROR flag.
    */

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

    import com.goldencode.p2j.persist.serial.*;
    import com.goldencode.p2j.util.*;
    import com.goldencode.p2j.xml.*;

    import java.io.*;
    import java.util.*;

    /**
     * Object which describes an external source from which data is read into a temp-table buffer or dataset
     * member buffer.
     */
    public class SourceData
    implements Serializator
    {
       /** Normalized input stream */
       private InputStream stream = null;

       /** The file name if such source was created. */
       private String fileName = null;

       /**
        * Constant used to identify the calls from READ-XML method. Also used to store the supported stream types
        * for this method.
        */
       public static final String SD_READ_XML = "READ-XML";

       /**
        * Constant used to identify the calls from READ-XMLSCHEMA method. Also used to store the supported stream
        * types for this method.
        */
       public static final String SD_READ_XMLSCHEMA = "READ-XMLSCHEMA";

       /**
        * Constant used to identify the calls from READ-JSON method. Also used to store the supported stream types
        * for this method.
        */
       public static final String SD_READ_JSON = "READ-JSON";

       /* The initialization of static member data. */
       private static final Map<String, Integer> supportedStreams = new HashMap<>();
       static
       {
          supportedStreams.put(SD_READ_XML, SER_FILE | SER_MEMPTR | SER_HANDLE | SER_LONGCHAR);
          supportedStreams.put(SD_READ_XMLSCHEMA, SER_FILE | SER_MEMPTR | SER_HANDLE | SER_LONGCHAR);
          supportedStreams.put(SD_READ_JSON,
                               SER_FILE | SER_MEMPTR | SER_HANDLE | SER_LONGCHAR | SER_JSON_ARRAY | SER_JSON_OBJECT);
       }

       /** Local copy of the stream type configured in constructor. */
       private final String origType;

       /** Local reference to stream (or stream name), as configured in constructor. */
       private final BaseDataType origSrc;

       /**
        * The constructor saves the configured parameters but does not process them in any way. The validation
        * will be executed later, when the calling method is in progress.
        *
        * @param   type
        *          The source stream type.
        * @param   source
        *          The reference to resource or the file name.
        */
       public SourceData(character type, BaseDataType source)
       {
          this((type == null) ? null : type.toJavaType(), source);
       }

       /**
        * The constructor saves the configured parameters but does not process them in any way. The validation
        * will be executed later, when the calling method is in progress.
        *
        * @param   type
        *          The source stream type.
        * @param   source
        *          The reference to resource or the file name.
        */
       public SourceData(String type, BaseDataType source)
       {
          origType = type;
          origSrc = source;
       }

       /**
        * The constructor saves the configured parameters but does not process them in any way. The validation
        * will be executed later, when the calling method is in progress.
        *
        * @param   type
        *          The source stream type.
        * @param   source
        *          The file name.
        */
       public SourceData(String type, String source)
       {
          origType = type;
          origSrc = new character(source);
       }

       /**
        * Configures the resource stream types for the current usage. The caller passes in its name and the
        * method does the selection. It also does the verification whether the already configured parameters (in
        * the constructor) are valid and eventual raise the error condition.
        *
        * @param   method
        *          The identifier for the method using the source stream. It is used to get the set of acceptable
        *          stream types to check against them.
        * @param   widgetType
        *          The parent widget. Only used for composing the error messages.
        *
        * @return  {@code true} if the parameters configured in constructor seems correct. This method does not
        *          check the content, only the variable types. If there is not a match with the possible streams
        *          supported by the {@code method}, {@code false} is returned, after eventually raising a specific
        *          error condition.
        */
       public boolean configureSupportedSources(String method, String widgetType)
       {
          boolean isJson = method.contains("JSON");
          if (origType == null)
          {
             ErrorManager.recordOrShowError(5442, method, "character");
             // Invalid datatype for argument to method ''<name>. Expecting ''<name>
             return false;
          }

          if (origSrc == null || origSrc.isUnknown())
          {
             ErrorManager.recordOrShowError(4065, false, method, widgetType);
             // **The <attribute> attribute on the <widget id> has invalid arguments. (4065)
             return false;
          }

          // [method] must always be one of the supported methods
          int supportedSources = supportedStreams.get(method);

          switch (origType.toUpperCase())
          {
             case TYPE_FILE:
                if ((supportedSources & SER_FILE) != 0)
                {
                   if ((origSrc instanceof longchar))
                   {
                      // no error, but false
                      return false;
                   }

                   if (!(origSrc instanceof character))
                   {
                      ErrorManager.recordOrShowError(4065, false, method, widgetType);
                      // **The <attribute> attribute on the <widget id> has invalid arguments. (4065)
                      return false;
                   }
                   return true;
                }
                break;

             case TYPE_STREAM:
                if ((supportedSources & SER_STREAM) != 0)
                {
                   return true;
                }
                break;

             case TYPE_STREAM_HANDLE:
                if ((supportedSources & SER_STREAM_HANDLE) != 0)
                {
                   return true;
                }
                break;

             case TYPE_MEMPTR:
                if ((supportedSources & SER_MEMPTR) != 0)
                {
                   if (!(origSrc instanceof memptr))
                   {
                      if (isJson)
                      {
                         ErrorManager.recordOrShowError(15362, "", "");
                         // READ-JSON source is not a valid LONGCHAR or MEMPTR. (15362)
                         ErrorManager.recordOrShowError(17956, "", "");
                         // Unable to create reader for READ-JSON (17956)
                      }
                      else
                      {
                         ErrorManager.recordOrShowError(4065, false, method, widgetType);
                         // **The <attribute> attribute on the <widget id> has invalid arguments. (4065)
                      }
                      return false;
                   }
                   return true;
                }
                break;

             case TYPE_HANDLE:
                if (isJson)
                {
                   ErrorManager.recordOrShowError(15356, "", "");
                   // Handle type not valid as JSON input source. (15356)
                }
                else
                {
                   // 1. not unknown
                   if (origSrc.isUnknown())
                   {
                      ErrorManager.recordOrShowError(4065, false, method, widgetType);
                      // **The <attribute> attribute on the <widget id> has invalid arguments. (4065)
                      return false;
                   }

                   // 2. not a handle or the handle's type is not X-Document
                   boolean validType = false;
                   if (origSrc instanceof handle)
                   {
                      WrappedResource res = ((handle) origSrc).getResource();
                      if (res instanceof XDocument)
                      {
                         validType = true;
                      }
                      else if (res instanceof XNodeRef)
                      {
                         // TODO: allow X-Noderef
                         UnimplementedFeature.missing(method + " with X-Noderef target is not supported.");
                         validType = false;
                      }
                   }

                   if (!validType)
                   {
                      ErrorManager.recordOrShowError(10515, false, "", "");
                      // Handle type not valid as XML input source. (10515)
                      ErrorManager.recordOrShowError(4065, false, method, widgetType);
                      // **The <attribute> attribute on the <widget id> has invalid arguments. (4065)
                      return false;
                   }

                   return true;
                }
                return false;

             case TYPE_LONGCHAR:
                if ((supportedSources & SER_LONGCHAR) != 0)
                {
                   if (!(origSrc instanceof longchar))
                   {
                      if (isJson)
                      {
                         ErrorManager.recordOrShowError(15362, "", "");
                         // READ-JSON source is not a valid LONGCHAR or MEMPTR. (15362)
                         ErrorManager.recordOrShowError(17956, "", "");
                         // Unable to create reader for READ-JSON (17956)
                      }
                      else
                      {
                         ErrorManager.recordOrShowError(4065, false, method, widgetType);
                         // **The <attribute> attribute on the <widget id> has invalid arguments. (4065)
                         return false;
                      }
                      return false;
                   }
                   return true;
                }
                break;

             case TYPE_JSON_OBJECT:
                if ((supportedSources & SER_JSON_OBJECT) != 0)
                {
                   return true;
                }
                break;

             case TYPE_JSON_ARRAY:
                if ((supportedSources & SER_JSON_ARRAY) != 0)
                {
                   return true;
                }
                break;
          }

          ErrorManager.recordOrShowWarning(isJson ? 15357 : 13184, origType);
          // err 13184: Invalid source-type for READ-XML: <argument>.
          // err 15357: Invalid source-type for READ-JSON: <type>.
          return false;
       }

       /**
        * Get the input stream representing the source resource from which data will be read. This may be backed
        * by a remote or a local resource.
        *
        * @return  Input stream.
        *
        * @throws  IOException
        *          if the method encounters issues with the resource.
        */
       @Override
       public InputStream getStream()
       throws IOException
       {
          // if already built, return it again
          if (stream != null)
          {
             return stream;
          }

          switch (origType.toUpperCase())
          {
             case TYPE_FILE:
                if (origSrc instanceof character)
                {
                   fileName = ((character) origSrc).toJavaType();
                   try
                   {
                      stream = new InputStreamWrapper(StreamFactory.openFileStream(fileName, false, false));
                   }
                   catch (ErrorConditionException ece)
                   {
                      throw new FileNotFoundException(fileName);
                   }
                   return stream;
                }
                return null;

             case TYPE_LONGCHAR:
                if (origSrc instanceof longchar)
                {
                   longchar source = (longchar) origSrc;
                   stream = new ByteArrayInputStream(source.asByteArray(0, source.lengthOf()));
                   return stream;
                }
                return null;

             case TYPE_MEMPTR:
                if (origSrc instanceof memptr)
                {
                   memptr source = (memptr) origSrc;
                   stream = new ByteArrayInputStream(source.asByteArray(0, source.lengthOf()));
                   return stream;
                }
                return null;
          }

          return null;
       }

       /**
        * Close the input stream underlying this data source.
        *
        * @throws  IOException
        *          if there is an error closing the stream.
        */
       public void close()
       throws IOException
       {
          if (stream != null)
          {
             stream.close();
          }
       }

       /**
        * Obtain the file name of the source, if one was used to create the source.
        *
        * @return  the file name of the source, if one was used to create the source. Otherwise {@code null}.
        */
       public String getFileName()
       {
          return fileName;
       }

       /**
        * Obtain the original source.
        *
        * @return  the original source this object was created for.
        */
       public BaseDataType getSource()
       {
          return origSrc;
       }

       /**
        * Obtain the type of source this objects wraps.
        *
        * @return  the type of source this objects wraps.
        */
       public String getType()
       {
          return origType;
       }
    }