Parses a string of all the command line options converting them into an array of arguments to pass to #parse(String..args)

@param commandName The command name
@param args The string
@return The command line
516326
public CommandLine parseString(String commandName, String args) {
        // Steal ants implementation for argument splitting. Handles quoted arguments with " or '.
        // Doesn't handle escape sequences with \
        String[] argArray = translateCommandline(args);
        DefaultCommandLine cl = createCommandLine();
        cl.setCommandName(commandName);
        parseInternal(cl, argArray, false);
        return cl;
    }
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);
        }
    }
1047515
public void parseAndEmit(String[] args) {
    	logger.finest("Checking command line arguments.");
        if (args.length != 2) {
        	final String version = new Version().getVersion();
        	logger.info("jADT version " + version + ".");
        	logger.info("Not enough arguments provided to jADT");
        	logger.info("usage: java sfdc.adt.JADT [source file or directory with .jadt files] [output directory]");
            throw new IllegalArgumentException("\njADT version " + version + "\nusage: java sfdc.adt.JADT [source file or directory with .jadt files] [output directory]");
        }
        
        final String srcPath = args[0];
        final String destDirName = args[1];

        parseAndEmit(srcPath, destDirName);        
    }
1241530
public CommandLine parse(String[] args) throws ParseException {
        // create the command line parser
        GnuParser parser = new GnuParser();
        Options buildCommandLineOptions = buildCommandLineOptions();
        CommandLine cmd = null;
        try {
            cmd = parser.parse(buildCommandLineOptions, args);
            if (cmd.getOptions().length == 0 || cmd.hasOption("h")) {
                printHelp(buildCommandLineOptions);
                return null;
            }
            if (cmd.getArgList().isEmpty()) {
                throw new MissingOptionException("The 'inputPage' is mandatory! No page to run given");
            }
            return cmd;
        } catch (MissingOptionException e) {
            if (args == null || args.length == 0) {
                logger.debug("option --help has been set. Ignoring Missing Option exception");
                printHelp(buildCommandLineOptions);
                return cmd;
            }
            for (String arg : args) {
                if (StringUtils.equals("-h", arg) || StringUtils.equals("--help", arg)) {
                    logger.debug("option --help has been set. Ignoring Missing Option exception");
                    printHelp(buildCommandLineOptions);
                    return null;
                }
            }
            handleParseException(buildCommandLineOptions, e);
            throw e;
        } catch (ParseException e) {
            handleParseException(buildCommandLineOptions, e);
            throw e;
        }
    }
664686
public int parseParameters(String[] args) {

		// check for action
		if (args.length < 1) {
			CliFrontendParser.printHelp(customCommandLines);
			System.out.println("Please specify an action.");
			return 1;
		}

		// get action
		String action = args[0];

		// remove action from parameters
		final String[] params = Arrays.copyOfRange(args, 1, args.length);

		try {
			// do action
			switch (action) {
				case ACTION_RUN:
					run(params);
					return 0;
				case ACTION_LIST:
					list(params);
					return 0;
				case ACTION_INFO:
					info(params);
					return 0;
				case ACTION_CANCEL:
					cancel(params);
					return 0;
				case ACTION_STOP:
					stop(params);
					return 0;
				case ACTION_SAVEPOINT:
					savepoint(params);
					return 0;
				case "-h":
				case "--help":
					CliFrontendParser.printHelp(customCommandLines);
					return 0;
				case "-v":
				case "--version":
					String version = EnvironmentInformation.getVersion();
					String commitID = EnvironmentInformation.getRevisionInformation().commitId;
					System.out.print("Version: " + version);
					System.out.println(commitID.equals(EnvironmentInformation.UNKNOWN) ? "" : ", Commit ID: " + commitID);
					return 0;
				default:
					System.out.printf("\"%s\" is not a valid action.\n", action);
					System.out.println();
					System.out.println("Valid actions are \"run\", \"list\", \"info\", \"savepoint\", \"stop\", or \"cancel\".");
					System.out.println();
					System.out.println("Specify the version option (-v or --version) to print Flink version.");
					System.out.println();
					System.out.println("Specify the help option (-h or --help) to get help on the command.");
					return 1;
			}
		} catch (CliArgsException ce) {
			return handleArgException(ce);
		} catch (ProgramParametrizationException ppe) {
			return handleParametrizationException(ppe);
		} catch (ProgramMissingJobException pmje) {
			return handleMissingJobException();
		} catch (Exception e) {
			return handleError(e);
		}
	}
1228645
@SuppressWarnings("unchecked")
        public static void executeCommand(String[] args) throws IOException {

            OptionParser parser = getParser();

            // declare parameters
            List<String> metaKeys = null;
            String url = null;
            List<Integer> nodeIds = null;
            Boolean allNodes = true;
            List<String> storeNames = null;

            // parse command-line input
            args = AdminToolUtils.copyArrayAddFirst(args, "--" + OPT_HEAD_META_GET_RO);
            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, OPT_HEAD_META_GET_RO);
            AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);
            AdminParserUtils.checkOptional(options,
                                           AdminParserUtils.OPT_NODE,
                                           AdminParserUtils.OPT_ALL_NODES);
            AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_STORE);

            // load parameters
            metaKeys = (List<String>) options.valuesOf(OPT_HEAD_META_GET_RO);
            url = (String) options.valueOf(AdminParserUtils.OPT_URL);
            if(options.has(AdminParserUtils.OPT_NODE)) {
                nodeIds = (List<Integer>) options.valuesOf(AdminParserUtils.OPT_NODE);
                allNodes = false;
            }
            storeNames = (List<String>) options.valuesOf(AdminParserUtils.OPT_STORE);

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

            if(allNodes) {
                nodeIds = AdminToolUtils.getAllNodeIds(adminClient);
            }

            if(metaKeys.size() == 1 && metaKeys.get(0).equals(METAKEY_ALL)) {
                metaKeys = Lists.newArrayList();
                metaKeys.add(KEY_MAX_VERSION);
                metaKeys.add(KEY_CURRENT_VERSION);
                metaKeys.add(KEY_STORAGE_FORMAT);
            }

            doMetaGetRO(adminClient, nodeIds, storeNames, metaKeys);
        }
390030
public static void main(String[] args) {
        try {
            ParsedCommandLine pcl = new ParsedCommandLine(args);
            Callable<String> command = pcl.getCommand();
            if (command == null) {
                System.out.println(pcl.getHelpText());
            } else {
                System.out.println(command.call());
            }
        } catch (Exception ex) {
            System.err.println("ERROR: " + ex.getMessage());
        }
    }
1139484
static void processArgs(String[] args, final PrintStream out) {
        Options options = buildOptions();

        try {
            CommandLine cmd = parseCommandLine(options, args);

            if (cmd.hasOption('h')) {
                printHelp(out, options);
            } else if (cmd.hasOption('v')) {
                String version = GroovySystem.getVersion();
                out.println("Groovy Version: " + version + " JVM: " + System.getProperty("java.version") + 
                        " Vendor: " + System.getProperty("java.vm.vendor")  + " OS: " + System.getProperty("os.name"));
            } else {
                // If we fail, then exit with an error so scripting frameworks can catch it
                // TODO: pass printstream(s) down through process
                if (!process(cmd)) {
                    System.exit(1);
                }
            }
        } catch (ParseException pe) {
            out.println("error: " + pe.getMessage());
            printHelp(out, options);
        } catch (IOException ioe) {
            out.println("error: " + ioe.getMessage());
        }
    }
1229230
public static CommandLine processCommandLineArgs(Option[] customOptions, String[] args) {
    Options options = new Options();

    options.addOption("h", "help", false, "Print this message");
    options.addOption("v", "verbose", false, "Generate verbose log messages");

    if (customOptions != null) {
      for (int i = 0; i < customOptions.length; i++)
        options.addOption(customOptions[i]);
    }

    CommandLine cli = null;
    try {
      cli = (new GnuParser()).parse(options, args);
    } catch (ParseException exp) {
      boolean hasHelpArg = false;
      if (args != null && args.length > 0) {
        for (int z = 0; z < args.length; z++) {
          if ("-h".equals(args[z]) || "-help".equals(args[z])) {
            hasHelpArg = true;
            break;
          }
        }
      }
      if (!hasHelpArg) {
        System.err.println("Failed to parse command-line arguments due to: " + exp.getMessage());
      }
      HelpFormatter formatter = new HelpFormatter();
      formatter.printHelp(SparkApp.class.getName(), options);
      System.exit(1);
    }

    if (cli.hasOption("help")) {
      HelpFormatter formatter = new HelpFormatter();
      formatter.printHelp(SparkApp.class.getName(), options);
      System.exit(0);
    }

    return cli;
  }
50667
private void parseCommandLineArgs(String[] args) throws ConfigurationException {
        if (args == null || args.length == 0) {
            return;
        }
        logger.info("Parsing command line arguments");
        m_commandLineArgs = args;
        
        try {
            for (int inx = 0; inx < args.length; inx++) {
                String arg = args[inx];
                if (arg.equals("-?") || arg.equalsIgnoreCase("-h") || arg.equalsIgnoreCase("-help")) {
                    System.out.println("See documentation and doradus.yaml for help.");
                    System.exit(0);
                }
                Utils.require(arg.charAt(0) == '-', "Unrecognized argument: %s", arg);
                Utils.require(inx + 1 < args.length, "A value is expected after: %s", arg);
                String name = arg.substring(1);
                String value = args[++inx];
                setCommandLineParam(name, value);
            }
        } catch (Exception e) {
            logger.error("Failed to parse command line arguments", e);
            throw new ConfigurationException("Failed to parse command line arguments", e);
        }
    }
335599
function parseCommandLine(args) {

    var parsed_cmds = [];

    if (args.length <= 2) {
        parsed_cmds.push(defaultCommand());
    } else {

        var cli = args.slice(2);

        var pos = 0;
        var cmd;

        cli.forEach(function(element, index, array) {

            //replace alias name with real name.
            if (element.indexOf('--') === -1 && element.indexOf('-') === 0) {
                cli[index] = alias_map[element];
            }

            //parse command and args
            if (cli[index].indexOf('--') === -1) {
                cmd.args.push(cli[index]);
            } else {

                if (keys[cli[index]] == "undefined") {
                    throw new Error("not support command:" + cli[index]);
                };

                pos = index;
                cmd = commands[cli[index]];
                if (typeof cmd.args == 'undefined') {
                    cmd.args = [];
                };
                parsed_cmds.push(cmd);
            }
        });
    };

    return parsed_cmds;
}
519291
function parseCommandLine() {
	var commands = process.argv.slice(2);
	var args = {};

	for (var i = 0; i < commands.length; i++) {
		var match = commands[i].match(/^--(.+)=(.+)$/);
		if (match)
			args[match[1]] = match[2];
		else if (i < commands.length - 1 && commands[i].substr(0, 1) === "-") {
			args[commands[i].substr(1)] = commands[i + 1];
			i++;
		}
		else if (i === 0) args[commandKey] = commands[i];
		else if (i === 1) args[commandHost] = commands[i];
	}

	return args;
}
526491
@SuppressWarnings("unchecked")
    public List<String> getOptionValues(final String optionName) {
        if (optionName.length() == 1) {
            return getOptionValues(optionName.charAt(0));
        }

        return commandLine.getValues("--" + optionName);
    }
271468
function ParseArguments(cmd, args) {
  assert(_.isObject(cmd), 'require an object argument for "cmd".');
  assert(_.isObject(args), 'require an object argument for "args".');
  const argSpec = cmd.argSpec || [];
  const cmdName = cmd.name;

  //
  // Build a map of all flag aliases.
  //
  const allAliases = _.fromPairs(_.map(_.flatten(_.map(argSpec, 'flags')), (flagAlias) => {
    return [flagAlias, true];
  }));

  //
  // Make sure all provided flags are specified in the argSpec.
  //
  _.forEach(args, (argVal, argKey) => {
    if (argKey === '_') return; // ignore positional arguments
    if (!(argKey in allAliases)) {
      const d = argKey.length === 1 ? '-' : '--';
      throw new Error(
        `Unknown command-line option "${col.bold(d + argKey)}" specified ` +
        `for command "${col.bold(cmdName)}".`);
    }
  });

  //
  // Handle boolean flags specified as string values on the command line.
  //
  args = _.mapValues(args, (flagVal) => {
    if (_.isString(flagVal)) {
      if (flagVal === 'true') {
        return true;
      }
      if (flagVal === 'false') {
        return false;
      }
    }
    return flagVal;
  });

  //
  // For each flag in the argSpec, see if any alias of the flag is
  // present in `args`. If it is, then assign that value to *all*
  // aliases of the flag. If it is not present, then assign the
  // default value. Throw on unspecified required flags.
  //
  const finalFlags = {};
  _.forEach(argSpec, (aspec, idx) => {
    // Find the first alias of this flag that is specified in args, if at all.
    const foundAlias = _.find(aspec.flags, (flagAlias) => {
      return flagAlias && (flagAlias in args);
    });
    let assignValue = foundAlias ? args[foundAlias] : (aspec.defVal || aspec.default);

    // If defVal is an object, then we need to execute a function to get the
    // default value.
    if (_.isObject(assignValue)) {
      assert(
        _.isFunction(assignValue.fn),
        `Argspec entry ${idx} has an invalid 'defVal'/'default' property.`);
      assignValue = assignValue.fn.call(argSpec);
    }

    if (!_.isUndefined(assignValue)) {
      // Assign value to all aliases of flag.
      _.forEach(aspec.flags, (flagAlias) => {
        finalFlags[flagAlias] = assignValue;
      });
    }
  });

  // Copy positional arguments to finalFlags.
  finalFlags._ = args._;

  return finalFlags;
}
388315
private static boolean parseInputArgs(String[] args) {
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;
    try {
      cmd = parser.parse(OPTIONS, args);
    } catch (ParseException e) {
      System.out.println("Failed to parse input args: " + e);
      return false;
    }
    sHelp = cmd.hasOption("help");
    sType = OperationType.valueOf(cmd.getOptionValue("type", "READ"));
    sFileSize = FormatUtils.parseSpaceSize(cmd.getOptionValue("fileSize", "1KB"));
    sIterations = Integer.parseInt(cmd.getOptionValue("iterations", "1"));
    sConcurrency = Integer.parseInt(cmd.getOptionValue("concurrency", "1"));

    return true;
  }
45694
void parseArgs(String[] args) {
    int i = 0;
    while (true) {
      if (i >= args.length) {
        break;
      }

      String s = args[i];
      if (s.equals("-h") ||
              s.equals("help") ||
              s.equals("-help") ||
              s.equals("--help")) {
        usage();
      }
      else if (s.equals("-n") ||
              s.equals("-nodes")) {
        i++; if (i >= args.length) { usage(); }
        numNodes = Integer.parseInt(args[i]);
      }
      else if (s.equals("-o") ||
              s.equals("-output")) {
        i++; if (i >= args.length) { usage(); }
        outputPath = args[i];
      }
      else if (s.equals("-jobname")) {
        i++; if (i >= args.length) { usage(); }
        jobtrackerName = args[i];
      }
      else if (s.equals("-mapperXmx")) {
        i++; if (i >= args.length) { usage(); }
        mapperXmx = args[i];
      }
      else if (s.equals("-extramempercent")) {
        i++; if (i >= args.length) { usage(); }
        extraMemPercent = Integer.parseInt(args[i]);
      }
      else if (s.equals("-driverif")) {
        i++; if (i >= args.length) { usage(); }
        driverCallbackIp = args[i];
      }
      else if (s.equals("-driverport")) {
        i++; if (i >= args.length) { usage(); }
        driverCallbackPort = Integer.parseInt(args[i]);
      }
      else if (s.equals("-network")) {
        i++; if (i >= args.length) { usage(); }
        network = args[i];
      }
      else if (s.equals("-timeout")) {
        i++; if (i >= args.length) { usage(); }
        cloudFormationTimeoutSeconds = Integer.parseInt(args[i]);
      }
      else if (s.equals("-disown")) {
        disown = true;
      }
      else if (s.equals("-notify")) {
        i++; if (i >= args.length) { usage(); }
        clusterReadyFileName = args[i];
      }
      else if (s.equals("-nthreads")) {
        i++; if (i >= args.length) { usage(); }
        nthreads = Integer.parseInt(args[i]);
      }
      else if (s.equals("-many_cols")) {
        manyCols = true;
      }
      else if (s.equals("-chunk_bytes")) {
        i++; if (i >= args.length) { usage(); }
        chunk_bytes = Integer.parseInt(args[i]);
      }
      else if (s.equals("-data_max_factor_levels")) {
        i++; if (i >= args.length) { usage(); }
        data_max_factor_levels = Integer.parseInt(args[i]);
      }
      else if (s.equals("-baseport")) {
        i++; if (i >= args.length) { usage(); }
        basePort = Integer.parseInt(args[i]);
        if ((basePort < 0) || (basePort > 65535)) {
            error("Base port must be between 1 and 65535");
        }
      }
      else if (s.equals("-beta")) {
        beta = true;
      }
      else if (s.equals("-random_udp_drop")) {
        enableRandomUdpDrop = true;
      }
      else if (s.equals("-ea")) {
        enableExceptions = true;
      }
      else if (s.equals("-verbose:gc")) {
        enableVerboseGC = true;
      }
      else if (s.equals("-verbose:class")) {
        enableVerboseClass = true;
      }
      else if (s.equals("-XX:+PrintCompilation")) {
        enablePrintCompilation = true;
      }
      else if (s.equals("-exclude")) {
        enableExcludeMethods = true;
      }
      else if (s.equals("-Dlog4j.defaultInitOverride=true")) {
        enableLog4jDefaultInitOverride = true;
      }
      else if (s.equals("-debug")) {
        enableDebug = true;
      }
      else if (s.equals("-suspend")) {
        enableSuspend = true;
      }
      else if (s.equals("-debugport")) {
        i++; if (i >= args.length) { usage(); }
        debugPort = Integer.parseInt(args[i]);
        if ((debugPort < 0) || (debugPort > 65535)) {
          error("Debug port must be between 1 and 65535");
        }
      }
      else if (s.equals("-XX:+PrintGCDetails")) {
        enablePrintGCDetails = true;
      }
      else if (s.equals("-XX:+PrintGCTimeStamps")) {
        enablePrintGCTimeStamps = true;
      }
      else if (s.equals("-gc")) {
        enableVerboseGC = true;
        enablePrintGCDetails = true;
        enablePrintGCTimeStamps = true;
      }
      else if (s.equals("-license")) {
        i++; if (i >= args.length) { usage(); }
        licenseFileName = args[i];
      }
      else if (s.equals("-extraJavaOpts")) {
        i++; if (i >= args.length) { usage(); }
        extraJavaOpts = args[i];
      }
      else {
        error("Unrecognized option " + s);
      }

      i++;
    }

    // Check for mandatory arguments.
    if (numNodes < 1) {
      error("Number of H2O nodes must be greater than 0 (must specify -n)");
    }
    if (outputPath == null) {
      error("Missing required option -output");
    }
    if (mapperXmx == null) {
      error("Missing required option -mapperXmx");
    }

    // Check for sane arguments.
    if (! mapperXmx.matches("[1-9][0-9]*[mgMG]")) {
      error("-mapperXmx invalid (try something like -mapperXmx 4g)");
    }

    if (extraMemPercent < 0) {
      extraMemPercent = DEFAULT_EXTRA_MEM_PERCENT;
    }

    if (jobtrackerName == null) {
      Random rng = new Random();
      int num = rng.nextInt(99999);
      jobtrackerName = "H2O_" + num;
    }

    if (network == null) {
      network = "";
    }
    else {
      String[] networks;
      if (network.contains(",")) {
        networks = network.split(",");
      }
      else {
        networks = new String[1];
        networks[0] = network;
      }

      for (int j = 0; j < networks.length; j++) {
        String n = networks[j];
        Pattern p = Pattern.compile("(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)/(\\d+)");
        Matcher m = p.matcher(n);
        boolean b = m.matches();
        if (! b) {
          error("network invalid: " + n);
        }

        for (int k = 1; k <=4; k++) {
          int o = Integer.parseInt(m.group(k));
          if ((o < 0) || (o > 255)) {
            error("network invalid: " + n);
          }

          int bits = Integer.parseInt(m.group(5));
          if ((bits < 0) || (bits > 32)) {
            error("network invalid: " + n);
          }
        }
      }
    }

    if (network == null) {
      error("Internal error, network should not be null at this point");
    }

    if ((nthreads >= 0) && (nthreads < 4)) {
      error("nthreads invalid (must be >= 4): " + nthreads);
    }

    if (licenseFileName != null) {
      try {
        licenseData = readFile(licenseFileName);
      }
      catch (Exception xe) {
        StringBuilder sb = new StringBuilder();
        sb.append("Failed to read license file: ");
        if (xe.getLocalizedMessage() != null) {
          sb.append(xe.getLocalizedMessage());
        }
        else {
          sb.append(licenseFileName);
        }

        error(sb.toString());
      }
    }
  }
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;
    }