# JsonConstruct.java

    /*
    ** Module   : JsonConstruct.java
    ** Abstract : Implementation of the Progress.Json.Objectmodel.JsonConstruct builtin class.
    **
    ** Copyright (c) 2018-2024, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ---------------------------------------Description---------------------------------------
    ** 001 OM  20181218 First version.
    ** 002 GES 20190308 Added correct annotations, basic implementation and javadoc.
    ** 003 CA  20190423 Added LegacyResource annotation.
    ** 004 CA  20190527 Added annotations for property accessors and class event methods.
    ** 005 CA  20190706 Added Write(OUTPUT target AS CHARACTER).
    ** 006 HC  20190701 Implemented most of the legacy methods.
    **     HC  20190707 Implemented read(dataSet) and read(tempTable) methods of JsonObject legacy class.
    ** 007 HC  20190712 Fixed writeStream method. Stream-by-name resolution happens on the server, not the client.
    **     HC  20190714 Implemented stream name server-client serialization. Other fixes.
    ** 008 IAS 20190914 Fixed write(memptr) method.
    ** 009 CA  20191024 Added method support levels and updated the class support level.
    ** 010 CA  20200503 Added stub for JsonConstruct:read(handle).
    ** 011 ME  20201028 Add routine level undo throw to avoid 'eating' errors.
    **         20210128 Fix longchar to utf-8 for jsonText, 'null' string for nulls.
    **         20210209 Fix encoding parameter sent to write method (unknown instead of null).
    **         20210215 Remove clean/read methods, refactor write.
    ** 012 CA  20210221 Fixed 'qualified', 'extent' and 'returns' annotations at the legacy signature.
    **     ME  20210319 Fix write stream, add method to throw stream not found exception.
    **     CA  20210609 Updated INPUT/INPUT-OUTPUT parameters to the new approach, where they are explicitly
    **                  initialized at the method's execution, and not at the caller's arguments.
    **     OM  20210809 Fixed javadoc errors.
    **     CA  20220923 Variable definitions (including associated with parameters) must be done always outside of
    **                  the BlockManager API
    ** 013 GBB 20230512 Logging methods replaced by CentralLogger/ConversionStatus.
    ** 014 CA  20231113 The 'execute' method must be annotated with LegacySignature Type.Execute, and also can be
    **                  dropped if is a no-op.
    ** 015 AP  20240910 Extended the access modifier for the ObjectBuilder class in order to be used in another
    **                  packages.
    */

    /*
    ** 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 com.goldencode.p2j.oo.json.*;
    import com.goldencode.p2j.oo.lang.*;
    import com.goldencode.p2j.persist.serial.*;
    import com.goldencode.p2j.util.*;
    import com.goldencode.p2j.util.ErrorManager;
    import com.goldencode.p2j.util.BlockManager.Action;
    import com.goldencode.p2j.util.BlockManager.Condition;
    import com.goldencode.p2j.util.logging.*;

    import java.io.*;
    import java.nio.charset.*;
    import java.util.*;
    import java.util.logging.*;
    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.JsonConstruct builtin class.
     */
    @LegacyResource(resource = "Progress.Json.Objectmodel.JsonConstruct")
    @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
    public abstract class JsonConstruct
    extends BaseObject
    {
       /** Logger. */
       private static final CentralLogger LOG = CentralLogger.get(JsonConstruct.class);

       /**
        * 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_JsonConstruct_execute__()
       {
          onBlockLevel(Condition.ERROR, Action.THROW);
       }

       /**
        * Method to duplicate the default constructor.
        * <p>
        * The original 4GL version had a private access mode.
        * <p>
        * Some Progress builtin classes have all constructors with private access mode but are
        * subclassed.  Since child classes must be able to reference at least one "constructor"
        * directly, this should be impossible.  This must be some kind of special case hidden
        * inside the OO4GL implmentation.  In Java the method must be public.
        */
       @LegacySignature(type = Type.CONSTRUCTOR)
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public void __json_objectmodel_JsonConstruct_constructor__()
       {
          internalProcedure(this, "__json_objectmodel_JsonConstruct_constructor__", new Block((Body) () ->
          {
             __lang_BaseObject_constructor__();
          }));
       }

       /**
        * Writes the object graph referenced by this JSON construct into the given target.
        *
        * @param    strHndl
        *           The stream handle to use as a target.
        *
        * @return   {@code true} if the serialization was successful.
        */
       @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "Write", parameters =
       {
          @LegacyParameter(name = "str-hndl", type = "HANDLE", mode = "INPUT"),
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public logical write(final handle strHndl)
       {
          return write(strHndl, new logical(false), new character());
       }

       /**
        * Writes the object graph referenced by this JSON construct into the given target.
        *
        * @param    strHndl
        *           The stream handle to use as a target.
        * @param    fmtted
        *           {@code true} to format with extra whitespace.
        *
        * @return   {@code true} if the serialization was successful.
        */
       @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "Write", parameters =
       {
          @LegacyParameter(name = "str-hndl", type = "HANDLE", mode = "INPUT"),
          @LegacyParameter(name = "fmtted", type = "LOGICAL", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public logical write(final handle strHndl, final logical fmtted)
       {
          return write(strHndl, fmtted, new character());
       }

       /**
        * Writes the object graph referenced by this JSON construct into the given target.
        *
        * @param    _strHndl
        *           The stream handle to use as a target.
        * @param    _fmtted
        *           {@code true} to format with extra whitespace.
        * @param    _enc
        *           The encoding name to use or "" for the default "UTF-8".
        *
        * @return   {@code true} if the serialization was successful.
        */
       @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "Write", parameters =
       {
          @LegacyParameter(name = "str-hndl", type = "HANDLE", mode = "INPUT"),
          @LegacyParameter(name = "fmtted", type = "LOGICAL", mode = "INPUT"),
          @LegacyParameter(name = "enc", type = "CHARACTER", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public logical write(final handle _strHndl, final logical _fmtted, final character _enc)
       {
          handle strHndl = TypeFactory.initInput(_strHndl);
          logical fmtted = TypeFactory.initInput(_fmtted);
          character enc = TypeFactory.initInput(_enc);
          logical ret = TypeFactory.logical();

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

             if (!strHndl._isValid() || !(strHndl.get() instanceof Stream))
             {
                ErrorManager.recordOrThrowError(new int[] { 14263, 15351 },
                         new String[] {
                                  "Invalid handle or handle type for STREAM-HANDLE",
                                  "WRITE-JSON( ) could not find the specified stream-handle." },
                         false, false, false);
             }

             OutputStream o = new OutputStreamWrapper(strHndl.unwrapStream());

             try
             {
                writeImpl(o, fmtted, enc);
                ret.assign(true);
             }
             catch (Exception e)
             {
                returnError(JsonError.newInstance(e.getMessage(), 0));
             }
             returnNormal(ret);
          }));
       }

       /**
        * Writes the object graph referenced by this JSON construct into the given target.
        *
        * @param    target
        *           The longchar instance to use as a target.
        *
        * @return   {@code true} if the serialization was successful.
        */
       @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "Write", parameters =
       {
          @LegacyParameter(name = "target", type = "LONGCHAR", mode = "INPUT-OUTPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public logical write(final longchar target)
       {
          return write(target, new logical(false), new character());
       }

       /**
        * Writes the object graph referenced by this JSON construct into the given target.
        *
        * @param    target
        *           The longchar instance to use as a target.
        * @param    fmtted
        *           {@code true} to format with extra whitespace.
        *
        * @return   {@code true} if the serialization was successful.
        */
       @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "Write", parameters =
       {
          @LegacyParameter(name = "target", type = "LONGCHAR", mode = "INPUT-OUTPUT"),
          @LegacyParameter(name = "fmtted", type = "LOGICAL", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public logical write(final longchar target, final logical fmtted)
       {
          return write(target, fmtted, new character());
       }

       /**
        * Writes the object graph referenced by this JSON construct into the given target.
        *
        * @param    _target
        *           The longchar instance to use as a target.
        * @param    _fmtted
        *           {@code true} to format with extra whitespace.
        * @param    _enc
        *           The encoding name to use or "" for the default "UTF-8".
        *
        * @return   {@code true} if the serialization was successful.
        */
       @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "Write", parameters =
       {
          @LegacyParameter(name = "target", type = "LONGCHAR", mode = "INPUT-OUTPUT"),
          @LegacyParameter(name = "fmtted", type = "LOGICAL", mode = "INPUT"),
          @LegacyParameter(name = "enc", type = "CHARACTER", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public logical write(final longchar _target, final logical _fmtted, final character _enc)
       {
          longchar target = TypeFactory.initInputOutput(_target);
          logical fmtted = TypeFactory.initInput(_fmtted);
          character enc  = TypeFactory.initInput(_enc);
          logical ret = TypeFactory.logical();

          return function(this, "Write", logical.class, new Block((Body) () ->
          {
             ByteArrayOutputStream out = new ByteArrayOutputStream();

             if (TextOps.isEmpty(enc))
             {
                enc.assign("UTF-8");
             }

             try {
                Charset ch = writeImpl(out, fmtted, enc);
                target.setUnknown();
                target.fixCodePage(enc);
                target.assign(new String(out.toByteArray(), ch));
                ret.assign(true);
             }
             catch (Exception e)
             {
                returnError(JsonError.newInstance(e.getMessage(), 0));
             }

             returnNormal(ret);
          }));
       }

       /**
        * Writes the object graph referenced by this JSON construct into the given target.
        *
        * @param    _target
        *           The memptr instance to use as a target.
        *
        * @return   {@code true} if the serialization was successful.
        */
       @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "Write", parameters =
       {
          @LegacyParameter(name = "target", type = "MEMPTR", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public logical write(final memptr _target)
       {
          return write(_target, new logical(false), new character());
       }

       /**
        * Writes the object graph referenced by this JSON construct into the given target.
        *
        * @param    _target
        *           The memptr instance to use as a target.
        * @param    _fmtted
        *           {@code true} to format with extra whitespace.
        *
        * @return   {@code true} if the serialization was successful.
        */
       @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "Write", parameters =
       {
          @LegacyParameter(name = "target", type = "MEMPTR", mode = "INPUT"),
          @LegacyParameter(name = "fmtted", type = "LOGICAL", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public logical write(final memptr _target, final logical _fmtted)
       {
          return write(_target, _fmtted, new character());
       }

       /**
        * Writes the object graph referenced by this JSON construct into the given target.
        *
        * @param    _target
        *           The memptr instance to use as a target.
        * @param    _fmtted
        *           {@code true} to format with extra whitespace.
        * @param    _enc
        *           The encoding name to use or "" for the default "UTF-8".
        *
        * @return   {@code true} if the serialization was successful.
        */
       @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "Write", parameters =
       {
          @LegacyParameter(name = "target", type = "MEMPTR", mode = "INPUT"),
          @LegacyParameter(name = "fmtted", type = "LOGICAL", mode = "INPUT"),
          @LegacyParameter(name = "enc", type = "CHARACTER", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public logical write(final memptr _target, final logical _fmtted, final character _enc)
       {
          logical fmtted = TypeFactory.initInput(_fmtted);
          character enc  = TypeFactory.initInput(_enc);
          logical ret = TypeFactory.logical();

          return function(this, "Write", logical.class, new Block((Body) () ->
          {
             ByteArrayOutputStream out = new ByteArrayOutputStream();

             try {
                Charset ch = writeImpl(out, fmtted, enc);
                _target.setLength(0);
                _target.setLength(out.size());
                _target.write(true, out.toByteArray(), 0, false);

                ret.assign(true);
             }
             catch (Exception e)
             {
                returnError(JsonError.newInstance(e.getMessage(), 0));
             }
             returnNormal(ret);
          }));
       }

       /**
        * Writes the object graph referenced by this JSON construct into the given target.
        *
        * @param    target
        *           The character instance to use as a target.
        *
        * @return   {@code true} if the serialization was successful.
        */
       @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "Write", parameters =
       {
          @LegacyParameter(name = "target", type = "CHARACTER", mode = "OUTPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public logical write(final character target)
       {
          return write(target, new logical(false), new character());
       }

       /**
        * Writes the object graph referenced by this JSON construct into the given target.
        *
        * @param    target
        *           The character instance to use as a target.
        * @param    _fmtted
        *           {@code true} to format with extra whitespace.
        *
        * @return   {@code true} if the serialization was successful.
        */
       @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "Write", parameters =
       {
          @LegacyParameter(name = "target", type = "CHARACTER", mode = "OUTPUT"),
          @LegacyParameter(name = "fmtted", type = "LOGICAL", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public logical write(final character target, final logical _fmtted)
       {
          return write(target, _fmtted, new character());
       }

       /**
        * Writes the object graph referenced by this JSON construct into the given target.
        *
        * @param    _target
        *           The character instance to use as a target.
        * @param    _fmtted
        *           {@code true} to format with extra whitespace.
        * @param    _enc
        *           The encoding name to use or "" for the default "UTF-8".
        *
        * @return   {@code true} if the serialization was successful.
        */
       @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "Write", parameters =
       {
          @LegacyParameter(name = "target", type = "CHARACTER", mode = "OUTPUT"),
          @LegacyParameter(name = "fmtted", type = "LOGICAL", mode = "INPUT"),
          @LegacyParameter(name = "enc", type = "CHARACTER", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public logical write(final character _target, final logical _fmtted, final character _enc)
       {
          character target = TypeFactory.initOutput(_target);
          logical fmtted = TypeFactory.initInput(_fmtted);
          character enc  = TypeFactory.initInput(_enc);
          logical ret = TypeFactory.logical();

          return function(this, "Write", logical.class, new Block((Body) () ->
          {
             ByteArrayOutputStream out = new ByteArrayOutputStream();

             try {
                Charset ch = writeImpl(out, fmtted, enc);
                target.assign(new String(out.toByteArray(), ch));
                ret.assign(true);
             }
             catch (Exception e)
             {
                returnError(JsonError.newInstance(e.getMessage(), 0));
             }

             returnNormal(ret);
          }));
       }

       /**
        * Writes the object graph referenced by this JSON construct into the given target.
        *
        * @param    _fname
        *           The filename to use as a target.
        *
        * @return   {@code true} if the serialization was successful.
        */
       @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "WriteFile", parameters =
       {
          @LegacyParameter(name = "fname", type = "CHARACTER", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public logical writeFile(final character _fname)
       {
          return writeFile(_fname, new logical(), new character());
       }

       /**
        * Writes the object graph referenced by this JSON construct into the given target.
        *
        * @param    _fname
        *           The filename to use as a target.
        * @param    _fmtted
        *           {@code true} to format with extra whitespace.
        *
        * @return   {@code true} if the serialization was successful.
        */
       @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "WriteFile", parameters =
       {
          @LegacyParameter(name = "fname", type = "CHARACTER", mode = "INPUT"),
          @LegacyParameter(name = "fmtted", type = "LOGICAL", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public logical writeFile(final character _fname, final logical _fmtted)
       {
          return writeFile(_fname, _fmtted, new character());
       }

       /**
        * Writes the object graph referenced by this JSON construct into the given target.
        *
        * @param    _fname
        *           The filename to use as a target.
        * @param    _fmtted
        *           {@code true} to format with extra whitespace.
        * @param    _enc
        *           The encoding name to use or "" for the default "UTF-8".
        *
        * @return   {@code true} if the serialization was successful.
        */
       @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "WriteFile", parameters =
       {
          @LegacyParameter(name = "fname", type = "CHARACTER", mode = "INPUT"),
          @LegacyParameter(name = "fmtted", type = "LOGICAL", mode = "INPUT"),
          @LegacyParameter(name = "enc", type = "CHARACTER", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public logical writeFile(final character _fname, final logical _fmtted, final character _enc)
       {
          character fname  = TypeFactory.initInput(_fname);
          logical fmtted = TypeFactory.initInput(_fmtted);
          character enc  = TypeFactory.initInput(_enc);
          logical ret = TypeFactory.logical();

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

             Stream s = StreamFactory.openFileStream(fname.toStringMessage(), true, false);
             OutputStream o = new OutputStreamWrapper(s);

             try {
                writeImpl(o, fmtted, enc);

                ret.assign(true);
             }
             catch (Exception e)
             {
                returnError(JsonError.newInstance(e.getMessage(), 0));
             } finally {
                s.closeOut();
             }

             returnNormal(ret);
          }));
       }

       /**
        * Writes the object graph referenced by this JSON construct into the given target.
        *
        * @param    _sname
        *           The stream name to use as a target.
        *
        * @return   {@code true} if the serialization was successful.
        */
       @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "WriteStream", parameters =
       {
          @LegacyParameter(name = "sname", type = "CHARACTER", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public logical writeStream(final character _sname)
       {
          return writeStream(_sname, new logical(false), new character());
       }

       /**
        * Writes the object graph referenced by this JSON construct into the given target.
        *
        * @param    _sname
        *           The stream name to use as a target.
        * @param    _fmtted
        *           {@code true} to format with extra whitespace.
        *
        * @return   {@code true} if the serialization was successful.
        */
       @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "WriteStream", parameters =
       {
          @LegacyParameter(name = "sname", type = "CHARACTER", mode = "INPUT"),
          @LegacyParameter(name = "fmtted", type = "LOGICAL", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public logical writeStream(final character _sname, final logical _fmtted)
       {
          return writeStream(_sname, _fmtted, new character());
       }

       /**
        * Writes the object graph referenced by this JSON construct into the given target.
        *
        * @param    _sname
        *           The stream name to use as a target.
        * @param    _fmtted
        *           {@code true} to format with extra whitespace.
        * @param    _enc
        *           The encoding name to use or "" for the default "UTF-8".
        *
        * @return   {@code true} if the serialization was successful.
        */
       @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "WriteStream", parameters =
       {
          @LegacyParameter(name = "sname", type = "CHARACTER", mode = "INPUT"),
          @LegacyParameter(name = "fmtted", type = "LOGICAL", mode = "INPUT"),
          @LegacyParameter(name = "enc", type = "CHARACTER", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public logical writeStream(final character _sname, final logical _fmtted, final character _enc)
       {
          character sname = TypeFactory.initInput(_sname);
          logical fmtted = TypeFactory.initInput(_fmtted);
          character enc = TypeFactory.initInput(_enc);
          logical ret = TypeFactory.logical();

          return function(this, "WriteStream", logical.class, new Block((Body) () ->
          {

             Stream s = StreamFactory.findOutputStream(sname.isUnknown() ? null : sname.toStringMessage());
             if (s != null)
             {
                boolean pretty = fmtted != null && !fmtted.isUnknown() && fmtted.booleanValue();
                OutputStream o = new OutputStreamWrapper(s);

                try
                {
                   JsonBackend.instance().write(o,
                                                this, pretty,
                                                enc.isUnknown() ? null : enc.toStringMessage());
                   ret.assign(true);
                }
                catch (Exception e)
                {
                   returnError(JsonError.newInstance(e.getMessage(), 0));
                }

                returnNormal(ret);
             }
             else
             {
                throwStreamNotFound(sname.toStringMessage());
             }

          }));
       }

       /**
        * Throw stream not found exception.
        *
        * The error number and message is different for JsonArray/JsonObject.
        *
        * @param   streamName
        *          The stream name.
        */
       protected void throwStreamNotFound(String streamName)
       {
          String msg = String.format("WRITE-JSON( ) could not find open stream \"%s\"", streamName);
          undoThrow(SysError.newInstance(msg, 15343, false, true));
       }

       /**
        * Adds a json element (object property or array element) to the json object.
        *
        * @param   name
        *          Name of the json element. This parameter is ignored if this is a json array.
        * @param   value
        *          Value of the json element.
        */
       public abstract void addElement(String name, object<? extends JsonConstruct> value);

       /**
        * Adds a json element (object property or array element) to the json object.
        *
        * @param   name
        *          Name of the json element. This parameter is ignored if this is a json array.
        * @param   value
        *          Value of the json element.
        */
       public abstract void addElement(String name, String value);

       /**
        * Adds a json element (object property or array element) to the json object.
        *
        * @param   name
        *          Name of the json element. This parameter is ignored if this is a json array.
        * @param   value
        *          Value of the json element.
        */
       public abstract void addElement(String name, Number value);

       /**
        * Adds a json element (object property or array element) to the json object.
        *
        * @param   name
        *          Name of the json element. This parameter is ignored if this is a json array.
        * @param   value
        *          Value of the json element.
        */
       public abstract void addElement(String name, Boolean value);

       /**
        * Adds null json element (object property or array element) to the json object.
        *
        * @param   name
        *          Name of the json element. This parameter is ignored if this is a json array.
        */
       public abstract void addElementNull(String name);

       /**
        * Serializes this json object or array and recursively all the child objects into byte array. The byte
        * array is passed to the supplied {@code converter} together with the Java character encoding resolved
        * from the legacy character encoding.
        *
        * @param   out
        *          Target output stream.
        * @param   fmted
        *          When set to {@code true} the serialized json text will be formatted.
        * @param   enc
        *          The legacy encoding name to be used during serialization.
        *
        * @throws  Exception
        *          in case of an IO error.
        */
       protected Charset writeImpl(OutputStream out, logical fmted, character enc)
       throws Exception
       {
          boolean pretty = fmted != null && !fmted.isUnknown() && fmted.booleanValue();
          String legacyEnc = enc != null && !enc.isUnknown() ? enc.toStringMessage() : null;

          return Charset.forName(JsonBackend.instance().write(out, this, pretty, legacyEnc));

       }

       /**
        * The method implements {@code GetJsonText} legacy methods on {@code JsonObject} and {@code JsonArray}
        * legacy classes.
        *
        * @param   jsonConstruct
        *          The {@linkplain JsonConstruct} instance to serialize.
        */
       protected void getJsonTextImpl(JsonConstruct jsonConstruct)
       {
          try
          {
             returnNormal(getJsonText(jsonConstruct));
          }
          catch (IOException e)
          {
             LOG.log(Level.WARNING, "", e);
             returnError(ObjectOps.newInstance(JsonError.class));
          }
       }

       /**
        * Serializes a {@linkplain JsonConstruct} instance into {@linkplain longchar}.
        *
        * @param   jsonConstruct
        *          The instance to serialize.
        *
        * @return  the serialized {@linkplain longchar}.
        *
        * @throws  IOException
        *          raised when there is an IO error during the serialization.
        */
       protected longchar getJsonText(JsonConstruct jsonConstruct)
       throws IOException
       {
          ByteArrayOutputStream out = new ByteArrayOutputStream();
          JsonBackend.instance().write(out, jsonConstruct, false, null);
          longchar ret = TypeFactory.longchar();
          ret.fixCodePage("UTF-8");
          ret.assign(out.toString("UTF-8"));

          return ret;
       }

       protected longchar getJsonText(Object o)
       throws IOException
       {
          if (o instanceof JsonConstruct)
          {
             return getJsonText((JsonConstruct) o);
          }
          else
          {
             longchar ret = TypeFactory.longchar();
             ret.fixCodePage("UTF-8");

             ret.assign(o == null ? "null" : o.toString());

             return ret;
          }
       }

       /**
        * Json structure callback for building the json objects.
        */
       public static class ObjectBuilder
       implements JsonStructureCallback
       {
          /** Stack of json construct objects */
          private final Stack<object<? extends JsonConstruct>> stack = new Stack<>();

          /** Json field name */
          private String fieldName;

          /**
           * Constructor.
           *
           * @param   root
           *          The root json construct that will be filled with deserialized json structure, may be
           *          {@code null}.
           */
          public ObjectBuilder(object<JsonConstruct> root)
          {
             if (root != null)
             {
                this.stack.push(root);
             }
          }

          /**
           * Constructor.
           *
           * @param   root
           *          The root json construct that will be filled with deserialized json structure, may be
           *          {@code null}.
           */
          public ObjectBuilder(JsonConstruct root)
          {
             if (root != null)
             {
                this.stack.push(new object(root));
             }
          }

          @Override
          public void startObject()
          {
             object<JsonObject> newObj = ObjectOps.newInstance(JsonObject.class);

             if (!stack.isEmpty())
             {
                object<? extends JsonConstruct> parent = stack.peek();
                parent.ref().addElement(fieldName, newObj);
             }

             stack.push(newObj);
             fieldName = null;
          }

          @Override
          public void endObject()
          {
             stack.pop();
          }

          @Override
          public void startArray()
          {
             object<JsonArray> newObj = ObjectOps.newInstance(JsonArray.class);

             if (!stack.isEmpty())
             {
                object<? extends JsonConstruct> parent = stack.peek();
                parent.ref().addElement(fieldName, newObj);
             }

             stack.push(newObj);
             fieldName = null;
          }

          @Override
          public void endArray()
          {
             stack.pop();
          }

          @Override
          public void fieldName(String name)
          {
             fieldName = name;
          }

          @Override
          public void booleanValue(boolean value)
          {
             object<? extends JsonConstruct> con = stack.peek();
             con.ref().addElement(fieldName, value);
          }

          @Override
          public void stringValue(String value)
          {
             object<? extends JsonConstruct> con = stack.peek();
             con.ref().addElement(fieldName, value);
          }

          @Override
          public void numberValue(Number value)
          {
             object<? extends JsonConstruct> con = stack.peek();
             con.ref().addElement(fieldName, value);
          }

          @Override
          public void nullValue()
          {
             object<? extends JsonConstruct> con = stack.peek();
             con.ref().addElementNull(fieldName);
          }

          @Override
          public void rawDecimalValue(String value)
          {
             decimal dec = decimal.fromLiteral(value);
             object<? extends JsonConstruct> con = stack.peek();
             con.ref().addElement(fieldName, dec.toBigDecimal());
          }
       }
    }