TargetData.java

/*
** Module   : TargetData.java
** Abstract : Describes an external target to which data is written from a buffer.
**
** Copyright (c) 2017-2024, Golden Code Development Corporation.
**
** -#- -I- --Date-- ---------------------------------------Description---------------------------------------
** 001 ECF 20170820 Created initial version.
** 002 CA  20170830 Added missing c'tor.
** 003 ECF 20171008 Rolled back #002. Implemented file as an output resource.
** 004 ECF 20190117 Implemented missing support for longchar target.
** 005 OM  20190328 Renamed to TargetData.
** 006 CA  20190604 Added c'tors for BUFFER:WRITE-JSON(JsonObject|JsonArray).
** 007 CA  20190720 byte[] must be converted to String before copying it.
**     CA  20190811 Added memptr support.
** 008 CA  20200910 Fixed Json c'tors - these can be any object, the type is checked at runtime.
**     OM  20201120 Implemented Closable interface. The file stream is lazily opened.
**     OM  20210120 Added full type support, including validation and error handling.
**     OM  20210809 Added implementation for SERIALIZE-ROW|WRITE-JSON}(JsonObject|JsonArray).
**     OM  20221004 Added missing STERAM targets.
** 009 CA  20230907 Added support for X-Document target.  X-Noderef is not yet supported.
** 010 SP  20240606 Error 4065 must not set ERROR-STATUS:ERROR flag.
** 011 CA  20240812 Do not re-close the stream if it was already closed.
*/

/*
** 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 java.io.*;
import java.util.*;
import com.goldencode.p2j.persist.serial.*;
import com.goldencode.p2j.util.*;
import com.goldencode.p2j.xml.*;

/**
 * Object which describes an external target into which data is written from a temp-table buffer
 * or data set member buffer.
 */
public class TargetData
implements Serializator
{
   /** Normalized output stream */
   private OutputStream stream;
   
   /** The file name if such destination was created. */
   private String fileName = null;
   
   /**
    * Constant used to identify the calls from WRITE-XML method. Also used to store the supported stream types
    * for this method.
    */
   public static final String TD_WRITE_XML = "WRITE-XML";
   
   /**
    * Constant used to identify the calls from WRITE-XMLSCHEMA method. Also used to store the supported stream
    * types for this method.
    */
   public static final String TD_WRITE_XMLSCHEMA = "WRITE-XMLSCHEMA";
   
   /**
    * Constant used to identify the calls from WRITE-JSON method. Also used to store the supported stream
    * types for this method.
    */
   public static final String TD_WRITE_JSON = "WRITE-JSON";
   
   /**
    * Constant used to identify the calls from SERIALIZE-ROW method. Also used to store the supported stream
    * types for this method.
    */
   public static final String TD_SERIALIZE_ROW = "SERIALIZE-ROW";
   
   /* The initialization of static member data. */
   private static final Map<String, Integer> supportedStreams = new HashMap<>();
   static
   {
      supportedStreams.put(TD_WRITE_XML,
                           SER_FILE | SER_STREAM | SER_STREAM_HANDLE | SER_MEMPTR | SER_HANDLE | SER_LONGCHAR);
      supportedStreams.put(TD_WRITE_XMLSCHEMA,
                           SER_FILE | SER_STREAM | SER_STREAM_HANDLE | SER_MEMPTR | SER_HANDLE | SER_LONGCHAR);
      supportedStreams.put(TD_WRITE_JSON,
                           SER_FILE | SER_STREAM | SER_STREAM_HANDLE | SER_MEMPTR |              SER_LONGCHAR | SER_JSON_ARRAY | SER_JSON_OBJECT);
      supportedStreams.put(TD_SERIALIZE_ROW,
                           SER_FILE | SER_STREAM | SER_STREAM_HANDLE | SER_MEMPTR |              SER_LONGCHAR | SER_JSON_OBJECT);
   }
   
   /** The type of original destination of the operation. */
   private final String origType;
   
   /** The original destination of the operation. */
   private final BaseDataType origDst;
   
   /** Test whether the target object is a stream or a handle to a stream. U */
   private boolean isStream = false;
   
   /**
    * 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   target
    *          The reference to resource or the file name.
    */
   public TargetData(character type, BaseDataType target)
   {
      this((type == null) ? null : type.toJavaType(), target);
   }
   
   /**
    * 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   target
    *          The reference to resource or the file name.
    */
   public TargetData(String type, BaseDataType target)
   {
      origType = type;
      origDst = target;
   }
   
   /**
    * 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   target
    *          The file name.
    */
   public TargetData(String type, String target)
   {
      origType = type;
      origDst = new character(target);
   }
   
   /**
    * Configures the supported resource 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 configureSupportedTargets(String method, String format, String widgetType)
   {
      boolean isJson = format.contains("JSON");
      if (origType == null)
      {
         ErrorManager.recordOrShowError(5442, method, "character");
         // Invalid datatype for argument to method ''<name>. Expecting ''<name>
         return false;
      }
      
      if (origDst == null || origDst.isUnknown())
      {
         if (method.equalsIgnoreCase(TargetData.TD_SERIALIZE_ROW) ||
             method.equalsIgnoreCase(TargetData.TD_WRITE_JSON))
         {
            ErrorManager.recordOrShowError(19079, false, "JsonObject", method);
            // <argument> argument for <method-name> is not valid. (19079)
         }
         
         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 supportedDestinations = supportedStreams.get(method);
      
      switch (origType.toUpperCase())
      {
         case TYPE_FILE:
            if ((supportedDestinations & SER_FILE) != 0)
            {
               if (!(origDst 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 ((supportedDestinations & SER_STREAM) != 0)
            {
               return true;
            }
            break;
         
         case TYPE_STREAM_HANDLE:
            if ((supportedDestinations & SER_STREAM_HANDLE) != 0)
            {
               return true;
            }
            break;
         
         case TYPE_MEMPTR:
            if ((supportedDestinations & SER_MEMPTR) != 0)
            {
               if (!(origDst instanceof memptr))
               {
                  break;
               }
               return true;
            }
            break;
         
         case TYPE_HANDLE:
            if (!isJson)
            {
               // 1. not unknown
               if (origDst.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 (origDst instanceof handle)
               {
                  WrappedResource res = ((handle) origDst).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(13186, false);
                  // Handle type not valid as WRITE-XML target. (13186)
                  ErrorManager.recordOrShowError(4065, false, method, widgetType);
                  // **The <attribute> attribute on the <widget id> has invalid arguments. (4065)
                  return false;
               }
               
               return true;
            }
            break;
         
         case TYPE_LONGCHAR:
            if ((supportedDestinations & SER_LONGCHAR) != 0)
            {
               if (!(origDst instanceof longchar))
               {
                  ErrorManager.recordOrShowError(4065, false, method, widgetType);
                  // **The <attribute> attribute on the <widget id> has invalid arguments. (4065)
                  return false;
               }
               return true;
            }
            break;
         
         case TYPE_JSON_OBJECT:
            if ((supportedDestinations & SER_JSON_OBJECT) != 0)
            {
               return true;
            }
            break;
         
         case TYPE_JSON_ARRAY:
            if ((supportedDestinations & SER_JSON_ARRAY) != 0)
            {
               return true;
            }
            break;
      }
      
      if (isJson)
      {
         ErrorManager.recordOrShowError(15344, origType, method);
         // Invalid mode '<mode>' for <method>. (15344)
      }
      else
      {
         ErrorManager.recordOrShowError(13185, origType);
         // Invalid target-type for WRITE-XML: <argument>. (13185)
         ErrorManager.recordOrShowError(4065, false, method, widgetType);
         // **The <attribute> attribute on the <widget id> has invalid arguments. (4065)
      }
      return false;
   }
   
   /**
    * Get the output stream representing the target resource to which data will be written.
    * This may be a remote or a local resource.
    *
    * @return  Output stream.
    */
   @Override
   public OutputStream getStream()
   {
      if (stream != null)
      {
         return stream;
      }
      
      switch (origType.toUpperCase())
      {
         case TYPE_JSON_ARRAY:
         case TYPE_JSON_OBJECT:
            throw new RuntimeException("No stream for JsonObject/Array targets.");
         
         case TYPE_STREAM:
            if (origDst instanceof character)
            {
               fileName = ((character) origDst).toJavaType();
               stream = new OutputStreamWrapper(StreamWrapper.getRemoteStreamRef(fileName), false);
               isStream = true;
               return stream;
            }
            return null;
            
         case TYPE_STREAM_HANDLE:
            if (origDst instanceof handle)
            {
               TransparentWrapper resource = (TransparentWrapper) ((handle) origDst).getResource();
               stream = new OutputStreamWrapper((StreamWrapper) resource.get(), false);
               isStream = true;
               return stream;
            }
            return null;
            
         case TYPE_FILE:
            if (origDst instanceof character)
            {
               fileName = ((character) origDst).toJavaType();
               stream = new OutputStreamWrapper(StreamFactory.openFileStream(fileName, true, false));
               return stream;
            }
            return null;
         
         case TYPE_LONGCHAR:
            if (origDst instanceof longchar)
            {
               longchar dest = (longchar) origDst;
               stream = new ByteArrayOutputStream()
               {
                  boolean closed = false;
                  
                  @Override
                  public void close()
                  throws IOException
                  {
                     if (closed)
                     {
                        return;
                     }
                     
                     flush();
                     super.close();
                     dest.assign(this.toString());
                     closed = true;
                  }
               };
               return stream;
            }
            return null;
         
         case TYPE_MEMPTR:
            if (origDst instanceof memptr)
            {
               memptr dest = (memptr) origDst;
               stream = new ByteArrayOutputStream()
               {
                  boolean closed = false;
                  
                  @Override
                  public void close()
                  throws IOException
                  {
                     if (closed)
                     {
                        return;
                     }
                     
                     flush();
                     super.close();
                     dest.assign(this.toByteArray());
                     closed = true;
                  }
               };
               return stream;
            }
            return null;
      }
      
      return null;
   }
   
   /**
    * Close the output stream underlying this data source.
    *
    * @throws  IOException
    *          if there is an error closing the stream.
    */
   @Override
   public void close()
   throws IOException
   {
      if (stream != null)
      {
         if (isStream())
         {
            ((OutputStreamWrapper) stream).setClosable();
         }
         else
         {
            // do not close the streams, the ABL programmer is responsible for their management 
            stream.close();
         }
         stream = null; 
      }
   }
   
   /**
    * Checks if the target of this operation is a Json or Json Array object.
    *
    * @return  {@code true} if the target of this operation is a Json or Json Array object.
    */
   public boolean isJson()
   {
      String type = origType.toUpperCase();
      return type.equals(TYPE_JSON_OBJECT) || type.equals(TYPE_JSON_ARRAY);
   }
   
   /**
    * Checks if the target of this operation is a STREAM-type object.
    *
    * @return  {@code true} if the target of this operation is a STREAM-type object.
    */
   public boolean isStream()
   {
      return isStream;
   }
   
   /**
    * Obtain the original destination of the operation.
    * 
    * @return  the original destination of the operation.
    */
   public Object getDestination()
   {
      return origDst;
   }
   
   /**
    * Obtain the original type of the stream.
    * 
    * @return the type of the stream.
    */
   public String getType()
   {
      return origType;
   }
}