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.rapleaf.hank.cli.AddDomainGroup.java

public static void main(String args[])
        throws InterruptedException, IOException, ParseException, InvalidConfigurationException {
    Options options = new Options();
    options.addOption("n", "name", true, "the name of the domain to be created");
    options.addOption("c", "config", true,
            "path of a valid config file with coordinator connection information");
    try {/*from  w w  w .j a v  a  2  s .c  om*/
        CommandLine line = new GnuParser().parse(options, args);
        CommandLineChecker.check(line, options, new String[] { "config", "name" }, AddDomainGroup.class);
        ClientConfigurator configurator = new YamlClientConfigurator(line.getOptionValue("config"));
        addDomainGroup(configurator, line.getOptionValue("name"));
    } catch (ParseException e) {
        new HelpFormatter().printHelp("add_domain", options);
        throw e;
    }
}

From source file:com.google.api.codegen.CodeGeneratorTool.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("h", "help", false, "show usage");
    options.addOption(Option.builder().longOpt("descriptor_set")
            .desc("The descriptor set representing the compiled input protos.").hasArg()
            .argName("DESCRIPTOR-SET").required(true).build());
    options.addOption(//  w  w  w  .  j a v  a 2  s .co m
            Option.builder().longOpt("service_yaml").desc("The service YAML configuration file or files.")
                    .hasArg().argName("SERVICE-YAML").required(true).build());
    options.addOption(Option.builder().longOpt("gapic_yaml").desc("The GAPIC YAML configuration file or files.")
            .hasArg().argName("GAPIC-YAML").required(true).build());
    options.addOption(Option.builder().longOpt("package_yaml")
            .desc("The package metadata YAML configuration file.").hasArg().argName("PACKAGE-YAML").build());
    options.addOption(Option.builder("o").longOpt("output")
            .desc("The directory in which to output the generated client library.").hasArg()
            .argName("OUTPUT-DIRECTORY").build());
    options.addOption(Option.builder().longOpt("enabled_artifacts")
            .desc("Optional. Artifacts enabled for the generator. "
                    + "Currently supports 'surface' and 'test'.")
            .hasArg().argName("ENABLED_ARTIFACTS").required(false).build());

    CommandLine cl = (new DefaultParser()).parse(options, args);
    if (cl.hasOption("help")) {
        HelpFormatter formater = new HelpFormatter();
        formater.printHelp("CodeGeneratorTool", options);
    }

    int exitCode = generate(cl.getOptionValue("descriptor_set"), cl.getOptionValues("service_yaml"),
            cl.getOptionValues("gapic_yaml"), cl.getOptionValue("package_yaml"),
            cl.getOptionValue("output", ""), cl.getOptionValues("enabled_artifacts"));
    System.exit(exitCode);
}

From source file:com.edduarte.vokter.Main.java

public static void main(String[] args) {

    installUncaughtExceptionHandler();//from  ww  w .java2s.c om

    CommandLineParser parser = new GnuParser();
    Options options = new Options();

    options.addOption("t", "threads", true, "Number of threads to be used "
            + "for computation and indexing processes. Defaults to the number " + "of available cores.");

    options.addOption("p", "port", true, "Core server port. Defaults to 9000.");

    options.addOption("dbh", "db-host", true, "Database host. Defaults to localhost.");

    options.addOption("dbp", "db-port", true, "Database port. Defaults to 27017.");

    options.addOption("case", "preserve-case", false, "Keyword matching with case sensitivity.");

    options.addOption("stop", "stopwords", false, "Keyword matching with stopword filtering.");

    options.addOption("stem", "stemming", false, "Keyword matching with stemming (lexical variants).");

    options.addOption("h", "help", false, "Shows this help prompt.");

    CommandLine commandLine;
    try {
        // Parse the program arguments
        commandLine = parser.parse(options, args);
    } catch (ParseException ex) {
        logger.error("There was a problem processing the input arguments. "
                + "Write -h or --help to show the list of available commands.");
        logger.error(ex.getMessage(), ex);
        return;
    }

    if (commandLine.hasOption('h')) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar vokter-core.jar", options);
        return;
    }

    int maxThreads = Runtime.getRuntime().availableProcessors() - 1;
    maxThreads = maxThreads > 0 ? maxThreads : 1;
    if (commandLine.hasOption('t')) {
        String threadsText = commandLine.getOptionValue('t');
        maxThreads = Integer.parseInt(threadsText);
        if (maxThreads <= 0 || maxThreads > 32) {
            logger.error("Invalid number of threads. Must be a number between 1 and 32.");
            return;
        }
    }

    int port = 9000;
    if (commandLine.hasOption('p')) {
        String portString = commandLine.getOptionValue('p');
        port = Integer.parseInt(portString);
    }

    String dbHost = "localhost";
    if (commandLine.hasOption("dbh")) {
        dbHost = commandLine.getOptionValue("dbh");
    }

    int dbPort = 27017;
    if (commandLine.hasOption("dbp")) {
        String portString = commandLine.getOptionValue("dbp");
        dbPort = Integer.parseInt(portString);
    }

    boolean isIgnoringCase = true;
    if (commandLine.hasOption("case")) {
        isIgnoringCase = false;
    }

    boolean isStoppingEnabled = false;
    if (commandLine.hasOption("stop")) {
        isStoppingEnabled = true;
    }

    boolean isStemmingEnabled = false;
    if (commandLine.hasOption("stem")) {
        isStemmingEnabled = true;
    }

    try {
        Context context = Context.getInstance();
        context.setIgnoreCase(isIgnoringCase);
        context.setStopwordsEnabled(isStoppingEnabled);
        context.setStemmingEnabled(isStemmingEnabled);
        context.start(port, maxThreads, dbHost, dbPort);

    } catch (Exception ex) {
        ex.printStackTrace();
        logger.info("Shutting down the server...");
        System.exit(1);
    }
}

From source file:com.betfair.cougar.test.socket.app.SocketCompatibilityTestingApp.java

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

    Parser parser = new PosixParser();
    Options options = new Options();
    options.addOption("r", "repo", true, "Repository type to search: local|central");
    options.addOption("c", "client-concurrency", true,
            "Max threads to allow each client tester to run tests, defaults to 10");
    options.addOption("t", "test-concurrency", true, "Max client testers to run concurrently, defaults to 5");
    options.addOption("m", "max-time", true,
            "Max time (in minutes) to allow tests to complete, defaults to 10");
    options.addOption("v", "version", false, "Print version and exit");
    options.addOption("h", "help", false, "This help text");
    CommandLine commandLine = parser.parse(options, args);
    if (commandLine.hasOption("h")) {
        System.out.println(options);
        System.exit(0);//from   w  w w  .  j av a  2 s . co  m
    }
    if (commandLine.hasOption("v")) {
        System.out.println("How the hell should I know?");
        System.exit(0);
    }
    // 1. Find all testers in given repos
    List<RepoSearcher> repoSearchers = new ArrayList<>();
    for (String repo : commandLine.getOptionValues("r")) {
        if ("local".equals(repo.toLowerCase())) {
            repoSearchers.add(new LocalRepoSearcher());
        } else if ("central".equals(repo.toLowerCase())) {
            repoSearchers.add(new CentralRepoSearcher());
        } else {
            System.err.println("Unrecognized repo: " + repo);
            System.err.println(options);
            System.exit(1);
        }
    }
    int clientConcurrency = 10;
    if (commandLine.hasOption("c")) {
        try {
            clientConcurrency = Integer.parseInt(commandLine.getOptionValue("c"));
        } catch (NumberFormatException nfe) {
            System.err.println(
                    "client-concurrency is not a valid integer: '" + commandLine.getOptionValue("c") + "'");
            System.exit(1);
        }
    }
    int testConcurrency = 5;
    if (commandLine.hasOption("t")) {
        try {
            testConcurrency = Integer.parseInt(commandLine.getOptionValue("t"));
        } catch (NumberFormatException nfe) {
            System.err.println(
                    "test-concurrency is not a valid integer: '" + commandLine.getOptionValue("t") + "'");
            System.exit(1);
        }
    }
    int maxMinutes = 10;
    if (commandLine.hasOption("m")) {
        try {
            maxMinutes = Integer.parseInt(commandLine.getOptionValue("m"));
        } catch (NumberFormatException nfe) {
            System.err.println("max-time is not a valid integer: '" + commandLine.getOptionValue("m") + "'");
            System.exit(1);
        }
    }

    Properties clientProps = new Properties();
    clientProps.setProperty("client.concurrency", String.valueOf(clientConcurrency));

    File baseRunDir = new File(System.getProperty("user.dir") + "/run");
    baseRunDir.mkdirs();

    File tmpDir = new File(baseRunDir, "jars");
    tmpDir.mkdirs();

    List<ServerRunner> serverRunners = new ArrayList<>();
    List<ClientRunner> clientRunners = new ArrayList<>();
    for (RepoSearcher searcher : repoSearchers) {
        List<File> jars = searcher.findAndCache(tmpDir);
        for (File f : jars) {
            ServerRunner serverRunner = new ServerRunner(f, baseRunDir);
            System.out.println("Found tester: " + serverRunner.getVersion());
            serverRunners.add(serverRunner);
            clientRunners.add(new ClientRunner(f, baseRunDir, clientProps));
        }
    }

    // 2. Start servers and collect ports
    System.out.println();
    System.out.println("Starting " + serverRunners.size() + " servers...");
    for (ServerRunner server : serverRunners) {
        server.startServer();
    }
    System.out.println();

    List<TestCombo> tests = new ArrayList<>(serverRunners.size() * clientRunners.size());
    for (ServerRunner server : serverRunners) {
        for (ClientRunner client : clientRunners) {
            tests.add(new TestCombo(server, client));
        }
    }

    System.out.println("Enqueued " + tests.size() + " test combos to run...");

    long startTime = System.currentTimeMillis();
    // 3. Run every client against every server, collecting results
    BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue(serverRunners.size() * clientRunners.size());
    ThreadPoolExecutor service = new ThreadPoolExecutor(testConcurrency, testConcurrency, 5000,
            TimeUnit.MILLISECONDS, workQueue);
    service.prestartAllCoreThreads();
    workQueue.addAll(tests);
    while (!workQueue.isEmpty()) {
        Thread.sleep(1000);
    }
    service.shutdown();
    service.awaitTermination(maxMinutes, TimeUnit.MINUTES);
    long endTime = System.currentTimeMillis();
    long totalTimeSecs = Math.round((endTime - startTime) / 1000.0);
    for (ServerRunner server : serverRunners) {
        server.shutdownServer();
    }

    System.out.println();
    System.out.println("=======");
    System.out.println("Results");
    System.out.println("-------");
    // print a summary
    int totalTests = 0;
    int totalSuccess = 0;
    for (TestCombo combo : tests) {
        String clientVer = combo.getClientVersion();
        String serverVer = combo.getServerVersion();
        String results = combo.getClientResults();
        ObjectMapper mapper = new ObjectMapper(new JsonFactory());
        JsonNode node = mapper.reader().readTree(results);
        JsonNode resultsArray = node.get("results");
        int numTests = resultsArray.size();
        int numSuccess = 0;
        for (int i = 0; i < numTests; i++) {
            if ("success".equals(resultsArray.get(i).get("result").asText())) {
                numSuccess++;
            }
        }
        totalSuccess += numSuccess;
        totalTests += numTests;
        System.out.println(clientVer + "/" + serverVer + ": " + numSuccess + "/" + numTests
                + " succeeded - took " + String.format("%2f", combo.getRunningTime()) + " seconds");
    }
    System.out.println("-------");
    System.out.println(
            "Overall: " + totalSuccess + "/" + totalTests + " succeeded - took " + totalTimeSecs + " seconds");

    FileWriter out = new FileWriter("results.json");
    PrintWriter pw = new PrintWriter(out);

    // 4. Output full results
    pw.println("{\n  \"results\": [");
    for (TestCombo combo : tests) {
        combo.emitResults(pw, "    ");
    }
    pw.println("  ],");
    pw.println("  \"servers\": [");
    for (ServerRunner server : serverRunners) {
        server.emitInfo(pw, "    ");
    }
    pw.println("  ],");
    pw.close();
}

From source file:com.haulmont.mp2xls.MessagePropertiesProcessor.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption(READ_OPT, "read", false, "read messages from project and save to XLS");
    options.addOption(WRITE_OPT, "write", false, "load messages from XLS and write to project");
    options.addOption(OVERWRITE_OPT, "overwrite", false,
            "overwrite existing messages by changed messages from XLS file");
    options.addOption(PROJECT_DIR_OPT, "projectDir", true, "project root directory");
    options.addOption(XLS_FILE_OPT, "xlsFile", true, "XLS file with translations");
    options.addOption(LOG_FILE_OPT, "logFile", true, "log file");
    options.addOption(LANGUAGES_OPT, "languages", true,
            "list of locales separated by comma, for example: 'de,fr'");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;/*  ww w  . ja  v  a  2  s . c o  m*/
    try {
        cmd = parser.parse(options, args);
        if ((!cmd.hasOption(READ_OPT) && !cmd.hasOption(WRITE_OPT)) || !cmd.hasOption(PROJECT_DIR_OPT)
                || !cmd.hasOption(XLS_FILE_OPT) || !cmd.hasOption(LANGUAGES_OPT)) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("Messages To/From XLS Convertor", options);
            System.exit(-1);
        }
        if (cmd.hasOption(READ_OPT) && cmd.hasOption(WRITE_OPT)) {
            System.out.println("Please provide either 'read' or 'write' option");
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("Messages To/From XLS Convertor", options);
            System.exit(-1);
        }

        Set<String> languages = getLanguages(cmd.getOptionValue(LANGUAGES_OPT));

        if (cmd.hasOption(READ_OPT)) {
            LocalizationsBatch localizationsBatch = new LocalizationsBatch(cmd.getOptionValue(PROJECT_DIR_OPT));
            localizationsBatch.setScanLocalizationIds(languages);

            LocalizationBatchExcelWriter.exportToXls(localizationsBatch, cmd.getOptionValue(XLS_FILE_OPT));

        } else if (cmd.hasOption(WRITE_OPT)) {
            LocalizationsBatch sourceLocalization = new LocalizationsBatch(cmd.getOptionValue(PROJECT_DIR_OPT));
            sourceLocalization.setScanLocalizationIds(languages);

            LocalizationsBatch fileLocalization = new LocalizationsBatch(cmd.getOptionValue(XLS_FILE_OPT),
                    cmd.getOptionValue(PROJECT_DIR_OPT));
            fileLocalization.setScanLocalizationIds(languages);

            LocalizationBatchFileWriter fileWriter = new LocalizationBatchFileWriter(sourceLocalization,
                    fileLocalization);
            String logFile = StringUtils.isNotEmpty(cmd.getOptionValue(LOG_FILE_OPT))
                    ? cmd.getOptionValue(LOG_FILE_OPT)
                    : "log.xls";
            fileWriter.process(logFile, cmd.hasOption(OVERWRITE_OPT));
        }
    } catch (Throwable e) {
        e.printStackTrace();
        System.exit(-1);
    }
}

From source file:net.palette_software.pet.restart.Main.java

public static void main(String[] args) {
    //if true, help will shown
    boolean need_help = true;

    //fast&dirty cli implementation
    CommandLineParser parser = new GnuParser();
    Options options = new Options();

    //create the command line options
    CliControl.createCommandLineOptions(options);

    try {/*from w  w  w .j  a v a 2  s  .  c  o m*/

        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        //Turn simulation on if the simulation cli flag is set.
        CliControl.useCommandLineOptionSimulation(line);

        if (CliControl.isSimulation()) {
            HelperLogger.loggerStdOut.info("Running simulation.");
        }

        //check if tabsvc is running
        if (HelperWindowsTask.isTabsvcRunning()) {

            HelperLogger.loggerStdOut.info("tabsvc.exe not ruinning...");

        } else {

            //Turn force-restart on if the force cli flag is set.
            CliControl.useCommandLineOptionForce(line);

            //change tabsvc config dir if it has been set in command line.
            CliControl.useCommandLineOptionTabsvcConfigDir(line);

            //change tableau installation dir if it has been set in command line.
            CliControl.useCommandLineOptionTableauInstallationDir(line);

            //change force restart timeout if it has been set in command line.
            CliControl.useCommandLineOptionForceRestartTimeout(line);

            //change JMX polling timeout if it has been set in command line.
            CliControl.useCommandLineOptionJmxPollingTime(line);

            //change wait time between pet-restart operations if it has been set in command line.
            CliControl.useCommandLineOptionWait(line);

            //change wait time after something went wrong if it has been set in command line.
            CliControl.useCommandLineOptionWaitErrors(line);

            need_help = CliControl.runCliControlledTasks(line);
        }

        //Show CLI help if it is needed
        CliControl.showCommandLineHelp(need_help, options, line);

    } catch (Exception e) {
        //e.printStackTrace();
        HelperLogger.loggerStdOut.info(e.getMessage());
        HelperLogger.loggerFile.fatal("fatal:", e);
    }
}

From source file:com.falcon.orca.Main.java

public static void main(String[] args) throws IOException {
    Option mode = Option.builder("mo").longOpt("mode").required(true).hasArg(true)
            .desc("Mode to start the node " + "in, possible values are standalone master slave").build();
    Option host = Option.builder("ho").longOpt("host").hasArg(true).desc("Machine name").build();
    Options modeOptions = new Options();
    modeOptions.addOption(mode);//from  w ww  . ja v  a 2  s .co m
    modeOptions.addOption(host);
    CommandLineParser commandLineParser = new DefaultParser();
    ModeHandler handler;
    final ActorSystem actorSystem = ActorSystem.create();
    String machineName = "127.0.0.1";
    try {
        CommandLine commandLine = commandLineParser.parse(modeOptions, args);
        if (commandLine.hasOption("host")) {
            machineName = commandLine.getOptionValue("host");
        }
        if (commandLine.hasOption("mode")) {
            String modeValue = commandLine.getOptionValue("mode");
            if ("standalone".equalsIgnoreCase(modeValue)) {
                handler = new StandAloneHandler(actorSystem);
                handler.handle();
            } else if ("master".equalsIgnoreCase(modeValue)) {
                handler = new MasterHandler(actorSystem, 1, machineName);
                handler.handle();
            } else if ("slave".equalsIgnoreCase(modeValue)) {
                handler = new SlaveHandler(actorSystem);
                handler.handle();
            } else {
                actorSystem.shutdown();
                System.out
                        .println("Mode is required, use -mo or --mode, possible values are standalone, master "
                                + "and slave");
            }
        } else {
            actorSystem.shutdown();
            System.out
                    .println("Mode is required, use -mo or --mode, possible values are standalone, master and "
                            + "slave");
        }
    } catch (ParseException e) {
        actorSystem.shutdown();
        System.out.println(
                "Mode is required, use -mo or --mode, possible values are standalone, master and slave");
    }
}

From source file:com.hurence.logisland.runner.SparkJobLauncher.java

/**
 * main entry point/*from  w ww .  ja  v  a  2  s .  co  m*/
 *
 * @param args
 */
public static void main(String[] args) {

    logger.info("starting StreamProcessingRunner");

    //////////////////////////////////////////
    // Commande lien management
    Parser parser = new GnuParser();
    Options options = new Options();

    String helpMsg = "Print this message.";
    Option help = new Option("help", helpMsg);
    options.addOption(help);

    OptionBuilder.withArgName(AGENT);
    OptionBuilder.withLongOpt("agent-quorum");
    OptionBuilder.isRequired();
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("logisland agent quorum like host1:8081,host2:8081");
    Option agent = OptionBuilder.create(AGENT);
    options.addOption(agent);

    OptionBuilder.withArgName(JOB);
    OptionBuilder.withLongOpt("job-name");
    OptionBuilder.isRequired();
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("logisland agent quorum like host1:8081,host2:8081");
    Option job = OptionBuilder.create(JOB);
    options.addOption(job);

    String logisland = "                      \n"
            + "     ????????   ?????     ??  ??\n"
            + "                    \n"
            + "             ????     ??  \n"
            + "??     ?\n"
            + "??????? ??????  ??????   ??????????????????  ????  ??????????   v0.10.0-SNAPSHOT\n\n\n";

    System.out.println(logisland);
    Optional<EngineContext> engineInstance = Optional.empty();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);
        String agentQuorum = line.getOptionValue(AGENT);
        String jobName = line.getOptionValue(JOB);

        // instanciate engine and all the processor from the config
        engineInstance = new RestComponentFactory(agentQuorum).getEngineContext(jobName);
        assert engineInstance.isPresent();
        assert engineInstance.get().isValid();

        logger.info("starting Logisland session version {}", engineInstance.get());
    } catch (Exception e) {
        logger.error("unable to launch runner : {}", e.toString());
    }

    try {
        // start the engine
        EngineContext engineContext = engineInstance.get();
        engineInstance.get().getEngine().start(engineContext);
    } catch (Exception e) {
        logger.error("something went bad while running the job : {}", e);
        System.exit(-1);
    }

}

From source file:GossipP2PServer.java

public static void main(String args[]) {
    // Arguments that should be passed in
    int port = -1;
    String databasePath = "";

    // Set up arg options
    Options options = new Options();
    Option p = new Option("p", true, "Port for server to listen on.");
    options.addOption(p);//from   w w  w  . ja v  a2 s  .c o  m
    Option d = new Option("d", true, "Path to database.");
    options.addOption(d);

    CommandLineParser clp = new DefaultParser();

    try {
        CommandLine cl = clp.parse(options, args);

        if (cl.hasOption("p")) {
            port = Integer.parseInt(cl.getOptionValue("p"));
        }
        if (cl.hasOption("d")) {
            databasePath = cl.getOptionValue("d");
        }

        // If we have all we need start the server and setup database.
        if (port != -1 && !databasePath.isEmpty() && databasePath != null) {
            Database.getInstance().initializeDatabase(databasePath);
            runConcurrentServer(port);
        } else {
            showArgMenu(options);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.jingx.main.Main.java

/**
 * @param args/*from  ww w.  ja v a  2  s .  c  o m*/
 * @throws IOException 
 */
public static void main(String[] args) {
    CommandLineParser parser = new PosixParser();
    Options options = new Options();
    options.addOption(CLI_SECRET, true, "generate secret key (input is the configuration key from google)");
    options.addOption(CLI_PASSCODE, true, "generate passcode (input is the secret key)");
    options.addOption(new Option(CLI_HELP, "print this message"));
    try {
        CommandLine line = parser.parse(options, args);
        if (line.hasOption(CLI_SECRET)) {
            String confKey = line.getOptionValue(CLI_SECRET);
            String secret = generateSecret(confKey);
            System.out.println("Your secret to generate pins: " + secret);
        } else if (line.hasOption(CLI_PASSCODE)) {
            String secret = line.getOptionValue(CLI_PASSCODE);
            String pin = computePin(secret, null);
            System.out.println(pin);
        } else if (line.hasOption(CLI_HELP)) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("GAuthCli", options);
        } else {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try {
                        MainGui window = new MainGui();
                        window.doSetVisible();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            return;
        }
        System.out.println("Press any key to exit");
        System.in.read();
    } catch (Exception e) {
        System.out.println("Unexpected exception:" + e.getMessage());
    }
    System.exit(0);
}