Example usage for org.apache.commons.cli CommandLineParser parse

List of usage examples for org.apache.commons.cli CommandLineParser parse

Introduction

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

Prototype

CommandLine parse(Options options, String[] arguments) throws ParseException;

Source Link

Document

Parse the arguments according to the specified options.

Usage

From source file:cnxchecker.Server.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption("p", "port", true, "TCP port to bind to (random by default)");
    options.addOption("h", "help", false, "Print help");

    CommandLineParser parser = new GnuParser();
    try {//from w  w  w  .j  ava2s. co m
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("h")) {
            HelpFormatter hf = new HelpFormatter();
            hf.printHelp("server", options);
            System.exit(0);
        }

        int port = 0;
        if (cmd.hasOption("p")) {
            try {
                port = Integer.parseInt(cmd.getOptionValue("p"));
            } catch (NumberFormatException e) {
                printAndExit("Invalid port number " + cmd.getOptionValue("p"));
            }

            if (port < 0 || port > 65535) {
                printAndExit("Invalid port number " + port);
            }
        }

        Server server = new Server(port);
        server.doit();
    } catch (ParseException e) {
        printAndExit("Failed to parse options: " + e.getMessage());
    }
}

From source file:com.genentech.chemistry.openEye.apps.SDFConformerSampler.java

/**
 * @param args/*from   w w w. j av  a  2 s .  co m*/
 */
public static void main(String... args) throws IOException { // create command line Options object
    Options options = new Options();
    Option opt = new Option(OPT_INFILE, true,
            "input file oe-supported Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_OUTFILE, true, "output file oe-supported. Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_MAX_CONFS, true, "Maximum number of conformations per input.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_TORSION_FILE, true, "Optional: to overwrite torsion definition file.");
    opt.setRequired(false);
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }
    args = cmd.getArgs();

    if (cmd.hasOption("d")) {
        System.err.println("Start debugger and press return:");
        new BufferedReader(new InputStreamReader(System.in)).readLine();
    }

    String inFile = cmd.getOptionValue(OPT_INFILE);
    String outFile = cmd.getOptionValue(OPT_OUTFILE);
    String smartsFile = cmd.getOptionValue(OPT_TORSION_FILE);
    long maxConfs = Long.parseLong(cmd.getOptionValue(OPT_MAX_CONFS));

    SDFConformerSampler scanner = new SDFConformerSampler(smartsFile, outFile, maxConfs);

    scanner.run(inFile);
    scanner.close();
}

From source file:io.github.the28awg.okato.App.java

public static void main(String[] args) {
    Options options = new Options();

    options.addOption(Option.builder().longOpt("token").hasArg().required().argName("token")
            .desc(" ? ?  ??").build());
    options.addOption(Option.builder("t").longOpt("type").hasArg().required().argName("type")
            .desc("  [city, street, building]").build());
    options.addOption(Option.builder("q").longOpt("query").hasArg().argName("query")
            .desc(" ? ?  ").build());
    options.addOption(Option.builder("c").longOpt("city_id").hasArg().argName("city_id")
            .desc("  (? )").build());
    options.addOption(Option.builder("s").longOpt("street_id").hasArg().argName("street_id")
            .desc(" ").build());

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;//ww w.  j  av  a 2s  .  c  om

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        formatter.printHelp("okato", options);
        System.exit(1);
        return;
    }

    AddressFactory.token(cmd.getOptionValue("token"));

    String arg_type = cmd.getOptionValue("type");
    String arg_city_id = cmd.getOptionValue("city_id", "");
    String arg_street_id = cmd.getOptionValue("street_id", "");
    String arg_query = cmd.getOptionValue("query", "");
    if (arg_type.equalsIgnoreCase("city")) {
        try {
            log(SimpleOkato.toSimpleResponse(
                    AddressFactory.service().city(AddressFactory.token(), arg_query).execute().body()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else if (arg_type.equalsIgnoreCase("street")) {
        try {
            log(SimpleOkato.toSimpleResponse(AddressFactory.service()
                    .street(AddressFactory.token(), arg_city_id, arg_query).execute().body()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else if (arg_type.equalsIgnoreCase("building")) {
        try {
            log(SimpleOkato.toSimpleResponse(AddressFactory.service()
                    .building(AddressFactory.token(), arg_city_id, arg_street_id, arg_query).execute().body()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

From source file:net.skyebook.zerocollada.ZeroCollada.java

/**
 * @param args//from  w  w w.  j  a va2s.c  om
 * @throws ParseException 
 * @throws IOException 
 * @throws JDOMException 
 */
public static void main(String[] args) throws ParseException, JDOMException, IOException {
    // Setup Apache Commons CLI
    optionsSetup();

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);

    if (args.length == 0 || cmd.hasOption(ZCOpts.help)) {
        showHelp();
    }

    // was there a valid operation specified?
    if (hasValidOption(cmd)) {
        File fileFromCommandLine = new File(args[args.length - 1]);
        if (!fileFromCommandLine.exists()) {
            System.err.println(
                    "The file located at " + fileFromCommandLine.toString() + " does not exist!  Qutting.");
            return;
        } else if (fileFromCommandLine.isFile() && fileFromCommandLine.toString().endsWith(".dae")) {
            // we've been given a single file.  Act on this single file
            doRequestedAction(fileFromCommandLine, cmd);
        } else if (fileFromCommandLine.isDirectory()) {
            // We've been given a directory of files process the ones that are .dae
            for (File file : fileFromCommandLine.listFiles()) {
                if (file.isFile() && file.toString().endsWith(".dae")) {
                    doRequestedAction(file, cmd);
                } else {
                    System.err.println(file.toString() + " does not seem to be a COLLADA file");
                }
            }
        }
    } else {
        // Then why are we here?
        if (cmd.hasOption(ZCOpts.includeY)) {
            System.err.println(
                    "You have used the " + ZCOpts.includeY + " option but have not asked for a transform (t)");
        } else if (cmd.hasOption(ZCOpts.anchorCenter)) {
            System.err.println(
                    "You have used the " + ZCOpts.includeY + " option but have not asked for a transform (t)");
        }
    }

}

From source file:com.mozilla.bagheera.consumer.KafkaLoggerConsumer.java

public static void main(String[] args) {
    OptionFactory optFactory = OptionFactory.getInstance();
    Options options = KafkaConsumer.getOptions();
    options.addOption(optFactory.create("lv", "logvalues", false, "Log values."));

    CommandLineParser parser = new GnuParser();
    ShutdownHook sh = ShutdownHook.getInstance();
    try {/*from  w  w  w  . ja v  a2 s.c  o m*/
        // Parse command line options
        CommandLine cmd = parser.parse(options, args);

        final KafkaConsumer consumer = KafkaConsumer.fromOptions(cmd);
        sh.addFirst(consumer);

        // Create a sink for storing data
        SinkConfiguration sinkConfig = new SinkConfiguration();
        sinkConfig.setBoolean("loggersink.logvalues", cmd.hasOption("logvalues"));
        KeyValueSinkFactory sinkFactory = KeyValueSinkFactory.getInstance(LoggerSink.class, sinkConfig);
        sh.addLast(sinkFactory);

        // Set the sink for consumer storage
        consumer.setSinkFactory(sinkFactory);

        prepareHealthChecks();

        // Initialize metrics collection, reporting, etc.
        final MetricsManager manager = MetricsManager.getDefaultMetricsManager();

        // Begin polling
        consumer.poll();
    } catch (ParseException e) {
        LOG.error("Error parsing command line options", e);
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(KafkaHBaseConsumer.class.getName(), options);
    }
}

From source file:edu.umd.cloud9.example.bigram.AnalyzeBigramRelativeFrequencyJson.java

@SuppressWarnings({ "static-access" })
public static void main(String[] args) {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT));

    CommandLine cmdline = null;//from  w ww. j a va  2s  .c  o  m
    CommandLineParser parser = new GnuParser();

    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT)) {
        System.out.println("args: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp(AnalyzeBigramRelativeFrequencyJson.class.getName(), options);
        ToolRunner.printGenericCommandUsage(System.out);
        System.exit(-1);
    }

    String inputPath = cmdline.getOptionValue(INPUT);
    System.out.println("input path: " + inputPath);

    List<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>> pairs = SequenceFileUtils
            .readDirectory(new Path(inputPath));

    List<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>> list1 = Lists.newArrayList();
    List<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>> list2 = Lists.newArrayList();

    for (PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> p : pairs) {
        BigramRelativeFrequencyJson.MyTuple bigram = p.getLeftElement();

        if (bigram.getJsonObject().get("Left").getAsString().equals("light")) {
            list1.add(p);
        }

        if (bigram.getJsonObject().get("Left").getAsString().equals("contain")) {
            list2.add(p);
        }
    }

    Collections.sort(list1,
            new Comparator<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>>() {
                public int compare(PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> e1,
                        PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> e2) {
                    if (e1.getRightElement().compareTo(e2.getRightElement()) == 0) {
                        return e1.getLeftElement().compareTo(e2.getLeftElement());
                    }

                    return e2.getRightElement().compareTo(e1.getRightElement());
                }
            });

    Iterator<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>> iter1 = Iterators
            .limit(list1.iterator(), 10);
    while (iter1.hasNext()) {
        PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> p = iter1.next();
        BigramRelativeFrequencyJson.MyTuple bigram = p.getLeftElement();
        System.out.println(bigram + "\t" + p.getRightElement());
    }

    Collections.sort(list2,
            new Comparator<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>>() {
                public int compare(PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> e1,
                        PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> e2) {
                    if (e1.getRightElement().compareTo(e2.getRightElement()) == 0) {
                        return e1.getLeftElement().compareTo(e2.getLeftElement());
                    }

                    return e2.getRightElement().compareTo(e1.getRightElement());
                }
            });

    Iterator<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>> iter2 = Iterators
            .limit(list2.iterator(), 10);
    while (iter2.hasNext()) {
        PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> p = iter2.next();
        BigramRelativeFrequencyJson.MyTuple bigram = p.getLeftElement();
        System.out.println(bigram + "\t" + p.getRightElement());
    }
}

From source file:ar.com.ergio.uncoma.cei.MiniPas.java

/**
 * @param args/*from  w  w  w.j a v  a2  s.c  o  m*/
 * @throws IOException 
 */
@SuppressWarnings("static-access")
public static void main(String[] args) throws IOException {
    // Config logging system -- TODO improve this
    Handler console = new ConsoleHandler();
    ROOT_LOG.addHandler(console);

    // Create cmdline options - TODO - I18N
    final Options options = new Options();
    options.addOption(new Option("help", "Muestra este mensaje"));
    options.addOption(new Option("version", "Muestra la informaci\u00f3 de versi\u00f3n y termina"));
    options.addOption(new Option("debug", "Muestra informaci\u00f3n para depuraci\u00f3n"));
    options.addOption(
            OptionBuilder.withArgName("file").hasArg().withDescription("Archivo de log").create("logFile"));

    final CommandLineParser cmdlineParser = new GnuParser();
    final HelpFormatter formatter = new HelpFormatter();
    try {
        final CommandLine cmdline = cmdlineParser.parse(options, args);

        // Process command line args  -- TODO Improve this
        if (args.length == 0 || cmdline.hasOption("help")) {
            formatter.printHelp("minipas", options, true);
        } else if (cmdline.hasOption("version")) {
            System.out.println("MiniPas versi\u00f3n: 0.0.1");
        } else if (cmdline.hasOption("debug")) {
            ROOT_LOG.setLevel(Level.FINE);
        } else {
            ROOT_LOG.fine("Arguments: " + Arrays.toString(args));
            final Scanner scanner = new Scanner(args[0]);
            while (scanner.hasTokens()) {
                System.out.println(scanner.nextToken());
            }
        }

    } catch (ParseException e) {
        formatter.printHelp("minipas", options, true);
    }
}

From source file:eu.optimis.monitoring.amazoncollector.Collector.java

public static void main(String[] args) {

    Collector collector = new Collector();
    Options options = new Options();
    Option id = OptionBuilder.withArgName("id").hasArg().withDescription("use given collector ID")
            .create(ID_OPT);// ww w .j a  va2s . c o m
    Option conf = OptionBuilder.withArgName("configuration path").hasArg().withDescription("Configuration path")
            .create(PATH_OPT);
    options.addOption(id);
    options.addOption(conf);

    CommandLineParser parser = new GnuParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Incorrect parameters: " + exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("collector", options);
        System.exit(2); //Incorrect usage
    }

    if (line.hasOption(ID_OPT)) {
        String cid = line.getOptionValue(ID_OPT);
        Measurement.setDefCollectorId(cid);
        System.out.println("Using Collector ID: " + cid);
    } else {
        System.out.println("Using default Collector ID: " + DEFAULT_ID + " (To use custom ID use -i argument)");
        Measurement.setDefCollectorId(DEFAULT_ID);
    }

    if (line.hasOption(PATH_OPT)) {
        collector.propertiesPath = line.getOptionValue(PATH_OPT);
        System.out.println("Using Properties file: " + collector.propertiesPath);
    } else {
        System.out.println("Using default Configuration file: " + DEFAULT_PROPERTIES_PATH
                + " (To use custom path use -c argument)");
        collector.propertiesPath = DEFAULT_PROPERTIES_PATH;
    }

    collector.getProperties();

    MeasurementsHelper helper = new MeasurementsHelper(collector.accessKey, collector.secretKey);
    List<Measurement> measurements = helper.getMeasurements();

    String xmlData = XMLHelper.createDocument(measurements);
    RESTHelper rest = new RESTHelper(collector.aggregatorURL);
    rest.sendDocument(xmlData);
}

From source file:com.esri.geoevent.clusterSimulator.GeoeventClusterSimulator.java

public static void main(String[] args) {
    Options options = MyOptions.createOptions();
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;// w ww  .j  av a 2s.  c o m
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e1) {
        MyOptions.printUsageAndExit();
    }

    try {
        ClientServerMode mode = getMode(cmd.getOptionValue('m', "CLIENT"));
        Simulator simulator = null;
        int batchSize = 1;
        if (cmd.hasOption('b')) {
            try {
                batchSize = Integer.parseInt(cmd.getOptionValue('b'));
                if (batchSize < 1) {
                    batchSize = 1;
                    System.err.println("Error : " + cmd.getOptionValue('b')
                            + " is not a valid value for the batch size.  Using \'1\' instead.");
                }
            } catch (NumberFormatException ex) {
                System.err.println(
                        "Error : " + cmd.getOptionValue('b') + " is not a valid value for the batch size.");
            }
        }
        boolean trustAllSSLCerts = cmd.hasOption('t');
        int period = Integer.parseInt(cmd.getOptionValue('d', "1000"));
        switch (mode) {
        case CLIENT:
            simulator = getSimulator(cmd.getOptionValue('f'), true, cmd.hasOption('l'), batchSize, period);
            serverAdminClient = new ServerAdminClient(cmd.getOptionValue('h'),
                    cmd.getOptionValue('u', "siteadmin"), cmd.getOptionValue('p', "password"), simulator,
                    (trustAllSSLCerts) ? new AcceptAlwaysCertChecker() : new CommandLineCertChecker());
            simulator.start();
            break;
        case SERVER:
            simulator = getSimulator(cmd.getOptionValue('f'), false, cmd.hasOption('l'), batchSize, period);
            tcpServer = new TCPServer(simulator);
            simulator.start();
            break;
        default:
            break;
        }
    } catch (Exception e) {
        System.err.println("Error : " + e.getMessage());
        System.exit(1);
    }
}

From source file:com.genentech.chemistry.openEye.apps.SDFMolSeparator.java

/**
 * @param args// ww w .  java  2  s.c  o m
 */
public static void main(String... args) throws IOException { // create command line Options object
    Options options = new Options();
    Option opt = new Option(OPT_INFILE, true,
            "input file oe-supported Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_OUTFILE, true, "output file oe-supported. Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }
    args = cmd.getArgs();

    if (cmd.hasOption("d")) {
        System.err.println("Start debugger and press return:");
        new BufferedReader(new InputStreamReader(System.in)).readLine();
    }

    String inFile = cmd.getOptionValue(OPT_INFILE);
    String outFile = cmd.getOptionValue(OPT_OUTFILE);
    SDFMolSeparator separator = new SDFMolSeparator(outFile);

    try {
        separator.run(inFile);

    } catch (IndexOutOfBoundsException iie) {
        System.err.println(iie.toString());
        exitWithHelp(options);
    } finally {
        separator.close();
    }

}