# MessageWriterBuilder.java

    /*
    ** Module   : MessageWriterBuilder.java
    ** Abstract : Implementation of the builtin class.
    **
    ** Copyright (c) 2019-2023, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ---------------------------------------Description----------------------------------------
    ** 001 CA  20190526 First version, stubs taken by converting the skeleton using FWD.
    ** 002 CA  20191024 Added method support levels and updated the class support level.
    ** 003 MP  20200611 Modify methods to match converting code signature.
    **         20201218 Implement as of OE12.2.
    **         20210208 Fix static registry property initialization.
    ** 004 CA  20210221 Fixed 'qualified', 'extent' and 'returns' annotations at the legacy signature.
    **     ME  20210310 Add block 'referent' for static methods, use initInput for object params.
    **     ME  20210330 Fix registry class type.
    ** 005 ME  20210519 Fix registry lazy loading.
    **     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.
    ** 006 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.writer;

    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.core.*;
    import com.goldencode.p2j.oo.lang.*;
    import com.goldencode.p2j.oo.net.http.*;
    import com.goldencode.p2j.oo.net.http.BuilderRegistry;
    import com.goldencode.p2j.oo.net.http.ConfigBuilder;
    import com.goldencode.p2j.oo.net.http.filter.payload.*;
    import com.goldencode.p2j.security.*;
    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.*;

    /**
     *
     * Builds a request writer for a given type of entity
     *
     */
    @LegacyResource(resource = "OpenEdge.Net.HTTP.Filter.Writer.MessageWriterBuilder")
    @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
    public abstract class MessageWriterBuilder
    extends ConfigBuilder
    {
       /** Builder registry */
       @LegacySignature(type = Type.PROPERTY, name = "Registry")
       private static ContextLocal<object<? extends BuilderRegistry>> REGISTRY =
             new ContextLocal<object<? extends BuilderRegistry>>()
       {
          /**
           * Create initial value.
           */
          @Override
          protected object<? extends BuilderRegistry> initialValue()
          {
             return TypeFactory.object(BuilderRegistry.class);
          }
       };

       /** content type */
       @LegacySignature(type = Type.PROPERTY, name = "ContentType")
       protected final character contentType = TypeFactory.character();

       /** writer registry */
       @LegacySignature(type = Type.PROPERTY, name = "WriterRegistry")
       protected final object<? extends BuilderRegistry> writerRegistry =
             TypeFactory.object(BuilderRegistry.class);

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

       /**
        * Constructor
        *
        * @param _pcContentType content type
        * @param poRegistry writer registry
        */
       @LegacySignature(type = Type.CONSTRUCTOR, parameters =
       {
             @LegacyParameter(name = "pcContentType", type = "CHARACTER", mode = "INPUT"),
             @LegacyParameter(name = "poRegistry", type = "OBJECT",
             qualified = "openedge.net.http.builderregistry", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public void __net_http_filter_writer_MessageWriterBuilder_constructor__(
             character _pcContentType,
             object<? extends BuilderRegistry> poRegistry)
       {
          character pcContentType = TypeFactory.initInput(_pcContentType);
          internalProcedure(this, "__net_http_filter_writer_MessageWriterBuilder_constructor__",
                new Block((Body) () -> {

             Assert.notNull(pcContentType, new character("Content type"));
             Assert.notNull(poRegistry, new character("Writer registry"));
             __net_http_ConfigBuilder_constructor__();
             this.contentType.assign(pcContentType);
             this.writerRegistry.assign(poRegistry);
          }));
       }

       @LegacySignature(type = Type.CONSTRUCTOR)
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public static void __net_http_filter_writer_MessageWriterBuilder_constructor__static__()
       {
          externalProcedure(MessageWriterBuilder.class, new Block((Body) () -> {

             onBlockLevel(Condition.ERROR, Action.THROW);
          }));
       }

       /**
        * Get registry.
        *
        * @return registry.
        */
       @LegacySignature(returns = "OBJECT", qualified = "OpenEdge.Net.HTTP.BuilderRegistry", type = Type.GETTER, name = "Registry")
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public static object<? extends BuilderRegistry> getRegistry()
       {

          return function(BodyWriterRegistry.class, "Registry", object.class, new Block((Body) () -> {

            if (!REGISTRY.get()._isValid())
            {
               REGISTRY.get().assign(ObjectOps.newInstance(BuilderRegistry.class, "I",
                        ObjectOps.getLegacyClass(MessageWriterBuilder.class)));
               initializeRegistry(REGISTRY.get());
            }

            returnNormal(REGISTRY.get());
          }));
       }

       /**
        * Initialize registry.
        *
        * @param _poRegistry to be initialized.
        */
       @LegacySignature(type = Type.METHOD, name = "InitializeRegistry", parameters =
       {
             @LegacyParameter(name = "poRegistry", type = "OBJECT", qualified = "openedge.net.http.builderregistry", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       private static void initializeRegistry(final object<? extends BuilderRegistry> _poRegistry)
       {
          object<? extends BuilderRegistry> poRegistry = TypeFactory.initInput(_poRegistry);

          internalProcedure(MessageWriterBuilder.class, "InitializeRegistry", new Block((Body) ()-> {

             poRegistry.ref().put(new character(ObjectOps.getLegacyName(MessageWriterBuilder.class)),
                   ObjectOps.getLegacyClass(DefaultMessageWriterBuilder.class));
          }));
       }

       /**
        * Get writer registry
        *
        * @return writer registry
        */
       @LegacySignature(returns = "OBJECT", qualified = "OpenEdge.Net.HTTP.BuilderRegistry", type = Type.GETTER, name = "WriterRegistry")
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       protected object<? extends BuilderRegistry>  getWriterRegistry()
       {
          return function(MessageWriterBuilder.class, "WriterRegistry", object.class,
                new Block((Body) () -> {

             returnNormal(this.writerRegistry);
          }));
       }

       /**
        * Create writer
        *
        * @return created writer
        */
       @LegacySignature(returns = "OBJECT", qualified = "OpenEdge.Net.HTTP.Filter.Payload.MessageWriter", type = Type.GETTER, name = "Writer")
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public abstract object<? extends MessageWriter>  getWriter();

       /**
        * Get content type
        *
        * @return content type
        */
       @LegacySignature(returns = "CHARACTER", type = Type.GETTER, name = "ContentType")
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       protected character getContentType()
       {
          return function(MessageWriterBuilder.class, "ContentType", character.class,
                new Block((Body) () -> {

             returnNormal(this.contentType);
          }));
       }

       /**
        * Returns an entity writer for a message
        *
        * @param _poMessage http message
        * @param _poRegistry builder registry
        *
        * @return an entity writer for a message
        */
       @LegacySignature(returns = "OBJECT", qualified = "OpenEdge.Net.HTTP.Filter.Writer.MessageWriterBuilder", type = Type.METHOD, name = "Build", parameters =
       {
          @LegacyParameter(name = "poMessage", type = "OBJECT", qualified = "OpenEdge.Net.HTTP.IHttpMessage", mode = "INPUT"),
          @LegacyParameter(name = "poRegistry", type = "OBJECT", qualified = "OpenEdge.Net.HTTP.BuilderRegistry", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public static object<? extends MessageWriterBuilder> build(
             object<? extends IhttpMessage> _poMessage,
             object<? extends BuilderRegistry> _poRegistry)
       {
          object<? extends IhttpMessage> poMessage = TypeFactory.initInput(_poMessage);
          object<? extends BuilderRegistry> poRegistry = TypeFactory.initInput(_poRegistry);
          object<? extends HttpHeader> contentType = TypeFactory.object(HttpHeader.class);

          return function(MessageWriterBuilder.class, "Build", object.class, new Block((Body)() -> {

             contentType.assign(poMessage.ref().getHeader(new character("Content-Type")));
             returnNormal(
                   build(poMessage.ref().getContentType(), poRegistry).
                      ref().option(new character("encodedAs"),
                            contentType.ref().getParameterValue(new character("charset"))).
                      ref().option(new character("multipartBoundary"),
                            contentType.ref().getParameterValue(new character("boundary")))
             );
          }));
       }

       /**
        * Returns an entity writer for a content type
        *
        * @param _pcContentType
        *         content type.
        * @param _poRegistry
        *         builder registry.
        *
        * @return an entity writer for a content type.
        */
       @LegacySignature(returns = "OBJECT", qualified = "OpenEdge.Net.HTTP.Filter.Writer.MessageWriterBuilder", type = Type.METHOD, name = "Build", parameters =
       {
          @LegacyParameter(name = "pcContentType", type = "CHARACTER", mode = "INPUT"),
          @LegacyParameter(name = "poRegistry", type = "OBJECT", qualified = "OpenEdge.Net.HTTP.BuilderRegistry", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public static object<? extends MessageWriterBuilder> build(character _pcContentType,
             object<? extends BuilderRegistry> _poRegistry)
       {
          character pcContentType = TypeFactory.initInput(_pcContentType);
          object<? extends BuilderRegistry> poRegistry = TypeFactory.initInput(_poRegistry);
          object<? extends MessageWriterBuilder> builder = TypeFactory.object(MessageWriterBuilder.class);
          object<? extends LegacyClass> builderType = TypeFactory.object(LegacyClass.class);

          return function(MessageWriterBuilder.class, "Build", object.class, new Block((Body)() -> {

             Assert.notNull(pcContentType, new character("Content type"));
             Assert.notNull(poRegistry, new character("Writer registry"));

             builderType.assign(getRegistry().ref().get(new character(ObjectOps.getLegacyName(MessageWriterBuilder.class))));

             Assert.isType(builderType, ObjectOps.getLegacyClass(MessageWriterBuilder.class));

             builder.assign(ObjectOps.newDynamicInstance(
                   builderType.ref().getTypeName(), "II", pcContentType, poRegistry));

             if (ObjectOps.typeOf(builder, ISupportInitialize.class).booleanValue())
             {
                ObjectOps.cast(builder, ISupportInitialize.class).ref().initialize();
             }
             returnNormal(builder);
          }));
       }

       /**
        * Specifies the Entity object to use for the message body

        * @param _poEntity - message body
        *
        * @return the writer builder used
        */
       @LegacySignature(returns = "OBJECT", qualified = "OpenEdge.Net.HTTP.Filter.Writer.MessageWriterBuilder", type = Type.METHOD, name = "WriteTo", parameters =
       {
          @LegacyParameter(name = "poEntity", type = "OBJECT",
                qualified = "progress.lang.object", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public object<? extends MessageWriterBuilder> writeTo(final object<? extends com.goldencode.p2j.oo.lang._BaseObject_> _poEntity)
       {
          object<? extends com.goldencode.p2j.oo.lang._BaseObject_> poEntity = TypeFactory.initInput(_poEntity);
          return function(this, "WriteTo", object.class, new Block((Body)() -> {

             Assert.notNull(poEntity, new character("Message Body"));
             setOption(new character("entity"), poEntity);
             setOption(new character("entityType"),
                   new character(poEntity.ref().getLegacyClass().ref().getTypeName()));
             returnNormal(new object<>(this));
          }));
       }

       /**
        * Adds or overwrites an option for the client library.

        * @param _pcName option name.
        * @param _pcValue option value.
        *
        * @return the writer builder used
        */
       @LegacySignature(returns = "OBJECT", qualified = "OpenEdge.Net.HTTP.Filter.Writer.MessageWriterBuilder", type = Type.METHOD, name = "Option", parameters =
       {
          @LegacyParameter(name = "p1", type = "CHARACTER", mode = "INPUT"),
          @LegacyParameter(name = "p2", type = "CHARACTER", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public object<? extends MessageWriterBuilder> option(character _pcName, character _pcValue)
       {
          character pcName = TypeFactory.initInput(_pcName);
          character  value = TypeFactory.initInput(_pcValue);
          return function(this, "Option", object.class, new Block((Body)() -> {

             Assert.notNullOrEmpty(pcName, new character("Option name"));
             setOption(pcName, value);
             returnNormal(new object<>(this));
          }));
       }

       /**
        * Adds or overwrites an option for the client library.

        * @param _pcName option name.
        * @param _poValue option value.
        *
        * @return the writer builder used
        */
       @LegacySignature(returns = "OBJECT", qualified = "OpenEdge.Net.HTTP.Filter.Writer.MessageWriterBuilder", type = Type.METHOD, name = "SetOption", parameters =
       {
          @LegacyParameter(name = "p1", type = "CHARACTER", mode = "INPUT"),
          @LegacyParameter(name = "p2", type = "OBJECT",
          qualified = "progress.lang.object", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public object<? extends MessageWriterBuilder> option(character _pcName,
             object<? extends _BaseObject_> _poValue)
       {
          character pcName = TypeFactory.initInput(_pcName);
          object<? extends _BaseObject_>  value = TypeFactory.initInput(_poValue);

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

             Assert.notNullOrEmpty(pcName, new character("Option name"));
             setOption(pcName, value);
             returnNormal(new object<>(this));
          }));
       }

       /**
        * Adds or overwrites an option for the client library.

        * @param _pcName option name.
        * @param _piValue option value.
        *
        * @return the writer builder used
        */
       @LegacySignature(returns = "OBJECT", qualified = "OpenEdge.Net.HTTP.Filter.Writer.MessageWriterBuilder", type = Type.METHOD, name = "Option", parameters =
       {
          @LegacyParameter(name = "p1", type = "CHARACTER", mode = "INPUT"),
          @LegacyParameter(name = "p2", type = "INT64", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public object<? extends MessageWriterBuilder> option(character _pcName, int64 _piValue)
       {
          character pcName = TypeFactory.initInput(_pcName);
          int64 value = TypeFactory.initInput(_piValue);
          return function(this, "Option", object.class, new Block((Body)() -> {

             Assert.notNullOrEmpty(pcName, new character("Option name"));
             setOption(pcName, new decimal(value));
             returnNormal(new object<>(this));
          }));
       }

       /**
        * Adds or overwrites an option for the client library.

        * @param _pcName option name.
        * @param _pdValue option value.
        *
        * @return the writer builder used
        */
       @LegacySignature(returns = "OBJECT", qualified = "OpenEdge.Net.HTTP.Filter.Writer.MessageWriterBuilder", type = Type.METHOD, name = "Option", parameters =
       {
          @LegacyParameter(name = "p1", type = "CHARACTER", mode = "INPUT"),
          @LegacyParameter(name = "p2", type = "DECIMAL", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public object<? extends MessageWriterBuilder> option(character _pcName, decimal _pdValue)
       {
          character pcName = TypeFactory.initInput(_pcName);
          decimal value = TypeFactory.initInput(_pdValue);
          return function(this, "Option", object.class, new Block((Body)() -> {

             Assert.notNullOrEmpty(pcName, new character("Option name"));
             setOption(pcName, value);
             returnNormal(new object<>(this));
          }));
       }

       /**
        * Adds or overwrites an option for the client library.

        * @param _pcName option name.
        * @param _plValue option value.
        *
        * @return the writer builder used
        */
       @LegacySignature(returns = "OBJECT", qualified = "OpenEdge.Net.HTTP.Filter.Writer.MessageWriterBuilder", type = Type.METHOD, name = "Option", parameters =
       {
          @LegacyParameter(name = "p1", type = "CHARACTER", mode = "INPUT"),
          @LegacyParameter(name = "p2", type = "LOGICAL", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public object<? extends MessageWriterBuilder> option(character _pcName, logical _plValue)
       {
          character pcName = TypeFactory.initInput(_pcName);
          logical value = TypeFactory.initInput(_plValue);
          return function(this, "Option", object.class, new Block((Body)() -> {

             Assert.notNullOrEmpty(pcName, new character("Option name"));
             setOption(pcName, value);
             returnNormal(new object<>(this));
          }));
       }

       /**
        * Returns a content type writer.
        *
        *  The search alogrithm is
        *  1. Exact match - type / sub-type
        *  2. Vendor types - type / vendor-prefix-removed-sub-type
        *  3. General type - type / *
        *  4. Fallback to HTTP default - application/octet-stream
        *
        * @param  _pcContentType
        *         the content type
        * @return a content type writer
        */
       @LegacySignature(returns = "OBJECT", qualified = "Progress.Lang.Class", type = Type.METHOD, name = "GetWriter", parameters =
       {
          @LegacyParameter(name = "pcContentType", type = "CHARACTER", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       protected object<? extends LegacyClass> getWriter(character _pcContentType)
       {
          character pcContentType = TypeFactory.initInput(_pcContentType);
          object<? extends LegacyClass> writer = TypeFactory.object(LegacyClass.class);

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

             Assert.notNull(pcContentType, new character("Content type"));

             if (TextOps.isEmpty(pcContentType.getValue()))
             {
                returnNormal(writer);
             }

             String contentType = pcContentType.getValue();
             int pp = contentType.indexOf(';');
             if (pp >= 0)
             {
                contentType = contentType.substring(0, pp);
             }

             String type = TextOps.entry(1, contentType, "/").getValue();
             String subtype = TextOps.entry(2, contentType, "/").getValue();

             writer.assign(this.writerRegistry.ref().get(new character(contentType)));

             if (!writer.isValid().booleanValue() && subtype.startsWith("vnd."))
             {
                int p = subtype.indexOf('+');
                if (p > 0)
                {
                   subtype = subtype.substring(p + 1);
                   writer.assign(this.writerRegistry.ref().get(new character(type + "/" + subtype)));
                }
             }

             if (!writer.isValid().booleanValue())
             {
                writer.assign(this.writerRegistry.ref().get(new character(type + "/*")));
             }

             if (!writer.isValid().booleanValue())
             {
                writer.assign(this.writerRegistry.ref().get(
                      new character("application/octet-stream")));
             }
             returnNormal(writer);
          }));
       }
    }