# ChUIPrinterStreamSupport.java

    /*
    ** Module : ChUIPrinterStreamSupport.java
    ** Public : Printer streams implementation for different OS
    **
    ** Copyright (c) 2006-2024, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ----------------Description-----------------
    ** 001 VIG 20130923 Created initial version which provides
    **                  stream instantiation method and LINUX print
    **                  command line generation
    ** 002 HC  20171024 Renamed from PrinterStream to ChUIPrinterStreamSupport.
    ** 003 GBB 20240912 Accessing process Launcher via OSResourceManager.
    */
    /*
    ** 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.util;

    import java.util.*;

    import com.goldencode.p2j.directory.*;
    import com.goldencode.p2j.util.osresource.*;
    import com.goldencode.util.*;

    /**
     * Creates remote stream instances for OUTPUT TO PRINTER statements.
     * Implementation depends on OS
     *
     * @author    VIG
     */
    public class ChUIPrinterStreamSupport
    {
       /** Error msg, thrown when {@link OSResourceManager#getProcessLauncher()} is null when it used */
       private static final String  PROCESS_DMN_IS_NOT_INITED = "ProcessDaemon is not initialized";

       /** Args separated by space in the Unix command line */
       private static final String ARG_SEPARATOR = " ";

       /** Backslash - escaped symbol for Unix command line */
       private static final String BACKSLASH = "\\";

       /** Key for spooler command (Linux) intended for printer name */
       private static final String D_KEY = "-d";

       /** Param in Directory, corresponding to val of -o Progress start param */
       private static final String PRINTER_PARAM = "printerName";

       /**
        * The value of progress command line parameter -o for Linux,
        * which is default print command line string
        */
       private static final String defSpoolerCmd = "lp -s";

       /**
        * Constructs a remote stream instance representing the printer Stream
        * result of the OUTPUT TO PRINTER statement and registers it in
        * StreamDaemon.streams cache.
        * It can be assigned as unnamed output (OUTPUT TO PRINTER statement)
        * or as named stream (OUTPUT STREAM someStream TO PRINTER)
        *
        * @param  printer
        *         name of target printer
        * @param  sd
        *         Stream daemon for remote stream operations.
        *         Used to cache created printer stream
        *
        * @return The stream id which is used to route operations to the
        *         newly created instance.
        */
       public static int openPrinterStream(String printer, StreamDaemon sd)
       {
          int streamId = -1;

          /* TODO make more appropriate check for linux */
          boolean isWin = PlatformHelper.isUnderWindowsFamily();

          if (!isWin)
          {
             // Linux and Unix

             Launcher processLauncher = OSResourceManager.getProcessLauncher();
             if (processLauncher == null)
             {
                throw new IllegalStateException(PROCESS_DMN_IS_NOT_INITED);
             }

             streamId = sd.store(new ProcessStream());

             processLauncher.launch(generatePrinterCmd(printer), -1, streamId);
          }
          else
          {
             // windows
             streamId = sd.store(new NullStream());
          }

          return streamId;
       }

       /**
        * Generates the print command line for with specified printer name
        * suitable only for Linux or Unix
        *
        * @param  printer
        *         Name of printer, to generate the command line for
        *
        * @return The strings array of command (command string separated by ' ')
        */
       private static String[] generatePrinterCmd(String printer)
       {
          Directory dir = DirectoryManager.getInstance();

          // default value of -o progress4gl command line param from directory
          String cmdStr = dir.getString(Directory.ID_RELATIVE,
                                     PRINTER_PARAM,
                                     defSpoolerCmd);

          String[] cmd = cmdStr.split(ARG_SEPARATOR);

          // if printer name is specified - add it to command line
          if (printer != null && printer.trim().length() > 0)
          {
             // remove any back slashes from printerName (as Progress does)
             String resPrinter = printer.replace(BACKSLASH, "");
             cmd = Arrays.copyOf(cmd, cmd.length + 2);
             cmd[cmd.length - 2] = D_KEY;
             cmd[cmd.length - 1] = resPrinter;
          }

          return cmd;
       }
    }