Java Code Examples for org.apache.commons.cli.CommandLine#getOptions()

The following examples show how to use org.apache.commons.cli.CommandLine#getOptions() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: KeywordOptimizer.java    From keyword-optimizer with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the only specified 'seed' option or an exception if no or more than one is specified.
 *
 * @param cmdLine the parsed command line parameters
 * @return the 'seed' {@link Option}
 * @throws KeywordOptimizerException in case there is no or more than one 'seed' parameter
 *         specified
 */
private static Option getOnlySeedOption(CommandLine cmdLine) throws KeywordOptimizerException {
  Option seedOption = null;

  for (Option option : cmdLine.getOptions()) {
    if (option.getOpt().startsWith("s")) {
      if (seedOption != null) {
        throw new KeywordOptimizerException("Only one 'seed' option is allowed "
            + "(remove either " + seedOption.getOpt() + " or " + option.getOpt() + ")");
      }

      seedOption = option;
    }
  }

  if (seedOption == null) {
    throw new KeywordOptimizerException("You must specify a 'seed' parameter");
  }

  return seedOption;
}
 
Example 2
Source File: SolrCLI.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public int runTool(CommandLine cli) throws Exception {
  raiseLogLevelUnlessVerbose(cli);
  if (cli.getOptions().length == 0 || cli.getArgs().length == 0 || cli.getArgs().length > 1 || cli.hasOption("h")) {
    new HelpFormatter().printHelp("bin/solr auth <enable|disable> [OPTIONS]", getToolOptions(this));
    return 1;
  }

  ensureArgumentIsValidBooleanIfPresent(cli, "blockUnknown");
  ensureArgumentIsValidBooleanIfPresent(cli, "updateIncludeFileOnly");

  String type = cli.getOptionValue("type", "basicAuth");
  switch (type) {
    case "basicAuth":
      return handleBasicAuth(cli);
    case "kerberos":
      return handleKerberos(cli);
    default:
      CLIO.out("Only type=basicAuth or kerberos supported at the moment.");
      exit(1);
  }
  return 1;
}
 
Example 3
Source File: ServerUtil.java    From rocketmq-all-4.1.0-incubating with Apache License 2.0 6 votes vote down vote up
public static Properties commandLine2Properties(final CommandLine commandLine) {
    Properties properties = new Properties();
    Option[] opts = commandLine.getOptions();

    if (opts != null) {
        for (Option opt : opts) {
            String name = opt.getLongOpt();
            String value = commandLine.getOptionValue(name);
            if (value != null) {
                properties.setProperty(name, value);
            }
        }
    }

    return properties;
}
 
Example 4
Source File: ServerUtil.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
public static Properties commandLine2Properties(final CommandLine commandLine) {
    Properties properties = new Properties();
    Option[] opts = commandLine.getOptions();

    if (opts != null) {
        for (Option opt : opts) {
            String name = opt.getLongOpt();
            String value = commandLine.getOptionValue(name);
            if (value != null) {
                properties.setProperty(name, value);
            }
        }
    }

    return properties;
}
 
Example 5
Source File: PublicMethodsCliObjectFactory.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * For each method for which the helper created an {@link Option} and for which the input {@link CommandLine} contains
 * that option, this method will automatically call the method on the input object with the correct
 * arguments.
 */
public void applyCommandLineOptions(CommandLine cli, T embeddedGobblin) {
  try {
    for (Option option : cli.getOptions()) {
      if (!this.methodsMap.containsKey(option.getOpt())) {
        // Option added by cli driver itself.
        continue;
      }
      if (option.hasArg()) {
        this.methodsMap.get(option.getOpt()).invoke(embeddedGobblin, option.getValue());
      } else {
        this.methodsMap.get(option.getOpt()).invoke(embeddedGobblin);
      }
    }
  } catch (IllegalAccessException | InvocationTargetException exc) {
    throw new RuntimeException("Could not apply options to " + embeddedGobblin.getClass().getName(), exc);
  }
}
 
Example 6
Source File: ConstructorAndPublicMethodsCliObjectFactory.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Builds an instance of T using the selected constructor getting the constructor
 * parameters from the {@link CommandLine}.
 *
 * Note: this method will also automatically call {@link #applyCommandLineOptions(CommandLine, T)} on
 * the constructed object.
 */
private T buildInstance(CommandLine cli) {
  String[] constructorArgs = new String[this.constructor.getParameterTypes().length];
  for (Option option : cli.getOptions()) {
    if (this.constructoArgumentsMap.containsKey(option.getOpt())) {
      int idx = this.constructoArgumentsMap.get(option.getOpt());
      constructorArgs[idx] = option.getValue();
    }
  }

  T embeddedGobblin;
  try {
    embeddedGobblin = this.constructor.newInstance((Object[]) constructorArgs);
    return embeddedGobblin;
  } catch (IllegalAccessException | InvocationTargetException | InstantiationException exc) {
    throw new RuntimeException("Could not instantiate " + this.klazz.getName(), exc);
  }
}
 
Example 7
Source File: ServerUtil.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
public static Properties commandLine2Properties(final CommandLine commandLine) {
    Properties properties = new Properties();
    Option[] opts = commandLine.getOptions();

    if (opts != null) {
        for (Option opt : opts) {
            String name = opt.getLongOpt();
            String value = commandLine.getOptionValue(name);
            if (value != null) {
                properties.setProperty(name, value);
            }
        }
    }

    return properties;
}
 
Example 8
Source File: JobSetupUtil.java    From datawave with Apache License 2.0 5 votes vote down vote up
public static Configuration configure(String[] args, Configuration conf, Logger log) throws ParseException {
    log.info("Searching for metrics.xml on classpath.");
    URL cpConfig = Thread.currentThread().getContextClassLoader().getResource("metrics.xml");
    if (cpConfig == null) {
        log.error("No configuration file specified nor runtime args supplied- exiting.");
        System.exit(1);
    } else {
        log.info("Using conf file located at " + cpConfig);
        conf.addResource(cpConfig);
    }
    
    MetricsOptions mOpts = new MetricsOptions();
    CommandLine cl = new GnuParser().parse(mOpts, args);
    // add the file config options first
    String confFiles = cl.getOptionValue("conf", "");
    if (confFiles != null && !confFiles.isEmpty()) {
        for (String confFile : confFiles.split(",")) {
            
            if (!confFile.isEmpty()) {
                log.trace("Adding " + confFile + " to configurations resource base.");
                conf.addResource(confFile);
            }
        }
    }
    
    // now get the runtime overrides
    for (Option opt : cl.getOptions()) {
        // Ensure we don't try to set a null value (option-only) because this will
        // cause an NPE out of Configuration/Hashtable
        conf.set(MetricsConfig.MTX + opt.getOpt(), null == opt.getValue() ? "" : opt.getValue());
    }
    return conf;
}
 
Example 9
Source File: PythonProgramOptions.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
protected String[] extractProgramArgs(CommandLine line) {
	String[] args;
	if (isPythonEntryPoint(line)) {
		String[] rawArgs = line.hasOption(ARGS_OPTION.getOpt()) ?
			line.getOptionValues(ARGS_OPTION.getOpt()) :
			line.getArgs();
		// copy python related parameters to program args and place them in front of user parameters
		List<String> pyArgList = new ArrayList<>();
		Set<Option> pyOptions = new HashSet<>();
		pyOptions.add(PY_OPTION);
		pyOptions.add(PYMODULE_OPTION);
		for (Option option : line.getOptions()) {
			if (pyOptions.contains(option)) {
				pyArgList.add("--" + option.getLongOpt());
				pyArgList.add(option.getValue());
			}
		}
		String[] newArgs = pyArgList.toArray(new String[rawArgs.length + pyArgList.size()]);
		System.arraycopy(rawArgs, 0, newArgs, pyArgList.size(), rawArgs.length);
		args = newArgs;
	} else {
		args = super.extractProgramArgs(line);
	}

	return args;
}
 
Example 10
Source File: CLIParserBenchmarker.java    From metanome-algorithms with Apache License 2.0 5 votes vote down vote up
public THashMap<String, String> parse(String[] input) {
	THashMap<String, String> result = new THashMap<>();
	try {
		CommandLine cmdLine = this.parse(this.getOptions(), input);
		for (Option option : cmdLine.getOptions()) {
			result.put(option.getOpt(), option.getValue());
		}
	} catch (ParseException e) {
		e.printStackTrace();
	}
	return result;
}
 
Example 11
Source File: SolrCLI.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public int runTool(CommandLine cli) throws Exception {
  if (cli.getOptions().length == 0 || cli.getArgs().length > 0 || cli.hasOption("h")) {
    new HelpFormatter().printHelp("bin/solr utils [OPTIONS]", getToolOptions(this));
    return 1;
  }
  if (cli.hasOption("s")) {
    serverPath = Paths.get(cli.getOptionValue("s"));
  }
  if (cli.hasOption("l")) {
    logsPath = Paths.get(cli.getOptionValue("l"));
  }
  if (cli.hasOption("q")) {
    beQuiet = cli.hasOption("q");
  }
  if (cli.hasOption("remove_old_solr_logs")) {
    if (removeOldSolrLogs(Integer.parseInt(cli.getOptionValue("remove_old_solr_logs"))) > 0) return 1;
  }
  if (cli.hasOption("rotate_solr_logs")) {
    if (rotateSolrLogs(Integer.parseInt(cli.getOptionValue("rotate_solr_logs"))) > 0) return 1;
  }
  if (cli.hasOption("archive_gc_logs")) {
    if (archiveGcLogs() > 0) return 1;
  }
  if (cli.hasOption("archive_console_logs")) {
    if (archiveConsoleLogs() > 0) return 1;
  }
  return 0;
}
 
Example 12
Source File: ClientProto.java    From submarine with Apache License 2.0 5 votes vote down vote up
public static CommandLineProto convertCommandLineToCommandLineProto(
    CommandLine parsedCommandLine) {
  List<OptionProto> optionProtos = new ArrayList<>();

  for (Option option : parsedCommandLine.getOptions()) {
    OptionProto optionProto = OptionProto.newBuilder()
        .setOpt(option.getOpt())
        .addAllValues(option.getValuesList()).build();
    optionProtos.add(optionProto);
  }

  CommandLineProto commandLineProto =
      CommandLineProto.newBuilder().addAllOptions(optionProtos).build();
  return commandLineProto;
}
 
Example 13
Source File: OptimizerOptions.java    From incubator-hivemall with Apache License 2.0 5 votes vote down vote up
public static void processOptions(@Nullable CommandLine cl,
        @Nonnull Map<String, String> options) {
    if (cl == null) {
        return;
    }
    for (Option opt : cl.getOptions()) {
        String optName = opt.getLongOpt();
        if (optName == null) {
            optName = opt.getOpt();
        }
        options.put(optName, opt.getValue());
    }
}
 
Example 14
Source File: FHIRCLI.java    From FHIR with Apache License 2.0 5 votes vote down vote up
/**
 * Visits each "queryParameter" option and adds it to the InvocationContext.
 */
private void collectQueryParameters(CommandLine cmdline, InvocationContext ic) {
    for (Option option : cmdline.getOptions()) {
        if (option.getOpt().equals(OptionNames.QUERYPARAMETER.getShortName())) {
            List<String> values = option.getValuesList();
            if (values != null && values.size() >= 2) {
                ic.addQueryParameter(values.get(0), values.get(1));
            }
        }
    }
}
 
Example 15
Source File: CreateTableCommand.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
private Map<String, String> getProps(CommandLine cmd, String opt) {
  Map<String, String> props = new HashMap<String, String>();
  Option[] options = cmd.getOptions();
  for (Option option : options) {
    if (option.getOpt().equals(opt)) {
      String[] values = option.getValues();
      props.put(values[0], values[1]);
    }
  }
  return props;
}
 
Example 16
Source File: SolrCLI.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
/**
 * Custom run method which may return exit code
 * @param cli the command line object
 * @return 0 on success, or a number corresponding to number of tests that failed
 * @throws Exception if a tool failed, e.g. authentication failure
 */
protected int runAssert(CommandLine cli) throws Exception {
  if (cli.getOptions().length == 0 || cli.getArgs().length > 0 || cli.hasOption("h")) {
    new HelpFormatter().printHelp("bin/solr assert [-m <message>] [-e] [-rR] [-s <url>] [-S <url>] [-c <url>] [-C <url>] [-u <dir>] [-x <dir>] [-X <dir>]", getToolOptions(this));
    return 1;
  }
  if (cli.hasOption("m")) {
    message = cli.getOptionValue("m");
  }
  if (cli.hasOption("t")) {
    timeoutMs = Optional.of(Long.parseLong(cli.getOptionValue("t")));
  }
  if (cli.hasOption("e")) {
    useExitCode = true;
  }

  int ret = 0;
  if (cli.hasOption("r")) {
    ret += assertRootUser();
  }
  if (cli.hasOption("R")) {
    ret += assertNotRootUser();
  }
  if (cli.hasOption("x")) {
    ret += assertFileExists(cli.getOptionValue("x"));
  }
  if (cli.hasOption("X")) {
    ret += assertFileNotExists(cli.getOptionValue("X"));
  }
  if (cli.hasOption("u")) {
    ret += sameUser(cli.getOptionValue("u"));
  }
  if (cli.hasOption("s")) {
    ret += assertSolrRunning(cli.getOptionValue("s"));
  }
  if (cli.hasOption("S")) {
    ret += assertSolrNotRunning(cli.getOptionValue("S"));
  }
  if (cli.hasOption("c")) {
    ret += assertSolrRunningInCloudMode(cli.getOptionValue("c"));
  }
  if (cli.hasOption("C")) {
    ret += assertSolrNotRunningInCloudMode(cli.getOptionValue("C"));
  }
  return ret;
}
 
Example 17
Source File: AbstractPropertyCommand.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public final R execute(final CommandLine commandLine) throws CommandException {
    try {
        final Properties properties = new Properties();

        // start by loading the properties file if it was specified
        if (commandLine.hasOption(CommandOption.PROPERTIES.getLongName())) {
            final String propertiesFile = commandLine.getOptionValue(CommandOption.PROPERTIES.getLongName());
            if (!StringUtils.isBlank(propertiesFile)) {
                try (final InputStream in = new FileInputStream(propertiesFile)) {
                    properties.load(in);
                }
            }
        } else {
            // no properties file was specified so see if there is anything in the session
            final SessionVariable sessionVariable = getPropertiesSessionVariable();
            if (sessionVariable != null) {
                final Session session = getContext().getSession();
                final String sessionPropsFiles = session.get(sessionVariable.getVariableName());
                if (!StringUtils.isBlank(sessionPropsFiles)) {
                    try (final InputStream in = new FileInputStream(sessionPropsFiles)) {
                        properties.load(in);
                    }
                }
            }
        }

        // add in anything specified on command line, and override anything that was already there
        for (final Option option : commandLine.getOptions()) {
            final String optValue = option.getValue() == null ? "" : option.getValue();
            properties.setProperty(option.getLongOpt(), optValue);
        }

        // delegate to sub-classes
        return doExecute(properties);

    } catch (CommandException ce) {
        throw ce;
    } catch (Exception e) {
        throw new CommandException("Error executing command '" + getName() + "' : " + e.getMessage(), e);
    }
}
 
Example 18
Source File: CLIParser.java    From Android-Monkey-Adapter with Apache License 2.0 4 votes vote down vote up
public boolean parse(String [] args) {
	Options options = new Options();
	
	options.addOption("d", "device-id", true, "the id list of the devices which is need to run monkey test");
	options.addOption("r", "user-name", true, "user name of this job owner");
	options.addOption("v", "pkg-version", true, "version of this application");
	options.addOption("n", "pkg-name", true, "package name of this appliacation");
	options.addOption("p", "pkg-path", true, "point to an Android application path in the storage");
	options.addOption("t", "series-duration", true, "expected total monkey jobs duration (hour)");
	options.addOption("s", "single-duration", true, "expected one monkey job duration (hour)");
	options.addOption("u", "unlock-cmd-path", true, "point to an unlock script path which must be standalone executable");
	options.addOption("h", "help", false, "Output help information!");
	
	String formatstr = "java -jar jarfile [-options/ --options]...\n";
	String headerstr = "options are as below:";

	CommandLineParser parser = new GnuParser();
	HelpFormatter formatter = new HelpFormatter();
	CommandLine cmd = null;
	
	try {
		cmd = parser.parse( options, args );
	} catch (ParseException e) {
		formatter.printHelp(formatstr, headerstr, options, "");
		return false;
	}	
	
	if (cmd == null || cmd.hasOption("h") || cmd.getOptions().length == 0) {
		formatter.printHelp(formatstr, options);
		return false;
	}
	if (cmd.hasOption("d")) {
		this.deivcesId = cmd.getOptionValues("d");
	}
	if (cmd.hasOption("r")) {
		this.user = cmd.getOptionValue("r");
	}
	if (cmd.hasOption("u")) {
		this.unlockCmd = cmd.getOptionValue("u");
	}
	if (cmd.hasOption("v")) {
		this.pkgVersion = cmd.getOptionValue("v");
	}
	if (cmd.hasOption("n")) {
		this.pkgName = cmd.getOptionValue("n");
	}
	if (cmd.hasOption("p")) {
		this.pkgPath = cmd.getOptionValue("p");
	}
	if (cmd.hasOption("t")) {
		this.seriesDuration = cmd.getOptionValue("t");
	}
	if (cmd.hasOption("s")) {
		this.singleDuration = cmd.getOptionValue("s");
	}
	if (cmd.hasOption("u")) {
		this.unlockCmd = cmd.getOptionValue("u");
	}
	return true;	
}
 
Example 19
Source File: CliOptsProcessor.java    From Project-Tauro with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Processes the command line options.
 *
 * @param args              The command line options
 * @return                  A map of the options and their values
 * @throws ParseException   In case of Exception parsing the options
 */
public static Map<String, String> processOptions(String[] args) throws ParseException {
  CommandLineParser commandLineParser = new DefaultParser();
  CommandLine commandLine = commandLineParser.parse(options, args);

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

  if ((commandLine.getOptions().length == 1) && (commandLine.hasOption(resumeOptVal) || commandLine.hasOption(resumeOpt))) {
    parsedOpts.put(resumeOptVal, null);
  } else {
    if (commandLine.hasOption(ispOptVal) || commandLine.hasOption(ispOpt)) {
      parsedOpts.put(ispOptVal, getOptionValue(ispOption, commandLine));
    }

    if (commandLine.hasOption(portOptVal) || commandLine.hasOption(portOpt)) {
      parsedOpts.put(portOptVal, getOptionValue(portOption, commandLine));
    }

    if (commandLine.hasOption(hostsFileOptVal) || commandLine.hasOption(hostsFileOpt)) {
      parsedOpts.put(hostsFileOptVal, getOptionValue(hostsFileOption, commandLine));
    }

    if (commandLine.hasOption(networkOptVal) || commandLine.hasOption(networkOpt)) {
      parsedOpts.put(networkOptVal, getOptionValue(networkOption, commandLine));
    }

    if (commandLine.hasOption(hostsOptVal) || commandLine.hasOption(hostsOpt)) {
      parsedOpts.put(hostsOptVal, getOptionValue(hostsOption, commandLine));
    }

    if (commandLine.hasOption(exclusionsOptVal) || commandLine.hasOption(exclusionsOpt)) {
      parsedOpts.put(exclusionsOptVal, getOptionValue(exclusionsOption, commandLine));
    }

    if (commandLine.hasOption(genMasscanOptVal) || commandLine.hasOption(genMasscanOpt)) {
      parsedOpts.put(genMasscanOptVal, getOptionValue(genMasscanOption, commandLine));
    }
  }

  return parsedOpts;
}
 
Example 20
Source File: CommandArgs.java    From gdx-proto with Apache License 2.0 4 votes vote down vote up
public static ScreenSize process(String[] args) {
	Options options = new Options();
	options.addOption("s", "server", false, "start online server");
	options.addOption("p", "port", true, "specify TCP port to either host on (server) or connect to (client)");
	options.addOption("c", "client", false, "connect to server as a client");
	options.addOption("a", "address", true, "supply hostname address to connect to");
	options.addOption("d", "lag-delay", true, "simulate lag with argument = milliseconds of lag");
	options.addOption("z", "screensize", true, "supply screen size in the form of WIDTHxHEIGHT, i.e. 1920x1080");
	options.addOption("h", "help", false, "print help");

	boolean printHelpAndQuit = false;

	ScreenSize screenSize = null;

	CommandLineParser parser = new BasicParser();
	CommandLine cli = null;
	try {
		cli = parser.parse(options, args);
	} catch (ParseException e) {
		e.printStackTrace();
		printHelpAndQuit = true;
	}
	if (cli != null && cli.hasOption('h')) {
		printHelpAndQuit = true;
	}
	if (cli != null && cli.getOptions().length == 0) {
		Main.serverType = ServerType.Local;
		Main.hasClient = true;
	}
	else if (cli != null && !printHelpAndQuit) {
		if (cli.hasOption('z')) {
			String[] pieces = cli.getOptionValue('z').split("x");
			int width = Integer.parseInt(pieces[0]);
			int height = Integer.parseInt(pieces[1]);
			screenSize = new ScreenSize();
			screenSize.width = width;
			screenSize.height = height;
		}
		if (cli.hasOption('s')) {
			Main.serverType = ServerType.Online;
			System.out.println("server type: online");
		}
		if (cli.hasOption('l')) {
			if (Main.serverType != null) {
				System.out.println("please choose local or online server, not both");
				printHelpAndQuit = true;
			} else {
				Main.serverType = ServerType.Local;
			}
		}
		if (cli.hasOption('c')) {
			Main.hasClient = true;
		}
		if (cli.hasOption('a')) {
			String value = cli.getOptionValue('a');
			if (value != null) {
				NetManager.host = value;
			}
		}
		if (cli.hasOption('p')) {
			int port = Integer.parseInt(cli.getOptionValue('p'));
			NetManager.tcpPort = port;
		}
		if (cli.hasOption('d')) {
			NetServer.simulateLag = true;
			int lagMillis = Integer.parseInt(cli.getOptionValue('d'));
			NetServer.lagMin = lagMillis;
			NetServer.lagMax = lagMillis;
		}
		// verify
		if (!Main.isClient() && !Main.isServer()) {
			System.out.println("please choose client and server options");
			printHelpAndQuit = true;
		}
	}
	if (printHelpAndQuit) {
		HelpFormatter hf = new HelpFormatter();
		hf.printHelp("java -jar myjarfile.jar <args>", options);
		System.exit(1);
	}
	return screenSize;
}