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:eu.itesla_project.offline.mpi.Master.java

public static void main(String[] args) throws Exception {
    try {//w  w w  .  ja v a2  s.c  o m
        CommandLineParser parser = new GnuParser();
        CommandLine line = parser.parse(OPTIONS, args);

        Mode mode = Mode.valueOf(line.getOptionValue("mode"));
        String simulationDbName = line.hasOption("simulation-db-name")
                ? line.getOptionValue("simulation-db-name")
                : OfflineConfig.DEFAULT_SIMULATION_DB_NAME;
        String rulesDbName = line.hasOption("rules-db-name") ? line.getOptionValue("rules-db-name")
                : OfflineConfig.DEFAULT_RULES_DB_NAME;
        String metricsDbName = line.hasOption("metrics-db-name") ? line.getOptionValue("metrics-db-name")
                : OfflineConfig.DEFAULT_METRICS_DB_NAME;
        Path tmpDir = Paths.get(line.getOptionValue("tmp-dir"));
        Class<?> statisticsFactoryClass = Class.forName(line.getOptionValue("statistics-factory-class"));
        Path statisticsDbDir = Paths.get(line.getOptionValue("statistics-db-dir"));
        String statisticsDbName = line.getOptionValue("statistics-db-name");
        int coresPerRank = Integer.parseInt(line.getOptionValue("cores"));
        Path stdOutArchive = line.hasOption("stdout-archive") ? Paths.get(line.getOptionValue("stdout-archive"))
                : null;
        String workflowId = line.hasOption("workflow") ? line.getOptionValue("workflow") : null;

        MpiExecutorContext mpiExecutorContext = new MultiStateNetworkAwareMpiExecutorContext();
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        ExecutorService offlineExecutorService = MultiStateNetworkAwareExecutors
                .newSizeLimitedThreadPool("OFFLINE_POOL", 100);
        try {
            MpiStatisticsFactory statisticsFactory = statisticsFactoryClass
                    .asSubclass(MpiStatisticsFactory.class).newInstance();
            try (MpiStatistics statistics = statisticsFactory.create(statisticsDbDir, statisticsDbName)) {
                try (ComputationManager computationManager = new MpiComputationManager(tmpDir, statistics,
                        mpiExecutorContext, coresPerRank, false, stdOutArchive)) {
                    OfflineConfig config = OfflineConfig.load();
                    try (LocalOfflineApplication application = new LocalOfflineApplication(config,
                            computationManager, simulationDbName, rulesDbName, metricsDbName,
                            scheduledExecutorService, offlineExecutorService)) {
                        switch (mode) {
                        case ui:
                            application.await();
                            break;

                        case simulations: {
                            if (workflowId == null) {
                                workflowId = application.createWorkflow(null,
                                        OfflineWorkflowCreationParameters.load());
                            }
                            application.startWorkflowAndWait(workflowId, OfflineWorkflowStartParameters.load());
                        }
                            break;

                        case rules: {
                            if (workflowId == null) {
                                throw new RuntimeException("Workflow '" + workflowId + "' not found");
                            }
                            application.computeSecurityRulesAndWait(workflowId);
                        }
                            break;

                        default:
                            throw new IllegalArgumentException("Invalid mode " + mode);
                        }
                    }
                }
            }
        } finally {
            mpiExecutorContext.shutdown();
            offlineExecutorService.shutdown();
            scheduledExecutorService.shutdown();
            offlineExecutorService.awaitTermination(15, TimeUnit.MINUTES);
            scheduledExecutorService.awaitTermination(15, TimeUnit.MINUTES);
        }
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("master", OPTIONS, true);
        System.exit(-1);
    } catch (Throwable t) {
        LOGGER.error(t.toString(), t);
        System.exit(-1);
    }
}

From source file:com.dasasian.chok.tool.ZkTool.java

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

    Option lsOption = new Option("ls", true, "list zp path contents");
    lsOption.setArgName("path");
    Option readOption = new Option("read", true, "read and print zp path contents");
    readOption.setArgName("path");
    Option rmOption = new Option("rm", true, "remove zk files");
    rmOption.setArgName("path");
    Option rmrOption = new Option("rmr", true, "remove zk directories");
    rmrOption.setArgName("path");

    OptionGroup actionGroup = new OptionGroup();
    actionGroup.setRequired(true);//w w w. j a  v  a2  s  .c  o m
    actionGroup.addOption(lsOption);
    actionGroup.addOption(readOption);
    actionGroup.addOption(rmOption);
    actionGroup.addOption(rmrOption);
    options.addOptionGroup(actionGroup);

    final CommandLineParser parser = new GnuParser();
    HelpFormatter formatter = new HelpFormatter();
    try {
        final CommandLine line = parser.parse(options, args);
        ZkTool zkTool = new ZkTool();
        if (line.hasOption(lsOption.getOpt())) {
            String path = line.getOptionValue(lsOption.getOpt());
            zkTool.ls(path);
        } else if (line.hasOption(readOption.getOpt())) {
            String path = line.getOptionValue(readOption.getOpt());
            zkTool.read(path);
        } else if (line.hasOption(rmOption.getOpt())) {
            String path = line.getOptionValue(rmOption.getOpt());
            zkTool.rm(path, false);
        } else if (line.hasOption(rmrOption.getOpt())) {
            String path = line.getOptionValue(rmrOption.getOpt());
            zkTool.rm(path, true);
        }
        zkTool.close();
    } catch (ParseException e) {
        System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());
        formatter.printHelp(ZkTool.class.getSimpleName(), options);
    }

}

From source file:com.genentech.struchk.OEMDLPercieveChecker.java

public static void main(String[] args) throws ParseException, JDOMException, IOException {
    // create command line Options object
    Options options = new Options();
    Option opt = new Option("i", true, "input file [.ism,.sdf,...]");
    opt.setRequired(true);/*from   w w  w  .  j av a  2 s  .  c  o  m*/
    options.addOption(opt);

    opt = new Option("o", true, "output file");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("d", false, "debug: wait for user to press key at startup.");
    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();
    }

    if (args.length != 0) {
        exitWithHelp(options);
    }

    String inFile = cmd.getOptionValue("i");
    String outFile = cmd.getOptionValue("o");

    OEMDLPercieveChecker checker = null;
    try {
        checker = new OEMDLPercieveChecker();

        oemolostream out = new oemolostream(outFile);
        oemolistream in = new oemolistream(inFile);

        OEGraphMol mol = new OEGraphMol();
        while (oechem.OEReadMolecule(in, mol)) {
            if (!checker.checkMol(mol))
                oechem.OEWriteMolecule(out, mol);
        }
        checker.delete();
        in.close();
        in.delete();

        out.close();
        out.delete();

    } catch (Exception e) {
        throw new Error(e);
    }
    System.err.println("Done:");
}

From source file:de.thomasvolk.genexample.GenAlg.java

public static void main(String[] args) throws IOException, ParseException {
    System.out.println("Genetische Algorithmen");

    Options options = new Options();
    options.addOption(option("s", "Jede s Generation wird im Bericht ausgegeben"));
    options.addOption(option("w", "Quelldatei Wagon"));
    options.addOption(option("l", "Quelldatei Passagierliste"));
    options.addOption(option("d", "Zielverzeichnis Bericht"));
    options.addOption(option("a", "Algorithmus Typ " + Arrays.asList(AlgorithmusTyp.values()).toString()));
    options.addOption(option("g", "Anzahl der Generationen"));
    options.addOption(option("p", "Anzahl der Populationen"));
    options.addOption("h", false, "Hilfe");
    CommandLineParser parser = new PosixParser();
    try {/*from  ww w. j a  v a  2  s.  com*/
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption('h')) {
            printUsage(options);
            System.exit(0);
        }

        int generationen = getNummer(options, cmd.getOptionValue('g'), 2000);
        int populationen = getNummer(options, cmd.getOptionValue('p'), 20);
        int schritte = getNummer(options, cmd.getOptionValue('s'), 100);
        AlgorithmusTyp[] alg = AlgorithmusTyp.values();
        if (cmd.hasOption('a')) {
            try {
                alg = new AlgorithmusTyp[] { AlgorithmusTyp.valueOf(cmd.getOptionValue('a')) };
            } catch (IllegalArgumentException e) {
                printErrorAndExit(e, options);
            }
        }
        String reportDir = cmd.getOptionValue('d');
        reportDir = StringUtils.isBlank(reportDir) ? "report" : reportDir;
        String wagonDatei = cmd.getOptionValue('w');
        String passagierDatei = cmd.getOptionValue('l');
        if (wagonDatei == null) {
            wagonDatei = erzeugeBeispielDatei("wagon.txt");
        }
        if (passagierDatei == null) {
            passagierDatei = erzeugeBeispielDatei("passagiere.csv");
        }
        System.out.println("Wagon Datein: " + wagonDatei);
        System.out.println("Passagier Datei: " + passagierDatei);
        System.out.println("Bericht: " + new File(reportDir).getAbsolutePath());
        System.out.println("Anzahl Generationen: " + generationen);
        System.out.println("Anzahl Populationen: " + populationen);
        System.out.printf("Protokolliere jede %dte Generation im Bericht\n", schritte);

        WagonFactory wagonFactory = new WagonFactory();
        PassagierFactory passagierFactory = new CSVPassagierFactory();

        GenAlg genAlg = new GenAlg(wagonFactory, passagierFactory);
        genAlg.run(alg, passagierDatei, wagonDatei, reportDir, schritte, generationen, populationen);
    } catch (ParseException e) {
        printErrorAndExit(e, options);
    }
}

From source file:com.opengamma.bbg.replay.BloombergTicksCollectorLauncher.java

/**
 * Starts the Bloomberg Ticks Collector.
 * /* ww w  .j  ava  2 s.  c  o  m*/
 * @param args Not needed
 */
public static void main(String[] args) { // CSIGNORE

    int duration = 0;
    CommandLineParser parser = new PosixParser();
    Options options = new Options();
    options.addOption("d", "duration", true, "minutes to run");
    try {
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("duration")) {
            duration = Integer.parseInt(cmd.getOptionValue("duration"));
        }
    } catch (ParseException exp) {
        s_logger.error("Option parsing failed: {}", exp.getMessage());
        return;
    }

    BloombergTicksCollectorLauncher launcher = new BloombergTicksCollectorLauncher();
    launcher.run();
    if (duration > 0) {
        try {
            Thread.sleep(duration * 60 * 1000);
        } catch (InterruptedException e) {
        }
        launcher.exit();
    }
}

From source file:edu.cmu.lti.oaqa.bio.index.medline.annotated.query.SimpleQueryApp.java

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

    options.addOption("u", null, true, "Solr URI");
    options.addOption("n", null, true, "Max # of results");

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    try {/*from  ww w. j a va 2 s  . c  o  m*/
        CommandLine cmd = parser.parse(options, args);
        String solrURI = null;

        solrURI = cmd.getOptionValue("u");
        if (solrURI == null) {
            Usage("Specify Solr URI");
        }

        SolrServerWrapper solr = new SolrServerWrapper(solrURI);

        int numRet = 10;

        if (cmd.hasOption("n")) {
            numRet = Integer.parseInt(cmd.getOptionValue("n"));
        }

        List<String> fieldList = new ArrayList<String>();
        fieldList.add(UtilConstMedline.ID_FIELD);
        fieldList.add(UtilConstMedline.SCORE_FIELD);
        fieldList.add(UtilConstMedline.ARTICLE_TITLE_FIELD);
        fieldList.add(UtilConstMedline.ENTITIES_DESC_FIELD);
        fieldList.add(UtilConstMedline.ABSTRACT_TEXT_FIELD);

        BufferedReader sysInReader = new BufferedReader(new InputStreamReader(System.in));
        Joiner commaJoiner = Joiner.on(',');

        while (true) {
            System.out.println("Input query: ");
            String query = sysInReader.readLine();
            if (null == query)
                break;

            QueryTransformer qt = new QueryTransformer(query);

            String tranQuery = qt.getQuery();

            System.out.println("Translated query:");
            System.out.println(tranQuery);
            System.out.println("=========================");

            SolrDocumentList res = solr.runQuery(tranQuery, fieldList, numRet);

            System.out.println("Found " + res.getNumFound() + " entries");

            for (SolrDocument doc : res) {
                String id = (String) doc.getFieldValue(UtilConstMedline.ID_FIELD);
                float score = (Float) doc.getFieldValue(UtilConstMedline.SCORE_FIELD);
                String title = (String) doc.getFieldValue(UtilConstMedline.ARTICLE_TITLE_FIELD);
                String titleAbstract = (String) doc.getFieldValue(UtilConstMedline.ABSTRACT_TEXT_FIELD);

                System.out.println(score + " PMID=" + id + " " + titleAbstract);

                String entityDesc = (String) doc.getFieldValue(UtilConstMedline.ENTITIES_DESC_FIELD);
                System.out.println("Entities:");
                for (EntityEntry e : EntityEntry.parseEntityDesc(entityDesc)) {
                    System.out.println(String.format("[%d %d] concept=%s concept_ids=%s", e.mStart, e.mEnd,
                            e.mConcept, commaJoiner.join(e.mConceptIds)));
                }
            }
        }

        solr.close();

    } catch (ParseException e) {
        Usage("Cannot parse arguments");
    } catch (Exception e) {
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }
}

From source file:galen.api.server.GalenApiServer.java

public static void main(String[] args) {
    CommandLineParser parser = new GnuParser();
    Options options = defineCommandOptions();
    HelpFormatter formatter = new HelpFormatter();
    try {/*ww w  .j a va2s . co  m*/
        CommandLine commandLine = parser.parse(options, args);

        if (asList(args).size() == 0) {
            formatter.printHelp("galen-api-server", options);
            System.exit(0);
        } else if (commandLine.hasOption("help")) {
            formatter.printHelp("galen-api-server", options);
        } else if (commandLine.hasOption("run")) {
            String port = commandLine.getOptionValue("run");
            int serverPort = valueOf(port);
            handler = new GalenCommandExecutor();
            processor = new GalenApiRemoteService.Processor(handler);
            log.info("Starting server on port " + serverPort);
            runService(processor, serverPort);

        }
    } catch (ParseException e) {
        System.out.print("Invalid usage: ");
        System.out.println(e.getMessage());
        formatter.printHelp("galen-api-server", options);
    }
}

From source file:com.aestel.chemistry.openEye.fp.apps.SDFFPSphereExclusion.java

public static void main(String... args) throws IOException { // create command line Options object
    Options options = new Options();
    Option opt = new Option("in", true, "input file [.sdf,...]");
    opt.setRequired(true);/*from  w  w  w. j ava2  s.  c  o m*/
    options.addOption(opt);

    opt = new Option("out", true, "output file oe-supported");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("ref", true, "refrence file to be loaded before starting");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("fpTag", true, "field containing fingerpPrint");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option("maxTanimoto", false,
            "If given the modified maxTanimoto will be used = common/(2*Max(na,nb)-common).");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("radius", true, "radius of exclusion sphere, exclude anything with similarity >= radius.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option("printSphereMatchCount", false,
            "check and print membership of candidates not "
                    + " only to the first centroid which has sim >= radius but to all centroids"
                    + " found up to that input. This will output a candidate multiple times."
                    + " Implies checkSpheresInOrder.");
    options.addOption(opt);

    opt = new Option("checkSpheresInOrder", false,
            "For each candiate: compare to centroids from first to last (default is last to first)");
    options.addOption(opt);

    opt = new Option("printAll", false, "print all molecule, check includeIdx tag");
    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();
    }

    // the only reason not to match centroids in reverse order id if
    // a non-centroid is to be assigned to multiple centroids
    boolean printSphereMatchCount = cmd.hasOption("printSphereMatchCount");
    boolean reverseMatch = !cmd.hasOption("checkSpheresInOrder") && !printSphereMatchCount;
    boolean printAll = cmd.hasOption("printAll") || printSphereMatchCount;
    boolean doMaxTanimoto = cmd.hasOption("maxTanimoto");
    String fpTag = cmd.getOptionValue("fpTag");
    double radius = Double.parseDouble(cmd.getOptionValue("radius"));
    String inFile = cmd.getOptionValue("in");
    String outFile = cmd.getOptionValue("out");
    String refFile = cmd.getOptionValue("ref");

    SimComparatorFactory<OEMolBase, FPComparator, FPComparator> compFact = new FPComparatorFact(doMaxTanimoto,
            fpTag);
    SphereExclusion<FPComparator, FPComparator> alg = new SphereExclusion<FPComparator, FPComparator>(compFact,
            refFile, outFile, radius, reverseMatch, printSphereMatchCount, printAll);
    alg.run(inFile);
    alg.close();
}

From source file:com.ibm.watson.app.qaclassifier.AddQuestionsToMockClassifier.java

public static void main(String[] args) throws IOException {
    Option urlOption = CliUtils.createOption(URL_OPTION, URL_OPTION_LONG, true,
            "The root URL of the application to connect to. If omitted, the default will be used ("
                    + DEFAULT_URL + ")",
            false, URL_OPTION_LONG);
    Option pathOption = CliUtils.createOption(FILE_OPTION, FILE_OPTION_LONG, true,
            "The file to be used as training data, can point to the file system or the class path", true,
            FILE_OPTION_LONG);//from w w w.j  a  va  2s  .c  om
    Option userOption = CliUtils.createOption(USER_OPTION, USER_OPTION_LONG, true,
            "The username for the manage API", true, USER_OPTION_LONG);
    Option passwordOption = CliUtils.createOption(PASSWORD_OPTION, PASSWORD_OPTION_LONG, true,
            "The password for the manage API", true, PASSWORD_OPTION_LONG);

    final Options options = CliUtils.buildOptions(urlOption, pathOption, userOption, passwordOption);

    CommandLine cmd;
    try {
        CommandLineParser parser = new GnuParser();
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println("Could not parse cmd line arguments.\n" + e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(120, "java " + AddQuestionsToMockClassifier.class.getName(), null, options, null);
        return;
    }

    final String url = cmd.getOptionValue(URL_OPTION, DEFAULT_URL);
    final String path = cmd.getOptionValue(FILE_OPTION);
    final String user = cmd.getOptionValue(USER_OPTION);
    final String password = cmd.getOptionValue(PASSWORD_OPTION);

    AddQuestionsToMockClassifier mockSetup = new AddQuestionsToMockClassifier(url, path, user, password);

    System.out.println("Creating mock responses for the questions in " + path + "...");
    mockSetup.mockResponsesForTrainingData();

    System.out.println("Creating mock responses for the sample questions...");
    mockSetup.mockResponse(SampleQuestions.HIGH_CONFIDENCE, "mock_one_answer", HIGH_CONFIDENCE,
            "This is a question that will be answered by the mock classifier with high confidence");
    mockSetup.mockResponse(SampleQuestions.LOW_CONFIDENCE, "mock_multiple_answers", LOW_CONFIDENCE,
            "This is a question that will be answered by the mock classifier with low confidence");
    mockSetup.mockResponse(SampleQuestions.NO_ANSWERS, "mock_no_answers", NO_ANSWER_CONFIDENCE,
            "This is a question that will be answered by the mock classifier with very low confidence");
    System.out.println("Done.");
}

From source file:main.Main.java

/**
 * The public main function.//from  www.j  a  va  2 s.  c o  m
 * @param args
 */
public static void main(String[] args) {
    System.out.println("Starting");

    Options options = new Options();

    Option solutionOption = new Option("s", "solution", true,
            "This will be the " + "solution of the cross word game. (aka. This will be the first"
                    + " vertical word on the canvas.)");

    //        solutionOption.setRequired(true);

    Option numOfBatchOption = new Option("n", "numOfBatch", true, "");

    Option verboseOption = new Option("v", "verbose", false, "Print some debug information during running.");
    Option veryVerboseOption = new Option("vv", "very-verbose", false, "Print more debug information.");

    options.addOption(solutionOption);
    options.addOption(numOfBatchOption);
    options.addOption(verboseOption);
    options.addOption(veryVerboseOption);

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

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

        System.exit(1);
        return;
    }

    System.out.println(cmd.getArgList());

    int debugLevel = 0;
    if (cmd.hasOption("verbose")) {
        debugLevel = 1;
    }
    if (cmd.hasOption("very-verbose")) {
        debugLevel = 2;
    }
    String solution = cmd.getOptionValue("solution");
    if (null == solution) {
        startGui();
    } else {
        int numOfBatch = Integer.valueOf(cmd.getOptionValue("numOfBatch", "200"));
        System.out.println(solution);
        Generator gen = new Generator(solution, debugLevel); // <---- EDIT THIS LINE FOR DIFFERENT SOLUTIONS.
        long startTime = System.currentTimeMillis();
        gen.generate(numOfBatch);
        long estimatedTime = System.currentTimeMillis() - startTime;
        System.out.print("estimatedTime: " + estimatedTime + "ms");
    }
}