# MultipartFormBodyWriter.java

    /*
    ** Module   : MultipartFormBodyWriter.java
    ** Abstract : Implementation of the builtin class.
    **
    ** Copyright (c) 2020-2023, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ---------------------------------------Description----------------------------------------
    ** 001 MP  20200603 First version, stubs taken by converting the skeleton using FWD.
    ** 002 CA  20210221 Fixed 'qualified', 'extent' and 'returns' annotations at the legacy signature.
    ** 003 ME  20210331 Implemented as per OE12.2.
    **     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  20220923 Variable definitions (including associated with parameters) must be done always outside of
    **                  the BlockManager API
    ** 004 CA  20231113 The 'execute' method must be annotated with LegacySignature Type.Execute, and also can be
    **                  dropped if is a no-op.
    ** 005 AL2 20240930 Delete temporary ByteBuckets; they are still in memory due to positive reference count.
    */

    /*
    ** 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 com.goldencode.p2j.util.*;
    import com.goldencode.p2j.util.BlockManager.Action;
    import com.goldencode.p2j.util.BlockManager.Condition;

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

    import java.io.File;

    import com.goldencode.p2j.oo.common.support.ImemptrHolder;
    import com.goldencode.p2j.oo.core.Assert;
    import com.goldencode.p2j.oo.core.ByteBucket;
    import com.goldencode.p2j.oo.core.LegacyString;
    import com.goldencode.p2j.oo.core.collections.Iiterator;
    import com.goldencode.p2j.oo.core.collections.Imap;
    import com.goldencode.p2j.oo.core.collections.LegacyMap;
    import com.goldencode.p2j.oo.core.collections.LegacyMapEntry;
    import com.goldencode.p2j.oo.io.FileInputStream;
    import com.goldencode.p2j.oo.net.FileTypeRegistry;
    import com.goldencode.p2j.oo.net.MessagePart;
    import com.goldencode.p2j.oo.net.MultipartEntity;
    import com.goldencode.p2j.oo.net.http.HttpHeader;
    import com.goldencode.p2j.oo.net.http.HttpHeaderBuilder;
    import com.goldencode.p2j.oo.net.http.filter.writer.BodyWriterBuilder;

    /**
     * Business logic (converted to Java from the 4GL source code
     * in OpenEdge/Net/HTTP/Filter/Payload/MultipartFormBodyWriter.cls).
     */
    @LegacyResource(resource = "OpenEdge.Net.HTTP.Filter.Payload.MultipartFormBodyWriter")
    @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
    public class MultipartFormBodyWriter
    extends com.goldencode.p2j.oo.net.http.filter.payload.MessageWriter
    implements com.goldencode.p2j.oo.net.ISupportMultipartEntity,
               com.goldencode.p2j.oo.core.ISupportEncoding
    {
       private static final String CRLF = "\r\n";

       @LegacySignature(type = Type.PROPERTY, name = "Boundary")
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       private character boundary = TypeFactory.character();

       @LegacySignature(type = Type.PROPERTY, name = "Encoding")
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       private character encoding = TypeFactory.character();

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

       @LegacySignature(returns = "CHARACTER", type = Type.GETTER, name = "Boundary")
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public character getBoundary()
       {
          return function(MultipartFormBodyWriter.class, this, "Boundary", character.class, new Block((Body) () ->
          {
             returnNormal(boundary);
          }));
       }

       @LegacySignature(type = Type.SETTER, name = "Boundary", parameters =
       {
          @LegacyParameter(name = "var", type = "CHARACTER", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public void setBoundary(final character _var)
       {
          character var = TypeFactory.initInput(_var);

          internalProcedure(MultipartFormBodyWriter.class, this, "Boundary", new Block((Body) () ->
          {
             boundary.assign(var);
          }));
       }

       @LegacySignature(returns = "CHARACTER", type = Type.GETTER, name = "Encoding")
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public character getEncoding()
       {
          return function(MultipartFormBodyWriter.class, this, "Encoding", character.class, new Block((Body) () ->
          {
             returnNormal(encoding);
          }));
       }

       @LegacySignature(type = Type.SETTER, name = "Encoding", parameters =
       {
          @LegacyParameter(name = "var", type = "CHARACTER", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public void setEncoding(final character _var)
       {
          character var = TypeFactory.initInput(_var);

          internalProcedure(MultipartFormBodyWriter.class, this, "Encoding", new Block((Body) () ->
          {
             encoding.assign(var);
          }));
       }

       @LegacySignature(type = Type.CONSTRUCTOR)
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public void __net_http_filter_payload_MultipartFormBodyWriter_constructor__()
       {
          internalProcedure(MultipartFormBodyWriter.class, this, "__net_http_filter_payload_MultipartFormBodyWriter_constructor__", new Block((Body) () ->
          {
             __net_http_filter_payload_MessageWriter_constructor__(ObjectOps.getLegacyClass(ByteBucket.class));
             this.boundary.assign(SecurityOps.convertUniversalUIDToGlobalUID());
          }));
       }

       @LegacySignature(type = Type.METHOD, name = "Open")
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       @Override
       public void open()
       {
          internalProcedure(MultipartFormBodyWriter.class, this, "Open", new Block((Body) () ->
          {
             if (!this.entity._isValid())
             {
                this.entity.assign(ByteBucket.instance());
             }
             super.open();
          }));
       }

       @LegacySignature(returns = "INT64", type = Type.METHOD, name = "Write", parameters =
       {
          @LegacyParameter(name = "pData", type = "OBJECT", qualified = "openedge.net.multipartentity", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_STUB)
       protected int64 write_1(final object<? extends com.goldencode.p2j.oo.net.MultipartEntity> _pData)
       {
          object<? extends com.goldencode.p2j.oo.net.MultipartEntity> pData = TypeFactory.initInput(_pData);
          object<? extends HttpHeader>[] oHhext[] = new object[][]
          {
             TypeFactory.objectExtent(HttpHeader.class, false)
          };

          return function(MultipartFormBodyWriter.class, this, "Write", int64.class, new Block((Body) () ->
          {
             Assert.notNull(pData, new character("Multipart entity"));

             ByteBucket bucket = ObjectOps.cast(this.entity, ByteBucket.class).ref();
             long init = bucket.getSize().longValue();

             this.boundary.assign(pData.ref().getBoundary());

             character chunk = pData.ref().getPrologue();

             // prologue
             if (!TextOps.isEmpty(chunk))
                bucket.putString(new longchar(TextOps.substitute("&1&2", chunk, CRLF)));

             for (int i = 0; i < pData.ref().getSize().intValue(); i++)
             {
                bucket.putString(new longchar(TextOps.substitute("--&1&2", this.boundary, CRLF)));
                writePart(bucket, pData.ref().getPart(new integer(i + 1)), oHhext);
             }

             // end data
             bucket.putString(new longchar(TextOps.substitute("--&1--&2", this.boundary, CRLF)));

             // epilogue
             chunk.assign(pData.ref().getEpilogue());
             if (!TextOps.isEmpty(chunk))
             {
                bucket.putString(new longchar(chunk));
             }
             else
             {
                // end
                bucket.putString(new longchar(CRLF));
             }

             returnNormal(new int64(bucket.getSize().longValue() - init));
          }));
       }

       private void writePart(ByteBucket bucket, object<? extends MessagePart> part, object<? extends HttpHeader>[][] oHhext)
       {
          object<? extends ByteBucket> msgPart = ByteBucket.instance();
          object<? extends MessageWriter> writer = BodyWriterBuilder.build(part)
                   .ref().writeTo(msgPart)
                   .ref().getWriter();
          try
          {

             Assert.notNull(writer, new character("Part writer"));
             writer.ref().open();
             writer.ref().write(part.ref().getBody());
             writer.ref().close();
             integer iRsp = TypeFactory.integer();

             iRsp.assign(part.ref().getHeaders().ref().getAll(new OutputExtentParameter<object<? extends com.goldencode.p2j.oo.net.http.HttpHeader>>()
             {
                public object<? extends com.goldencode.p2j.oo.net.http.HttpHeader>[] getVariable()
                {
                   return oHhext[0];
                }

                public void setVariable(final object<? extends com.goldencode.p2j.oo.net.http.HttpHeader>[] newRef)
                {
                   oHhext[0] = newRef;
                }
             }));

             for (int i = oHhext[0].length; i > 0; i--)
             {
                bucket.putString(new longchar(TextOps.substitute("&1&2", oHhext[0][i - 1].ref().toLegacyString(), CRLF)));
             }

             // end header
             bucket.putString(new longchar(CRLF));

             bucket.putBytes(msgPart);
             // end part
             bucket.putString(new longchar(CRLF));
          }
          finally
          {
             if (msgPart._isValid())
             {
                ObjectOps.delete(msgPart);
             }
             if (writer._isValid())
             {
                ObjectOps.delete(writer);
             }
          }
       }

       @LegacySignature(returns = "INT64", type = Type.METHOD, name = "Write", parameters =
       {
          @LegacyParameter(name = "pData", type = "OBJECT", qualified = "progress.lang.object", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       @Override
       public int64 write(final object<? extends com.goldencode.p2j.oo.lang._BaseObject_> _pData)
       {
          object<? extends com.goldencode.p2j.oo.lang._BaseObject_> pData = TypeFactory.initInput(_pData);

          return function(MultipartFormBodyWriter.class, this, "Write", int64.class, new Block((Body) () ->
          {
             if (!pData._isValid())
             {
                returnNormal(write_2(ObjectOps.newInstance(LegacyMap.class)));
             }
             else if (ObjectOps.typeOf(pData, Imap.class).booleanValue())
             {
                returnNormal(write_2(ObjectOps.cast(pData, Imap.class)));
             }
             else if (ObjectOps.typeOf(pData, MultipartEntity.class).booleanValue())
             {
                returnNormal(write_1(ObjectOps.cast(pData, MultipartEntity.class)));
             }
             else
             {
                unsupported(pData);
             }
          }));
       }

       @LegacySignature(returns = "INT64", type = Type.METHOD, name = "Write", parameters =
       {
          @LegacyParameter(name = "pData", type = "OBJECT", qualified = "openedge.core.collections.imap", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       protected int64 write_2(final object<? extends com.goldencode.p2j.oo.core.collections.Imap> _pData)
       {
          object<? extends com.goldencode.p2j.oo.core.collections.Imap> pData = TypeFactory.initInput(_pData);

          return function(MultipartFormBodyWriter.class, this, "Write", int64.class, new Block((Body) () ->
          {
             ByteBucket bucket = ObjectOps.cast(this.entity, ByteBucket.class).ref();

             long init = bucket.getSize().longValue();

             // encodings
             if (!TextOps.isEmpty(this.encoding))
                writeField(ObjectOps.newInstance(LegacyString.class, "I", "_charset_"), ObjectOps.newInstance(LegacyString.class, "I", this.encoding));

             Iiterator it = pData.ref().getEntrySet().ref().iterator().ref();
             object<LegacyMapEntry> entry;

             while (it.hasNext().booleanValue())
             {
                entry = ObjectOps.cast(it.next_(), LegacyMapEntry.class);
                bucket.putString(new longchar(TextOps.substitute("--&1&2", this.boundary, CRLF)));
                writeField(entry.ref().getKey(), entry.ref().getValue());
             }

             // end data
             bucket.putString(new longchar(TextOps.substitute("--&1--&2", this.boundary, CRLF)));

             // end
             bucket.putString(new longchar(CRLF));

             returnNormal(new int64(bucket.getSize().longValue() - init));
          }));
       }

       @LegacySignature(type = Type.METHOD, name = "WriteField", parameters =
       {
          @LegacyParameter(name = "pKey", type = "OBJECT", qualified = "progress.lang.object", mode = "INPUT"),
          @LegacyParameter(name = "pValue", type = "OBJECT", qualified = "progress.lang.object", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       protected void writeField(
                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);
          character contentType = TypeFactory.character("text/plain");

          internalProcedure(MultipartFormBodyWriter.class, this, "WriteField", new Block((Body) () ->
          {
             Assert.notNull(pKey, new character("Form field name"));

             ByteBucket bucket = ObjectOps.cast(this.entity, ByteBucket.class).ref();

             object<? extends HttpHeader> hContentDispo = HttpHeaderBuilder.build(new character("Content-Disposition"))
                      .ref().value(new character("form-data"))
                      .ref().getHeader();

             hContentDispo.ref().setParameterValue(new character("name"), TextOps.substitute("\"&1\"", pKey.ref().toLegacyString()));

             if (pValue._isValid())
             {
                if (ObjectOps.typeOf(pValue, ImemptrHolder.class).booleanValue())
                {
                   contentType.assign("application/octet-stream");
                }
                else if (ObjectOps.typeOf(pValue, FileInputStream.class).booleanValue())
                {
                   object<FileInputStream> fs = ObjectOps.cast(pValue, FileInputStream.class);

                   String fileName = new File(fs.ref().getFileName().getValue()).getName();
                   String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);

                   hContentDispo.ref().setParameterValue(new character("filename"), TextOps.substitute("\"&1\"", fileName));

                   contentType.assign(FileTypeRegistry.getRegistry().ref().get(new character(fileExt)));
                }

             }

             bucket.putString(new longchar(TextOps.substitute("&1&2", hContentDispo.ref().toLegacyString(), CRLF)));

             if (pValue._isValid())
             {
                // content-type header
                object<? extends HttpHeader> hContentType = HttpHeaderBuilder.build(new character("Content-Type"))
                         .ref().value(contentType)
                         .ref().getHeader();
                bucket.putString(new longchar(TextOps.substitute("&1&2", hContentType.ref().toLegacyString(), CRLF)));

                // end header
                bucket.putString(new longchar(CRLF));

                // part body
                object<? extends ByteBucket> msgPart = ByteBucket.instance();
                object<? extends MessageWriter> writer = BodyWriterBuilder.build(contentType)
                         .ref().writeTo(msgPart)
                         .ref().getWriter();

                Assert.notNull(writer, new character("Part writer"));
                writer.ref().open();
                writer.ref().write(pValue);
                writer.ref().close();

                bucket.putBytes(msgPart);
             }
             else
             {
             // end header
                bucket.putString(new longchar(CRLF));
             }
             // end part
             bucket.putString(new longchar(CRLF));
          }));
       }
    }