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

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

Introduction

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

Prototype

public String getArgName() 

Source Link

Document

Gets the display name for the argument value.

Usage

From source file:org.apache.tez.analyzer.plugins.TezAnalyzerBase.java

private void printUsage() {
    System.err.println("Analyzer base options are");
    Options options = buildOptions();/*from  www .ja  v a 2 s.c  o  m*/
    for (Object obj : options.getOptions()) {
        Option option = (Option) obj;
        System.err.println(option.getArgName() + " : " + option.getDescription());
    }
}

From source file:org.apparatus_templi.Coordinator.java

/**
 * Parse all command line arguments. Any preferences read from the command like will be put into
 * the {@link Prefs} singleton.//from ww  w.j  a v a 2  s. c o  m
 * 
 * @param argv
 *            the command line arguments to be parsed
 */

private static void parseCommandLineOptions(String[] argv) {
    assert argv != null : "command line arguments should never be null";

    // Using apache commons cli to parse the command line options
    Options options = new Options();
    options.addOption("help", false, "Display this help message.");

    // the commons cli parser does not allow '.' within the option names, so we have to replace
    // the periods with underscores for now. When parsing the args later the underscores will be
    // converted back to proper dot notation
    for (String key : prefs.getDefPreferencesMap().keySet()) {
        String optName;
        if (key.contains(".")) {
            optName = key.replaceAll("\\.", "_");
        } else {
            optName = key;
        }

        options.addOption(OptionBuilder.withArgName(optName).hasArg()
                .withDescription(prefs.getPreferenceDesc(key)).create(optName));
    }

    CommandLineParser cliParser = new org.apache.commons.cli.PosixParser();
    try {
        CommandLine cmd = cliParser.parse(options, argv);
        if (cmd.hasOption("help")) {
            // show help message and exit
            HelpFormatter formatter = new HelpFormatter();
            formatter.setOptPrefix("--");
            formatter.setLongOptPrefix("--");

            formatter.printHelp(TAG, options);
            System.exit(0);
        }

        // Load the configuration file URI
        String configFile;
        if (cmd.hasOption(Prefs.Keys.configFile)) {
            configFile = cmd.getOptionValue(Prefs.Keys.configFile);
            if (configFile.startsWith("~" + File.separator)) {
                configFile = System.getProperty("user.home") + configFile.substring(1);
            }
        } else {
            configFile = prefs.getDefPreference(Prefs.Keys.configFile);
        }
        prefs.putPreference(Prefs.Keys.configFile, configFile);

        // Read in preferences from the config file
        prefs.readPreferences(configFile);

        // Read in preferences from the command line options
        for (Option opt : cmd.getOptions()) {
            // Apache CLI parser does not allow '.' within option names, so we have to convert
            // all '_' back to the '.' notation
            String key = opt.getArgName().replace("_", ".");
            String value = opt.getValue();
            prefs.putPreference(key, value);
        }
    } catch (ParseException e) {
        System.out.println("Error processing options: " + e.getMessage());
        new HelpFormatter().printHelp("Diff", options);
        Coordinator.exitWithReason("Error parsing command line options");
    }
}

From source file:org.Cherry.Main.Application.java

void process() {
    final Option httpPortOption = OptionBuilder.withArgName(CmdLineArg.httpPort.name()).hasArg()
            .withDescription("port to listen on [8080]").create(CmdLineArg.httpPort.name()),
            configFileOption = OptionBuilder.withArgName(CmdLineArg.configFile.name()).hasArg()
                    .withDescription("configuration file to use").create(CmdLineArg.configFile.name()),
            controllerNamespaces = OptionBuilder.withArgName(CmdLineArg.controllerNamespaces.name()).hasArg()
                    .withDescription("Controller namespace declarations")
                    .create(CmdLineArg.controllerNamespaces.name());

    final Options options = new Options();

    options.addOption(configFileOption);
    options.addOption(httpPortOption);/*from ww w.j  a  v  a  2  s . c  om*/
    options.addOption(controllerNamespaces);

    final CommandLineParser parser = new GnuParser();
    CommandLine commandLine = null;

    try {
        commandLine = parser.parse(options, INSTANCE_ARGUMENTS);
    } catch (final ParseException e) {
        error(e, "");

        throw new IllegalArgumentException(e);
    }

    final Option[] processedOptions = commandLine.getOptions();

    if (null != processedOptions && 0 < processedOptions.length) {

        final Map<CmdLineArg, Object> optionMap = new HashMap<CmdLineArg, Object>(processedOptions.length);

        CmdLineArg cmdLineArg;
        Boolean configFileDeclared = false;

        for (final Option option : processedOptions) {
            cmdLineArg = CmdLineArg.valueOf(option.getArgName());

            switch (cmdLineArg) {
            case configFile:
                if (configFileDeclared)
                    throw new IllegalArgumentException(
                            "Duplicated declaration for argument [" + cmdLineArg + "]");
                optionMap.put(cmdLineArg, option.getValue());
                configFileDeclared = true;
                break;

            case httpPort:
                if (configFileDeclared) {
                    warn("{}", "Configuration file foumd, all other options - including [" + cmdLineArg
                            + "] will be ignored!");
                    continue;
                }
                if (optionMap.containsKey(cmdLineArg))
                    throw new IllegalArgumentException(
                            "Duplicated declaration for argument [" + cmdLineArg + "]");
                optionMap.put(cmdLineArg, option.getValue());
                break;

            case controllerNamespaces:
                if (configFileDeclared) {
                    warn("{}", "Configuration file foumd, all other options - including [" + cmdLineArg
                            + "] will be ignored!");
                    continue;
                }
                if (optionMap.containsKey(cmdLineArg))
                    throw new IllegalArgumentException(
                            "Duplicated declaration for argument [" + cmdLineArg + "]");
                optionMap.put(cmdLineArg, option.getValue());
                break;

            default:
                warn("Will ignore [{}]=[{}]", cmdLineArg, option.getValue());
            }
        }

        final File cfgFile = new File((String) optionMap.get(CmdLineArg.configFile));

        if (!cfgFile.exists() || cfgFile.isDirectory())
            throw new IllegalArgumentException(
                    "Missing configuration file [" + cfgFile.getPath() + "] or it is a directory!");

        FileInputStream fis = null;
        Configuration configuration;

        try {
            fis = new FileInputStream(cfgFile);
            configuration = getObjectMapperService().readValue(fis, Configuration.class);
        } catch (final IOException e) {
            error(e, "");
            throw new IllegalArgumentException(e);
        } finally {
            try {
                fis.close();
            } catch (final IOException e) {
                error(e, "");
            }
        }

        debug("{}", configuration);

        getApplicationRepositoryService().put(ApplicationKey.Configuration,
                new ApplicationEntry<Configuration>(configuration));
    }
}

From source file:org.finra.dm.core.ArgumentParserTest.java

@Test
public void testGetUsageInformation() {
    List<Option> optionsIn = new ArrayList<>();
    optionsIn.add(new Option("a", "some_flag", false, "Some flag parameter"));
    optionsIn.add(new Option("b", "some_parameter", true, "Some parameter with an argument"));

    ArgumentParser argParser = new ArgumentParser("TestApp");
    argParser.addArgument(optionsIn.get(0), false);
    argParser.addArgument(optionsIn.get(1), true);

    String usage = argParser.getUsageInformation();

    assertNotNull(usage);/*w w  w.j av  a2  s  . co  m*/
    assertTrue(usage.contains(String.format("usage: %s", argParser.getApplicationName())));

    for (Option option : optionsIn) {
        assertTrue(usage.contains(String.format("-%s,", option.getOpt())));
        assertTrue(usage.contains(String.format("--%s", option.getLongOpt())));
        assertTrue(usage.contains(option.getDescription()));
        assertTrue(!option.hasArg() || usage.contains(String.format("<%s>", option.getArgName())));
    }
}

From source file:org.mifos.core.PseudoLocalizationGenerator.java

private static void missingOption(Option option) {
    fail("Missing required option: " + option.getArgName());
}

From source file:org.mitre.secretsharing.cli.cmd.AbstractCommand.java

protected String checkArgument(CommandLine cmd, Option o) {
    String invalid = "";
    if (!requiredArguments().contains(o))
        return invalid;
    if ((o.getOpt() == null || !cmd.hasOption(o.getOpt().charAt(0))) && !cmd.hasOption(o.getLongOpt())) {
        if (o.getOpt() != null)
            invalid += "-" + o.getOpt() + ",";
        invalid += "--" + o.getLongOpt();
        if (o.hasArg())
            invalid += " <" + o.getArgName() + ">";
        invalid += " is missing.\n";
    }// w w w  .j  a  va 2s.c  o m
    return invalid;
}

From source file:org.pz.platypus.commandline.ClParser.java

/**
 * Return all possible options as a sorted TreeMap of option, description
 *///from ww  w . ja  v a  2 s  .  c  o  m
public TreeMap<String, String> getAllOptions() {
    ClOptions clo = new ClOptions();
    TreeMap<String, String> optionsWithDesc = new TreeMap<String, String>();
    for (Option o : clo.getOptions()) {
        optionsWithDesc.put("-" + o.getOpt() + (o.hasArg() ? (" [" + o.getArgName() + "]") : ""),
                o.getDescription());
    }
    return (optionsWithDesc);
}