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:com.hortonworks.streamline.storage.tool.SQLScriptRunner.java

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

    options.addOption(option(1, "c", OPTION_CONFIG_FILE_PATH, "Config file path"));
    options.addOption(option(Option.UNLIMITED_VALUES, "f", OPTION_SCRIPT_PATH, "Script path to execute"));
    options.addOption(option(Option.UNLIMITED_VALUES, "m", OPTION_MYSQL_JAR_URL_PATH,
            "Mysql client jar url to download"));
    CommandLineParser parser = new BasicParser();
    CommandLine commandLine = parser.parse(options, args);

    if (!commandLine.hasOption(OPTION_CONFIG_FILE_PATH) || !commandLine.hasOption(OPTION_SCRIPT_PATH)
            || commandLine.getOptionValues(OPTION_SCRIPT_PATH).length <= 0) {
        usage(options);/*from  w w w .  j ava  2 s  .co  m*/
        System.exit(1);
    }

    String confFilePath = commandLine.getOptionValue(OPTION_CONFIG_FILE_PATH);
    String[] scripts = commandLine.getOptionValues(OPTION_SCRIPT_PATH);
    String mysqlJarUrl = commandLine.getOptionValue(OPTION_MYSQL_JAR_URL_PATH);

    try {
        Map<String, Object> conf = Utils.readStreamlineConfig(confFilePath);

        StorageProviderConfigurationReader confReader = new StorageProviderConfigurationReader();
        StorageProviderConfiguration storageProperties = confReader.readStorageConfig(conf);

        String bootstrapDirPath = System.getProperty("bootstrap.dir");

        MySqlDriverHelper.downloadMySQLJarIfNeeded(storageProperties, bootstrapDirPath, mysqlJarUrl);

        SQLScriptRunner sqlScriptRunner = new SQLScriptRunner(storageProperties);
        try {
            sqlScriptRunner.initializeDriver();
        } catch (ClassNotFoundException e) {
            System.err.println(
                    "Driver class is not found in classpath. Please ensure that driver is in classpath.");
            System.exit(1);
        }

        for (String script : scripts) {
            sqlScriptRunner.runScriptWithReplaceDBType(script);
        }
    } catch (IOException e) {
        System.err.println("Error occurred while reading config file: " + confFilePath);
        System.exit(1);
    }
}

From source file:cc.twittertools.search.api.RunQueriesThrift.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(//  w w  w  .  j  a 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);
        int i = 1;
        Set<Long> tweetIds = new HashSet<Long>();
        for (TResult result : results) {
            if (!tweetIds.contains(result.id)) {
                tweetIds.add(result.id);
                out.println(
                        String.format("%s Q0 %d %d %f %s", query.getId(), result.id, i, result.rsv, runtag));
                if (verbose) {
                    out.println("# " + result.toString().replaceAll("[\\n\\r]+", " "));
                }
                i++;
            }
        }
    }
    out.close();
}

From source file:com.example.geomesa.kafka.KafkaListener.java

public static void main(String[] args) throws Exception {
    // read command line args for a connection to Kafka
    CommandLineParser parser = new BasicParser();
    Options options = getCommonRequiredOptions();
    CommandLine cmd = parser.parse(options, args);

    // create the consumer KafkaDataStore object
    Map<String, String> dsConf = getKafkaDataStoreConf(cmd);
    DataStore consumerDS = DataStoreFinder.getDataStore(dsConf);

    // verify that we got back our KafkaDataStore object properly
    if (consumerDS == null) {
        throw new Exception("Null consumer KafkaDataStore");
    }//from w w w.  j a  v a 2s .  c  o m

    Map<String, FeatureListener> listeners = new HashMap<>();

    try {
        for (String typeName : consumerDS.getTypeNames()) {
            System.out.println("Registering a feature listener for type " + typeName + ".");
            FeatureListener listener = new FeatureListener() {
                @Override
                public void changed(FeatureEvent featureEvent) {
                    System.out.println("Received FeatureEvent from layer " + typeName + " of Type: "
                            + featureEvent.getType());
                    if (featureEvent.getType() == FeatureEvent.Type.CHANGED
                            && featureEvent instanceof KafkaFeatureChanged) {
                        printFeature(((KafkaFeatureChanged) featureEvent).feature());
                    } else if (featureEvent.getType() == FeatureEvent.Type.REMOVED) {
                        System.out.println("Received Delete for filter: " + featureEvent.getFilter());
                    }
                }
            };
            consumerDS.getFeatureSource(typeName).addFeatureListener(listener);
            listeners.put(typeName, listener);
        }

        while (true) {
            // Wait for user to terminate with ctrl-C.
        }
    } finally {
        for (Entry<String, FeatureListener> entry : listeners.entrySet()) {
            consumerDS.getFeatureSource(entry.getKey()).removeFeatureListener(entry.getValue());
        }
        consumerDS.dispose();
    }
}

From source file:com.google.flightmap.parsing.faa.nasr.AirspaceParser.java

public static void main(String args[]) {
    CommandLine line = null;//from   ww  w . j a  va2  s  .co m
    try {
        final CommandLineParser parser = new PosixParser();
        line = parser.parse(OPTIONS, args);
    } catch (ParseException pEx) {
        System.err.println(pEx.getMessage());
        printHelp(line);
        System.exit(1);
    }

    if (line.hasOption(HELP_OPTION)) {
        printHelp(line);
        System.exit(0);
    }

    final String[] shapefiles = line.getOptionValues(SHAPEFILES_OPTION);
    final String dbFile = line.getOptionValue(AVIATION_DB_OPTION);

    try {
        for (String shapefile : shapefiles) {
            (new AirspaceParser(shapefile, dbFile)).execute();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        System.exit(1);
    }
}

From source file:de.jackwhite20.japs.server.Main.java

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

    Config config = null;//  ww w.  j a v a2 s  .  c om

    if (args.length > 0) {
        Options options = new Options();
        options.addOption("h", true, "Address to bind to");
        options.addOption("p", true, "Port to bind to");
        options.addOption("b", true, "The backlog");
        options.addOption("t", true, "Worker thread count");
        options.addOption("d", false, "If debug is enabled or not");
        options.addOption("c", true, "Add server as a cluster");
        options.addOption("ci", true, "Sets the cache check interval");
        options.addOption("si", true, "Sets the snapshot interval");

        CommandLineParser commandLineParser = new BasicParser();
        CommandLine commandLine = commandLineParser.parse(options, args);

        if (commandLine.hasOption("h") && commandLine.hasOption("p") && commandLine.hasOption("b")
                && commandLine.hasOption("t")) {

            List<ClusterServer> clusterServers = new ArrayList<>();

            if (commandLine.hasOption("c")) {
                for (String c : commandLine.getOptionValues("c")) {
                    String[] splitted = c.split(":");
                    clusterServers.add(new ClusterServer(splitted[0], Integer.parseInt(splitted[1])));
                }
            }

            config = new Config(commandLine.getOptionValue("h"),
                    Integer.parseInt(commandLine.getOptionValue("p")),
                    Integer.parseInt(commandLine.getOptionValue("b")), commandLine.hasOption("d"),
                    Integer.parseInt(commandLine.getOptionValue("t")), clusterServers,
                    (commandLine.hasOption("ci")) ? Integer.parseInt(commandLine.getOptionValue("ci")) : 300,
                    (commandLine.hasOption("si")) ? Integer.parseInt(commandLine.getOptionValue("si")) : -1);
        } else {
            System.out.println(
                    "Usage: java -jar japs-server.jar -h <Host> -p <Port> -b <Backlog> -t <Threads> [-c IP:Port IP:Port] [-d]");
            System.out.println(
                    "Example (with debugging enabled): java -jar japs-server.jar -h localhost -p 1337 -b 100 -t 4 -d");
            System.out.println(
                    "Example (with debugging enabled and cluster setup): java -jar japs-server.jar -h localhost -p 1337 -b 100 -t 4 -c localhost:1338 -d");
            System.exit(-1);
        }
    } else {
        File configFile = new File("config.json");
        if (!configFile.exists()) {
            try {
                Files.copy(JaPS.class.getClassLoader().getResourceAsStream("config.json"), configFile.toPath(),
                        StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException e) {
                System.err.println("Unable to load default config!");
                System.exit(-1);
            }
        }

        try {
            config = new Gson().fromJson(
                    Files.lines(configFile.toPath()).map(String::toString).collect(Collectors.joining(" ")),
                    Config.class);
        } catch (IOException e) {
            System.err.println("Unable to load 'config.json' in current directory!");
            System.exit(-1);
        }
    }

    if (config == null) {
        System.err.println("Failed to create a Config!");
        System.err.println("Please check the program parameters or the 'config.json' file!");
    } else {
        System.err.println("Using Config: " + config);

        JaPS jaPS = new JaPS(config);
        jaPS.init();
        jaPS.start();
        jaPS.stop();
    }
}

From source file:io.github.azige.whitespace.Cli.java

public static void main(String[] args) {
    Options options = new Options().addOption("h", "help", false, "??")
            .addOptionGroup(new OptionGroup()
                    .addOption(new Option("p",
                            "????????"))
                    .addOption(new Option("c", "?????")))
            .addOption(null, "szm", false,
                    "????")
            .addOption("e", "encoding", true, "??" + DEFAULT_ENCODING);

    try {/*from ww  w .  java2s .c o  m*/
        CommandLineParser parser = new BasicParser();
        CommandLine cl = parser.parse(options, args);

        if (cl.hasOption('h')) {
            printHelp(System.out, options);
            return;
        }

        if (cl.hasOption('e')) {
            encoding = Charset.forName(cl.getOptionValue('e'));
        } else {
            encoding = Charset.forName(DEFAULT_ENCODING);
        }

        if (cl.hasOption("szm")) {
            useSzm = true;
        }

        String[] fileArgs = cl.getArgs();
        if (fileArgs.length != 1) {
            printHelp(System.err, options);
            return;
        }

        try (InputStream input = Files.newInputStream(Paths.get(fileArgs[0]))) {
            if (cl.hasOption('p')) {
                printPseudoCode(input);
            } else if (cl.hasOption('c')) {
                compile(input, fileArgs[0]);
            } else {
                execute(input, fileArgs[0]);
            }
        }
    } catch (ParseException ex) {
        ex.printStackTrace();
        printHelp(System.err, options);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.act.biointerpretation.analytics.ReactionDeletion.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());/*from w  w  w  . j ava  2s .  com*/
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        LOGGER.error(String.format("Argument parsing failed: %s\n", e.getMessage()));
        HELP_FORMATTER.printHelp(ReactionCountProvenance.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(ReactionCountProvenance.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        return;
    }

    if (!cl.hasOption(OPTION_OUTPUT_PATH)) {
        LOGGER.error("Input -o prefix");
        return;
    }

    NoSQLAPI srcApi = new NoSQLAPI(cl.getOptionValue(OPTION_SOURCE_DB), cl.getOptionValue(OPTION_SOURCE_DB));
    NoSQLAPI sinkApi = new NoSQLAPI(cl.getOptionValue(OPTION_SINK_DB), cl.getOptionValue(OPTION_SINK_DB));

    searchForDroppedReactions(srcApi, sinkApi, new File(cl.getOptionValue(OPTION_OUTPUT_PATH)));
}

From source file:com.act.lcms.v2.TraceIndexAnalyzer.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());//from  ww w.  j a  va2  s  .co  m
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        System.err.format("Argument parsing failed: %s\n", e.getMessage());
        HELP_FORMATTER.printHelp(TraceIndexExtractor.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(TraceIndexExtractor.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        return;
    }

    File rocksDBFile = new File(cl.getOptionValue(OPTION_INDEX_PATH));
    if (!rocksDBFile.exists()) {
        System.err.format("Index file at %s does not exist, nothing to analyze", rocksDBFile.getAbsolutePath());
        HELP_FORMATTER.printHelp(TraceIndexExtractor.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    LOGGER.info("Starting analysis");

    TraceIndexAnalyzer analyzer = new TraceIndexAnalyzer();
    analyzer.runExtraction(rocksDBFile, new File(cl.getOptionValue(OPTION_OUTPUT_PATH)));

    LOGGER.info("Done");
}

From source file:edu.usc.pgroup.floe.flake.FlakeService.java

/**
 * Entry point for the flake./* w  ww  .ja  va2  s  .c  om*/
 *
 * @param args commandline arguments. (TODO)
 */
public static void main(final String[] args) {

    Options options = buildOptions();

    CommandLineParser parser = new BasicParser();
    CommandLine line;
    try {
        line = parser.parse(options, args);

    } catch (ParseException e) {
        LOGGER.error("Invalid command: " + e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("FlakeService", options);
        return;
    }

    String pid = line.getOptionValue("pid");
    String id = line.getOptionValue("id");
    String cid = line.getOptionValue("cid");
    String appName = line.getOptionValue("appname");
    String token = line.getOptionValue("token");
    String jar = null;
    if (line.hasOption("jar")) {
        jar = line.getOptionValue("jar");
    }

    LOGGER.info("pid: {}, id:{}, cid:{}, app:{}, jar:{}", pid, id, cid, appName, jar);
    try {
        new FlakeService(pid, id, cid, appName, jar).start();
    } catch (Exception e) {
        LOGGER.error("Exception while creating flake: {}", e);
        return;
    }
}

From source file:keepassj.cli.KeepassjCli.java

/**
 * @param args the command line arguments
 * @throws org.apache.commons.cli.ParseException
 * @throws java.io.IOException/*from www.j ava2  s.  c  o m*/
 */
public static void main(String[] args) throws ParseException, IOException {
    Options options = KeepassjCli.getOptions();
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);
    if (!KeepassjCli.validateOptions(cmd)) {
        HelpFormatter help = new HelpFormatter();
        help.printHelp("Usage: java -jar KeepassjCli -f dbfile [options]", options);
    } else {
        String password;
        if (cmd.hasOption('p')) {
            password = cmd.getOptionValue('p');
        } else {
            Console console = System.console();
            char[] hiddenString = console.readPassword("Enter password for %s\n", cmd.getOptionValue('f'));
            password = String.valueOf(hiddenString);
        }
        KeepassjCli instance = new KeepassjCli(cmd.getOptionValue('f'), password, cmd.getOptionValue('k'));
        System.out.println("Description:" + instance.db.getDescription());
        PwGroup rootGroup = instance.db.getRootGroup();
        System.out.println(String.valueOf(rootGroup.GetEntriesCount(true)) + " entries");
        if (cmd.hasOption('l')) {
            instance.printEntries(rootGroup.GetEntries(true), false);
        } else if (cmd.hasOption('s')) {
            PwObjectList<PwEntry> results = instance.search(cmd.getOptionValue('s'));
            System.out.println("Found " + results.getUCount() + " results for:" + cmd.getOptionValue('s'));
            instance.printEntries(results, false);
        } else if (cmd.hasOption('i')) {
            System.out.println("Entering interactive mode.");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            String input = null;
            PwObjectList<PwEntry> results = null;
            while (!"\\q".equals(input)) {
                if (results != null) {
                    System.out.println("Would you like to view a specific entry? y/n");
                    input = bufferedReader.readLine();
                    if ("y".equalsIgnoreCase(input)) {
                        System.out.print("Enter the title number:");
                        input = bufferedReader.readLine();
                        instance.printCompleteEntry(results.GetAt(Integer.parseInt(input) - 1)); // Since humans start counting at 1
                    }
                    results = null;
                    System.out.println();
                } else {
                    System.out.print("Enter something to search for (or \\q to quit):");
                    input = bufferedReader.readLine();
                    if (!"\\q".equalsIgnoreCase(input)) {
                        results = instance.search(input);
                        instance.printEntries(results, true);
                    }
                }
            }
        }

        // Close before exit
        instance.db.Close();
    }
}