Example usage for org.apache.commons.cli Option getValue

List of usage examples for org.apache.commons.cli Option getValue

Introduction

In this page you can find the example usage for org.apache.commons.cli Option getValue.

Prototype

public String getValue() 

Source Link

Document

Returns the specified value of this Option or null if there is no value.

Usage

From source file:edu.umass.cs.gnsserver.utils.ParametersAndOptions.java

/**
 * Returns a hash map with all options including options in config file and the command line arguments
 *
 * @param className// w ww  . j  a v a2 s  .c  om
 * @param commandLineOptions
 * @param args command line arguments given to JVM
 * @return hash map with KEY = parameter names, VALUE = values of parameters in String form
 * @throws IOException
 */
public static HashMap<String, String> getParametersAsHashMap(String className, Options commandLineOptions,
        String... args) throws IOException {
    CommandLine parser = null;

    try {
        parser = new GnuParser().parse(commandLineOptions, args);
    } catch (ParseException e) {
        System.err.println("Problem parsing command line:" + e);
        printUsage(className, commandLineOptions);
        System.exit(1);
    }

    if (parser.hasOption(HELP)) {
        printUsage(className, commandLineOptions);
        System.exit(0);
    }

    // load options given in config file in a java properties object
    Properties prop = new Properties();

    if (parser.hasOption(CONFIG_FILE)) {
        String value = parser.getOptionValue(CONFIG_FILE);
        File f = new File(value);
        if (f.exists() == false) {
            System.err.println("Config file not found:" + value);
            System.exit(2);
        }
        InputStream input = new FileInputStream(value);
        // load a properties file
        prop.load(input);

    }

    // create a hash map with all options including options in config file and the command line arguments
    HashMap<String, String> allValues = new HashMap<String, String>();

    // add options given in config file to hash map
    for (String propertyName : prop.stringPropertyNames()) {
        allValues.put(propertyName, prop.getProperty(propertyName));
    }

    // add options given via command line to hashmap. these options can override options given in config file.
    for (Option option : parser.getOptions()) {
        String argName = option.getOpt();
        String value = option.getValue();
        // if an option has a boolean value, the command line arguments do not say true/false for some of these options
        // if option name is given as argument on the command line, it means the value is true. therefore, the hashmap
        // will also assign the value true for these options.
        if (value == null) {
            value = "true";
        }
        allValues.put(argName, value);
    }

    return allValues;
}

From source file:com.aliyun.openservices.odps.console.resource.CreateResourceCommand.java

public static AddResourceCommand parse(String commandString, ExecutionContext sessionContext)
        throws ODPSConsoleException {

    String[] tokens = new AntlrObject(commandString).getTokenStringArray();

    if (tokens != null && tokens.length >= 2 && tokens[0].toUpperCase().equals("CREATE")
            && tokens[1].toUpperCase().equals("RESOURCE")) {

        GnuParser parser = new GnuParser();
        Options options = new Options();
        options.addOption("p", "project", true, null);
        options.addOption("c", "comment", true, null);
        options.addOption("f", "force", false, null);

        try {//  w  ww .j  a va 2  s  . c o m
            CommandLine cl = parser.parse(options, tokens);

            String refName = null;
            String alias = "";
            String comment = null;
            String type = null;
            String partitionSpec = "";
            boolean isUpdate = false;

            List<String> argList = cl.getArgList();
            int size = argList.size();

            if (size < 4) {
                throw new ODPSConsoleException(ODPSConsoleConstants.BAD_COMMAND + "Missing parameters");
            }

            ListIterator<String> iter = argList.listIterator();
            iter.next();
            iter.next();
            type = iter.next();
            refName = iter.next();
            if (iter.hasNext()) {
                String item = iter.next();
                if (item.equals("(")) {
                    boolean isParenPaired = false;

                    while (iter.hasNext()) {
                        String s = iter.next();
                        if (s.equals(")")) {
                            isParenPaired = true;
                            break;
                        }
                        partitionSpec += s;
                    }

                    if (!isParenPaired) {
                        throw new ODPSConsoleException(
                                ODPSConsoleConstants.BAD_COMMAND + "Unpaired parenthesis");
                    }

                    if (!iter.hasNext()) {
                        throw new ODPSConsoleException(
                                ODPSConsoleConstants.BAD_COMMAND + "Missing parameter: alias");
                    }
                    item = iter.next();
                }

                alias = item;
            }

            if (iter.hasNext()) {
                throw new ODPSConsoleException(
                        ODPSConsoleConstants.BAD_COMMAND + "Illegal parameter: " + iter.next());
            }

            String projectName = null;
            Option[] opts = cl.getOptions();
            for (Option opt : opts) {
                if ("f".equals(opt.getOpt())) {
                    isUpdate = true;
                } else if ("c".equals(opt.getOpt())) {
                    comment = opt.getValue();
                } else if ("p".equals(opt.getOpt())) {
                    projectName = opt.getValue();
                } else {
                    throw new ODPSConsoleException(
                            ODPSConsoleConstants.BAD_COMMAND + "Illegal option: " + opt.getOpt());
                }
            }

            return new AddResourceCommand(commandString, sessionContext, refName, alias, comment, type,
                    partitionSpec, isUpdate, projectName);
        } catch (ParseException e) {
            throw new ODPSConsoleException(ODPSConsoleConstants.BAD_COMMAND + "Invalid parameters");
        }
    } else {
        return null;
    }
}

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());
    }/*from  w  w w.j a  v a  2  s .  com*/
    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.cloudera.beeswax.Server.java

/**
 * Parse command line options.//  w  w w  . j a  v  a 2  s . c om
 *
 * -b <port> specifies the port for beeswax to use.
 * -m <port>, if given, starts the metastore at this port.
 */
private static void parseArgs(String[] args) throws ParseException {
    Options options = new Options();

    Option metastoreOpt = new Option("m", "metastore", true, "port to use for metastore");
    metastoreOpt.setRequired(false);
    options.addOption(metastoreOpt);

    Option beeswaxOpt = new Option("b", "beeswax", true, "port to use for beeswax");
    beeswaxOpt.setRequired(true);
    options.addOption(beeswaxOpt);

    Option dtHostOpt = new Option("h", "desktop-host", true, "host running desktop");
    dtHostOpt.setRequired(true);
    options.addOption(dtHostOpt);

    Option dtHttpsOpt = new Option("s", "desktop-https", true, "desktop is running https");
    options.addOption(dtHttpsOpt);

    Option dtPortOpt = new Option("p", "desktop-port", true, "port used by desktop");
    dtPortOpt.setRequired(true);
    options.addOption(dtPortOpt);

    Option superUserOpt = new Option("u", "superuser", true, "Username of Hadoop superuser (default: hadoop)");
    superUserOpt.setRequired(false);
    options.addOption(superUserOpt);

    PosixParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);
    if (!cmd.getArgList().isEmpty()) {
        throw new ParseException("Unexpected extra arguments: " + cmd.getArgList());
    }

    for (Option opt : cmd.getOptions()) {
        if (opt.getOpt() == "m") {
            mport = parsePort(opt);
        } else if (opt.getOpt() == "b") {
            bport = parsePort(opt);
        } else if (opt.getOpt() == "u") {
            superUser = opt.getValue();
        } else if (opt.getOpt() == "h") {
            dtHost = opt.getValue();
        } else if (opt.getOpt() == "p") {
            dtPort = parsePort(opt);
        } else if (opt.getOpt() == "s") {
            dtHttps = true;
        }
    }
}

From source file:io.janusproject.Boot.java

private static void parseCommandLineForVerbosity(CommandLine cmd) {
    // The order of the options is important.
    int verbose = LoggerCreator.toInt(JanusConfig.VERBOSE_LEVEL_VALUE);
    if (cmd.hasOption('v') || cmd.hasOption('q') || cmd.hasOption('l')) {
        @SuppressWarnings("unchecked")
        Iterator<Option> optIterator = cmd.iterator();
        while (optIterator.hasNext()) {
            Option opt = optIterator.next();
            switch (opt.getOpt()) {
            case "l": //$NON-NLS-1$
                verbose = LoggerCreator.toInt(opt.getValue());
                break;
            case "q": //$NON-NLS-1$
                --verbose;/*from  w  ww .  j av  a  2s. c  o  m*/
                break;
            case "v": //$NON-NLS-1$
                ++verbose;
                break;
            default:
            }
        }
        System.setProperty(JanusConfig.VERBOSE_LEVEL_NAME, Integer.toString(verbose));
    }

    // Show the Janus logo?
    if (cmd.hasOption("nologo") || verbose == 0) { //$NON-NLS-1$
        System.setProperty(JanusConfig.JANUS_LOGO_SHOW_NAME, Boolean.FALSE.toString());
    }
}

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  a  va2 s  .  c o  m*/
            setContextValue(op.getLongOpt(), v);
        }
    }
}

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;// w  ww.j  a v  a  2 s.  co m
    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:eu.project.ttc.tools.cli.TermSuiteCLIUtils.java

/**
 * Displays all command line options in log messages.
 * @param line/*from w  w  w. j  a v a 2 s.  c o m*/
 */
public static void logCommandLineOptions(CommandLine line) {
    for (Option myOption : line.getOptions()) {
        String message;
        String opt = "";
        if (myOption.getOpt() != null) {
            opt += "-" + myOption.getOpt();
            if (myOption.getLongOpt() != null)
                opt += " (--" + myOption.getLongOpt() + ")";
        } else
            opt += "--" + myOption.getLongOpt() + "";

        if (myOption.hasArg())
            message = opt + " " + myOption.getValue();
        else
            message = opt;

        LOGGER.info("with option: " + message);
    }
}

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

/**
 * //from  w  ww. j  a va 2s .co m
 * 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:eu.alpinweiss.filegen.service.impl.FdrServiceImpl.java

@Override
public void run(String[] args) {

    if (injector == null) {
        throw new RuntimeException("Injector is null");
    }//from   ww  w.ja  v a  2 s  . co  m

    Model model = new Model();
    Map<String, Class<? extends CommandStep>> commandSteps = optionHolder.getCommandStepMap();
    Options options = optionHolder.getAppOptions();

    CommandLineParser parser = new PosixParser();
    try {
        CommandLine cmd = parser.parse(options, args);
        Option[] cmdOptions = cmd.getOptions();
        for (Option cmdOption : cmdOptions) {
            model.addParameter(cmdOption.getOpt(), cmdOption.getValue());
            model.addCommand(injector.getInstance(commandSteps.get(cmdOption.getOpt())));
        }
    } catch (ParseException e) {
        LOGGER.error(e.getMessage(), e);
    }

    commandRunner.run(model);
}