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:com.googlecode.jmxtrans.cli.CommonsCliArgumentParser.java

/** Parse the options given on the command line. */
@Nonnull//from w  w  w  . jav  a  2  s .c  o m
@Override
public JmxTransConfiguration parseOptions(@Nonnull String[] args)
        throws OptionsException, org.apache.commons.cli.ParseException {
    CommandLineParser parser = new GnuParser();
    CommandLine cl = parser.parse(getOptions(), args);
    Option[] options = cl.getOptions();

    JmxTransConfiguration configuration = new JmxTransConfiguration();

    for (Option option : options) {
        if (option.getOpt().equals("c")) {
            configuration.setContinueOnJsonError(Boolean.parseBoolean(option.getValue()));
        } else if (option.getOpt().equals("j")) {
            File jsonDir = new File(option.getValue());
            if (jsonDir.exists() && jsonDir.isDirectory()) {
                configuration.setJsonDir(jsonDir);
            } else {
                throw new OptionsException("Path to json directory is invalid: " + jsonDir);
            }
        } else if (option.getOpt().equals("f")) {
            File jsonFile = new File(option.getValue());
            if (jsonFile.exists() && jsonFile.isFile()) {
                configuration.setJsonFile(jsonFile);
            } else {
                throw new OptionsException("Path to json file is invalid: " + jsonFile);
            }
        } else if (option.getOpt().equals("e")) {
            configuration.setRunEndlessly(true);
        } else if (option.getOpt().equals("q")) {
            File quartzConfigFile = new File(option.getValue());
            if (quartzConfigFile.exists() && quartzConfigFile.isFile()) {
                configuration.setQuartzPropertiesFile(quartzConfigFile);
            } else {
                throw new OptionsException("Could not find path to the quartz properties file: "
                        + quartzConfigFile.getAbsolutePath());
            }
        } else if (option.getOpt().equals("s")) {
            try {
                configuration.setRunPeriod(Integer.parseInt(option.getValue()));
            } catch (NumberFormatException nfe) {
                throw new OptionsException("Seconds between server job runs must be an integer");
            }
        } else if (option.getOpt().equals("a")) {
            configuration.setAdditionalJars(option.getValuesList());
        } else if (option.getOpt().equals("h")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("java -jar jmxtrans-all.jar", getOptions());
            configuration.setHelp(true);
        }
    }
    if ((!configuration.isHelp()) && (configuration.getJsonDirOrFile() == null)) {
        throw new OptionsException("Please specify either the -f or -j option.");
    }
    return configuration;
}

From source file:ca.phon.app.modules.EntryPointArgs.java

/**
 * Parse command line arguments.//from   ww  w .j  a  v a 2 s  . co m
 * 
 * @param args
 */
public void parseArgs(String[] args) {
    final Options options = new Options();
    options.addOption(PROJECT_NAME_OPT, PROJECT_NAME, true, PROJECT_NAME_DESC);
    options.addOption(PROJECT_LOCATION_OPT, PROJECT_LOCATION, true, PROJECT_LOCATION_DESC);
    options.addOption(CORPUS_NAME_OPT, CORPUS_NAME, true, CORPUS_NAME_DESC);
    options.addOption(SESSION_NAME_OPT, SESSION_NAME, true, SESSION_NAME_DESC);

    final CommandLineParser parser = new EntryPointArgParser();

    try {
        final CommandLine cmdLine = parser.parse(options, args, false);
        for (Option opt : cmdLine.getOptions()) {
            put(opt.getLongOpt(), opt.getValue());
        }
    } catch (ParseException e) {
        LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
    }
}

From source file:com.cloudera.csd.tools.MetricDescriptorGeneratorTool.java

private MapConfiguration generateAndValidateConfig(CommandLine cmdLine) throws ParseException {
    Preconditions.checkNotNull(cmdLine);
    MapConfiguration ret = new MapConfiguration(Maps.<String, Object>newHashMap());

    for (Option option : cmdLine.getOptions()) {
        ret.addProperty(option.getLongOpt(), option.getValue());
    }/*from   w ww . j  a va 2 s.  com*/

    if (null == ret.getProperty(OPT_INPUT_MDL.getLongOpt())) {
        throw new ParseException("MetricGeneratorTool missing mdl file " + "location");
    } else {
        String fileName = ret.getString(OPT_INPUT_MDL.getLongOpt());
        File file = new File(fileName);
        if (!file.exists()) {
            throw new ParseException("MDL file '" + fileName + "' does not " + "exist");
        } else if (!file.isFile()) {
            throw new ParseException("MDL file '" + fileName + "' is not a " + "file");
        }
    }

    if (null == ret.getProperty(OPT_INPUT_FIXTURE.getLongOpt())) {
        throw new ParseException("MetricGeneratorTool missing fixture file " + "location");
    } else {
        String fileName = ret.getString(OPT_INPUT_FIXTURE.getLongOpt());
        File file = new File(fileName);
        if (!file.exists()) {
            throw new ParseException("Fixture file '" + fileName + "' does not " + "exist");
        } else if (!file.isFile()) {
            throw new ParseException("Fixture file '" + fileName + "' is not a " + "file");
        }
    }

    if (null != ret.getProperty(OPT_INPUT_CONVENTIONS.getLongOpt())) {
        String fileName = ret.getString(OPT_INPUT_CONVENTIONS.getLongOpt());
        File file = new File(fileName);
        if (!file.exists()) {
            throw new ParseException("Conventions file '" + fileName + "' does " + "not exist");
        } else if (!file.isFile()) {
            throw new ParseException("Conventions file '" + fileName + "' is " + "not a file");
        }
    }

    if (null == ret.getProperty(OPT_ADAPTER_CLASS.getLongOpt())) {
        throw new ParseException("MetricGeneratorTool missing adapter class");
    } else {
        String className = ret.getString(OPT_ADAPTER_CLASS.getLongOpt());
        try {
            Class<?> adapterClass = this.getClass().getClassLoader().loadClass(className);
            if (!MetricFixtureAdapter.class.isAssignableFrom(adapterClass)) {
                throw new ParseException("Adapter class " + className + "is of the " + "wrong type");
            }
            ret.addProperty(ADAPTER_CLASS_CONFIG, adapterClass);
        } catch (ClassNotFoundException e) {
            throw new ParseException("Unknown metric adapter " + className);
        }
    }
    return ret;
}

From source file:de.yaio.commons.config.Configuration.java

public void putCliOptions(org.apache.commons.cli.Option[] cliOptions) {
    for (final org.apache.commons.cli.Option prop : Arrays.asList(cliOptions)) {
        if (!StringUtils.isEmpty(prop.getLongOpt())) {
            this.putCliOption(new ConfigurationOption(prop.getLongOpt(), prop.getValue()));
        }/*from   ww w .j  av a  2  s  . c om*/
        if (!StringUtils.isEmpty(prop.getOpt())) {
            this.putCliOption(new ConfigurationOption(prop.getOpt(), prop.getValue()));
        }
    }
}

From source file:gobblin.runtime.cli.ConstructorAndPublicMethodsCliObjectFactory.java

/**
 * 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.//  w ww .ja  v  a  2 s. co m
 */
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);
    }
}

From source file:gobblin.runtime.cli.ConstructorAndPublicMethodsGobblinCliFactory.java

/**
 * Builds an instance of {@link EmbeddedGobblin} using the selected constructor getting the constructor
 * parameters from the {@link CommandLine}.
 *
 * Note: this method will also automatically call {@link #applyCommandLineOptions(CommandLine, EmbeddedGobblin)} on
 * the constructed {@link EmbeddedGobblin}.
 *//*from   w  w w .j  a  v  a 2s. c om*/
public EmbeddedGobblin 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();
        }
    }

    EmbeddedGobblin 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);
    }
}

From source file:com.splunk.Command.java

public Command parse(String[] argv) {
    CommandLineParser parser = new PosixParser();

    CommandLine cmdline = null;/*w w w  .ja  v a2 s .co m*/
    try {
        cmdline = parser.parse(this.rules, argv);
    } catch (ParseException e) {
        error(e.getMessage());
    }

    // Unpack the cmdline into a simple Map of options and optionally
    // assign values to any corresponding fields found in the Command class.
    for (Option option : cmdline.getOptions()) {
        String name = option.getLongOpt();
        Object value = option.getValue();

        // Figure out the type of the option and convert the value.
        if (!option.hasArg()) {
            // If it has no arg, then its implicitly boolean and presence
            // of the argument indicates truth.
            value = true;
        } else {
            Class type = (Class) option.getType();
            if (type == null) {
                // Null implies String, no conversion necessary
            } else if (type == Integer.class) {
                value = Integer.parseInt((String) value);
            } else {
                assert false; // Unsupported type
            }
        }

        this.opts.put(name, value);

        // Look for a field of the Command class (or subclass) that
        // matches the long name of the option and, if found, assign the
        // corresponding option value in order to provide simplified
        // access to command options.
        try {
            java.lang.reflect.Field field = this.getClass().getField(name);
            field.set(this, value);
        } catch (NoSuchFieldException e) {
            continue;
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    String[] orig = this.args;
    String[] more = cmdline.getArgs();
    this.args = new String[orig.length + more.length];
    System.arraycopy(orig, 0, this.args, 0, orig.length);
    System.arraycopy(more, 0, this.args, orig.length, more.length);

    if (this.help) {
        printHelp();
        System.exit(0);
    }

    return this;
}

From source file:com.github.horrorho.inflatabledonkey.args.PropertyLoader.java

String parse(Option option) {
    testIntegers(option);/*w  w w .  jav a2 s. c om*/

    if (option.hasArgs()) {
        // Array
        return option.getValuesList().stream().collect(Collectors.joining(" "));
    }
    if (option.hasArg()) {
        // Value
        return option.getValue();
    }
    // Boolean
    return Boolean.TRUE.toString();
}

From source file:com.github.horrorho.inflatabledonkey.args.ArgsManager.java

String parse(Option option, UnaryOperator<String> parser) {
    if (option.hasArgs()) {
        return option.getValuesList().stream().map(u -> parse(option.getLongOpt(), u, parser))
                .collect(Collectors.joining(" "));
    }//  w  w  w  .  j  ava2  s  .c o  m
    if (option.hasArg()) {
        return parse(option.getLongOpt(), option.getValue(), parser);
    }
    return Boolean.TRUE.toString();
}

From source file:edu.vt.middleware.ldap.cli.AbstractCli.java

/**
 * Reads the options from the supplied command line and returns a properties
 * containing those options./*w  w w .  j av a2  s . c o  m*/
 *
 * @param  domain  to place property names in
 * @param  line  command line
 *
 * @return  properties for each option and value
 */
protected Properties getPropertiesFromOptions(final String domain, final CommandLine line) {
    final Properties props = new Properties();
    for (Option o : line.getOptions()) {
        if (o.hasArg()) {
            // if provider property, split the value
            if (o.getOpt().equals(OPT_PROVIDER_PROPERTIES)) {
                final String[] s = o.getValue().split("=");
                props.setProperty(s[0], s[1]);
                // add the domain to vt-ldap properties
            } else {
                props.setProperty(domain + o.getOpt(), o.getValue());
            }
        }
    }
    return props;
}