# Util.java

    /*
    ** Module   : Util.java
    ** Abstract : Common utility methods and static data for JSON and XML serialization.
    **
    ** Copyright (c) 2019-2024, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ----------------------------------------Description---------------------------------------
    ** 001 OM  20190628 Initial revision with common content from JSON and XML Exports.
    ** 002 OM  20190831 Added hidden fields and index specific to BEFORE TEMP-TABLES.
    ** 003 OM  20191014 Added testing utility support methods.
    ** 004 CA  20200914 Added blob/clob support.
    **     CA  20200927 Use IdentityHashMap instead of plain map when the key is a Class.
    **     OM  20201120 Added missing datatypes. Made are immutable now.
    **     CA  20210609 Reworked INPUT/INPUT-OUTPUT parameters to a new approach, where they are explicitly
    **                  initialized at the method's execution, and not at the caller's arguments.
    **     OM  20210809 Added type support for [object] class.
    **     TJD 20220504 Upgrade do Java 11 minor changes
    ** 005 GBB 20230512 Logging methods replaced by CentralLogger/ConversionStatus.
    ** 006 IAS 20230519 Added conversion of the BaseDataType to the XML type string.
    ** 007 RAA 20230525 Creating a new BaseDataType instance is now done using BaseDataTypeFactory.
    ** 008 CA  20240320 Avoid BDTs within internal FWD runtime.  Replaced iterators with Java 'for', where it
    **                  applies.
    */

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

    import com.goldencode.p2j.directory.Base64;
    import com.goldencode.p2j.persist.*;
    import com.goldencode.p2j.util.*;
    import com.goldencode.p2j.util.logging.*;

    import java.util.*;

    /**
     * A class that help de-duplicating code from {@link JsonExport} and {@link XmlExport}. It groups
     * common utility methods and static data for JSON and XML serialization. All member of this class
     * are only package-accessible.
     */
    public class Util
    {
       /** Logger */
       private static final CentralLogger LOG = CentralLogger.get(Util.class);

       /** The String representation of {@code Buffer.ROW_CREATED} records. */
       static final String STR_ROW_CREATED = "created";

       /** The String representation of {@code Buffer.ROW_DELETED} records. */
       static final String STR_ROW_DELETED = "deleted";

       /** The String representation of {@code Buffer.ROW_MODIFIED} records. */
       static final String STR_ROW_MODIFIED= "modified";

       /** Mapping between supported ABL/FWD types and XSD type used for writing schema. */
       static final Map<Class<? extends BaseDataType>, String> xsdMap;

       /** The default values for each supported ABL/FWD types. */
       static final Map<Class<? extends BaseDataType>, String> defaultValuesMap;

       /** Extended information for XSD types that coalesce multiple ABL/FWD types. */
       static final Map<Class<? extends BaseDataType>, String> xsdProdataMap;

       /* Initialize the static final internal data. */
       static
       {
          Map<Class<? extends BaseDataType>, String> mutableDefMap = new IdentityHashMap<>();
          mutableDefMap.put(blob.class, "?");
          mutableDefMap.put(character.class,  "");
          mutableDefMap.put(clob.class,       "?");
          mutableDefMap.put(comhandle.class,  "?");
          mutableDefMap.put(date.class,       "?");
          mutableDefMap.put(datetime.class,   "?");
          mutableDefMap.put(datetimetz.class, "?");
          mutableDefMap.put(decimal.class,    "0");
          mutableDefMap.put(int64.class,      "0");
          mutableDefMap.put(integer.class,    "0");
          mutableDefMap.put(logical.class,    "false");
          mutableDefMap.put(raw.class,        "");
          mutableDefMap.put(recid.class,      "?");
          mutableDefMap.put(rowid.class,      "?");
          mutableDefMap.put(handle.class,     "?"); /* widget-handle */
          mutableDefMap.put(object.class,     "?"); /* ??? */
          defaultValuesMap = Collections.unmodifiableMap(mutableDefMap);

          Map<Class<? extends BaseDataType>, String> mutableTypeMap = new IdentityHashMap<>();
          mutableTypeMap.put(blob.class,       "xsd:base64Binary");
          mutableTypeMap.put(character.class,  "xsd:string");
          mutableTypeMap.put(clob.class,       "xsd:string");
          mutableTypeMap.put(comhandle.class,  "xsd:long");
          mutableTypeMap.put(date.class,       "xsd:date");
          mutableTypeMap.put(datetime.class,   "xsd:dateTime");
          mutableTypeMap.put(datetimetz.class, "xsd:dateTime");
          mutableTypeMap.put(decimal.class,    "xsd:decimal");
          mutableTypeMap.put(int64.class,      "xsd:long");
          mutableTypeMap.put(integer.class,    "xsd:int");
          mutableTypeMap.put(logical.class,    "xsd:boolean");
          mutableTypeMap.put(raw.class,        "xsd:base64Binary");
          mutableTypeMap.put(recid.class,      "xsd:long");
          mutableTypeMap.put(rowid.class,      "xsd:base64Binary");
          mutableTypeMap.put(handle.class,     "xsd:long"); /* widget-handle */
          mutableTypeMap.put(object.class,     "xsd:long"); /* ??? */
          xsdMap = Collections.unmodifiableMap(mutableTypeMap);

          Map<Class<? extends BaseDataType>, String> mutableSubTypeMap = new IdentityHashMap<>();
          mutableSubTypeMap.put(blob.class,      "prodata:blob");
          mutableSubTypeMap.put(clob.class,      "prodata:clob");
          mutableSubTypeMap.put(comhandle.class, "prodata:comHandle");
          mutableSubTypeMap.put(datetime.class,  "prodata:dateTime");
          mutableSubTypeMap.put(recid.class,     "prodata:recid");
          mutableSubTypeMap.put(rowid.class,     "prodata:rowid");
          mutableSubTypeMap.put(handle.class,    "prodata:handle"); /* widget-handle */
          mutableSubTypeMap.put(object.class,    "prodata:Progress.Lang.Object"); /* ??? */
          xsdProdataMap = Collections.unmodifiableMap(mutableSubTypeMap);

          // longchar not supported
          // memptr not supported
          // class Progress.Lang.Object not supported at runtime
       }

       /**
        * Encodes a {@code Long} value using a BASE64 algorithm. Used for serialization in both JSON
        * and XML.
        *
        * @param   val
        *          The value to be encoded.
        *
        * @return  The BASE64 encoding of the int64 value.
        */
       static String encodeBase64(Long val)
       {
          if (val == null)
          {
             return null;
          }

          // the Long value is converted to a byte[] array (in C/C++ this would be a simple type cast)
          byte[] rowidAsBytes = new byte[8];
          for (int i = 0; i < 8; i++)
          {
             rowidAsBytes[7 - i] = (byte) (val & 0xFF);
             val >>= 8;
          }
          // then convert it to BASE64
          return Base64.byteArrayToBase64(rowidAsBytes);
       }

       /**
        * Get a String representation of an integer ROW-STATE flag.
        *
        * @param   rowState
        *          The integer value to be converted.
        *
        * @return  The string representation of the {@code rowState}.
        */
       static String getRowStateAsString(int rowState)
       {
          switch (rowState)
          {
             case Buffer.ROW_CREATED:
                return STR_ROW_CREATED;
             case Buffer.ROW_DELETED:
                return STR_ROW_DELETED;
             case Buffer.ROW_MODIFIED:
                return STR_ROW_MODIFIED;
             default:
                return null;
          }
       }

       /**
        * Checks whether a TEMP-TABLE has columns whose types do not support XML serialization.
        *
        * @param   schema
        *          The schema of the TEMP-TABLE to be checked.
        *
        * @return  {@code null} if the whose TEMP-TABLE is compatible to be XML serialized or the
        *          ABLE legacy type of the first column that is not supported.
        */
       static String checkSupportedTypes(TempTableSchema schema)
       {
          ArrayList<TempTableSchema.Column> columns = schema.columns();
          for (int k = 0; k < columns.size(); k++)
          {
             TempTableSchema.Column column = columns.get(k);

             Class<? extends BaseDataType> bdtClass = column.getType();
             if (!xsdMap.containsKey(bdtClass))
             {
                return getLegacyType(bdtClass);
             }
          }

          return null;
       }

       /**
        * Checks whether a column of a TEMP-TABLE might not be supported by XML/JSON serialization.
        *
        * @param   column
        *          The column of the TEMP-TABLE to be checked.
        *
        * @return  {@code true} if the whose TEMP-TABLE is compatible to be XML serialized.
        */
       static boolean checkSupportedType(TempTableSchema.Column column)
       {
          Class<? extends BaseDataType> bdtClass = column.getType();
          return xsdMap.containsKey(bdtClass);
       }

       /**
        * Resolve the legacy name based on the FWD BDT implementation class.
        *
        * @param   bdtClass
        *          The datatype to be converted.
        *
        * @return  The legacy name of the specified FWD class.
        */
       static String getLegacyType(Class<? extends BaseDataType> bdtClass)
       {
          if (bdtClass.isAnonymousClass())
          {
             bdtClass = (Class<? extends BaseDataType>) bdtClass.getSuperclass();
          }

          String type = "BaseDataType";
          try
          {
             BaseDataType bdt = BaseDataTypeFactory.instantiate(bdtClass);
             type = bdt.getTypeName().toLowerCase();
          }
          catch (ReflectiveOperationException e)
          {
             LOG.warning("", e);
          }
          return type;
       }

       /**
        * Test whether two representation of a field type are the same.
        *
        * @param   dataType
        *          The FWD class.
        * @param   type
        *          The XML type information.
        * @param   fieldType
        *          Additional ABL XML type information.
        *
        * @return  {@code true} only if both representations are the same.
        */
       public static boolean checkType(Class<? extends BaseDataType> dataType,
                                       String type,
                                       String fieldType)
       {
          String s1 = xsdMap.get(dataType);
          if (s1 == null || !s1.equals(type))
          {
             return false;
          }

          if (fieldType == null)
          {
             return true;
          }

          String s2 = xsdProdataMap.get(dataType);
          return (s2 != null) && s2.equals(fieldType);
       }

       /**
        * Test whether two representation of a field have same 'extent' property.
        *
        * @param   extent
        *          The ABL extent information.
        * @param   extentMax
        *          The XML extent information.
        *
        * @return  {@code true} only if both representations are the same.
        */
       public static boolean checkExtent(int extent, String extentMax)
       {
          if (extent == 0 && extentMax == null)
          {
             return true; // no extent
          }
          if (extent == 0 || extentMax == null)
          {
             return true; // one yes, one no
          }
          return Integer.parseInt(extentMax) == extent;
       }

       /**
        * Test whether two representation of a field have same 'mandatory' property.
        *
        * @param   mandatory
        *          The ABL mandatory information.
        * @param   nullable
        *          The XML nillable information.
        *
        * @return  {@code true} only if both representations are the same.
        */
       public static boolean checkMandatory(boolean mandatory, String nullable)
       {
          return mandatory == Boolean.parseBoolean(nullable);
       }

       /**
        * Get the XML type name for the BaseDataType class
        * @param c
        *        BaseDataType class
        * @return XML type name for the class
        */
       public static String getXmlType(Class<? extends BaseDataType> c)
       {
          String xsd = xsdMap.get(c);
          return xsd == null ? null : xsd.substring(4);
       }
    }