# FileInputStream.java

    /*
    ** Module   : FileInputStream.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   20200703 Complete code with methods like legacy class
    ** 003 MP   20210112 improve constructor behavior and add file name in loop
    ** 004 ME   20210128 Fix ctor/execute names.
    **     ME   20210204 Complete implementation as of OE12.2.
    ** 005 CA   20210221 Fixed 'qualified', 'extent' and 'returns' annotations at the legacy
    **                   signature.
    **     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.
    **     ME   20211001 Do not attempt to open the stream in ctor, delay it till read/skip is used.
    ** 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.io;

    import static com.goldencode.p2j.util.BlockManager.externalProcedure;
    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.report.ReportConstants.*;
    import static com.goldencode.p2j.util.BlockManager.returnNormal;
    import static com.goldencode.p2j.util.BlockManager.undoThrow;

    import com.goldencode.p2j.oo.lang.SysError;
    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.*;

    /**
     * Business logic (converted to Java from the 4GL source code
     * in Progress/IO/FileInputStream.cls).
     */
    @LegacyResource(resource = "Progress.IO.FileInputStream")
    @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
    public class FileInputStream
    extends InputStream
    {
       @LegacySignature(type = Type.PROPERTY, name = "FileName")
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_STUB)
       private character fileName = TypeFactory.character();
       private long fileSize;
       private long bytesLeft;

       private Stream sFileStream = new StreamWrapper("sFile");

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

       @LegacySignature(type = Type.CONSTRUCTOR, parameters =
       {
          @LegacyParameter(name = "filename", type = "CHARACTER", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public void __io_FileInputStream_constructor__(final character _filename)
       {
          character filename = TypeFactory.initInput(_filename);

          internalProcedure(FileInputStream.class, this, "__io_FileInputStream_constructor__", new Block((Body) () ->
          {
             __io_InputStream_constructor__();

             if (filename.isUnknown())
             {
                undoThrow(SysError.newInstance("Invalid file name specified  for 'Progress.IO.FileInputStream'", 18195, false, false));
             }

             this.fileName.assign(filename);

          }));
       }

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

       @LegacySignature(type = Type.METHOD, name = "Close")
       @Override
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public void close()
       {
          internalProcedure(FileInputStream.class, this, "Close", new Block((Body) () ->
          {
             if(sFileStream.isValid())
                sFileStream.closeIn();

             super.close();
          }));
       }

       @LegacySignature(returns = "INT64", type = Type.METHOD, name = "Read", parameters =
       {
          @LegacyParameter(name = "target", type = "MEMPTR", mode = "INPUT")
       })
       @Override
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public int64 read(final memptr target)
       {
          return function(FileInputStream.class, this, "Read", int64.class, new Block((Body) () ->
          {
             returnNormal(read(target, new int64(1), target.length()));
          }));
       }

       @LegacySignature(returns = "INT64", type = Type.METHOD, name = "SkipBytes", parameters =
       {
          @LegacyParameter(name = "n", type = "INT64", mode = "INPUT")
       })
       @Override
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public int64 skipBytes(final int64 _n)
       {
          int64 n = TypeFactory.initInput(_n);
          memptr mdata = TypeFactory.memptr();

          return function(FileInputStream.class, this, "SkipBytes", int64.class, new Block((Body) () ->
          {
             if (getClosed().booleanValue())
             {
                undoThrow(SysError.newInstance("Cannot invoke method 'SkipBytes' after stream has been closed", 18196, false, false));
             }

             if (n.isUnknown())
             {
                undoThrow(SysError.newInstance("Invalid value specified for parameter 'length' of method or constructor 'SkipBytes'", 18193, false, true));
             }

             if (n.longValue() < 1)
             {
                returnNormal(0);
             }

             mdata.setLength(n);

             read(mdata);

             returnNormal(n);

          }, (Fini) () -> {
             mdata.setLength(0);
          }));
       }

       @LegacySignature(returns = "INT64", type = Type.METHOD, name = "Read", parameters =
       {
          @LegacyParameter(name = "target", type = "MEMPTR", mode = "INPUT"),
          @LegacyParameter(name = "offset", type = "INT64", mode = "INPUT"),
          @LegacyParameter(name = "length", type = "INT64", mode = "INPUT")
       })
       @Override
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public int64 read(final memptr _target, final int64 _offset, final int64 _length)
       {
          memptr target = TypeFactory.initInput(_target);
          int64 offset = TypeFactory.initInput(_offset);
          int64 length = TypeFactory.initInput(_length);
          memptr vmem = TypeFactory.memptr();

          return function(FileInputStream.class, this, "Read", int64.class, new Block((Body) () ->
          {
             if (getClosed().booleanValue())
             {
                undoThrow(SysError.newInstance("Cannot invoke method 'Read' after stream has been closed", 18196, false, false));
             }

             if (target.length().longValue() == 0)
             {
                undoThrow(SysError.newInstance("Invalid parameter: An initialized MEMPTR must be provided for the Read method or constructor", 19066, false, true));
             }

             if (offset.isUnknown() || offset.longValue() < 1 || offset.longValue() > target.length().longValue())
             {
                undoThrow(SysError.newInstance("Invalid value specified for parameter 'offset' of method or constructor 'Read'", 18193, false, true));
             }

             if (length.isUnknown() || length.longValue() < 0)
             {
                undoThrow(SysError.newInstance("Invalid value specified for parameter 'length' of method or constructor 'Read'", 18193, false, true));
             }

             _checkOpen();

             long toRead = bytesLeft;

             if (bytesLeft > 0)
             {
                toRead = Math.min(bytesLeft, Math.min(length.longValue(), target.length().longValue() + 1 - offset.longValue()));
             }

             // easy way out
             if (toRead > 0)
             {
                bytesLeft -= toRead;

                // read straight into the given memptr
                if (offset.longValue() == 1 && toRead == target.length().longValue())
                {
                   sFileStream.readBlock(target);
                }
                else
                {
                   vmem.setLength(toRead);
                   sFileStream.readBlock(vmem);
                   target.setBytes(vmem, offset);
                }

                sFileStream.resetCurrentLine();
             }

             returnNormal(toRead);
          }, (Fini) () -> {
             vmem.setLength(0);
          }));
       }

       @LegacySignature(returns = "INT64", type = Type.METHOD, name = "Read", parameters =
       {
          @LegacyParameter(name = "delimiter", type = "CHARACTER", mode = "INPUT"),
          @LegacyParameter(name = "target", type = "CHARACTER", mode = "OUTPUT")
       })
       @Override
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public int64 read(final character _delimiter, final character _target)
       {
          character target = TypeFactory.initOutput(_target);

          return function(FileInputStream.class, this, "Read", int64.class, new Block((Body) () ->
          {
             undoThrow(SysError.newInstance("Cannot invoke Read method in 'Progress.IO.FileInputStream' because it is not implemented", 18192, false, false));
          }));
       }

       @LegacySignature(returns = "INT64", type = Type.METHOD, name = "Read", parameters =
       {
          @LegacyParameter(name = "delimiter", type = "CHARACTER", mode = "INPUT"),
          @LegacyParameter(name = "target", type = "LONGCHAR", mode = "OUTPUT")
       })
       @Override
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public int64 read(final character _delimiter, final longchar _target)
       {
          longchar target = TypeFactory.initOutput(_target);

          return function(FileInputStream.class, this, "Read", int64.class, new Block((Body) () ->
          {
             undoThrow(SysError.newInstance("Cannot invoke Read method in 'Progress.IO.FileInputStream' because it is not implemented", 18192, false, false));
          }));
       }

       private void _checkOpen () {
          if (!sFileStream.isValid())
          {
             try
             {
                sFileStream.assign(StreamFactory.openFileStream((fileName).toStringMessage(), false, false));
                sFileStream.setBinary();
                sFileStream.setConvert(false);

                FileSystemOps.initFileInfo(fileName);
                fileSize = FileSystemOps.fileInfoGetSize().longValue();
                bytesLeft = fileSize;
             }
             catch (Exception e)
             {
                undoThrow(SysError.newInstance("Cannot find or open file %s, errno = 2", 11294, true, false));
             }
          }
       }
    }