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.pixida.logtest.buildserver.RunIntegrationTests.java

boolean parseCommandLine(final String[] args) {
    final Options options = createOptions();
    final CommandLineParser parser = new DefaultParser();
    try {//from ww w. j a  va2s.  com
        final CommandLine params = parser.parse(options, args);
        if (params.hasOption(HELP_SWITCH)) {
            printHelp(options);
            return false;
        }

        this.applyVerbositySwitch(params);

        this.loadDefaultParameters(params);

        this.configuredExecutions = this.groupAutomatonsByTraceFile(params);

        final String param = params.getOptionValue(REPORT_SWITCH);
        if (param != null) {
            this.jUnitReportTarget = new File(param);
        }

        try {
            if (params.hasOption(LOG_READER_CONFIG_SWITCH)) {
                this.logReaderConfigFromCommandLine = new JSONObject(
                        params.getOptionValue(LOG_READER_CONFIG_SWITCH));
            }
        } catch (final JSONException jsonEx) {
            throw new ParseException("Failed to parse log reader configuration JSON data from command line: "
                    + jsonEx.getMessage());
        }

        File logReaderConfigurationFile = null;
        try {
            if (params.hasOption(LOG_READER_CONFIG_FILE_SWITCH)) {
                logReaderConfigurationFile = new File(params.getOptionValue(LOG_READER_CONFIG_FILE_SWITCH));
                this.logReaderConfigFromFile = new JSONObject(
                        IOUtils.toString(logReaderConfigurationFile.toURI(), StandardCharsets.UTF_8));
                LOG.debug("Using log reader configuration file '{}'",
                        logReaderConfigurationFile.getCanonicalPath());
            } else {
                LOG.debug("No log reader configuration file set.");
            }
        } catch (final JSONException jsonEx) {
            throw new ParseException(
                    "Failed to parse log reader configuration JSON data from file: " + jsonEx.getMessage());
        } catch (final IOException e) {
            throw new ParseException("Failed to read log reader configuration file '"
                    + logReaderConfigurationFile.getAbsolutePath() + "': " + e.getMessage());
        }
    } catch (final ParseException e) {
        // CHECKSTYLE:OFF We intentionally print to STDERR here
        System.err.println(e.getMessage());
        System.err.println();
        printHelp(options);
        // CHECKSTYLE:ON

        // Abort with failure - build server job must not succeed if the calling convention is erroneous
        throw new ExitWithFailureException();
    }

    return true;
}

From source file:edu.illinois.cs.cogcomp.datalessclassification.ta.ESADatalessAnnotator.java

public static CommandLine getCMDOpts(String[] args) {
    Options options = new Options();

    Option configOpt = new Option("c", "config", true, "config file path");
    configOpt.setRequired(false);//from   www  .ja va2  s . c om
    options.addOption(configOpt);

    Option testFileOption = new Option("f", "testFile", true, "File to annotate using Dataless");
    testFileOption.setRequired(false);
    options.addOption(testFileOption);

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();

    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        formatter.printHelp("utility-name", options);

        System.exit(1);
        return cmd;
    }

    return cmd;
}

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

@Test
public void testArgs_invalidInternalCombination()
        throws NoSuchMethodException, ParseException, InvocationTargetException, IllegalAccessException {
    CliParser cliParser = new CliParser();
    Method argsValidation = cliParser.getClass().getDeclaredMethod("areCmdArgsValid", CommandLine.class);
    argsValidation.setAccessible(true);//w  w w. jav a  2s . c  o m
    CommandLineParser parser = new DefaultParser();

    CommandLine cmdArgs = parser.parse(options, new String[] { "-i", "-w", "1002", "publicApi.xml" });
    Boolean result = (Boolean) argsValidation.invoke(cliParser, cmdArgs);
    Assert.assertTrue(result);

    cmdArgs = parser.parse(options, new String[] { "-i", "-b", "1002", "publicApi.xml" });
    result = (Boolean) argsValidation.invoke(cliParser, cmdArgs);
    Assert.assertFalse(result);
}

From source file:com.coprtools.cli.ApacheCliConsole.java

@Override
public void parse() throws ArgumentParseException {
    CommandLineParser parser = new DefaultParser();
    try {/*w  w  w .j  av  a  2s .  c  o  m*/
        this.cmd = parser.parse(options, this.arguments);
    } catch (ParseException e) {
        throw new ArgumentParseException(e.getMessage());
    }
}

From source file:io.joynr.performance.EchoProviderInvocationParameters.java

private CommandLine parseCommandLineArgs(String[] args) throws ParseException {
    Options options = new Options();

    options.addOption(Option.builder("d").longOpt(CMDLINE_OPTIONNAME_DOMAINNAME).required(true).hasArg()
            .argName("domain").type(String.class).desc("Provider domain").build());

    options.addOption(Option.builder("s").longOpt(CMDLINE_OPTIONNAME_SCOPE).required(false).hasArg()
            .argName("scope").type(ProviderScope.class)
            .desc("Scope of the provider. Can be LOCAL or GLOBAL. Default is " + providerScope.toString())
            .build());//  w  w  w .ja  v a 2s. c o  m

    options.addOption(Option.builder("r").longOpt(CMDLINE_OPTIONNAME_RUNTIMECFG).required(false).hasArg()
            .argName("runtime").type(RuntimeConfig.class)
            .desc("Runtime module configuration. "
                    + "At the moment only IN_PROCESS_CC is supported. Default is " + runtimeConfig.toString())
            .build());

    options.addOption(Option.builder("b").longOpt(CMDLINE_OPTIONNAME_BACKENDCFG).required(false).hasArg()
            .argName("backend").type(BackendConfig.class)
            .desc("Backend configuration. At the moment only MQTT is supported. Default is "
                    + backendConfig.toString())
            .build());

    options.addOption(Option.builder("mbu").longOpt(CMDLINE_OPTIONNAME_MQTTBROKERURI).required(false).hasArg()
            .argName("uri").type(String.class).desc("MQTT broker URI. Default is " + mqttBrokerUri).build());

    CommandLineParser parser = new DefaultParser();

    try {
        return parser.parse(options, args);
    } catch (ParseException exception) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("PerformanceTestEchoProviderApplication", "", options, "", true);
        throw exception;
    }
}

From source file:dumptspacket.Main.java

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

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

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

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

    final Option pidsOption = Option.builder("p").required().longOpt("pids")
            .desc("pid(?16?)").type(String.class).hasArgs().build();

    Options opts = new Options();
    opts.addOption(fileNameOption);//from   w  w  w  .  j  a  v a2  s .c o  m
    opts.addOption(limitOption);
    opts.addOption(pidsOption);
    CommandLineParser parser = new DefaultParser();
    CommandLine cl;
    HelpFormatter help = new HelpFormatter();

    try {

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

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

        // handlet destination option.
        Long xl = null;
        try {
            xl = Long.parseUnsignedLong(cl.getOptionValue(limitOption.getOpt()));
        } catch (NumberFormatException e) {
            xl = null;
        } finally {
            limit = xl;
        }

        Set<Integer> x = new HashSet<>();
        List<String> ls = new ArrayList<>();
        ls.addAll(Arrays.asList(cl.getOptionValues(pidsOption.getOpt())));
        for (String s : ls) {
            try {
                x.add(Integer.parseUnsignedInt(s, 16));
            } catch (NumberFormatException e) {
                throw new ParseException(e.getMessage());
            }
        }
        pids = Collections.unmodifiableSet(x);

        System.out.println("Starting application...");
        System.out.println("filename   : " + fileName);
        System.out.println("limit : " + limit);
        System.out.println("pids : " + dumpSet(pids));

        // your code
        TsReader reader;
        if (limit == null) {
            reader = new TsReader(new File(fileName), pids);
        } else {
            reader = new TsReader(new File(fileName), pids, limit);
        }

        Map<Integer, List<TsPacketParcel>> ret = reader.getPackets();
        try {
            for (Integer pid : ret.keySet()) {

                FileWriter writer = new FileWriter(fileName + "_" + Integer.toHexString(pid) + ".txt");

                for (TsPacketParcel par : ret.get(pid)) {
                    String text = Hex.encodeHexString(par.getPacket().getData());
                    writer.write(text + "\n");

                }
                writer.flush();
                writer.close();
            }
        } catch (IOException ex) {
            LOG.fatal("", ex);
        }

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

From source file:gate.plugin.learningframework.engines.Parms.java

/**
 * Create a Parms object that contains the parsed values from the parmString.
 * The names are strings which consist of three parts, separated by colons: a short name,
 * a long name, and one of //from  ww w  .  j a  v a 2 s  .c o  m
 * b if the parameter is boolean and does not have a value, 
 * s if the parameter has a string  value,
 * d if the parameter has a double value or i if the parameter has an integer value.
 * B is used for a parameter with an excplicit boolean value.
 * If the value cannot be parsed to the given type, it is equivalent to the parameter missing.
 * @param names
 * @param parmString
 * @return 
 */
public Parms(String parmString, String... names) {
    // just treat a parmString of null equal to the empty string: do nothing
    if (parmString == null || parmString.isEmpty())
        return;
    List<String> longNames = new ArrayList<String>();
    List<String> types = new ArrayList<String>();
    Options options = new Options();
    for (String name : names) {
        String[] info = name.split(":");
        longNames.add(info[1]);
        types.add(info[2]);
        options.addOption(info[0], info[1], info[2].equals("b") ? false : true, "");
    }
    DefaultParser parser = new DefaultParser();
    parser.setIgnoreUnknownOptions(true);
    CommandLine cli = null;
    try {
        cli = parser.parse(options, parmString.split("\\s+"));
    } catch (ParseException ex) {
        //System.err.println("Parsing error");
        //ex.printStackTrace(System.err);
        logger.error("Could not parse parameters: " + parmString, ex);
    }
    if (cli != null) {
        for (int i = 0; i < longNames.size(); i++) {
            String longName = longNames.get(i);
            String type = types.get(i);
            Object value = null;
            boolean haveIt = cli.hasOption(longName);
            String optVal = cli.getOptionValue(longName);
            //System.err.println("OPTION value for "+longName+" is "+optVal+" class is "+((optVal==null)? "null" : optVal.getClass())+" have it: "+haveIt);
            if (haveIt) {
                if (type.equals("b")) {
                    value = haveIt;
                } else if (type.equals("s")) {
                    value = optVal;
                } else if (type.equals("d")) {
                    try {
                        value = Double.parseDouble(optVal);
                    } catch (Exception ex) {
                        System.err.println("Parms: cannot parse value as double, setting to null: " + optVal);
                    }
                } else if (type.equals("i")) {
                    try {
                        value = Integer.parseInt(optVal);
                    } catch (Exception ex) {
                        System.err.println("Parms: cannot parse value as int, setting to null: " + optVal);
                    }
                } else if (type.equals("B")) {
                    value = Boolean.parseBoolean(optVal);
                } else {
                    throw new GateRuntimeException("Not a valid type indicator for Parrms: " + type);
                }
            }
            parmValues.put(longName, value);
        }
    }
}

From source file:com.acmutv.ontoqa.ui.CliService.java

/**
 * Returns command line options/arguments parsing utility.
 * @param argv The command line arguments passed to the main method.
 * @return The command line options/arguments parsing utility.
 * @see CommandLineParser/*from   ww  w.ja  va 2s .com*/
 * @see CommandLine
 */
private static CommandLine getCommandLine(String argv[]) {
    CommandLineParser cmdParser = new DefaultParser();
    CommandLine cmd = null;

    try {
        cmd = cmdParser.parse(BaseOptions.getInstance(), argv);
    } catch (ParseException e) {
        LOGGER.error(e.getMessage());
        printHelp();
    }

    return cmd;
}

From source file:com.github.butterbrother.s2s_connection_checker.CmdLine.CmdLineParser.java

/**
 * ?   ?./*  w  ww . j a  va 2s  . co  m*/
 *
 * @param args   ?
 * @return ?  ,  ??   ?
 * @throws Exception ?, ?   .   
 *                     ??.
 */
public CmdLineOpts parseCmdLine(String... args) throws Exception {
    try {
        CommandLine commandLine = new DefaultParser().parse(cmdLineOptions, args, true);

        String configFileStringPath = commandLine.getOptionValue('c');
        Path configFilePath = Paths.get(configFileStringPath);

        if (Files.notExists(configFilePath))
            throw new IOException("Configuration file \"" + configFileStringPath + "\" not exists.");

        if (!Files.isRegularFile(configFilePath))
            throw new IOException("Configuration file \"" + configFileStringPath + "\" is not regular file.");

        boolean serverMode = commandLine.hasOption('s');

        boolean debugMode = commandLine.hasOption('d');

        return new CmdLineOpts(serverMode, configFilePath, debugMode);
    } catch (ParseException | IOException err) {
        throw new Exception(err.getMessage());
    }
}