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

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

Introduction

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

Prototype

public Options addOption(Option opt) 

Source Link

Document

Adds an option instance

Usage

From source file:com.msd.gin.halyard.tools.HalyardUpdate.java

/**
 * Main of the HalyardUpdate/*from ww  w.ja  va2  s  .c o m*/
 * @param args String command line arguments
 * @throws Exception throws Exception in case of any problem
 */
public static void main(final String args[]) throws Exception {
    if (conf == null)
        conf = new Configuration();
    Options options = new Options();
    options.addOption(newOption("h", null, "Prints this help"));
    options.addOption(newOption("v", null, "Prints version"));
    options.addOption(newOption("s", "source_htable", "Source HBase table with Halyard RDF store"));
    options.addOption(
            newOption("q", "sparql_query", "SPARQL tuple or graph query executed to export the data"));
    try {
        CommandLine cmd = new PosixParser().parse(options, args);
        if (args.length == 0 || cmd.hasOption('h')) {
            printHelp(options);
            return;
        }
        if (cmd.hasOption('v')) {
            Properties p = new Properties();
            try (InputStream in = HalyardUpdate.class
                    .getResourceAsStream("/META-INF/maven/com.msd.gin.halyard/hbasesail/pom.properties")) {
                if (in != null)
                    p.load(in);
            }
            System.out.println("Halyard Update version " + p.getProperty("version", "unknown"));
            return;
        }
        if (!cmd.getArgList().isEmpty())
            throw new ParseException("Unknown arguments: " + cmd.getArgList().toString());
        for (char c : "sq".toCharArray()) {
            if (!cmd.hasOption(c))
                throw new ParseException("Missing mandatory option: " + c);
        }
        for (char c : "sq".toCharArray()) {
            String s[] = cmd.getOptionValues(c);
            if (s != null && s.length > 1)
                throw new ParseException("Multiple values for option: " + c);
        }

        SailRepository rep = new SailRepository(
                new HBaseSail(conf, cmd.getOptionValue('s'), false, 0, true, 0, null));
        rep.initialize();
        try {
            Update u = rep.getConnection().prepareUpdate(QueryLanguage.SPARQL, cmd.getOptionValue('q'));
            LOG.info("Update execution started");
            u.execute();
            LOG.info("Update finished");
        } finally {
            rep.shutDown();
        }

    } catch (Exception exp) {
        System.out.println(exp.getMessage());
        printHelp(options);
        throw exp;
    }
}

From source file:com.github.r351574nc3.amex.assignment1.App.java

public static void main(final String... args) {
    if (args.length < 1) {
        printUsage();/*from   w  w w. java2 s.  co m*/
        System.exit(0);
    }

    final Options options = new Options();
    options.addOption(OptionBuilder.withArgName("output").hasArg(true).withDescription("Path for CSV output")
            .create("o"));
    options.addOption(
            OptionBuilder.withArgName("input").hasArg(true).withDescription("Path for CSV input").create("i"));

    final CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        printUsage();
        System.exit(0);
    }

    if ((cmd.hasOption('o') && cmd.hasOption('i')) || !(cmd.hasOption('o') || cmd.hasOption('i'))
            || (cmd.hasOption('o') && cmd.getArgs().length < 1)) {
        printUsage();
        System.exit(0);
    }

    if (cmd.hasOption('o') && cmd.getArgs().length > 0) {
        final String outputName = cmd.getOptionValue("o");
        final int iterations = Integer.parseInt(cmd.getArgs()[cmd.getArgs().length - 1]);
        new App().run(new File(outputName), iterations);
    } else if (cmd.hasOption('i')) {
        final String inputName = cmd.getOptionValue("i");
        new App().run(new File(inputName));
    }

    System.exit(0);
}

From source file:com.twitter.bazel.checkstyle.CppCheckstyle.java

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

    // create the Options
    Options options = new Options();
    options.addOption(Option.builder("f").required(true).hasArg().longOpt("extra_action_file")
            .desc("bazel extra action protobuf file").build());
    options.addOption(Option.builder("c").required(true).hasArg().longOpt("cpplint_file")
            .desc("Executable cpplint file to invoke").build());

    try {/*from   ww w  .j  a v  a  2  s .  c om*/
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        String extraActionFile = line.getOptionValue("f");
        String cpplintFile = line.getOptionValue("c");

        Collection<String> sourceFiles = getSourceFiles(extraActionFile);
        if (sourceFiles.size() == 0) {
            LOG.fine("No cpp files found by checkstyle");
            return;
        }

        LOG.fine(sourceFiles.size() + " cpp files found by checkstyle");

        // Create and run the command
        List<String> commandBuilder = new ArrayList<>();
        commandBuilder.add(cpplintFile);
        commandBuilder.add("--linelength=100");
        // TODO: https://github.com/twitter/heron/issues/466,
        // Remove "runtime/references" when we fix all non-const references in our codebase.
        // TODO: https://github.com/twitter/heron/issues/467,
        // Remove "runtime/threadsafe_fn" when we fix all non-threadsafe libc functions
        commandBuilder.add("--filter=-build/header_guard,-runtime/references,-runtime/threadsafe_fn");
        commandBuilder.addAll(sourceFiles);
        runLinter(commandBuilder);

    } catch (ParseException exp) {
        LOG.severe(String.format("Invalid input to %s: %s", CLASSNAME, exp.getMessage()));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java " + CLASSNAME, options);
    }
}

From source file:com.floragunn.searchguard.tools.Hasher.java

public static void main(final String[] args) {

    final Options options = new Options();
    final HelpFormatter formatter = new HelpFormatter();
    options.addOption(
            Option.builder("p").argName("password").hasArg().desc("Cleartext password to hash").build());
    options.addOption(Option.builder("env").argName("name environment variable").hasArg()
            .desc("name environment variable to read password from").build());

    final CommandLineParser parser = new DefaultParser();
    try {// w w  w  .j  a  v a 2 s .c  o  m
        final CommandLine line = parser.parse(options, args);

        if (line.hasOption("p")) {
            System.out.println(hash(line.getOptionValue("p").getBytes("UTF-8")));
        } else if (line.hasOption("env")) {
            final String pwd = System.getenv(line.getOptionValue("env"));
            if (pwd == null || pwd.isEmpty()) {
                throw new Exception("No environment variable '" + line.getOptionValue("env") + "' set");
            }
            System.out.println(hash(pwd.getBytes("UTF-8")));
        } else {
            final Console console = System.console();
            if (console == null) {
                throw new Exception("Cannot allocate a console");
            }
            final char[] passwd = console.readPassword("[%s]", "Password:");
            System.out.println(hash(new String(passwd).getBytes("UTF-8")));
        }
    } catch (final Exception exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        formatter.printHelp("hasher.sh", options, true);
        System.exit(-1);
    }
}

From source file:com.servioticy.dispatcher.DispatcherTopology.java

/**
 * @param args/*w w  w  .j  a v a  2  s  .  c o  m*/
 * @throws InvalidTopologyException
 * @throws AlreadyAliveException
 * @throws InterruptedException
 */
public static void main(String[] args)
        throws AlreadyAliveException, InvalidTopologyException, InterruptedException, ParseException {

    Options options = new Options();

    options.addOption(
            OptionBuilder.withArgName("file").hasArg().withDescription("Config file path.").create("f"));
    options.addOption(OptionBuilder.withArgName("topology").hasArg()
            .withDescription("Name of the topology in storm. If no name is given it will run in local mode.")
            .create("t"));
    options.addOption(OptionBuilder.withDescription("Enable debugging").create("d"));

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

    String path = null;
    if (cmd.hasOption("f")) {
        path = cmd.getOptionValue("f");
    }

    DispatcherContext dc = new DispatcherContext();
    dc.loadConf(path);

    TopologyBuilder builder = new TopologyBuilder();

    // TODO Auto-assign workers to the spout in function of the number of Kestrel IPs
    builder.setSpout("updates", new KestrelThriftSpout(Arrays.asList(dc.updatesAddresses), dc.updatesPort,
            dc.updatesQueue, new UpdateDescriptorScheme()));
    builder.setSpout("actions", new KestrelThriftSpout(Arrays.asList(dc.actionsAddresses), dc.actionsPort,
            dc.actionsQueue, new ActuationScheme()));

    builder.setBolt("prepare", new PrepareBolt(dc)).shuffleGrouping("updates");

    builder.setBolt("actuationdispatcher", new ActuationDispatcherBolt(dc)).shuffleGrouping("actions");

    builder.setBolt("subretriever", new SubscriptionRetrieveBolt(dc)).shuffleGrouping("prepare",
            "subscription");

    builder.setBolt("externaldispatcher", new ExternalDispatcherBolt(dc)).fieldsGrouping("subretriever",
            "externalSub", new Fields("subid"));
    builder.setBolt("internaldispatcher", new InternalDispatcherBolt(dc)).fieldsGrouping("subretriever",
            "internalSub", new Fields("subid"));

    builder.setBolt("streamdispatcher", new StreamDispatcherBolt(dc))
            .shuffleGrouping("subretriever", "streamSub").shuffleGrouping("prepare", "stream");
    builder.setBolt("streamprocessor", new StreamProcessorBolt(dc)).shuffleGrouping("streamdispatcher",
            "default");

    if (dc.benchmark) {
        builder.setBolt("benchmark", new BenchmarkBolt(dc)).shuffleGrouping("streamdispatcher", "benchmark")
                .shuffleGrouping("subretriever", "benchmark").shuffleGrouping("streamprocessor", "benchmark")
                .shuffleGrouping("prepare", "benchmark");
    }

    Config conf = new Config();
    conf.setDebug(cmd.hasOption("d"));
    if (cmd.hasOption("t")) {
        StormSubmitter.submitTopology(cmd.getOptionValue("t"), conf, builder.createTopology());
    } else {
        conf.setMaxTaskParallelism(4);
        LocalCluster cluster = new LocalCluster();
        cluster.submitTopology("dispatcher", conf, builder.createTopology());

    }

}

From source file:com.buddycloud.channeldirectory.cli.Main.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {

    JsonElement rootElement = new JsonParser().parse(new FileReader(QUERIES_FILE));
    JsonArray rootArray = rootElement.getAsJsonArray();

    Map<String, Query> queries = new HashMap<String, Query>();

    for (int i = 0; i < rootArray.size(); i++) {
        JsonObject queryElement = rootArray.get(i).getAsJsonObject();
        String queryName = queryElement.get("name").getAsString();
        String type = queryElement.get("type").getAsString();

        Query query = null;//www. ja v  a2 s  . c o m

        if (type.equals("solr")) {
            query = new QueryToSolr(queryElement.get("agg").getAsString(),
                    queryElement.get("core").getAsString(), queryElement.get("q").getAsString());
        } else if (type.equals("dbms")) {
            query = new QueryToDBMS(queryElement.get("q").getAsString());
        }

        queries.put(queryName, query);
    }

    LinkedList<String> queriesNames = new LinkedList<String>(queries.keySet());
    Collections.sort(queriesNames);

    Options options = new Options();
    options.addOption(OptionBuilder.isRequired(true).withLongOpt("query").hasArg(true)
            .withDescription("The name of the query. Possible queries are: " + queriesNames).create('q'));

    options.addOption(OptionBuilder.isRequired(false).withLongOpt("args").hasArg(true)
            .withDescription("Arguments for the query").create('a'));

    options.addOption(new Option("?", "help", false, "Print this message"));

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        printHelpAndExit(options);
    }

    if (cmd.hasOption("help")) {
        printHelpAndExit(options);
    }

    String queryName = cmd.getOptionValue("q");
    String argsCmd = cmd.getOptionValue("a");

    Properties configuration = ConfigurationUtils.loadConfiguration();

    Query query = queries.get(queryName);
    if (query == null) {
        printHelpAndExit(options);
    }

    System.out.println(query.exec(argsCmd, configuration));

}

From source file:com.act.biointerpretation.l2expansion.L2PredictionCorpusOperations.java

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

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

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(L2PredictionCorpusOperations.class.getCanonicalName(), HELP_MESSAGE, opts,
                null, true);
        System.exit(1);
    }

    if (cl.hasOption(OPTION_WRITE_PRODUCTS_AS_LIST_OF_INCHIS)) {
        L2PredictionCorpus corpus = L2PredictionCorpus.readPredictionsFromJsonFile(
                new File(cl.getOptionValue(OPTION_WRITE_PRODUCTS_AS_LIST_OF_INCHIS)));
        corpus.writePredictionsAsInchiList(
                new File(cl.getOptionValue(OPTION_WRITE_PRODUCTS_AS_LIST_OF_INCHIS)));
    }
}

From source file:cc.wikitools.lucene.SearchWikipedia.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(
            OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_OPTION));
    options.addOption(//from   w w  w  .  j  a  va2s.c  o  m
            OptionBuilder.withArgName("string").hasArg().withDescription("query text").create(QUERY_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of results to return")
            .create(NUM_RESULTS_OPTION));

    options.addOption(new Option(VERBOSE_OPTION, "print out complete document"));
    options.addOption(new Option(TITLE_OPTION, "search title"));
    options.addOption(new Option(ARTICLE_OPTION, "search article"));

    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(QUERY_OPTION) || !cmdline.hasOption(INDEX_OPTION)
            || !cmdline.hasOption(QUERY_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(SearchWikipedia.class.getName(), options);
        System.exit(-1);
    }

    File indexLocation = new File(cmdline.getOptionValue(INDEX_OPTION));
    if (!indexLocation.exists()) {
        System.err.println("Error: " + indexLocation + " does not exist!");
        System.exit(-1);
    }

    String queryText = cmdline.getOptionValue(QUERY_OPTION);
    int numResults = cmdline.hasOption(NUM_RESULTS_OPTION)
            ? Integer.parseInt(cmdline.getOptionValue(NUM_RESULTS_OPTION))
            : DEFAULT_NUM_RESULTS;
    boolean verbose = cmdline.hasOption(VERBOSE_OPTION);
    boolean searchArticle = !cmdline.hasOption(TITLE_OPTION);

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

    WikipediaSearcher searcher = new WikipediaSearcher(indexLocation);
    TopDocs rs = null;
    if (searchArticle) {
        rs = searcher.searchArticle(queryText, numResults);
    } else {
        rs = searcher.searchTitle(queryText, numResults);
    }

    int i = 1;
    for (ScoreDoc scoreDoc : rs.scoreDocs) {
        Document hit = searcher.doc(scoreDoc.doc);

        out.println(String.format("%d. %s (wiki id = %s, lucene id = %d) %f", i,
                hit.getField(IndexField.TITLE.name).stringValue(),
                hit.getField(IndexField.ID.name).stringValue(), scoreDoc.doc, scoreDoc.score));
        if (verbose) {
            out.println("# " + hit.toString().replaceAll("[\\n\\r]+", " "));
        }
        i++;
    }

    searcher.close();
    out.close();
}

From source file:com.xafero.vee.cmd.MainApp.java

public static void main(String[] args) {
    // Define options
    Option help = new Option("?", "help", false, "print this message");
    Option version = new Option("v", "version", false, "print the version information and exit");
    Option eval = Option.builder("e").desc("evaluate script").argName("file").longOpt("eval").hasArg().build();
    Option list = new Option("l", "list", false, "print all available languages");
    // Collect them
    Options options = new Options();
    options.addOption(help);
    options.addOption(version);/*from   w w  w  .java 2 s . c  o  m*/
    options.addOption(eval);
    options.addOption(list);
    // If nothing given, nothing will happen
    if (args == null || args.length < 1) {
        printHelp(options);
        return;
    }
    // Parse command line
    try {
        CommandLineParser parser = new DefaultParser();
        CommandLine line = parser.parse(options, args);
        // Work on it
        process(line, options);
    } catch (Throwable e) {
        System.err.printf("Error occurred: %n " + e.getMessage());
    }
}

From source file:com.chezzverse.timelogger.server.TimeLoggerServerMain.java

public static void main(String[] args) {

    // Initialize the default configuration file to the hard coded default path value.
    String configFileName = _DEFAULT_CONFIG_FILE;

    // Create all the available options
    Option portOpt = new Option("p", "port", true, "Set the listen port for the http server " + "instance.");
    portOpt.setArgName("number");

    Option htmlOpt = new Option("h", "html-root", true,
            "Set the root directory that " + "contains the required html files.");
    htmlOpt.setArgName("directory");

    Option configOpt = new Option("c", "config", true,
            "Get configuration options from the " + "specified file");
    Option backlogOpt = new Option("b", "backlog", true,
            "Set the number of connections to " + "queue for the server.");

    Options opts = new Options();
    opts.addOption(portOpt);
    opts.addOption(htmlOpt);//w  ww  .  ja v a 2 s  .  c om
    opts.addOption(configOpt);
    opts.addOption(backlogOpt);

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

    try {
        // Parse the command line arguments.
        cmd = parser.parse(opts, args);

        // Fist check to see if there is a custom defined config file, and load the config file.
        if (cmd.hasOption("c")) {
            configFileName = cmd.getOptionValue("c");
        }

        TimeLoggerConfig.getInstance().LoadConfigFile(configFileName);

        // Process the rest of the args and override any settings in the config file.
        if (cmd.hasOption("h")) {
            TimeLoggerConfig.getInstance().htmlRoot = cmd.getOptionValue("h");
        }

        if (cmd.hasOption("p")) {
            TimeLoggerConfig.getInstance().port = Integer.parseInt(cmd.getOptionValue("p"));
        }

        if (cmd.hasOption("b")) {
            TimeLoggerConfig.getInstance().maxBackLog = Integer.parseInt(cmd.getOptionValue("b"));
        }

    } catch (ParseException e) {
        System.out.println("Invalid argument.");
        formatter.printHelp("TimeLoggerServer", opts);
        System.exit(1);
    } catch (NumberFormatException e) {
        System.out.println("Invalid argument.");
        formatter.printHelp("TimeLoggerServer", opts);
        System.exit(1);
    } catch (Exception e) {
        e.printStackTrace();
    }

    TimeLoggerApp app = new TimeLoggerApp();

    if (app != null) {
        app.run();
    } else {
        System.exit(3); // Strange termination
    }
}