# ServerConnectHelper.java

    /*
    ** Module   : ServerConnectHelper.java
    ** Abstract : Helper methods for parsing the options in a connect-like method.
    **
    ** Copyright (c) 2013-2024, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ---------------------------------Description----------------------------------
    ** 001 CA  20130908 Created initial version.
    ** 002 GES 20150204 Remove enclosing single quote characters in string values.
    ** 003 AIL 20210311 Fixed connection string parsing.
    **     EVL 20220815 Added more logging instead of return null that causing abend.
    **     EVL 20220816 Notes resolution for previous change.
    ** 004 GBB 20230512 Logging methods replaced by CentralLogger/ConversionStatus.
    ** 005 GBB 20240101 Fixes -pf param resolvement and config file parsing. ConnectHelper renamed to
    **                  ServerConnectHelper. removeEnclosingQuotes() and related test moved to ParamFileReader.
    */
    /*
    ** 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.util.logging.*;

    /**
     * This is a helper class to bring to central point the options which can be passed to a connect
     * like methods. The options are passed as a string to {@link #parseOptions}; using the list of
     * valid options, this will be able to identify no-value options (which act like flags) and also
     * options which must receive an int value.
     * <p>
     * The <code>-pf file</code> option can be used to read a set of options from a file, and override
     * any existing ones.
     */
    public class ServerConnectHelper
    {
       /** Logger */
       private static final CentralLogger LOG = CentralLogger.get(ServerConnectHelper.class);

       /**
        * Parse and validate the given options; a map is returned with each parameters's value. If a
        * parameter doesn't have a value, the map will contain <code>null</code>.
        *
        * @param    options
        *           The options from which the parameters will be extracted.
        * @param    knownOptions
        *           Set of valid options.
        * @param    noValueOptions
        *           Set of options which require no argument, i.e. "flags".
        * @param    intOptions
        *           Set of options which requre an int argument.
        *
        * @return   The parameter-to-value map.
        */
       public static Map<String, String> parseOptions(character            options,
                                                      Set<String>          knownOptions,
                                                      Set<String>          noValueOptions,
                                                      Map<String, Integer> intOptions)
       {
          Map<String, String> inlineParams = new HashMap<>();
          parseOptions(options.toStringMessage(), knownOptions, noValueOptions, intOptions, inlineParams);
          return inlineParams;
       }

       /**
        * Parse and validate the given options; a map is returned with each parameters's value. If a
        * parameter doesn't have a value, the map will contain <code>null</code>.
        *
        * @param    options
        *           The options from which the parameters will be extracted.
        * @param    knownOptions
        *           Set of valid options.
        * @param    noValueOptions
        *           Set of options which require no argument, i.e. "flags".
        * @param    intOptions
        *           Set of options which require an int argument.
        * @param    params
        *           The parameter-to-value map.
        */
       private static void parseOptions(String               options,
                                        Set<String>          knownOptions,
                                        Set<String>          noValueOptions,
                                        Map<String, Integer> intOptions,
                                        Map<String, String>  params)
       {
          String[] opts = options.split(" ");

          String arg = null;

          Set<String> resolvedParamFiles = new HashSet<>();

          boolean isPfParam = false;
          for (int i = 0; i < opts.length; i++)
          {
             String txt = opts[i];

             if (txt.length() == 0)
                continue;

             boolean err = false;

             // the 4GL allows enclosing single or double quotes that it silently ignores
             txt = ParamFileReader.removeEnclosingQuotes(txt);

             if (txt.startsWith("-"))
             {
                isPfParam = txt.equalsIgnoreCase("-pf");

                if (arg != null)
                {
                   // a value for this argument should have been parsed, but it wasn't
                   final String format = "You have not supplied a parameter for argument %s";
                   final String msg1 = String.format(format, arg);
                   final String msg2 = "Unable to process parameters";
                   ErrorManager.displayError(1403, msg1, false);
                   ErrorManager.displayError(5509, msg2, false);
                   arg = null;
                }

                if (!knownOptions.contains(txt))
                {
                   err = true;
                }
                else
                {
                   arg = txt;
                }

                // some options do not have a corresponding value
                if (noValueOptions.contains(arg))
                {
                   params.put(arg, null);
                   arg = null;
                }
             }
             else
             {
                if (arg != null)
                {
                   if (isPfParam)
                   {
                      String paramFilePath = txt;
                      if (resolvedParamFiles.contains(paramFilePath))
                      {
                         LOG.warning("Recursive use of the configuration file " + paramFilePath);
                         continue;
                      }
                      resolvedParamFiles.add(paramFilePath);

                      Map<String, String> pfParams = readPfFile(paramFilePath, knownOptions, noValueOptions, intOptions);
                      if (pfParams == null)
                      {
                         final String msg = "Unable to open parameter file %s, errno 2";
                         ErrorManager.recordOrShowError(1247, String.format(msg, paramFilePath), false);
                      }
                      else
                      {
                         params.putAll(pfParams);
                      }
                      continue;
                   }

                   if (intOptions.containsKey(arg))
                   {
                      // ensure that int values can be parsed
                      int value = 0;
                      try
                      {
                         value = Integer.parseInt(txt);
                      }
                      catch (NumberFormatException e)
                      {
                         // ignore
                      }
                      int def = intOptions.get(arg);
                      if (value <= def)
                      {
                         final String msg1 = "The %s parameter requires an argument greater than %d";
                         final String msg2 = "Unable to process parameters";
                         ErrorManager.displayError(1404, String.format(msg1, arg, def), false);
                         ErrorManager.displayError(5509, msg2, false);
                         arg = null;
                         continue;
                      }
                   }

                   params.put(arg, txt);
                }
                else
                {
                   err = true;
                }

                arg = null;
             }

             if (err)
             {
                ErrorManager.displayError(301, "Could not recognise argument: " + txt);
                ErrorManager.displayError(5509, "Unable to process parameters", false);
             }
          }

          if (arg != null)
          {
             // a value for this argument should have been parsed, but it wasn't
             ErrorManager.displayError(1403, "You have not supplied a parameter for argument " + arg, false);
             ErrorManager.displayError(5509, "Unable to process parameters", false);
          }
       }

       /**
        * Parse the value for the specified key as an int, or default to the specified value if the
        * key does not exist.
        *
        * @param    parms
        *           The options map.
        * @param    key
        *           The key to search.
        * @param    def
        *           The default value to return if the key does not exist.
        *
        * @return   See above.
        */
       public static int getInt(Map<String, String> parms, String key, int def)
       {
          String sval = parms.get(key);
          if (sval == null)
          {
             return def;
          }

          int val = 0;
          try
          {
             return Integer.parseInt(sval);
          }
          catch (NumberFormatException e)
          {
             val = 0;
          }

          return val;
       }

       /**
        * Get a string from the parameters map, using the specified key and defaulting to the
        * specified value, if it does not exist.
        *
        * @param    parms
        *           The options map.
        * @param    key
        *           The key to search.
        * @param    def
        *           The default value to return if the key does not exist.
        *
        * @return   See above.
        */
       public static String getString(Map<String, String> parms, String key, String def)
       {
          String val = parms.get(key);

          return val == null ? def : val;
       }

       /**
        * Read the parameters configured in the given file.
        *
        * @param    file
        *           The file containing the parameters.
        * @param    knownOptions
        *           Set of valid options.
        * @param    noValueOptions
        *           Set of options which require no argument, i.e. "flags".
        * @param    intOptions
        *           Set of options which requre an int argument.
        *
        * @return   A map containing the value for each parameter or <code>null</code> if there were
        *           problems reading the file.
        */
       private static Map<String, String> readPfFile(String file,
                                                     Set<String> knownOptions,
                                                     Set<String> noValueOptions,
                                                     Map<String, Integer> intOptions)
       {
          String pfContent = ParamFileReader.readPfFile(file);
          if (pfContent == null)
          {
             return null;
          }

          Map<String, String> params = new HashMap<>();

          if (pfContent.length() > 0)
          {
             parseOptions(pfContent, knownOptions, noValueOptions, intOptions, params);
          }

          return params;
       }
    }