Parse the command line.

@param args the CLI arguments given to the program.
@return the arguments that are not recognized as CLI options.
778924
@SuppressWarnings({"checkstyle:cyclomaticcomplexity", "checkstyle:npathcomplexity"})
	public static String[] parseCommandLine(String[] args) {
		final CommandLineParser parser = new DefaultParser();
		try {
			final CommandLine cmd = parser.parse(getOptions(), args, false);

			boolean noLogo = false;
			boolean embedded = false;
			boolean userClasspath = false;
			int verbose = LoggerCreator.toInt(JanusConfig.VERBOSE_LEVEL_VALUE);

			final Iterator<Option> optIterator = cmd.iterator();
			while (optIterator.hasNext()) {
				final Option opt = optIterator.next();
				String optName = opt.getLongOpt();
				if (Strings.isNullOrEmpty(optName)) {
					optName = opt.getOpt();
				}
				switch (optName) {
				case CLI_OPTION_HELP_LONG:
					showHelp(true);
					return null;
				case CLI_OPTION_VERSION:
					showVersion(true);
					return null;
				case CLI_OPTION_SHOWDEFAULTS_LONG:
					showDefaults();
					return null;
				case CLI_OPTION_SHOWCLASSPATH:
					setDefaultClasspath(userClasspath);
					showClasspath();
					return null;
				case CLI_OPTION_SHOWCLIARGUMENTS_LONG:
					showCommandLineArguments(args);
					return null;
				case CLI_OPTION_FILE_LONG:
					final String rawFilename = opt.getValue();
					if (rawFilename == null || "".equals(rawFilename)) { //$NON-NLS-1$
						showHelp(true);
					}
					final File file = new File(rawFilename);
					if (!file.canRead()) {
						showError(MessageFormat.format(Messages.Boot_0,
								rawFilename), null);
						return null;
					}
					setPropertiesFrom(file);
					break;
				case CLI_OPTION_CLASSPATH_LONG:
					userClasspath = true;
					addToSystemClasspath(opt.getValue());
					break;
				case CLI_OPTION_OFFLINE_LONG:
					setOffline(true);
					break;
				case CLI_OPTION_RANDOMID_LONG:
					setRandomContextUUID();
					break;
				case CLI_OPTION_BOOTID_LONG:
					setBootAgentTypeContextUUID();
					break;
				case CLI_OPTION_WORLDID_LONG:
					setDefaultContextUUID();
					break;
				case CLI_OPTION_DEFINE_LONG:
					final String name = opt.getValue(0);
					if (!Strings.isNullOrEmpty(name)) {
						setProperty(name, Strings.emptyToNull(opt.getValue(1)));
					}
					break;
				case CLI_OPTION_LOG_LONG:
					verbose = Math.max(LoggerCreator.toInt(opt.getValue()), 0);
					break;
				case CLI_OPTION_QUIET_LONG:
					if (verbose > 0) {
						--verbose;
					}
					break;
				case CLI_OPTION_VERBOSE_LONG:
					++verbose;
					break;
				case CLI_OPTION_NOLOGO_LONG:
					noLogo = true;
					break;
				case CLI_OPTION_EMBEDDED_LONG:
					embedded = true;
					break;
				default:
				}
			}

			setDefaultClasspath(userClasspath);

			// Show the help when there is no argument.
			if (cmd.getArgs().length == 0) {
				showHelp(true);
				return null;
			}

			// Change the verbosity
			setVerboseLevel(verbose);
			// Do nothing at exit
			if (embedded) {
				setExiter(() -> {
					ExecutorService.neverReturn();
				});
			}
			// Show the Janus logo?
			if (noLogo || verbose == 0) {
				setProperty(JanusConfig.JANUS_LOGO_SHOW_NAME, Boolean.FALSE.toString());
			}
			return cmd.getArgs();
		} catch (IOException | ParseException e) {
			showError(e.getLocalizedMessage(), e);
			// Event if showError never returns, add the return statement for
			// avoiding compilation error.
			return null;
		}
	}
1080257
public <A extends BaseArgument> ArgumentParser add(A arg) {
        if (arg instanceof BaseOption) {
            return add((BaseOption) arg);
        }

        // No arguments can be added after a sub-command-set.
        if (arguments.size() > 0 && arguments.get(arguments.size() - 1) instanceof SubCommandSet) {
            throw new IllegalArgumentException("No arguments can be added after a sub-command set");
        }

        arguments.add(arg);
        return this;
    }
691343
private static CommandLine parseCommandLine(final String[] vsArgs) {
        try {
            Group opts = configureCommandLine();
            // configure a HelpFormatter
            HelpFormatter hf = new HelpFormatter();

            // configure a parser
            Parser p = new Parser();
            p.setGroup(opts);
            p.setHelpFormatter(hf);
            // p.setHelpTrigger("--help");
            return p.parse(vsArgs);
        } catch (OptionException oe) {
            printUsage(oe);
        } catch (Exception e) {
            e.printStackTrace();
            // Should never happen...
        }
        return null;
    }
617983
def parse_args(self, arguments=None):
        
        self._args = self.parser.parse_args(arguments)
        return self.args
268815
public static void executeCommand(String[] args) throws IOException {

            OptionParser parser = getParser();

            // declare parameters
            String url = null;

            // parse command-line input
            OptionSet options = parser.parse(args);
            if(options.has(AdminParserUtils.OPT_HELP)) {
                printHelp(System.out);
                return;
            }

            // check required options and/or conflicting options
            AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);

            // load parameters
            url = (String) options.valueOf(AdminParserUtils.OPT_URL);

            // execute command
            AdminClient adminClient = AdminToolUtils.getAdminClient(url);

            doMetaCheckVersion(adminClient);
        }
531015
def parse_arguments():
    

    parser = argparse.ArgumentParser()

    # Add options
    parser.add_argument(
        "-n", "--number", action="store", default=1000000, type=int,
        help="number of items")
    parser.add_argument(
        "-p", "--pause", action="store_true", help="pause after execution")

    # Parse command line
    return parser.parse_args(), parser
1063766
@Override
	public String parse(String argument) throws CommandLineException {

		File file = new File(argument);

		try {
			Assert.isTrue(file.exists(), "File '" + file + "' does not exist");
			Assert.isFalse(file.isDirectory(), "File '" + file + "' is a directory");
			Assert.isTrue(file.canRead(), "File '" + file + "' cannot be read");
		}
		catch (IllegalArgumentException e) {
			throw new CommandLineException(e.getMessage());
		}

		return file.getAbsolutePath();
	}
292839
public String[] parse(String[] args) throws ArgException {

    List<String> nonOptions = new ArrayList<>();
    // If true, then "--" has been seen and any argument starting with "-"
    // is processed as an ordinary argument, not as an option.
    boolean ignoreOptions = false;

    // Loop through each argument
    String tail = "";
    String arg;
    for (int ii = 0; ii < args.length; ) {
      // If there was a ',' separator in previous arg, use the tail as
      // current arg; otherwise, fetch the next arg from args list.
      if (tail.length() > 0) {
        arg = tail;
        tail = "";
      } else {
        arg = args[ii];
      }

      if (arg.equals("--")) {
        ignoreOptions = true;
      } else if ((arg.startsWith("--") || arg.startsWith("-")) && !ignoreOptions) {
        String argName;
        String argValue;

        // Allow ',' as an argument separator to get around
        // some command line quoting problems.  (markro)
        int splitPos = arg.indexOf(",-");
        if (splitPos == 0) {
          // Just discard the ',' if ",-" occurs at begining of string
          arg = arg.substring(1);
          splitPos = arg.indexOf(",-");
        }
        if (splitPos > 0) {
          tail = arg.substring(splitPos + 1);
          arg = arg.substring(0, splitPos);
        }

        int eqPos = arg.indexOf('=');
        if (eqPos == -1) {
          argName = arg;
          argValue = null;
        } else {
          argName = arg.substring(0, eqPos);
          argValue = arg.substring(eqPos + 1);
        }
        OptionInfo oi = nameMap.get(argName);
        if (oi == null) {
          StringBuilder msg = new StringBuilder();
          msg.append(String.format("unknown option name '%s' in arg '%s'", argName, arg));
          if (false) { // for debugging
            msg.append("; known options:");
            for (String optionName : sortedKeySet(nameMap)) {
              msg.append(" ");
              msg.append(optionName);
            }
          }
          throw new ArgException(msg.toString());
        }
        if (oi.argumentRequired() && (argValue == null)) {
          ii++;
          if (ii >= args.length) {
            throw new ArgException("option %s requires an argument", arg);
          }
          argValue = args[ii];
        }
        // System.out.printf ("argName = '%s', argValue='%s'%n", argName,
        //                    argValue);
        setArg(oi, argName, argValue);
      } else { // not an option
        if (!parseAfterArg) {
          ignoreOptions = true;
        }
        nonOptions.add(arg);
      }

      // If no ',' tail, advance to next args option
      if (tail.length() == 0) {
        ii++;
      }
    }
    String[] result = nonOptions.toArray(new String[nonOptions.size()]);
    return result;
  }
789042
@SuppressWarnings("checkstyle:regexp")
	public static void showCommandLineArguments(String[] args) {
		try (PrintStream os = getConsoleLogger()) {
			for (int i = 0; i < args.length; ++i) {
				os.println(i + ": " //$NON-NLS-1$
						+ args[i]);
			}
			os.flush();
		} catch (Throwable e) {
			e.printStackTrace();
		}
		getExiter().exit();
	}
1191532
public static HashMap<String,String> parse(String args){
		
		HashMap<String,String> map = new HashMap<>();
		
		if (args != null){
			String[] split = args.split(";");
			for (String nameValuePair : split) {
				String[] nameValue = nameValuePair.split("=");
				if (nameValue.length == 2){
					map.put(nameValue[0].toLowerCase(), nameValue[1]);
				}
			}
		}
		
		return map;
	}
607166
public void setArgs(String[] args) {
        if (args == null) {
            args = new String[]{};
        }
        this.args = args;
        this.argsList = Collections.unmodifiableList(new ArrayList<String>(Arrays.asList(args)));
    }
196719
public void parse(String... args) {
        try {
            parse(true /* validate */, args);
        } catch(ParameterException ex) {
            ex.setJCommander(this);
            throw ex;
        }
    }
784158
public void command(String... args)
    {
        try
        {
            setArgs(args);
        }
        catch (CmdArgsException ex)
        {
            ex.printStackTrace();
            Logger logger = Logger.getLogger(CmdArgs.class.getName());
            logger.log(Level.SEVERE, Arrays.toString(args));
            logger.log(Level.SEVERE, ex.getMessage(), ex);
            logger.log(Level.SEVERE, ex.usage());
            System.exit(-1);
        }
    }
272529
public String[] parse(@NonNull String[] args) {
      List<String> filtered = new ArrayList<>();
      List<String> cleanedArgs = new ArrayList<>();

      //Pass through the args once to do a clean up will make the next round easier to parser.
      for (String c : args) {
         if (c.endsWith(KEY_VALUE_SEPARATOR) && isOptionName(c)) {
            //If it is ends with a key/value separator and is an option
            //lets separate them into two tokens.
            cleanedArgs.add(c.substring(0, c.length() - 1));
            cleanedArgs.add(KEY_VALUE_SEPARATOR);
         } else if (c.contains(KEY_VALUE_SEPARATOR) && isOptionName(c)) {
            //If it contains a key/value separator, but doesn't end in one and is an option
            //then we have a key value pair that will split into three tokens [key, =, value]
            int index = c.lastIndexOf(KEY_VALUE_SEPARATOR);
            cleanedArgs.add(c.substring(0, index));
            cleanedArgs.add(KEY_VALUE_SEPARATOR);
            cleanedArgs.add(c.substring(index + KEY_VALUE_SEPARATOR.length()));
         } else if (StringUtils.isNotNullOrBlank(c)) {
            //Anything else that isn't null or blank we keep as is
            cleanedArgs.add(c);
         }
      }

      for (int i = 0; i < cleanedArgs.size(); i++) {
         String current = cleanedArgs.get(i);

         //Check that the token isn't just a long or short argument marker.
         if (LONG.equals(current) || SHORT.equals(current)) {
            throw new CommandLineParserException(current, null);
         }

         if (current.startsWith(LONG)) {
            //We have a long form argument.
            String value = "true";
            String next = peek(cleanedArgs, i + 1);
            if (next.equalsIgnoreCase(KEY_VALUE_SEPARATOR)) {
               //If are peeked at value is our key value separator then lets set the value to what comes after.
               value = peek(cleanedArgs, i + 2);
               if (isOptionName(value)) {
                  //If the value is an option name, we have an error
                  throw new CommandLineParserException(current, null);
               }
               i += 2;
            } else if (!isOptionName(next)) {
               //If are peeked at value isn't our key value separator and isn't another option name, lets set the value to what comes after.
               i++;
               value = next;
            }
            setValue(current, value, filtered);
         } else if (current.startsWith(SHORT)) {
            //We have a short form argument.
            //Are we setting multiple "boolean" values?
            if (current.length() > 2) {
               //All of these will be set to true
               char[] opts = current.substring(1).toCharArray();
               for (char c : opts) {
                  setValue("-" + c, "true", filtered);
               }
            } else {
               String value = "true";
               String next = peek(cleanedArgs, i + 1);
               if (next.equalsIgnoreCase(KEY_VALUE_SEPARATOR)) {
                  //If are peeked at value is our key value separator then lets set the value to what comes after.
                  value = peek(cleanedArgs, i + 2);
                  if (isOptionName(value)) {
                     //If the value is an option name, we have an error
                     throw new CommandLineParserException(current, null);
                  }
                  i += 2;
               } else if (!isOptionName(next)) {
                  //If are peeked at value isn't our key value separator and isn't another option name, lets set the value to what comes after.
                  i++;
                  value = next;
               }
               setValue(current, value, filtered);
            }

         } else {
            filtered.add(current);
         }

      }

      //Check if the help was set, if a required argument was not set, and try to set the associated field on the owner object if one is set.
      optionSet.forEach(Unchecked.consumer(option -> {
         if (option.getName().equals("h") && Cast.<Boolean>as(option.getValue())) {
            showHelp();
            System.exit(0);
         } else if (option.isRequired() && !isSet(option.getName())) {
            System.err.println("ERROR: " + option.getName() + " is required, but was not set.");
            showHelp();
            System.exit(-1);
         }

         if (owner != null && option.getField() != null) {
            Reflect.onObject(owner).allowPrivilegedAccess().set(option.getField().getName(), option.getValue());
         }
      }));

      return filtered.toArray(new String[filtered.size()]);
   }
253452
public static void main(final String[] args) {
		EnvironmentInformation.logEnvironmentInfo(LOG, "Command Line Client", args);

		// 1. find the configuration directory
		final String configurationDirectory = getConfigurationDirectoryFromEnv();

		// 2. load the global configuration
		final Configuration configuration = GlobalConfiguration.loadConfiguration(configurationDirectory);

		// 3. load the custom command lines
		final List<CustomCommandLine<?>> customCommandLines = loadCustomCommandLines(
			configuration,
			configurationDirectory);

		try {
			final CliFrontend cli = new CliFrontend(
				configuration,
				customCommandLines);

			SecurityUtils.install(new SecurityConfiguration(cli.configuration));
			int retCode = SecurityUtils.getInstalledContext()
					.runSecured(() -> cli.parseParameters(args));
			System.exit(retCode);
		}
		catch (Throwable t) {
			final Throwable strippedThrowable = ExceptionUtils.stripException(t, UndeclaredThrowableException.class);
			LOG.error("Fatal error while running command line interface.", strippedThrowable);
			strippedThrowable.printStackTrace();
			System.exit(31);
		}
	}
945141
def _get_args_to_parse(args, sys_argv):
    
    arguments = args if args is not None else sys_argv[1:]
    _LOG.debug("Parsing arguments: %s", arguments)
    return arguments
618169
public static void main(final String[] args) {
        CommandLine cl = parseCommandLine(args);
        if (cl.hasOption("--help")) {
            if (!cl.hasOption("--conf")) {
                printUsage(null);
            }
        }

        if (cl.hasOption("--version")) {
            printVersion();
            System.exit(0);
        }

        JNRPEConfiguration conf = null;
        try {
            conf = loadConfiguration((String) cl.getValue("--conf"));
        } catch (Exception e) {
            System.out.println("Unable to parse the configuration at " + cl.getValue("--conf") + ". The error is : " + e.getMessage());
            e.printStackTrace();
            System.exit(-1);
        }

        String sPluginPath = conf.getServerSection().getPluginPath();
        if (sPluginPath == null) {
            System.out.println("Plugin path has not been specified");
            System.exit(-1);
        }
        File fPluginPath = new File(sPluginPath);

        if (fPluginPath.exists()) {
            if (!fPluginPath.isDirectory()) {
                System.out.println("Specified plugin path ('" + sPluginPath + "') must be a directory");
                System.exit(-1);
            }
        } else {
            System.out.println("Specified plugin path ('" + sPluginPath + "') do not exist");
            System.exit(-1);
        }

        IPluginRepository pr = null;
        try {
            pr = loadPluginDefinitions(conf.getServerSection().getPluginPath());
        } catch (PluginConfigurationException e) {
            System.out.println("An error has occurred while parsing " + "the plugin packages : " + e.getMessage());
            System.exit(-1);
        }

        if (cl.hasOption("--help") && cl.getValue("--help") != null) {
            printHelp(pr, (String) cl.getValue("--help"));
        }

        if (cl.hasOption("--list")) {
            printPluginList(pr);
        }

        CommandRepository cr = conf.createCommandRepository();

        JNRPEBuilder builder = JNRPEBuilder.forRepositories(pr, cr).acceptParams(conf.getServerSection().acceptParams())
                .withMaxAcceptedConnections(conf.getServerSection().getBacklogSize()).withReadTimeout(conf.getServerSection().getReadTimeout())
                .withWriteTimeout(conf.getServerSection().getWriteTimeout()).withListener(new EventLoggerListener());

        for (String sAcceptedAddress : conf.getServerSection().getAllowedAddresses()) {
            builder.acceptHost(sAcceptedAddress);
        }

        JNRPE jnrpe = builder.build();

        for (BindAddress bindAddress : conf.getServerSection().getBindAddresses()) {
            int iPort = DEFAULT_PORT;
            String[] vsParts = bindAddress.getBindingAddress().split(":");
            String sIp = vsParts[0];
            if (vsParts.length > 1) {
                iPort = Integer.parseInt(vsParts[1]);
            }

            try {
                jnrpe.listen(sIp, iPort, bindAddress.isSSL());
            } catch (UnknownHostException e) {
                System.out.println(String.format("Error binding the server to %s:%d : %s", sIp, iPort, e.getMessage()));
            }
        }

        if (cl.hasOption("--interactive")) {
            new JNRPEConsole(jnrpe, pr, cr).start();
            System.exit(0);
        }
    }