Example usage for org.apache.commons.cli DefaultParser DefaultParser

List of usage examples for org.apache.commons.cli DefaultParser DefaultParser

Introduction

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

Prototype

DefaultParser

Source Link

Usage

From source file:de.topobyte.utilities.apache.commons.cli.TestOptions.java

License:asdf

@Test
public void testShortAndLong() throws ParseException {
    Options options = new Options();
    OptionHelper.add(options, "f", "foo-boo", true, true, "an option");
    OptionHelper.add(options, "b", "bar-bar", true, true, "another option");

    String[] arguments = new String[] { "-f", "asdf", "--bar-bar", "test" };
    CommandLine line = new DefaultParser().parse(options, arguments);

    StringOption f = ArgumentHelper.getString(line, "f");
    StringOption fooboo = ArgumentHelper.getString(line, "foo-boo");
    StringOption b = ArgumentHelper.getString(line, "b");
    StringOption barbar = ArgumentHelper.getString(line, "bar-bar");

    assertTrue(f.hasValue());/*from w  w  w .  j  a  v  a  2  s . co m*/
    assertTrue(fooboo.hasValue());
    assertTrue(b.hasValue());
    assertTrue(barbar.hasValue());
    assertEquals("asdf", f.getValue());
    assertEquals("asdf", fooboo.getValue());
    assertEquals("test", b.getValue());
    assertEquals("test", barbar.getValue());
}

From source file:com.geeksaga.light.tools.Main.java

private CommandLine parseOption(String[] arguments) {
    CommandLineParser commandLineParser = new DefaultParser();

    try {//  ww  w  .j a  v a2 s  . co  m
        return commandLineParser.parse(getOptions(), arguments);
    } catch (ParseException parseException) {
        System.err.println("Parsing failed.  Reason: " + parseException.getMessage());
    }

    return null;
}

From source file:com.github.sakserv.lslock.cli.parser.LockListerCliParser.java

/**
 * Parses the passed in command line arguments
 *///from  ww w .  jav  a  2  s  . c o m
@Override
public void parse() {
    CommandLineParser commandLineParser = new DefaultParser();

    try {
        CommandLine commandLine = commandLineParser.parse(options, args);

        // Handle the help option
        if (commandLine.hasOption("h")) {
            help(options, NAME);
        }

        // Handle the lock directory option
        if (commandLine.hasOption("d")) {
            lockDirectory = new File(commandLine.getOptionValue("d"));
        } else {
            LOG.error("The directory option is required");
            help(options, NAME);
        }

    } catch (ParseException e) {
        LOG.error("Failed to parse command line args");
        help(options, NAME);
    }
}

From source file:com.twitter.heron.metricsmgr.MetricsManager.java

public static void main(String[] args) throws Exception {
    final Options options = constructOptions();
    final Options helpOptions = constructHelpOptions();

    final CommandLineParser parser = new DefaultParser();

    // parse the help options first.
    CommandLine cmd = parser.parse(helpOptions, args, true);
    if (cmd.hasOption("h")) {
        usage(options);//from   w  w  w  .  jav  a  2 s . co  m
        return;
    }

    try {
        // Now parse the required options
        cmd = parser.parse(options, args);
    } catch (ParseException pe) {
        usage(options);
        throw new RuntimeException("Error parsing command line options: ", pe);
    }

    String metricsmgrId = cmd.getOptionValue("id");
    int metricsPort = Integer.parseInt(cmd.getOptionValue("port"));
    String topologyName = cmd.getOptionValue("topology");
    String topologyId = cmd.getOptionValue("topology-id");
    String systemConfigFilename = cmd.getOptionValue("system-config-file");
    String overrideConfigFilename = cmd.getOptionValue("override-config-file");
    String metricsSinksConfigFilename = cmd.getOptionValue("sink-config-file");
    String cluster = cmd.getOptionValue("cluster");
    String role = cmd.getOptionValue("role");
    String environment = cmd.getOptionValue("environment");

    SystemConfig systemConfig = SystemConfig.newBuilder(true).putAll(systemConfigFilename, true)
            .putAll(overrideConfigFilename, true).build();

    // Add the SystemConfig into SingletonRegistry
    SingletonRegistry.INSTANCE.registerSingleton(SystemConfig.HERON_SYSTEM_CONFIG, systemConfig);

    // Init the logging setting and redirect the stdout and stderr to logging
    // For now we just set the logging level as INFO; later we may accept an argument to set it.
    Level loggingLevel = Level.INFO;
    String loggingDir = systemConfig.getHeronLoggingDirectory();

    // Log to file and TMaster
    LoggingHelper.loggerInit(loggingLevel, true);
    LoggingHelper.addLoggingHandler(LoggingHelper.getFileHandler(metricsmgrId, loggingDir, true,
            systemConfig.getHeronLoggingMaximumSize(), systemConfig.getHeronLoggingMaximumFiles()));
    LoggingHelper.addLoggingHandler(new ErrorReportLoggingHandler());

    LOG.info(String.format(
            "Starting Metrics Manager for topology %s with topologyId %s with "
                    + "Metrics Manager Id %s, Merics Manager Port: %d, for cluster/role/env %s.",
            topologyName, topologyId, metricsmgrId, metricsPort,
            String.format("%s/%s/%s", cluster, role, environment)));

    LOG.info("System Config: " + systemConfig);

    // Populate the config
    MetricsSinksConfig sinksConfig = new MetricsSinksConfig(metricsSinksConfigFilename);

    LOG.info("Sinks Config:" + sinksConfig.toString());

    MetricsManager metricsManager = new MetricsManager(topologyName, cluster, role, environment,
            METRICS_MANAGER_HOST, metricsPort, metricsmgrId, systemConfig, sinksConfig);
    metricsManager.start();

    LOG.info("Loops terminated. Metrics Manager exits.");
}

From source file:net.sf.jabref.cli.JabRefCLI.java

public JabRefCLI(String[] args) {

    Options options = getOptions();/*  w w  w.  j  a  v a  2s  .  c  o  m*/

    try {
        this.cl = new DefaultParser().parse(options, args);
        this.leftOver = cl.getArgs();
    } catch (ParseException e) {
        LOGGER.warn("Problem parsing arguments", e);

        this.printUsage();
        throw new RuntimeException();
    }
}

From source file:com.stratuscom.harvester.deployer.CommonsCLITest.java

/**
 * An exploratory test to confirm the expected behaviour of the Apache Commons
 * CLI parser.// ww  w.j a  v a2s. c  om
 * 
 * @throws Exception 
 */
@Test
public void testOptions() throws Exception {
    Options options = new Options();

    Option courses = Option.builder("with").argName("with").hasArgs().valueSeparator(',')
            .desc("comma-separated list of applications to run with the main app").build();
    options.addOption(courses);
    CommandLineParser parser = new DefaultParser();
    CommandLine commandLine = null;
    String[] args = { "-with", "reggie,test-module,A" };
    commandLine = parser.parse(options, args);
    assertEquals(3, commandLine.getOptionValues("with").length);

}

From source file:com.joowon.returnA.classifier.cli.ClassifierCliParser.java

public ClassifierCliParser(String[] args) {
    this();//w w w . j  a  va2s .c o  m

    try {
        CommandLineParser parser = new DefaultParser();
        commandLine = parser.parse(options, args);
    } catch (ParseException e) {
        e.printStackTrace();
        printHelp();
    }
    parse();
}

From source file:com.sumologic.commandline.SumoReportCommandParser.java

public void parse(String[] args) {
    CommandLineParser parser = new DefaultParser();
    try {//from ww w.j ava2  s . co m
        parseCommandLine(args, parser);
    } catch (ParseException e) {
        LOGGER.error("Unable to parse arguments!");
    } catch (ReportGenerationException e) {
        LOGGER.error("Unable to generate report!");
        LOGGER.error(e);
    } catch (IOException e) {
        LOGGER.error("Unable to open report config!");
        LOGGER.error(e);
    }
}

From source file:act.installer.UniprotInstaller.java

public static void main(String[] args)
        throws IOException, SAXException, ParserConfigurationException, CompoundNotFoundException {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());/*from w  w  w .  j  ava 2s  .  c  om*/
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        LOGGER.error("Argument parsing failed: %s", e.getMessage());
        HELP_FORMATTER.printHelp(UniprotInstaller.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(UniprotInstaller.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    File uniprotFile = new File(cl.getOptionValue(OPTION_UNIPROT_PATH));
    String dbName = cl.getOptionValue(OPTION_DB_NAME);

    if (!uniprotFile.exists()) {
        String msg = String.format("Uniprot file path is null");
        LOGGER.error(msg);
        throw new RuntimeException(msg);
    } else {
        MongoDB db = new MongoDB("localhost", 27017, dbName);

        DBIterator iter = db.getDbIteratorOverOrgs();

        Iterator<Organism> orgIterator = new Iterator<Organism>() {
            @Override
            public boolean hasNext() {
                boolean hasNext = iter.hasNext();
                if (!hasNext)
                    iter.close();
                return hasNext;
            }

            @Override
            public Organism next() {
                DBObject o = iter.next();
                return db.convertDBObjectToOrg(o);
            }

        };

        OrgMinimalPrefixGenerator prefixGenerator = new OrgMinimalPrefixGenerator(orgIterator);
        Map<String, String> minimalPrefixMapping = prefixGenerator.getMinimalPrefixMapping();

        UniprotInstaller installer = new UniprotInstaller(uniprotFile, db, minimalPrefixMapping);
        installer.init();
    }
}

From source file:alluxio.cli.Command.java

/**
 * Parses and validates the arguments.//w  ww .jav a  2 s .  c o m
 *
 * @param args the arguments for the command, excluding the command name
 * @return the parsed command line object
 * @throws InvalidArgumentException when arguments are not valid
 */
default CommandLine parseAndValidateArgs(String... args) throws InvalidArgumentException {
    CommandLine cmdline;
    Options opts = getOptions();
    CommandLineParser parser = new DefaultParser();
    try {
        cmdline = parser.parse(opts, args);
    } catch (ParseException e) {
        throw new InvalidArgumentException(String.format("Failed to parse args for %s", getCommandName()), e);
    }
    validateArgs(cmdline);
    return cmdline;
}