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:averroes.options.AverroesOptions.java

/**
 * Process the input arguments of Averroes.
 * // ww  w  .j a  va  2 s.co m
 * @param args
 */
public static void processArguments(String[] args) {
    try {
        cmd = new DefaultParser().parse(options, args);

        // Do we need to print out help messages?
        if (cmd.hasOption(help.getOpt())) {
            help();
        }
    } catch (ParseException e) {
        e.printStackTrace();
        help();
    }
}

From source file:com.hp.mqm.clt.CliParserTest.java

@Test
public void testArgs_invalidIntegerValue() throws ParseException {
    CommandLineParser parser = new DefaultParser();
    CommandLine commandLine = parser.parse(options, new String[] { "-i", "-r", "invalidIntegerValue" });
    Assert.assertTrue(commandLine.hasOption("r"));
    try {/* w  w  w.j  av  a  2  s.  c o m*/
        commandLine.getParsedOptionValue("r");
        Assert.fail();
    } catch (ParseException e) {
        Assert.assertEquals("For input string: \"invalidIntegerValue\"", e.getMessage());
    }
}

From source file:epgtools.dumpepgfromts.Main.java

public void start(String[] args) throws org.apache.commons.cli.ParseException {
    final String fileName;
    final Long limit;

    System.out.println("args   : " + dumpArgs(args));

    final Option fileNameOption = Option.builder("f").required().longOpt("tsfile").desc("ts")
            .hasArg().type(String.class).build();

    final Option limitOption = Option.builder("l").required(false).longOpt("limit").desc(
            "??(???????100000000)")
            .hasArg().type(Long.class).build();

    Options opts = new Options();
    opts.addOption(fileNameOption);/*from   ww w .j  ava 2s. c  o m*/
    //        opts.addOption(PhysicalChannelNumberOption);
    opts.addOption(limitOption);
    CommandLineParser parser = new DefaultParser();
    CommandLine cl;
    HelpFormatter help = new HelpFormatter();

    try {

        // parse options
        cl = parser.parse(opts, args);

        fileName = cl.getOptionValue(fileNameOption.getOpt());
        if (fileName == null) {
            throw new ParseException("????????");
        }

        Long xl = null;
        try {
            xl = Long.parseUnsignedLong(cl.getOptionValue(limitOption.getOpt()));
        } catch (NumberFormatException e) {
            xl = 10000000L;
        } finally {
            limit = xl;
        }

        LOG.info("Starting application...");
        LOG.info("filename   : " + fileName);
        LOG.info("limit : " + limit);

        FileLoader fl = new FileLoader(new File(fileName), limit);
        fl.load();

        //???
        Set<Channel> ch = fl.getChannels();
        LOG.info("?? = " + ch.size());
        for (Channel c : ch) {
            LOG.info(
                    "***********************************************************************************************************************************************************************************************************");
            LOG.info(c.getString());
            LOG.info(
                    "***********************************************************************************************************************************************************************************************************");
        }

        //            ?
        Set<Programme> p = fl.getProgrammes();
        LOG.info(" = " + p.size());
        for (Programme pg : p) {
            LOG.info(
                    "***********************************************************************************************************************************************************************************************************");
            LOG.info(pg.getString());
            LOG.info(
                    "***********************************************************************************************************************************************************************************************************");
        }

        System.gc();

    } catch (ParseException e) {
        // print usage.
        help.printHelp("My Java Application", opts);
        throw e;
    } catch (FileNotFoundException ex) {
        LOG.fatal("?????", ex);
    }
}

From source file:com.nishtahir.alang.ALang.java

/**
 * @param args command line arguments/*  ww  w  .j  a  va2  s . co  m*/
 * @return List of files to parse
 * @throws ParseException {@link ParseException}
 */
private List<String> parseCommandLineArguments(final String[] args) throws ParseException {
    CommandLineParser commandLineParser = new DefaultParser();

    CommandLine commandLine = commandLineParser.parse(commandLineOptions, args);

    if (commandLine.hasOption("h")) {
        displayHelpInformation();
    }

    if (commandLine.hasOption("version")) {
        displayVersionInformation();
    }

    if (commandLine.hasOption("v")) {
        setVerboseOutput(true);
    }

    if (commandLine.hasOption("c")) {
        switch (commandLine.getOptionValue("c")) {
        case "pico":
            visitor = new ALangPicoVisitor();
        }
    }

    return commandLine.getArgList();

}

From source file:edu.cmu.sv.modelinference.tracestool.STLog2TracesHandler.java

@Override
public Collection<TimedTrace<GridState>> process(String logFile, String logType, String[] additionalCmdArgs)
        throws LogProcessingException {
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;/* w ww  .  jav a2  s. c om*/
    try {
        cmd = parser.parse(cmdOpts, additionalCmdArgs, false);
    } catch (ParseException e) {
        logger.error(e.getMessage());
        System.err.println(e.getMessage());
        Util.printHelpAndExit(STLog2TracesHandler.class, cmdOpts);
    }

    GridPartitions parts = null;
    if (cmd.hasOption(GRID_DIM)) {
        String partStr = cmd.getOptionValue(GRID_DIM).trim();
        try {
            parts = STConfig.extractGridPartitions(partStr);
        } catch (ParseException e) {
            throw new LogProcessingException(e);
        }
    } else
        parts = GridPartitions.createDefault();

    LogEntryFilter<STEntry> filter = LogEntryFilter.<STEntry>EVERYTHING();

    LogReader<STEntry> reader = new SequentialLogReader<>(new STParser(), filter);
    GridDimensionsFinder d;
    try {
        d = new GridDimensionsFinder();
    } catch (IOException e) {
        throw new LogProcessingException(e);
    }
    Dimensions dim;
    try {
        dim = d.start(new File(logFile));
    } catch (IOException e) {
        throw new LogProcessingException(e);
    }
    STGridStateFactory stateGen = new STGridStateFactory(new Coord2d(dim.minX, dim.minY),
            new Coord2d(dim.maxX, dim.maxY), parts.horiz, parts.vert);

    TraceGenerator<STEntry, GridState> traceGenerator = new TraceGenerator<>(reader, stateGen);
    Collection<TimedTrace<GridState>> traces;
    try {
        traces = traceGenerator.computeTraces(new File(logFile));
    } catch (IOException e) {
        throw new LogProcessingException(e);
    }

    return traces;
}

From source file:act.installer.wikipedia.ImportantChemicalsWikipedia.java

public static void main(final String[] args) throws IOException {

    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());/*w  ww . ja v a2s . co  m*/
    }

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

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(ImportantChemicalsWikipedia.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        return;
    }

    String inputPath = cl.getOptionValue(OPTION_WIKIPEDIA_DUMP_FULL_PATH, "1000");
    String outputPath = cl.getOptionValue(OPTION_OUTPUT_PATH, "1000");
    Boolean outputTSV = cl.hasOption(OPTION_TSV_OUTPUT);

    ImportantChemicalsWikipedia importantChemicalsWikipedia = new ImportantChemicalsWikipedia();

    try (BufferedReader br = new BufferedReader(new FileReader(inputPath))) {
        String line;
        while ((line = br.readLine()) != null) {
            importantChemicalsWikipedia.processLine(line);
        }
    } catch (IOException e) {
        LOGGER.error(e);
    }

    if (outputTSV) {
        importantChemicalsWikipedia.writeToTSV(outputPath);
    } else {
        importantChemicalsWikipedia.writeToJSON(outputPath);
    }
}

From source file:com.emc.ecs.sync.config.ConfigUtilTest.java

@Test
public void testCliParse() throws Exception {
    String[] args = { "--my-value", "value", "--my-num", "7", "--no-negative-flag", "--my-enum", "TwoFoo",
            "--my-array", "one", "--my-array", "two", "--my-array", "three", "--my-flag" };

    ConfigWrapper<Foo> wrapper = ConfigUtil.wrapperFor(Foo.class);

    CommandLine commandLine = new DefaultParser().parse(wrapper.getOptions(), args);

    Foo foo = new Foo();
    foo.setMyValue("value");
    foo.setMyNum(7);//from  w w  w.  j a v a  2  s. c o  m
    foo.setMyFlag(true);
    foo.setNegativeFlag(false);
    foo.setMyEnum(FooType.TwoFoo);
    foo.setMyArray(new String[] { "one", "two", "three" });

    Foo foo2 = wrapper.parse(commandLine);

    Assert.assertEquals(foo.getMyValue(), foo2.getMyValue());
    Assert.assertEquals(foo.getMyNum(), foo2.getMyNum());
    Assert.assertEquals(foo.isMyFlag(), foo2.isMyFlag());
    Assert.assertEquals(foo.isNegativeFlag(), foo2.isNegativeFlag());
    Assert.assertEquals(foo.getMyEnum(), foo2.getMyEnum());
    Assert.assertArrayEquals(foo.getMyArray(), foo2.getMyArray());
}

From source file:io.github.retz.scheduler.MesosFrameworkLauncher.java

static Configuration parseConfiguration(String[] argv) throws ParseException, IOException, URISyntaxException {
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(OPTIONS, argv); //argumentList.getStandardAsArray());

    // This default path must match the prefix in build.gradle
    String configFile = cmd.getOptionValue(OPT_CONFIG.getOpt(), "/opt/retz-server/etc/retz.properties");

    Configuration conf = new Configuration(new FileConfiguration(configFile));
    LOG.info("Binding as {}", conf.fileConfig.getUri()); // TODO hostname, protocol

    return conf;//from   w  ww .jav a 2  s . c  om
}

From source file:edu.cmu.sv.modelinference.eventtool.charting.STEventChartHandler.java

@Override
public ValueTrackerProducer<?, DataPointCollection, ?> process(String logFile, String logType,
        String[] additionalCmdArgs) {
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;//from  w  w w .ja v  a2  s  .co m
    try {
        cmd = parser.parse(cmdOpts, additionalCmdArgs, false);
    } catch (ParseException exp) {
        logger.error(exp.getMessage());
        System.err.println(exp.getMessage());
        Util.printHelpAndExit(STEventChartHandler.class, cmdOpts);
    }

    try {
        trackedField = FIELD.valueOf(cmd.getOptionValue(FIELD_OPTS_ARG).toUpperCase());
    } catch (Exception exp) {
        logger.error(exp.getMessage());
        System.err.println(exp.getMessage());
        Util.printHelpAndExit(STEventChartHandler.class, cmdOpts);
    }

    if (cmd.hasOption(FLIGHTNAME_OPTS_ARG)) {
        hasFlightName = true;
        flightName = cmd.getOptionValue(FLIGHTNAME_OPTS_ARG); //e.g. USA5596
    }

    LogReader<STEntry> reader = null;
    if (hasFlightName) {
        LogEntryFilter<STEntry> filter = new LogEntryFilter<STEntry>() {
            @Override
            public boolean submitForProcessing(STEntry entry) {
                if (entry.getCallSign().equals(flightName)) {
                    return true;
                }
                return false;
            }
        };
        reader = new SequentialLogReader<>(new STParser(), filter);
    } else
        reader = new SequentialLogReader<>(new STParser());

    return new STValueTracker.STDataPointsGenerator(trackedField, reader);
}

From source file:gobblin.cli.Cli.java

/**
 * Parse and execute the appropriate command based on the args.
 * The general flow looks like this:// ww w. j  a v a  2 s.  c  o  m
 *
 * 1. Parse a set of global options (eg host/port for the admin server)
 * 2. Parse out the command name
 * 3. Pass the global options and any left over parameters to a command handler
 */
public void parseAndExecuteCommand() {
    CommandLineParser parser = new DefaultParser();
    try {
        CommandLine parsedOpts = parser.parse(this.options, this.args, true);
        GlobalOptions globalOptions = createGlobalOptions(parsedOpts);

        // Fetch the command and fail if there is ambiguity
        String[] remainingArgs = parsedOpts.getArgs();
        if (remainingArgs.length == 0) {
            printHelpAndExit("Command not specified!");
        }

        String commandName = remainingArgs[0].toLowerCase();
        remainingArgs = remainingArgs.length > 1 ? Arrays.copyOfRange(remainingArgs, 1, remainingArgs.length)
                : new String[] {};

        Command command = commandList.get(commandName);
        if (command == null) {
            System.out.println("Command " + commandName + " not known.");
            printHelpAndExit();
        } else {
            command.execute(globalOptions, remainingArgs);
        }
    } catch (ParseException e) {
        printHelpAndExit("Ran into an error parsing args.");
    }
}