# ObjectModelParser.java

    /*
    ** Module   : ObjectModelParser.java
    ** Abstract : Implementation of the Progress.Json.Objectmodel.ObjectModelParser builtin class.
    **
    ** Copyright (c) 2018-2023, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ---------------------------------------Description---------------------------------------
    ** 001 OM  20181218 First version.
    ** 002 GES 20190308 Added a basic implementation.
    ** 003 CA  20190423 Added LegacyResource annotation.
    ** 004 HC  20190701 Implemented most of the legacy methods.
    ** 005 CA  20191024 Added method support levels and updated the class support level.
    ** 006 ME  20210115 Fix (some of) the error handling to match the 4GL side.
    ** 007 CA  20210221 Fixed 'qualified', 'extent' and 'returns' annotations at the legacy signature.
    **     OM  20210329 FIX-CODEPAGE is emitted as static method call to accomodate dereferenciation cases.
    **     CA  20210709 JSON parse must use a pristine byte stream and use the reader to decode it.
    **     CA  20220120 Do not used TypeFactory.object when the OO reference must not be tracked or registered.
    **                  Do not use TypeFactory.object for internal usages, use ObjectVar if the reference must
    **                  be tracked.
    **                  All TypeFactory.object variable definitions must be done outside of the top-level block.
    **     ME  20220427 Simplify error messages for json parser errors, use character offset instead of binary.
    **     VVT 20221003 CommonHandle.getResourceType() method renamed to resourceType() to prevent conflicts
    **                  with namesakes in DMO. See #6694.
    **     CA  20221024 parse(memptr) must interpret the memptr bytes as UTF-8.
    ** 008 CA  20231113 The 'execute' method must be annotated with LegacySignature Type.Execute, and also can be
    **                  dropped if is a no-op.
    */

    /*
    ** 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.oo.json.objectmodel;

    import java.io.*;

    import com.fasterxml.jackson.core.JsonParseException;
    import com.goldencode.p2j.util.*;
    import com.goldencode.p2j.util.BlockManager.Action;
    import com.goldencode.p2j.util.BlockManager.Condition;
    import com.goldencode.p2j.oo.json.*;

    import static com.goldencode.p2j.util.BlockManager.*;
    import static com.goldencode.p2j.report.ReportConstants.*;
    import static com.goldencode.p2j.util.InternalEntry.Type;

    /**
     * Implementation of the Progress.Json.Objectmodel.ObjectModelParser builtin class.
     */
    @LegacyResource(resource = "Progress.Json.Objectmodel.ObjectModelParser")
    @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
    public class ObjectModelParser
    extends com.goldencode.p2j.oo.json.JsonParser
    {
       /**
        * Default external procedure method which exists to ensure that any
        * long lived resources can be initialized properly.
        */
       @LegacySignature(type = Type.EXECUTE)
       public void __json_objectmodel_ObjectModelParser_execute__()
       {
          onBlockLevel(Condition.ERROR, Action.THROW);
       }

       /**
        * Method to duplicate the default constructor.
        */
       @LegacySignature(type = Type.CONSTRUCTOR)
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public void __json_objectmodel_ObjectModelParser_constructor__()
       {
          internalProcedure(this, "__json_objectmodel_ObjectModelParser_constructor__", new Block((Body) () ->
          {
             __json_JsonParser_constructor__();
          }));
       }

       /**
        * Reads the JSON content from the given source, parses it and returns the top level
        * construct.
        *
        * @param    _str
        *           The stream handle source from which to read.
        *
        * @return   The top level JSON construct.
        */
       @LegacySignature(returns = "OBJECT", type = Type.METHOD, name = "Parse", qualified = "Progress.Json.ObjectModel.JsonConstruct", parameters =
       {
          @LegacyParameter(name = "str", type = "HANDLE", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public object<? extends JsonConstruct> parse(final handle _str)
       {
          handle str = TypeFactory.initInput(_str);
          object<? extends JsonConstruct> res = TypeFactory.object(JsonConstruct.class);

          return function(this, "Parse", object.class, new Block((Body) () ->
          {
             // TODO: wrap that to WEB-CONTEXT handle when available, only accepted input value
             if (str == null || str.isUnknown() || !LegacyResource.PSEUDO_WIDGET.equals(str.unwrapType().resourceType().getValue()))
             {
                undoThrow(JsonError.newInstance(ErrorManager.getInvalidParameterError("source", this,
                         "Parse", "Must be a WEB-CONTEXT handle."), 16071));
             }

             try (Reader reader = new InputStreamReader(new InputStreamWrapper((Stream) str.getResource())))
             {
                res.assign(JsonBackend.instance().parse(reader));
                reader.close();
             }
             catch (Exception exc)
             {
                handleError(exc);
             }

             returnNormal(res);
          }));
       }

       /**
        * Reads the JSON content from the given source, parses it and returns the top level construct.
        *
        * @param    _source
        *           The longchar source from which to read.
        *
        * @return   The top level JSON construct.
        */
       @LegacySignature(returns = "OBJECT", type = Type.METHOD, name = "Parse", qualified = "Progress.Json.ObjectModel.JsonConstruct", parameters = {
                @LegacyParameter(name = "source", type = "LONGCHAR", mode = "INPUT") })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
       public object<? extends JsonConstruct> parse(final longchar _source)
       {
          longchar source = TypeFactory.initInput(_source);
          object<? extends JsonConstruct> res = TypeFactory.object(JsonConstruct.class);

          return function(this, "Parse", object.class, new Block((Body) () -> {
             // only if unknown or empty space, spaces only are (attempted to be) parsed
             if (source.isUnknown() || source.getValue().isEmpty())
             {
                undoThrow(JsonError.newInstance(ErrorManager.getInvalidParameterError("source", this,
                         "Parse", "Can not be UNKNOWN (?) or empty string."), 16055));
             }

             String cp = source._getCodePage();
             cp = (cp != null) ? cp.toLowerCase() : I18nOps._getCPInternal().toLowerCase();

             if (!cp.startsWith("utf"))
             {
                undoThrow(JsonError.newInstance(
                      ErrorManager.getInvalidParameterError("encoding",
                                                            this,
                                                            "Parse",
                                                            "'" + cp + "' is not a valid UTF encoding."),
                      16063));
             }

             if (!cp.equals("utf-8"))
             {
                // create a new longchar and make sure it will use utf-8 CP before copying the content
                longchar utf8Source = new longchar();
                utf8Source.fixCodePage("utf-8");
                utf8Source.assign(source.getValue());
                returnNormal(parse(utf8Source));
             }
             else
             {
                try
                {
                   res.assign(JsonBackend.instance().parse(source.getValue()));
                }
                catch (Exception exc)
                {
                   handleError(exc);
                }

                returnNormal(res);
             }
          }));
       }

       /**
        * Reads the JSON content from the given source, parses it and returns the top level
        * construct.
        *
        * @param    _source
        *           The memptr source from which to read.
        *
        * @return   The top level JSON construct.
        */
       @LegacySignature(returns = "OBJECT", type = Type.METHOD, name = "Parse", qualified = "Progress.Json.ObjectModel.JsonConstruct", parameters =
       {
          @LegacyParameter(name = "source", type = "MEMPTR", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public object<? extends JsonConstruct> parse(final memptr _source)
       {
          memptr source = TypeFactory.initInput(_source);
          object<? extends JsonConstruct> res = TypeFactory.object(JsonConstruct.class);

          return function(this, "Parse", object.class, new Block((Body) () ->
          {
             if (source == null || source.isUnknown() || source.isUninitialized())
             {
                undoThrow(JsonError.newInstance(ErrorManager.getInvalidParameterError("source", this,
                         "Parse", "Can not be UNKNOWN (?) or empty string."), 16055));
             }

             // empty string does not throw as for character/longchar so parse the string directly

             try
             {
                res.assign(JsonBackend.instance().parse(new String(source.getByteArray(), "utf-8")));
             }
             catch (Exception exc)
             {
                handleError(exc);
             }

             returnNormal(res);
          }));
       }

       /**
        * Reads the JSON content from the given source, parses it and returns the top level
        * construct.
        *
        * @param    _source
        *           The character source from which to read.
        *
        * @return   The top level JSON construct.
        */
       @LegacySignature(returns = "OBJECT", type = Type.METHOD, name = "Parse", qualified = "Progress.Json.ObjectModel.JsonConstruct", parameters =
       {
          @LegacyParameter(name = "source", type = "CHARACTER", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public object<? extends JsonConstruct> parse(final character _source)
       {
          character source = TypeFactory.initInput(_source);
          object<? extends JsonConstruct> res = TypeFactory.object(JsonConstruct.class);

          return function(this, "Parse", object.class, new Block((Body) () ->
          {
             // only if unknown or empty space, spaces only are (attempted to be) parsed
             if (source == null || source.isUnknown() || source.getValue().isEmpty())
             {
                undoThrow(JsonError.newInstance(ErrorManager.getInvalidParameterError("source", this,
                         "Parse", "Can not be UNKNOWN (?) or empty string."), 16055));
             }

             try
             {
                res.assign(JsonBackend.instance().parse(source.toStringMessage()));
             }
             catch (Exception exc)
             {
                handleError(exc);
             }

             returnNormal(res);
          }));
       }

       /**
        * Reads the JSON content from the given source, parses it and returns the top level
        * construct.
        *
        * @param    _fname
        *           The filename from which to read the JSON.
        *
        * @return   The top level JSON construct.
        */
       @LegacySignature(returns = "OBJECT", type = Type.METHOD, name = "ParseFile", qualified = "Progress.Json.ObjectModel.JsonConstruct", parameters =
       {
          @LegacyParameter(name = "fname", type = "CHARACTER", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public object<? extends JsonConstruct> parseFile(final character _fname)
       {
          character fname = TypeFactory.initInput(_fname);
          object<? extends JsonConstruct> res = TypeFactory.object(JsonConstruct.class);

          return function(this, "ParseFile", object.class, new Block((Body) () ->
          {
             if (TextOps.isEmpty(fname))
             {
                undoThrow(JsonError.newInstance(ErrorManager.getInvalidParameterError("source", this,
                         "ParseFile", "Can not be UNKNOWN (?) or empty string."), 16055));
             }

             String filename = fname.toStringMessage();
             Stream stream   = StreamFactory.openFileStream(filename, false, false);

             // this reads the client-side file
             try (Reader reader = new InputStreamReader(new InputStreamWrapper(stream)))
             {
                res.assign(JsonBackend.instance().parse(reader));
                reader.close();
             }
             catch (Exception exc)
             {
                handleError(exc);
             }
             finally {
                stream.close();
             }

             returnNormal(res);
          }));
       }

       private void handleError (Exception exc) {
          if (exc.getCause() != null && exc.getCause() instanceof CharConversionException)
          {
             // offset seems to always be 1
             undoThrow(JsonParserError.newInstance("Json Parser Error at offset 1: lexical error: invalid char in json text..", 16068));
          }
          else if (exc instanceof JsonParseException)
          {
             // TODO: align the message details with 4GL
             undoThrow(JsonParserError.newInstance(String.format("Json Parser Error at offset %d: unknown error",
                         ((JsonParseException) exc).getLocation().getCharOffset()), 16068));
          }
          else
          {
             undoThrow(JsonParserError.newInstance("Json Parser Error: unknown error", 16068));
          }
       }
    }