Example usage for org.apache.commons.cli CommandLine getOptions

List of usage examples for org.apache.commons.cli CommandLine getOptions

Introduction

In this page you can find the example usage for org.apache.commons.cli CommandLine getOptions.

Prototype

public Option[] getOptions() 

Source Link

Document

Returns an array of the processed Option s.

Usage

From source file:com.aliyun.odps.ship.common.OptionsBuilder.java

private static void processOptions(CommandLine line) {
    // set context value from options
    Option[] ops = line.getOptions();
    for (Option op : ops) {
        String v = removeQuote(op.getValue());
        if (Constants.FIELD_DELIMITER.equals(op.getLongOpt())
                || Constants.RECORD_DELIMITER.equals(op.getLongOpt())) {
            setContextValue(op.getLongOpt(), processDelimiter(v));
        } else {/*from  w w  w.j  av a  2  s  . c om*/
            setContextValue(op.getLongOpt(), v);
        }
    }
}

From source file:alluxio.cli.ValidateEnv.java

private static boolean validateLocal(String target, String name, CommandLine cmd) throws InterruptedException {
    int validationCount = 0;
    Map<ValidationTask.TaskResult, Integer> results = new HashMap<>();
    Map<String, String> optionsMap = new HashMap<>();
    for (Option opt : cmd.getOptions()) {
        optionsMap.put(opt.getOpt(), opt.getValue());
    }/* w w  w.ja v a  2  s. c om*/
    Collection<ValidationTask> tasks = TARGET_TASKS.get(target);
    System.out.format("Validating %s environment...%n", target);
    for (ValidationTask task : tasks) {
        String taskName = TASKS.get(task);
        if (name != null && !taskName.startsWith(name)) {
            continue;
        }
        System.out.format("Validating %s...%n", taskName);
        ValidationTask.TaskResult result = task.validate(optionsMap);
        results.put(result, results.getOrDefault(result, 0) + 1);
        switch (result) {
        case OK:
            System.out.print(Constants.ANSI_GREEN);
            break;
        case WARNING:
            System.out.print(Constants.ANSI_YELLOW);
            break;
        case FAILED:
            System.out.print(Constants.ANSI_RED);
            break;
        case SKIPPED:
            System.out.print(Constants.ANSI_PURPLE);
            break;
        default:
            break;
        }
        System.out.print(result.name());
        System.out.println(Constants.ANSI_RESET);
        validationCount++;
    }
    if (results.containsKey(ValidationTask.TaskResult.FAILED)) {
        System.err.format("%d failures ", results.get(ValidationTask.TaskResult.FAILED));
    }
    if (results.containsKey(ValidationTask.TaskResult.WARNING)) {
        System.err.format("%d warnings ", results.get(ValidationTask.TaskResult.WARNING));
    }
    if (results.containsKey(ValidationTask.TaskResult.SKIPPED)) {
        System.err.format("%d skipped ", results.get(ValidationTask.TaskResult.SKIPPED));
    }
    System.err.println();
    if (validationCount == 0) {
        System.err.format("No validation task matched name \"%s\".%n", name);
        return false;
    }
    if (results.containsKey(ValidationTask.TaskResult.FAILED)) {
        return false;
    }
    System.out.println("Validation succeeded.");
    return true;
}

From source file:com.linkedin.databus2.client.util.CheckpointSerializerMain.java

private static void parseArgs(String[] args) throws Exception {
    CommandLineParser cliParser = new GnuParser();

    Options options = createOptions();// w  w  w.  ja  va 2 s .co  m

    CommandLine cmd = null;
    try {
        cmd = cliParser.parse(options, args);
    } catch (ParseException pe) {
        throw new RuntimeException("failed to parse command-line options.", pe);
    }

    if (cmd.hasOption(HELP_OPT_CHAR) || 0 == cmd.getOptions().length) {
        printCliHelp(options);
        System.exit(0);
    }

    try {
        _action = Action.valueOf(cmd.getOptionValue(ACTION_OPT_CHAR).toUpperCase());
    } catch (Exception e) {
        throw new RuntimeException("invalid action: " + cmd.getOptionValue(ACTION_OPT_CHAR), e);
    }

    if (!cmd.hasOption(SOURCES_OPT_CHAR)) {
        throw new RuntimeException("expected sources list; see --help for more info");
    }

    String sourcesListStr = cmd.getOptionValue(SOURCES_OPT_CHAR);
    _sources = sourcesListStr.split(",");
    if (null == _sources || 0 == _sources.length) {
        throw new RuntimeException("empty sources list");
    }
    for (int i = 0; i < _sources.length; ++i)
        _sources[i] = _sources[i].trim();

    if (Action.PRINT != _action && !cmd.hasOption(CLIENT_PROPS_FILE_OPT_CHAR)
            && !cmd.hasOption(CP3_PROPS_FILE_OPT_CHAR)) {
        throw new RuntimeException("expected client or CP3 configuration; see --help for more info");
    }

    String defaultPropPrefix = null;
    if (cmd.hasOption(CLIENT_PROPS_FILE_OPT_CHAR)) {
        try {
            _clientProps = loadProperties(cmd.getOptionValue(CLIENT_PROPS_FILE_OPT_CHAR));
            defaultPropPrefix = "databus2.client";
        } catch (Exception e) {
            throw new RuntimeException("unable to load client properties", e);
        }
    } else if (cmd.hasOption(CP3_PROPS_FILE_OPT_CHAR)) {
        try {
            _cp3Props = loadProperties(cmd.getOptionValue(CP3_PROPS_FILE_OPT_CHAR));
            defaultPropPrefix = "databus2.client.checkpointPersistence";
        } catch (Exception e) {
            throw new RuntimeException("unable to load CP3 properties", e);
        }
    }

    _propPrefix = cmd.hasOption(PROPS_PREFIX_OPT_CHAR) ? cmd.getOptionValue(PROPS_PREFIX_OPT_CHAR)
            : defaultPropPrefix;
    if (null != _propPrefix && !_propPrefix.endsWith(".")) {
        _propPrefix = _propPrefix + ".";
    }

    if (!cmd.hasOption(ACTION_OPT_CHAR)) {
        throw new RuntimeException("action expected; see --help for more info");
    }

    _scn = parseLongOption(cmd, SCN_OPT_CHAR, "sequence number");
    _sinceScn = parseLongOption(cmd, SINCE_SCN_OPT_CHAR, "last sequence number");
    _startScn = parseLongOption(cmd, START_SCN_OPT_CHAR, "start sequence number");
    _targetScn = parseLongOption(cmd, TARGET_SCN_OPT_CHAR, "target sequence number");

    if (cmd.hasOption(TYPE_OPT_CHAR)) {
        try {
            _cpType = DbusClientMode.valueOf(cmd.getOptionValue(TYPE_OPT_CHAR).toUpperCase());
        } catch (Exception e) {
            throw new RuntimeException("invalid checkpoint type:" + cmd.getOptionValue(TYPE_OPT_CHAR), e);
        }
    }

    if (cmd.hasOption(BOOTSTRAP_SOURCE_OPT_CHAR)) {
        _bootstrapSource = cmd.getOptionValue(BOOTSTRAP_SOURCE_OPT_CHAR);
    }
}

From source file:de.bmw.yamaica.common.console.CommandExecuter.java

/**
 * Converts an instance the CommandLine Object into an array of strings.
 *
 * @param commandLine/*from  www . j av  a 2  s  .  c  o  m*/
 *            instance
 * @param keepIdOption
 *            if true the returned array will contain the ID option if available
 * @return Arguments split into string array
 */
public static String[] getArguments(CommandLine commandLine, boolean keepIdOption) {
    Assert.isNotNull(commandLine);

    List<String> argumentsList = new ArrayList<String>();

    Option[] options = commandLine.getOptions();

    if (null != options) {
        for (Option option : options) {
            String optionString = option.getOpt();

            if (keepIdOption == false && SHORT_ID_OPTION.equals(optionString)) {
                continue;
            }

            argumentsList.add("-" + optionString);

            String[] values = option.getValues();

            if (null != values) {
                for (String value : values) {
                    argumentsList.add(value);
                }
            }
        }
    }

    return argumentsList.toArray(new String[argumentsList.size()]);
}

From source file:ch.zhaw.iamp.rct.App.java

private static void handleArguments(String[] args) {
    CommandLineParser parser = new BasicParser();
    CommandLine commandLine;

    try {/*from  www  . j a  v  a2  s . co m*/
        commandLine = parser.parse(cliOptions, args);
    } catch (ParseException ex) {
        System.out.println("The arguments could not be understood: " + ex.getMessage());
        printCliHelp();
        return;
    }

    if (commandLine.hasOption("g")) {
        System.out.println("The generation grammar is not implemented yet.");
        return;
    }

    if (commandLine.hasOption("w")) {
        String[] optionValues = commandLine.getOptionValues("w");
        Weights.calculateWeights(optionValues[0], optionValues[1], optionValues[2], 1000);
        return;
    }

    if (commandLine.getOptions() != null && commandLine.getOptions().length > 0) {
        System.out.println("The arguments could not be understood.\n");
        printCliHelp();
        return;
    }

    controller.showMainWindow();
}

From source file:com.google.api.ads.adwords.keywordoptimizer.KeywordOptimizer.java

/**
 * 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}//from ww w . ja v a2 s  .co m
 * @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;
}

From source file:lcmc.LCMC.java

/** Parse cluster options and create cluster button. */
private static void parseClusterOptions(final CommandLine cmd) throws ParseException {
    String clusterName = null;/*from  ww  w .  j av  a 2s.c  om*/
    List<HostOptions> hostsOptions = null;
    final Map<String, List<HostOptions>> clusters = new LinkedHashMap<String, List<HostOptions>>();
    for (final Option option : cmd.getOptions()) {
        final String op = option.getLongOpt();
        if (CLUSTER_OP.equals(op)) {
            clusterName = option.getValue();
            if (clusterName == null) {
                throw new ParseException("could not parse " + CLUSTER_OP + " option");

            }
            clusters.put(clusterName, new ArrayList<HostOptions>());
        } else if (HOST_OP.equals(op)) {
            final String[] hostNames = option.getValues();
            if (clusterName == null) {
                clusterName = "default";
                clusters.put(clusterName, new ArrayList<HostOptions>());
            }
            if (hostNames == null) {
                throw new ParseException("could not parse " + HOST_OP + " option");
            }
            hostsOptions = new ArrayList<HostOptions>();
            for (final String hostNameEntered : hostNames) {
                String hostName;
                String port = null;
                if (hostNameEntered.indexOf(':') > 0) {
                    final String[] he = hostNameEntered.split(":");
                    hostName = he[0];
                    port = he[1];
                    if ("".equals(port) || !Tools.isNumber(port)) {
                        throw new ParseException("could not parse " + HOST_OP + " option");
                    }
                } else {
                    hostName = hostNameEntered;
                }
                final HostOptions ho = new HostOptions(hostName);
                if (port != null) {
                    ho.setPort(port);
                }
                hostsOptions.add(ho);
                clusters.get(clusterName).add(ho);
            }
        } else if (SUDO_OP.equals(op)) {
            if (hostsOptions == null) {
                throw new ParseException(SUDO_OP + " must be defined after " + HOST_OP);
            }
            for (final HostOptions ho : hostsOptions) {
                ho.setSudo(true);
            }
        } else if (USER_OP.equals(op)) {
            if (hostsOptions == null) {
                throw new ParseException(USER_OP + " must be defined after " + HOST_OP);
            }
            final String userName = option.getValue();
            if (userName == null) {
                throw new ParseException("could not parse " + USER_OP + " option");
            }
            for (final HostOptions ho : hostsOptions) {
                ho.setUser(userName);
            }
        } else if (PORT_OP.equals(op)) {
            if (hostsOptions == null) {
                throw new ParseException(PORT_OP + " must be defined after " + HOST_OP);
            }
            final String port = option.getValue();
            if (port == null) {
                throw new ParseException("could not parse " + PORT_OP + " option");
            }
            for (final HostOptions ho : hostsOptions) {
                ho.setPort(port);
            }
        }
    }
    for (final String cn : clusters.keySet()) {
        for (final HostOptions hostOptions : clusters.get(cn)) {
            if (hostsOptions.size() < 1
                    || (hostsOptions.size() == 1 && !Tools.getConfigData().isOneHostCluster())) {
                throw new ParseException("not enough hosts for cluster: " + cn);
            }
        }
    }
    final String failedHost = Tools.setUserConfigFromOptions(clusters);
    if (failedHost != null) {
        Tools.appWarning("could not resolve host \"" + failedHost + "\" skipping");
    }
}

From source file:com.antsdb.saltedfish.nosql.HumpbackMetaMain.java

private void run() throws Exception {
    CommandLine line = this.cmd;

    if (line.getOptions().length == 0 || line.hasOption('h')) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("humpback-meta", getOptions());
        return;/*from  w ww  .j  a va2 s  .  c om*/
    }

    this.humpback = getHumpbackReadOnly();
    if (this.humpback == null) {
        return;
    }
    if (line.hasOption('n')) {
        findTable(line.getOptionValue('n'));
        return;
    }
    println("error: -n is not specified");
}

From source file:net.bican.wordpress.configuration.CliConfiguration.java

/**
 * //from w  w w. j a  v  a 2  s  .c  om
 * generates the configuration in terms of arguments and options
 * 
 * @param args Command line arguments
 * @param options Command line options
 * @throws ParseException When the configuration cannot be parsed
 */
public CliConfiguration(String[] args, Options options) throws ParseException {
    CommandLineParser parser = new BasicParser();
    CommandLine commandLine = parser.parse(options, args);
    for (Option option : commandLine.getOptions()) {
        String key = option.getLongOpt();
        String val = option.getValue();
        if (val == null) {
            this.addProperty(key, "N/A");
        } else {
            this.addProperty(key, val);
        }
    }
}

From source file:com.antsdb.saltedfish.nosql.HumpbackUtil.java

private void run(String[] args) throws Exception {
    CommandLine line = parse(getOptions(), args);

    if (line.getOptions().length == 0 || line.hasOption('h')) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("humpback-util", getOptions());
        return;//from w w  w.  ja va2  s.  co m
    }

    // options

    if (line.getOptionValue("home") == null) {
        err.println("error: data directory is not specified");
        return;
    }
    this.home = new File(line.getOptionValue("home"));
    if (!home.isDirectory()) {
        err.println("error: invalid home directory");
        return;
    }

    // commands

    if (line.hasOption("validate")) {
        validate();
    }
}