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

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

Introduction

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

Prototype

Options

Source Link

Usage

From source file:com.dattack.dbping.cli.PingAnalyzerCli.java

/**
 * The <code>main</code> method.
 *
 * @param args/*from w w w  . ja va2  s.  c  o  m*/
 *            the program arguments
 */
public static void main(final String[] args) {

    try {

        // create Options object
        final Options options = new Options();

        // add t option
        options.addOption(START_DATE_OPTION, true, "the date for an analysis run to begin");
        options.addOption(END_DATE_OPTION, true, "the date for an analysis run to finish");
        options.addOption(SPAN_OPTION, true, "the period of time between points");
        options.addOption(DATA_FILE_OPTION, true, "the data file to analyze");
        options.addOption(METRIC_OPTION, true, "the metric to analyze");
        options.addOption(MAX_VALUE_OPTION, true, "the maximum value to use");
        options.addOption(MIN_VALUE_OPTION, true, "the minimum value to use");

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

        final ReportContext context = new ReportContext();
        context.setStartDate(TimeUtils.parseDate(cmd.getOptionValue(START_DATE_OPTION)));
        context.setEndDate(TimeUtils.parseDate(cmd.getOptionValue(END_DATE_OPTION)));
        context.setTimeSpan(TimeUtils.parseTimeSpanMillis(cmd.getOptionValue(SPAN_OPTION)));
        context.setMaxValue(parseLong(cmd.getOptionValue(MAX_VALUE_OPTION)));
        context.setMinValue(parseLong(cmd.getOptionValue(MIN_VALUE_OPTION)));
        if (cmd.hasOption(METRIC_OPTION)) {
            for (final String metricName : cmd.getOptionValues(METRIC_OPTION)) {
                context.addMetricNameFilter(MetricName.parse(metricName));
            }
        }

        final PingAnalyzerCli ping = new PingAnalyzerCli();
        for (final String file : cmd.getOptionValues(DATA_FILE_OPTION)) {
            ping.execute(new File(file), context);
        }

    } catch (final ParseException | ConfigurationException e) {
        System.err.println(e.getMessage());
    }
}

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);//from   w ww. j  av a 2  s .  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:isi.pasco2.Main.java

public static void main(String[] args) {
    CommandLineParser parser = new PosixParser();

    Options options = new Options();
    Option undelete = new Option("d", "Undelete activity records");
    options.addOption(undelete);/*from w ww  .  j  a va 2s  .com*/
    Option disableAllocation = new Option("M", "Disable allocation detection");
    options.addOption(disableAllocation);
    Option fieldDelimeter = OptionBuilder.withArgName("field-delimeter").hasArg()
            .withDescription("Field Delimeter (TAB by default)").create("t");
    options.addOption(fieldDelimeter);

    Option timeFormat = OptionBuilder.withArgName("time-format").hasArg()
            .withDescription("xsd or standard (pasco1 compatible)").create("f");
    options.addOption(timeFormat);

    Option fileTypeOption = OptionBuilder.withArgName("file-type").hasArg()
            .withDescription("The type of file: cache or history").create("T");

    options.addOption(fileTypeOption);

    try {
        CommandLine line = parser.parse(options, args);
        boolean undeleteMethod = false;
        String delimeter = null;
        String format = null;
        String fileType = null;
        boolean disableAllocationTest = false;

        if (line.hasOption("d")) {
            undeleteMethod = true;
        }

        if (line.hasOption('t')) {
            delimeter = line.getOptionValue('t');
        }

        if (line.hasOption('M')) {
            disableAllocationTest = true;
        }

        if (line.hasOption('T')) {
            fileType = line.getOptionValue('T');
        }

        if (line.hasOption('f')) {
            format = line.getOptionValue('f');
        }

        if (line.getArgs().length != 1) {
            System.err.println("No file specified.");
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("pasco2", options);
            System.exit(1);
        }
        String fileName = line.getArgs()[0];

        try {
            IndexFile fr = new FastReadIndexFile(fileName, "r");

            CountingCacheHandler handler = null;

            if (fileType == null) {
                handler = new CountingCacheHandler();
            }
            if (fileType == null) {
                handler = new CountingCacheHandler();
            } else if (fileType.equals("cache")) {
                handler = new CountingCacheHandler();
            } else if (fileType.equals("history")) {
                handler = new Pasco2HistoryHandler();
            }

            if (format != null) {
                if (format.equals("pasco")) {
                    DateFormat regularDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.SSS");
                    handler.setDateFormat(regularDateFormat);
                    TimeZone tz = TimeZone.getTimeZone("Australia/Brisbane");
                    regularDateFormat.setTimeZone(tz);

                } else if (format.equals("standard")) {
                    DateFormat xsdDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
                    handler.setDateFormat(xsdDateFormat);
                    xsdDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
                } else {
                    System.err.println("Format not supported.");
                    HelpFormatter formatter = new HelpFormatter();
                    formatter.printHelp("pasco2", options);
                    System.exit(1);
                }
            }

            if (delimeter != null) {
                handler.setDelimeter(delimeter);
            }

            IEIndexFileParser logparser = null;
            if (fileType == null) {
                System.err.println("Using cache file parser.");
                logparser = new IECacheFileParser(fileName, fr, handler);
            } else if (fileType.equals("cache")) {
                logparser = new IECacheFileParser(fileName, fr, handler);
            } else if (fileType.equals("history")) {
                logparser = new IEHistoryFileParser(fileName, fr, handler);
            } else {
                System.err.println("Unsupported file type.");
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp("pasco2", options);
                System.exit(1);
            }
            if (disableAllocationTest) {
                logparser.setDisableAllocationTest(true);
            }
            logparser.parseFile();

        } catch (Exception ex) {
            System.err.println(ex.getMessage());
            ex.printStackTrace();
        }

    } catch (ParseException exp) {
        System.out.println("Unexpected exception:" + exp.getMessage());
    }
}

From source file:at.salzburgresearch.vgi.vgianalyticsframework.activityanalysis.application.OsmHistoryImporter.java

public static void main(String[] args) {
    /**// w  w w  .j  a  v a2s .  c  o m
     * Read input parameter
     */
    Options options = new Options();
    options.addOption("h", "help", false, "Display this help page");
    /** Settings */
    options.addOption(Option.builder("s").longOpt("settings").hasArg().argName("settings_file")
            .desc("settings file").build());
    options.addOption(Option.builder("p").longOpt("polygons").hasArg().argName("polygon_file")
            .desc("polygon file").build());
    /** OSM History importer */
    options.addOption(Option.builder("o").longOpt("osm").hasArg().argName("osm_history_file")
            .desc("osm history file").build());

    launch(options, args);
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.ase2015.CdoQuerySpecificInvisibleMethodDeclarations.java

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input CDO resource directory");
    inputOpt.setArgs(1);//from  ww  w  . j ava2s  .c  o  m
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    Option repoOpt = OptionBuilder.create(REPO_NAME);
    repoOpt.setArgName("REPO_NAME");
    repoOpt.setDescription("CDO Repository name");
    repoOpt.setArgs(1);
    repoOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);
    options.addOption(repoOpt);

    CommandLineParser parser = new PosixParser();

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

        String repositoryDir = commandLine.getOptionValue(IN);
        String repositoryName = commandLine.getOptionValue(REPO_NAME);

        Class<?> inClazz = CdoQuerySpecificInvisibleMethodDeclarations.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        EmbeddedCDOServer server = new EmbeddedCDOServer(repositoryDir, repositoryName);
        try {
            server.run();
            CDOSession session = server.openSession();
            CDOTransaction transaction = session.openTransaction();
            Resource resource = transaction.getRootResource();
            {
                Runtime.getRuntime().gc();
                long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
                LOG.log(Level.INFO, MessageFormat.format("Used memory before query: {0}",
                        MessageUtil.byteCountToDisplaySize(initialUsedMemory)));
                LOG.log(Level.INFO, "Start query");
                long begin = System.currentTimeMillis();
                EList<MethodDeclaration> list = ASE2015JavaQueries
                        .getSpecificInvisibleMethodDeclarations(resource);
                long end = System.currentTimeMillis();
                LOG.log(Level.INFO, "End query");
                LOG.log(Level.INFO, MessageFormat.format("Query result contains {0} elements", list.size()));
                LOG.log(Level.INFO,
                        MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
                Runtime.getRuntime().gc();
                long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
                LOG.log(Level.INFO, MessageFormat.format("Used memory after query: {0}",
                        MessageUtil.byteCountToDisplaySize(finalUsedMemory)));
                LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}",
                        MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory)));
            }

            transaction.close();
            session.close();
        } finally {
            server.stop();
        }
    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:com.esri.geoevent.test.performance.OrchestratorMain.java

/**
 * Main method - this is used to when running from command line
 *
 * @param args Command Line Arguments//from   w  ww.j a v a 2 s  . c o  m
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {
    // TODO: Localize the messages
    // test harness options
    Options testHarnessOptions = new Options();
    testHarnessOptions.addOption(OptionBuilder.withLongOpt("fixtures")
            .withDescription("The fixtures xml file to load and configure the performance test harness.")
            .hasArg().create("f"));
    testHarnessOptions.addOption("h", "help", false, "print the help message");

    // parse the command line
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(testHarnessOptions, args, false);
    } catch (ParseException ignore) {
        printHelp(testHarnessOptions);
        return;
    }

    if (cmd.getOptions().length == 0) {
        OrchestratorUI ui = new OrchestratorUI();
        ui.run(args);
    } else {
        if (cmd.hasOption("h")) {
            printHelp(testHarnessOptions);
            return;
        }

        if (cmd.hasOption("h") || !cmd.hasOption("f")) {
            printHelp(testHarnessOptions);
            return;
        }

        String fixturesFilePath = cmd.getOptionValue("f");
        // validate
        if (!validateFixturesFile(fixturesFilePath)) {
            printHelp(testHarnessOptions);
            return;
        }

        // parse the xml file
        final Fixtures fixtures;
        try {
            fixtures = fromXML(fixturesFilePath);
        } catch (JAXBException error) {
            System.err.println(ImplMessages.getMessage("TEST_HARNESS_EXECUTOR_CONFIG_ERROR", fixturesFilePath));
            error.printStackTrace();
            return;
        }

        // run the test harness
        try {
            OrchestratorRunner executor = new OrchestratorRunner(fixtures);

            executor.start();
        } catch (RunningException error) {
            error.printStackTrace();
        }

    }

}

From source file:com.redhat.poc.jdg.bankofchina.performance.TestCase51RemoteMultiThreads.java

public static void main(String[] args) throws Exception {
    CommandLine commandLine;/*from   ww w  .  j  av a  2s . co m*/
    Options options = new Options();
    options.addOption("n", true, "The read thread numbers option");
    options.addOption("t", true, "The thread read times option");
    BasicParser parser = new BasicParser();
    parser.parse(options, args);
    commandLine = parser.parse(options, args);
    if (commandLine.getOptions().length > 0) {
        if (commandLine.hasOption("n")) {
            String numbers = commandLine.getOptionValue("n");
            if (numbers != null && numbers.length() > 0) {
                readThreadNumbers = Integer.parseInt(numbers);
            }
        }
        if (commandLine.hasOption("t")) {
            String times = commandLine.getOptionValue("t");
            if (times != null && times.length() > 0) {
                threadReadTimes = Integer.parseInt(times);
            }
        }
    }

    System.out.println();
    System.out.println("%%%%%%%%%  userid.csv  %%%%%%%%%");
    LoadUserIdList();
    randomPoolSize = userIdList.size();
    System.out.println(
            "%%%%%%%%% ? userid.csv ,  " + randomPoolSize + " ?? %%%%%%%%%");
    randomPoolSizeByThread = randomPoolSize / readThreadNumbers;

    System.out.println();
    System.out.println(
            "%%%%%%%%% ?, " + readThreadNumbers + " ,, ???, "
                    + threadReadTimes + " ,?, ?(ms)," + new Date().getTime());

    for (int i = 0; i < readThreadNumbers; i++) {
        new TestCase51RemoteMultiThreads(i * randomPoolSizeByThread).start();
    }
}

From source file:com.redhat.poc.jdg.bankofchina.performance.TestCase52RemoteMultiThreads.java

public static void main(String[] args) throws Exception {
    CommandLine commandLine;//from w ww.  j  a va2  s  . com
    Options options = new Options();
    options.addOption("n", true, "The read thread numbers option");
    options.addOption("t", true, "The thread read times option");
    BasicParser parser = new BasicParser();
    parser.parse(options, args);
    commandLine = parser.parse(options, args);
    if (commandLine.getOptions().length > 0) {
        if (commandLine.hasOption("n")) {
            String numbers = commandLine.getOptionValue("n");
            if (numbers != null && numbers.length() > 0) {
                writeThreadNumbers = Integer.parseInt(numbers);
            }
        }
        if (commandLine.hasOption("t")) {
            String times = commandLine.getOptionValue("t");
            if (times != null && times.length() > 0) {
                threadWriteTimes = Integer.parseInt(times);
            }
        }
    }
    System.out.println();
    System.out.println("%%%%%%%%%  userid.csv  %%%%%%%%%");
    LoadUserIdList();
    randomPoolSize = userIdList.size();
    System.out.println(
            "%%%%%%%%% ? userid.csv ,  " + randomPoolSize + " ?? %%%%%%%%%");
    randomPoolSizeByThread = randomPoolSize / writeThreadNumbers;

    System.out.println();
    System.out.println(
            "%%%%%%%%% ?, " + writeThreadNumbers + ", , ??, "
                    + threadWriteTimes + " ,?, ?(ms)," + new Date().getTime());
    for (int i = 0; i < writeThreadNumbers; i++) {
        new TestCase52RemoteMultiThreads(i * randomPoolSizeByThread).start();
    }
}

From source file:edu.washington.data.sentimentreebank.StanfordNLPDict.java

public static void main(String args[]) {
    Options options = new Options();
    options.addOption("d", "dict", true, "dictionary file.");
    options.addOption("s", "sentiment", true, "sentiment value file.");

    CommandLineParser parser = new GnuParser();
    try {/* ww  w  .  j  a v a2s  .  c  o m*/
        CommandLine line = parser.parse(options, args);
        if (!line.hasOption("dict") && !line.hasOption("sentiment")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("StanfordNLPDict", options);
            return;
        }

        Path dictPath = Paths.get(line.getOptionValue("dict"));
        Path sentimentPath = Paths.get(line.getOptionValue("sentiment"));

        StanfordNLPDict snlp = new StanfordNLPDict(dictPath, sentimentPath);
        String sentence = "take off";
        System.out.printf("sentence [%1$s] %2$s\n", sentence,
                String.valueOf(snlp.getPhraseSentiment(sentence)));

    } catch (ParseException exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("StanfordNLPDict", options);
    } catch (IOException ex) {
        Logger.getLogger(StanfordNLPDict.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:cc.twittertools.search.api.RunQueriesBaselineThrift.java

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

    options.addOption(OptionBuilder.withArgName("string").hasArg().withDescription("host").create(HOST_OPTION));
    options.addOption(OptionBuilder.withArgName("port").hasArg().withDescription("port").create(PORT_OPTION));
    options.addOption(OptionBuilder.withArgName("file").hasArg()
            .withDescription("file containing topics in TREC format").create(QUERIES_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of results to return")
            .create(NUM_RESULTS_OPTION));
    options.addOption(//from  w w  w . ja  v  a2  s  . c o m
            OptionBuilder.withArgName("string").hasArg().withDescription("group id").create(GROUP_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("access token").create(TOKEN_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("runtag").create(RUNTAG_OPTION));
    options.addOption(new Option(VERBOSE_OPTION, "print out complete document"));

    CommandLine cmdline = null;
    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(HOST_OPTION) || !cmdline.hasOption(PORT_OPTION)
            || !cmdline.hasOption(QUERIES_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(RunQueriesThrift.class.getName(), options);
        System.exit(-1);
    }

    String queryFile = cmdline.getOptionValue(QUERIES_OPTION);
    if (!new File(queryFile).exists()) {
        System.err.println("Error: " + queryFile + " doesn't exist!");
        System.exit(-1);
    }

    String runtag = cmdline.hasOption(RUNTAG_OPTION) ? cmdline.getOptionValue(RUNTAG_OPTION) : DEFAULT_RUNTAG;

    TrecTopicSet topicsFile = TrecTopicSet.fromFile(new File(queryFile));

    int numResults = 1000;
    try {
        if (cmdline.hasOption(NUM_RESULTS_OPTION)) {
            numResults = Integer.parseInt(cmdline.getOptionValue(NUM_RESULTS_OPTION));
        }
    } catch (NumberFormatException e) {
        System.err.println("Invalid " + NUM_RESULTS_OPTION + ": " + cmdline.getOptionValue(NUM_RESULTS_OPTION));
        System.exit(-1);
    }

    String group = cmdline.hasOption(GROUP_OPTION) ? cmdline.getOptionValue(GROUP_OPTION) : null;
    String token = cmdline.hasOption(TOKEN_OPTION) ? cmdline.getOptionValue(TOKEN_OPTION) : null;

    boolean verbose = cmdline.hasOption(VERBOSE_OPTION);

    PrintStream out = new PrintStream(System.out, true, "UTF-8");

    TrecSearchThriftClient client = new TrecSearchThriftClient(cmdline.getOptionValue(HOST_OPTION),
            Integer.parseInt(cmdline.getOptionValue(PORT_OPTION)), group, token);

    for (cc.twittertools.search.TrecTopic query : topicsFile) {
        List<TResult> results = client.search(query.getQuery(), query.getQueryTweetTime(), numResults);

        SortedSet<TResultComparable> sortedResults = new TreeSet<TResultComparable>();
        for (TResult result : results) {
            // Throw away retweets.
            if (result.getRetweeted_status_id() == 0) {
                sortedResults.add(new TResultComparable(result));
            }
        }

        int i = 1;
        int dupliCount = 0;
        double rsvPrev = 0;
        for (TResultComparable sortedResult : sortedResults) {
            TResult result = sortedResult.getTResult();
            double rsvCurr = result.rsv;
            if (Math.abs(rsvCurr - rsvPrev) > 0.0000001) {
                dupliCount = 0;
            } else {
                dupliCount++;
                rsvCurr = rsvCurr - 0.000001 / numResults * dupliCount;
            }
            out.println(String.format("%s Q0 %d %d %." + (int) (6 + Math.ceil(Math.log10(numResults))) + "f %s",
                    query.getId(), result.id, i, rsvCurr, runtag));
            if (verbose) {
                out.println("# " + result.toString().replaceAll("[\\n\\r]+", " "));
            }
            i++;
            rsvPrev = result.rsv;
        }

    }
    out.close();
}