# JsonEntityWriter.java

    /*
    ** Module   : JsonEntityWriter.java
    ** Abstract : Implementation of the builtin class.
    **
    ** Copyright (c) 2019-2023, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ---------------------------------------Description----------------------------------------
    ** 001 IAS 20190923 First version.
    ** 002 MP  20200611 Added missing methods as stubs taken by converting the skeleton using FWD.
    ** 003 CA  20210221 Fixed 'qualified', 'extent' and 'returns' annotations at the legacy signature.
    ** 004 ME  20210324 Add missing methods, complete implementation as of OE12.2.
    **     VVT 20210917 Javadoc fixed.
    **     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.
    **     CA  20221024 write(ByteBucket) must interpret the bytes as 'utf-8' source codepage.
    ** 005 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.net.http.filter.payload;

    import static com.goldencode.p2j.util.BlockManager.externalProcedure;
    import static com.goldencode.p2j.report.ReportConstants.*;
    import static com.goldencode.p2j.util.BlockManager.function;
    import static com.goldencode.p2j.util.BlockManager.internalProcedure;
    import static com.goldencode.p2j.util.BlockManager.onBlockLevel;
    import static com.goldencode.p2j.util.BlockManager.returnNormal;

    import com.goldencode.p2j.oo.common.support.IcharacterHolder;
    import com.goldencode.p2j.oo.common.support.IhandleHolder;
    import com.goldencode.p2j.oo.common.support.IlongcharHolder;
    import com.goldencode.p2j.oo.core.*;
    import com.goldencode.p2j.oo.core.collections.Iiterator;
    import com.goldencode.p2j.oo.core.collections.Imap;
    import com.goldencode.p2j.oo.core.collections.ImapEntry;
    import com.goldencode.p2j.oo.core.collections.LegacyMap;
    import com.goldencode.p2j.oo.core.collections.LegacyMapEntry;
    import com.goldencode.p2j.oo.json.objectmodel.*;
    import com.goldencode.p2j.oo.lang.*;
    import com.goldencode.p2j.oo.net.http.Cookie;
    import com.goldencode.p2j.oo.net.http.HttpHeader;
    import com.goldencode.p2j.persist.BufferImpl;
    import com.goldencode.p2j.persist.DataSet;
    import com.goldencode.p2j.persist.TempTable;
    import com.goldencode.p2j.persist.serial.JsonExport;
    import com.goldencode.p2j.util.*;
    import com.goldencode.p2j.util.BlockManager.Action;
    import com.goldencode.p2j.util.BlockManager.Condition;
    import com.goldencode.p2j.util.InternalEntry.*;

    /**
     *
     * Parse application/json payload.
     *
     */
    @LegacyResource(resource = "OpenEdge.Net.HTTP.Filter.Payload.JsonEntityWriter")
    @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_PARTIAL)
    public class JsonEntityWriter
    extends MessageWriter
    {
       /** JSON parser */
       private object<? extends ObjectModelParser> moParser =
             TypeFactory.object(ObjectModelParser.class);

       /**
        * Execute
        */
       @LegacySignature(type = Type.EXECUTE)
       public void __net_http_filter_payload_JsonEntityWriter_execute__()
       {
          onBlockLevel(Condition.ERROR, Action.THROW);
       }

       /**
        * Constructor
        */
       @LegacySignature(type = Type.CONSTRUCTOR)
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public void __net_http_filter_payload_JsonEntityWriter_constructor__()
       {
          internalProcedure(this, "__net_http_filter_payload_JsonEntityWriter_constructor__",
                new Block((Body) () ->
          {
             __net_http_filter_payload_MessageWriter_constructor__(
                   ObjectOps.getLegacyClass(JsonConstruct.class)
             );
          }));
       }

       /**
        * Constructor
        *
        * @param _poType entity type
        */
       @LegacySignature(type = Type.CONSTRUCTOR, parameters =
       {
          @LegacyParameter(name = "poType", type = "OBJECT",
                qualified = "progress.lang.class", mode = "INPUT"),
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public void __net_http_filter_payload_JsonEntityWriter_constructor__(
             object<? extends LegacyClass> _poType)
       {
          object<? extends LegacyClass> poType = TypeFactory.initInput(_poType);
          internalProcedure(this, "__net_http_filter_payload_JsonEntityWriter_constructor__", new Block((Body) () ->
          {
             __net_http_filter_payload_MessageWriter_constructor__(poType);
          }));
       }

       /**
        * Opens the writer for output.
        */
       @LegacySignature(type = Type.METHOD, name = "Open")
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       @Override
       public void open()
       {
          internalProcedure(this, "Open", new Block((Body)() -> {
             super.open();
             moParser.assign(ObjectOps.newInstance(ObjectModelParser.class));
          }));
       }

       /**
        * Closes the writer.
        */
       @LegacySignature(type = Type.METHOD, name = "Close")
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       @Override
       public void close()
       {
          internalProcedure(this, "Close", new Block((Body)() -> {
             super.close();
             moParser.setUnknown();
          }));
       }

       /**
        * Write data to/from the entity
        *
        * @param _poData data to be written
        *
        * @return number of bytes written
        */
       @LegacySignature(returns = "INT64", type = Type.METHOD, name = "Write", parameters =
       {
          @LegacyParameter(name = "poData", type = "LONGCHAR", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       @Override
       public int64 write(longchar _poData)
       {
          return function(this, "Write", int64.class, new Block((Body) () ->
          {
             integer len = TextOps.byteLength(_poData);
             Assert.isZeroOrPositive(len, new character("Data"));
             if (len.intValue() == 0)
             {
                this.entity.assign(ObjectOps.newInstance(JsonObject.class));
             }
             else
             {
                this.entity.assign(ObjectOps.cast(moParser.ref().parse(_poData), JsonConstruct.class));
             }
             returnNormal(new int64(len));
          }));
       }

       /**
        * Write data to/from the entity
        *
        * @param _poData data to be written
        *
        * @return number of bytes written
        */
       @LegacySignature(returns = "INT64", type = Type.METHOD, name = "Write", parameters =
       {
          @LegacyParameter(name = "poData", type = "MEMPTR", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       @Override
       public int64 write(memptr _poData)
       {
          return function(this, "Write", int64.class, new Block((Body) () ->
          {
             int64 len = _poData.length();
             Assert.isZeroOrPositive(len, new character("Data size"));
             if (len.longValue() == 0)
             {
                this.entity.assign(ObjectOps.newInstance(JsonObject.class));
             }
             else
             {
                this.entity.assign(ObjectOps.cast(moParser.ref().parse(_poData), JsonConstruct.class));
             }
             returnNormal(len);
          }));
       }

       /**
        * Write data to/from the entity
        *
        * @param _poData data to be written
        *
        * @return number of bytes written
        */
       @LegacySignature(returns = "INT64", type = Type.METHOD, name = "Write", parameters =
       {
          @LegacyParameter(name = "poData", type = "CHARACTER", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       @Override
       public int64 write(character _poData)
       {
          return function(this, "Write", int64.class, new Block((Body) () ->
          {
             integer len = TextOps.byteLength(_poData);
             Assert.isZeroOrPositive(len, new character("Data"));
             if (len.intValue() == 0)
             {
                this.entity.assign(ObjectOps.newInstance(JsonObject.class));
             }
             else
             {
                this.entity.assign(ObjectOps.cast(moParser.ref().parse(_poData), JsonConstruct.class));
             }
             returnNormal(new int64(len));
          }));
       }

       /**
        * Write data to/from the entity
        *
        * @param _phData data to be written
        *
        * @return number of bytes written
        */
       @LegacySignature(returns = "INT64", type = Type.METHOD, name = "Write", parameters =
       {
          @LegacyParameter(name = "phData", type = "HANDLE", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       @Override
       public int64 write(handle _phData)
       {
          handle phData = TypeFactory.initInput(_phData);

          return function(this, "Write", int64.class, new Block((Body) () ->
          {
             Assert.notNull(phData, new character("Data"));

             WrappedResource res = phData.getResource();

             if (res instanceof TempTable || res instanceof DataSet || res instanceof BufferImpl)
             {
                this.entity.assign(ObjectOps.newInstance(JsonObject.class));
                ObjectOps.cast(this.entity, JsonObject.class).ref().read(phData);
             }

             returnNormal(new unknown());
          }));
       }

       @LegacySignature(returns = "INT64", type = Type.METHOD, name = "WriteHandle", parameters =
       {
          @LegacyParameter(name = "phData", type = "HANDLE", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public int64 writeHandle(final handle _phData)
       {
          handle phData = TypeFactory.initInput(_phData);

          return function(JsonEntityWriter.class, this, "WriteHandle", int64.class, new Block((Body) () ->
          {
             returnNormal(this.write(phData));
          }));
       }

       /**
        * Write data to/from the entity
        *
        * @param _poData data to be written
        *
        * @return number of bytes written
        */
       @LegacySignature(returns = "INT64", type = Type.METHOD, name = "Write", parameters =
       {
          @LegacyParameter(name = "poData", type = "OBJECT",
                qualified = "progress.lang.object", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       @Override
       public int64 write(object<? extends _BaseObject_> _poData)
       {
          object<? extends _BaseObject_> poData = TypeFactory.initInput(_poData);
          object<? extends Memptr> mptr = TypeFactory.object(Memptr.class);

          return function(this, "Write", int64.class, new Block((Body) () ->
          {
             if (!poData._isValid())
             {
                this.entity.assign(ObjectOps.newInstance(JsonObject.class));
                returnNormal(0L);
             }
             else if (ObjectOps.typeOf(poData, LegacyError.class).booleanValue())
             {
                writeError(ObjectOps.cast(poData, LegacyError.class));
                returnNormal(0L);
             }
             else if (ObjectOps.typeOf(poData, JsonConstruct.class).booleanValue())
             {
                this.entity.assign(poData);
                returnNormal(0L);
             }
             else if (ObjectOps.typeOf(poData, IlongcharHolder.class).booleanValue())
             {
                returnNormal(write(ObjectOps.cast(poData, IlongcharHolder.class).ref().getValue()));
             }
             else if (ObjectOps.typeOf(poData, IcharacterHolder.class).booleanValue())
             {
                returnNormal(write(ObjectOps.cast(poData, IcharacterHolder.class).ref().getValue()));
             }
             else if (ObjectOps.typeOf(poData, IhandleHolder.class).booleanValue())
             {
                returnNormal(write(ObjectOps.cast(poData, IhandleHolder.class).ref().getValue()));
             }
             else if (ObjectOps.typeOf(poData, ByteBucket.class).booleanValue())
             {
                ByteBucket bb = ObjectOps.cast(poData, ByteBucket.class).ref();
                returnNormal(write(bb.getString(new int64(1),
                                                bb.getSize(),
                                                new character("utf-8"),
                                                new character("utf-8"))));
             }
             else if (ObjectOps.typeOf(poData, Memptr.class).booleanValue())
             {
                mptr.assign(poData);
                int64 len = mptr.ref().getSize();
                if (len.longValue() == 0)
                {
                   this.entity.assign(ObjectOps.newInstance(JsonObject.class));
                }
                else
                {
                   this.entity.assign(ObjectOps.cast(moParser.ref().parse(mptr.ref().getValue()),
                         JsonConstruct.class));
                }
                returnNormal(len);
             }
             else if (ObjectOps.typeOf(poData, Cookie.class).booleanValue())
             {
                returnNormal(write(write_1(ObjectOps.cast(poData, Cookie.class))));
             }
             else if (ObjectOps.typeOf(poData, HttpHeader.class).booleanValue())
             {
                returnNormal(write(write_2(ObjectOps.cast(poData, HttpHeader.class))));
             }
             else if (ObjectOps.typeOf(poData, Imap.class).booleanValue())
             {
               writeMap(ObjectOps.cast(poData, Imap.class));
               returnNormal(0L);
             }
             else if (ObjectOps.typeOf(poData, ImapEntry.class).booleanValue())
             {
                object<ImapEntry> mEntry = ObjectOps.cast(poData, ImapEntry.class);

                writeTuple(mEntry.ref().getKey(), mEntry.ref().getValue());
                returnNormal(0L);
             }
             unsupported(poData);
          }));
       }

       @LegacySignature(type = Type.METHOD, name = "Write", returns = "OBJECT", qualified = "progress.json.objectmodel.jsonobject", parameters =
       {
          @LegacyParameter(name = "pCookie", type = "OBJECT", qualified = "openedge.net.http.cookie", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       protected object<? extends com.goldencode.p2j.oo.json.objectmodel.JsonObject> write_1(final object<? extends com.goldencode.p2j.oo.net.http.Cookie> _pCookie)
       {
          object<? extends com.goldencode.p2j.oo.net.http.Cookie> pCookie = TypeFactory.initInput(_pCookie);
          object<? extends com.goldencode.p2j.oo.json.objectmodel.JsonObject> oRet = TypeFactory.object(JsonObject.class);

          return function(JsonEntityWriter.class, this, "Write", object.class, new Block((Body) () -> {

             oRet.assign(ObjectOps.newInstance(JsonObject.class));
             oRet.ref().add(new character("name"), pCookie.ref().getName());
             oRet.ref().add(new character("value"), pCookie.ref().getValue());
             oRet.ref().add(new character("path"), pCookie.ref().getPath());
             oRet.ref().add(new character("domain"), pCookie.ref().getDomain());
             oRet.ref().add(new character("expires"), pCookie.ref().getExpiresAt());
             oRet.ref().add(new character("httpOnly"), pCookie.ref().getHttpOnly());
             oRet.ref().add(new character("secure"), pCookie.ref().getSecure());

             returnNormal(oRet);
          }));
       }

       @LegacySignature(type = Type.METHOD, name = "Write", returns = "OBJECT", qualified = "progress.json.objectmodel.jsonobject", parameters =
       {
          @LegacyParameter(name = "pHeader", type = "OBJECT", qualified = "openedge.net.http.httpheader", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       protected object<? extends com.goldencode.p2j.oo.json.objectmodel.JsonObject> write_2(final object<? extends com.goldencode.p2j.oo.net.http.HttpHeader> _pHeader)
       {
          object<? extends com.goldencode.p2j.oo.net.http.HttpHeader> pHeader = TypeFactory.initInput(_pHeader);
          object<? extends com.goldencode.p2j.oo.json.objectmodel.JsonObject> oRet = TypeFactory.object(JsonObject.class);

          return function(JsonEntityWriter.class, this, "Write", object.class, new Block((Body) () -> {

             oRet.assign(ObjectOps.newInstance(JsonObject.class));
             oRet.ref().add(new character("name"), pHeader.ref().getName());
             oRet.ref().add(new character("value"), pHeader.ref().getValue());

             // 4GL quirk, always invalid object, missing return maybe
             returnNormal(oRet);
          }));
       }

       /**
        * Write error.
        *
        * @param _poError error to be written.
        */
       @LegacySignature(type = Type.METHOD, name = "WriteError", parameters =
       {
          @LegacyParameter(name = "poError", type = "OBJECT", qualified = "progress.lang.error", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       protected void writeError(object<? extends LegacyError> _poError)
       {
          object<? extends com.goldencode.p2j.oo.lang.LegacyError> poError = TypeFactory.initInput(_poError);
          object<? extends com.goldencode.p2j.oo.json.objectmodel.JsonObject> jsonErr = TypeFactory.object(JsonObject.class);
          object<? extends com.goldencode.p2j.oo.json.objectmodel.JsonArray> jsonArr = TypeFactory.object(JsonArray.class);

          internalProcedure(JsonEntityWriter.class, this, "WriteError", new Block((Body) () -> {

             jsonErr.assign(JsonExport.serializeError(poError));

             if (this.entity._isValid())
             {
                if (ObjectOps.typeOf(this.entity, JsonArray.class).booleanValue())
                {
                   ObjectOps.cast(this.entity, JsonArray.class).ref().add_2(jsonErr);
                }
                else if (ObjectOps.typeOf(this.entity, JsonObject.class).booleanValue())
                {
                   jsonArr.assign(ObjectOps.newInstance(JsonArray.class));
                   jsonArr.ref().add_2(ObjectOps.cast(this.entity, JsonObject.class));
                   jsonArr.ref().add_2(jsonErr);

                   this.entity.assign(jsonArr);
                }
             }
             else
             {
                this.entity.assign(jsonErr);
             }
          }));
       }

       @LegacySignature(type = Type.METHOD, name = "WriteMap", parameters =
       {
          @LegacyParameter(name = "pValue", type = "OBJECT", qualified = "openedge.core.collections.imap", mode = "INPUT")
       })
       protected void writeMap(final object<? extends com.goldencode.p2j.oo.core.collections.Imap> _pValue)
       {
          object<? extends com.goldencode.p2j.oo.core.collections.Imap> pValue = TypeFactory.initInput(_pValue);
          object<? extends com.goldencode.p2j.oo.json.objectmodel.JsonObject> oRet = TypeFactory.object(JsonObject.class);

          internalProcedure(JsonEntityWriter.class, this, "WriteMap", new Block((Body) () -> {

             Assert.notNull(pValue, new character("Map"));

             oRet.assign(ObjectOps.newInstance(JsonObject.class));

             if (pValue.ref() instanceof LegacyMap)
             {
                ((LegacyMap) pValue.ref()).getMap().forEach((k, v) -> {
                  if (!k.isUnknown())
                  {
                     if (!v.isUnknown())
                     {
                        oRet.ref().add(k.ref().toLegacyString(), v.ref().toLegacyString());
                     }
                     else
                     {
                        oRet.ref().addNull(k.ref().toLegacyString());
                     }
                  }
                });
             }
             else
             {
                Iiterator it = pValue.ref().getEntrySet().ref().iterator().ref();

                while (it.hasNext().booleanValue())
                {
                   object<LegacyMapEntry> entry = ObjectOps.cast(it.next_(), LegacyMapEntry.class);
                   if (!entry.isUnknown() && !entry.ref().getKey().isUnknown())
                   {
                      if (!entry.ref().getValue().isUnknown())
                      {
                         oRet.ref().add(entry.ref().getKey().ref().toLegacyString(), entry.ref().getValue().ref().toLegacyString());
                      }
                      else
                      {
                         oRet.ref().addNull(entry.ref().getKey().ref().toLegacyString());
                      }
                   }
                }
             }

             this.entity.assign(oRet);
          }));
       }

       @LegacySignature(type = Type.METHOD, name = "WriteTuple", parameters =
       {
          @LegacyParameter(name = "pKey", type = "OBJECT", qualified = "progress.lang.object", mode = "INPUT"),
          @LegacyParameter(name = "pValue", type = "OBJECT", qualified = "progress.lang.object", mode = "INPUT")
       })
       protected void writeTuple(final object<? extends com.goldencode.p2j.oo.lang._BaseObject_> _pKey, final object<? extends com.goldencode.p2j.oo.lang._BaseObject_> _pValue)
       {
          object<? extends com.goldencode.p2j.oo.lang._BaseObject_> pKey = TypeFactory.initInput(_pKey);
          object<? extends com.goldencode.p2j.oo.lang._BaseObject_> pValue = TypeFactory.initInput(_pValue);
          object<? extends com.goldencode.p2j.oo.json.objectmodel.JsonObject> oRet = TypeFactory.object(JsonObject.class);

          internalProcedure(JsonEntityWriter.class, this, "WriteTuple", new Block((Body) () -> {

             Assert.notNull(pKey, new character("Tuple key"));

             character key = pKey.ref().toLegacyString();
             character val = pValue.isUnknown() ? new character() : pValue.ref().toLegacyString();

             if (this.entity.isUnknown() || ObjectOps.typeOf(this.entity, JsonArray.class).booleanValue())
             {
               oRet.assign(ObjectOps.newInstance(JsonObject.class));

               oRet.ref().add(key, val);

               if (this.entity.isUnknown())
               {
                  this.entity.assign(oRet);
               }
               else
               {
                  ObjectOps.cast(this.entity, JsonArray.class).ref().add_2(oRet);
               }
             }
             else if (ObjectOps.typeOf(this.entity, JsonObject.class).booleanValue())
             {
                oRet.assign(ObjectOps.cast(this.entity, JsonObject.class));
                if (oRet.ref().has(key).booleanValue())
                {
                   oRet.ref().set(key, val);
                }
                else
                {
                   oRet.ref().add(key, val);
                }
             }
          }));
       }
    }