Example usage for org.apache.commons.cli HelpFormatter printHelp

List of usage examples for org.apache.commons.cli HelpFormatter printHelp

Introduction

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

Prototype

public void printHelp(String cmdLineSyntax, Options options) 

Source Link

Document

Print the help for options with the specified command line syntax.

Usage

From source file:com.mozilla.bagheera.consumer.KafkaReplayConsumer.java

public static void main(String[] args) {
    OptionFactory optFactory = OptionFactory.getInstance();
    Options options = KafkaConsumer.getOptions();
    options.addOption(//from   www.j av  a2 s.  c  o  m
            optFactory.create("k", "copy-keys", true, "Whether or not to copy keys from the source data"));
    options.addOption(optFactory.create("d", "dest", true,
            "Destination host / url pattern (include '" + ReplaySink.KEY_PLACEHOLDER + "' for key placeholder)")
            .required());
    options.addOption(optFactory.create("s", "sample", true,
            "Rate at which to sample the source data (defaults to using all data)"));
    options.addOption(
            optFactory.create("D", "delete", true, "Also replay deletes (using the source keys by necessity)"));

    CommandLineParser parser = new GnuParser();
    ShutdownHook sh = ShutdownHook.getInstance();
    try {
        // Parse command line options
        CommandLine cmd = parser.parse(options, args);

        final KafkaConsumer consumer = KafkaConsumer.fromOptions(cmd);
        sh.addFirst(consumer);

        // Create a sink for storing data
        SinkConfiguration sinkConfig = new SinkConfiguration();
        if (cmd.hasOption("numthreads")) {
            sinkConfig.setInt("hbasesink.hbase.numthreads", Integer.parseInt(cmd.getOptionValue("numthreads")));
        }
        sinkConfig.setString("replaysink.keys", cmd.getOptionValue("copy-keys", "true"));
        sinkConfig.setString("replaysink.dest",
                cmd.getOptionValue("dest", "http://bogus:8080/submit/endpoint/" + ReplaySink.KEY_PLACEHOLDER));
        sinkConfig.setString("replaysink.sample", cmd.getOptionValue("sample", "1"));
        sinkConfig.setString("replaysink.delete", cmd.getOptionValue("delete", "true"));
        KeyValueSinkFactory sinkFactory = KeyValueSinkFactory.getInstance(ReplaySink.class, sinkConfig);
        sh.addLast(sinkFactory);

        // Set the sink factory for consumer storage
        consumer.setSinkFactory(sinkFactory);

        prepareHealthChecks();

        // Initialize metrics collection, reporting, etc.
        final MetricsManager manager = MetricsManager.getDefaultMetricsManager();

        // Begin polling
        consumer.poll();
    } catch (ParseException e) {
        LOG.error("Error parsing command line options", e);
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(KafkaReplayConsumer.class.getName(), options);
    }
}

From source file:com.linkedin.restli.tools.idlgen.RestLiResourceModelExporterCmdLineApp.java

/**
 * @param args restliexporter -sourcepath sourcepath -resourcepackages packagenames [-name api_name] [-outdir outdir]
 *//*w w w . j  a v a 2 s.com*/
public static void main(String[] args) {
    //    args = new String[] {"-name", "groups",
    //                         "-resourcepackages", "com.linkedin.groups.server.rest1.impl com.linkedin.groups.server.rest2.impl ",
    //                         "-resourceclasses", "com.linkedin.groups.server.restX.impl.FooResource",
    //                         "-sourcepath", "src/main/java",
    //                         "-outdir", "src/codegen/idl",
    //                         "-split"};

    CommandLine cl = null;
    try {
        final CommandLineParser parser = new GnuParser();
        cl = parser.parse(OPTIONS, args);
    } catch (ParseException e) {
        System.err.println("Invalid arguments: " + e.getMessage());
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(
                "restliexporter -sourcepath sourcepath [-resourcepackages packagenames] [-resourceclasses classnames]"
                        + "[-name api_name] [-outdir outdir]",
                OPTIONS);
        System.exit(0);
    }

    try {
        new RestLiResourceModelExporter().export(cl.getOptionValue("name"), null,
                cl.getOptionValues("sourcepath"), cl.getOptionValues("resourcepackages"),
                cl.getOptionValues("resourceclasses"), cl.getOptionValue("outdir", "."),
                AdditionalDocProvidersUtil.findDocProviders(log, cl.hasOption("loadAdditionalDocProviders")));
    } catch (Throwable e) {
        log.error("Error writing IDL files", e);
        System.exit(1);
    }
}

From source file:com.asual.lesscss.LessEngineCli.java

public static void main(String[] args) throws LessException, URISyntaxException {
    Options cmdOptions = new Options();
    cmdOptions.addOption(LessOptions.CHARSET_OPTION, true, "Input file charset encoding. Defaults to UTF-8.");
    cmdOptions.addOption(LessOptions.COMPRESS_OPTION, false, "Flag that enables compressed CSS output.");
    cmdOptions.addOption(LessOptions.CSS_OPTION, false, "Flag that enables compilation of .css files.");
    cmdOptions.addOption(LessOptions.LESS_OPTION, true, "Path to a custom less.js for Rhino version.");
    try {/* w w w.  ja va2 s.c o m*/
        CommandLineParser cmdParser = new GnuParser();
        CommandLine cmdLine = cmdParser.parse(cmdOptions, args);
        LessOptions options = new LessOptions();
        if (cmdLine.hasOption(LessOptions.CHARSET_OPTION)) {
            options.setCharset(cmdLine.getOptionValue(LessOptions.CHARSET_OPTION));
        }
        if (cmdLine.hasOption(LessOptions.COMPRESS_OPTION)) {
            options.setCompress(true);
        }
        if (cmdLine.hasOption(LessOptions.CSS_OPTION)) {
            options.setCss(true);
        }
        if (cmdLine.hasOption(LessOptions.LESS_OPTION)) {
            options.setLess(new File(cmdLine.getOptionValue(LessOptions.LESS_OPTION)).toURI().toURL());
        }
        LessEngine engine = new LessEngine(options);
        if (System.in.available() != 0) {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            StringWriter sw = new StringWriter();
            char[] buffer = new char[1024];
            int n = 0;
            while (-1 != (n = in.read(buffer))) {
                sw.write(buffer, 0, n);
            }
            String src = sw.toString();
            if (!src.isEmpty()) {
                System.out.println(engine.compile(src, null, options.isCompress()));
                System.exit(0);
            }
        }
        String[] files = cmdLine.getArgs();
        if (files.length == 1) {
            System.out.println(engine.compile(new File(files[0]), options.isCompress()));
            System.exit(0);
        }
        if (files.length == 2) {
            engine.compile(new File(files[0]), new File(files[1]), options.isCompress());
            System.exit(0);
        }

    } catch (IOException ioe) {
        System.err.println("Error opening input file.");
    } catch (ParseException pe) {
        System.err.println("Error parsing arguments.");
    }
    String[] paths = LessEngine.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()
            .split(File.separator);
    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp("java -jar " + paths[paths.length - 1] + " input [output] [options]", cmdOptions);
    System.exit(1);
}

From source file:cc.twittertools.index.ExtractTermStatisticsFromIndex.java

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

    options.addOption(OptionBuilder.withArgName("dir").hasArg().withDescription("index").create(INDEX_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("min").create(MIN_OPTION));

    CommandLine cmdline = null;/* w  w w  . j  av a  2 s .  c om*/
    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(INDEX_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(ExtractTermStatisticsFromIndex.class.getName(), options);
        System.exit(-1);
    }

    String indexLocation = cmdline.getOptionValue(INDEX_OPTION);
    int min = cmdline.hasOption(MIN_OPTION) ? Integer.parseInt(cmdline.getOptionValue(MIN_OPTION)) : 1;

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

    IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(indexLocation)));
    Terms terms = SlowCompositeReaderWrapper.wrap(reader).terms(StatusField.TEXT.name);
    TermsEnum termsEnum = terms.iterator(TermsEnum.EMPTY);

    long missingCnt = 0;
    int skippedTerms = 0;
    BytesRef bytes = new BytesRef();
    while ((bytes = termsEnum.next()) != null) {
        byte[] buf = new byte[bytes.length];
        System.arraycopy(bytes.bytes, 0, buf, 0, bytes.length);
        String term = new String(buf, "UTF-8");
        int df = termsEnum.docFreq();
        long cf = termsEnum.totalTermFreq();

        if (df < min) {
            skippedTerms++;
            missingCnt += cf;
            continue;
        }

        out.println(term + "\t" + df + "\t" + cf);
    }

    reader.close();
    out.close();
    System.err.println("skipped terms: " + skippedTerms + ", cnt: " + missingCnt);
}

From source file:io.wcm.devops.conga.plugins.aem.tooling.crypto.cli.AemCryptoCli.java

/**
 * CLI entry point/*from ww  w  .j  av a  2  s .c  om*/
 * @param args Command line arguments
 * @throws Exception Exception
 */
//CHECKSTYLE:OFF
public static void main(String[] args) throws Exception {
    //CHECKSTYLE:ON
    CommandLine commandLine = new DefaultParser().parse(CLI_OPTIONS, args, true);

    boolean generateCryptoKeys = commandLine.hasOption(CRYPTO_KEYS_GENERATE);
    boolean ansibleVaultEncrypt = commandLine.hasOption(CRYPTO_KEYS_ANSIBLE_VAULT_ENCRYPT);
    File targetDir = new File(commandLine.getOptionValue(TARGET, "target"));
    String ansibleVaultEncryptPath = commandLine.getOptionValue(ANSIBLE_VAULT_ENCRYPT);
    String ansibleVaultDecryptPath = commandLine.getOptionValue(ANSIBLE_VAULT_DECRYPT);

    if (generateCryptoKeys) {
        CryptoKeys.generate(targetDir, ansibleVaultEncrypt)
                .forEach(file -> System.out.println("Generated: " + file.getPath()));
        return;
    } else if (StringUtils.isNotBlank(ansibleVaultEncryptPath)) {
        AnsibleVault.encrypt(new File(ansibleVaultEncryptPath));
        return;
    } else if (StringUtils.isNotBlank(ansibleVaultDecryptPath)) {
        AnsibleVault.decrypt(new File(ansibleVaultDecryptPath));
        return;
    }

    // print usage help
    HelpFormatter formatter = new HelpFormatter();
    formatter.setWidth(150);
    formatter.printHelp("java -jar conga-aem-crypto-cli-<version>.jar <arguments>", CLI_OPTIONS);
}

From source file:com.ibm.crail.namenode.NameNode.java

public static void main(String args[]) throws Exception {
    LOG.info("initalizing namenode ");
    CrailConfiguration conf = new CrailConfiguration();
    CrailConstants.updateConstants(conf);

    URI uri = CrailUtils.getPrimaryNameNode();
    String address = uri.getHost();
    int port = uri.getPort();

    if (args != null) {
        Option addressOption = Option.builder("a").desc("ip address namenode is started on").hasArg().build();
        Option portOption = Option.builder("p").desc("port namenode is started on").hasArg().build();
        Options options = new Options();
        options.addOption(portOption);// w  ww.j  a  v a 2 s .  co m
        options.addOption(addressOption);
        CommandLineParser parser = new DefaultParser();

        try {
            CommandLine line = parser.parse(options, Arrays.copyOfRange(args, 0, args.length));
            if (line.hasOption(addressOption.getOpt())) {
                address = line.getOptionValue(addressOption.getOpt());
            }
            if (line.hasOption(portOption.getOpt())) {
                port = Integer.parseInt(line.getOptionValue(portOption.getOpt()));
            }
        } catch (ParseException e) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("Namenode", options);
            System.exit(-1);
        }
    }

    String namenode = "crail://" + address + ":" + port;
    long serviceId = CrailUtils.getServiceId(namenode);
    long serviceSize = CrailUtils.getServiceSize();
    if (!CrailUtils.verifyNamenode(namenode)) {
        throw new Exception("Namenode address/port [" + namenode
                + "] has to be listed in crail.namenode.address " + CrailConstants.NAMENODE_ADDRESS);
    }

    CrailConstants.NAMENODE_ADDRESS = namenode + "?id=" + serviceId + "&size=" + serviceSize;
    CrailConstants.printConf();
    CrailConstants.verify();

    RpcNameNodeService service = RpcNameNodeService.createInstance(CrailConstants.NAMENODE_RPC_SERVICE);
    RpcBinding rpcBinding = RpcBinding.createInstance(CrailConstants.NAMENODE_RPC_TYPE);
    rpcBinding.init(conf, null);
    rpcBinding.printConf(LOG);
    rpcBinding.run(service);
    System.exit(0);
    ;
}

From source file:com.uber.stream.kafka.mirrormaker.manager.ManagerStarter.java

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(ManagerConf.constructManagerOptions(), args);
    if (cmd.getOptions().length == 0 || cmd.hasOption("help")) {
        HelpFormatter f = new HelpFormatter();
        f.printHelp("OptionsTip", ManagerConf.constructManagerOptions());
        System.exit(0);//  w  w w. java 2  s .co m
    }
    final ManagerStarter managerStarter = ManagerStarter.init(cmd);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            try {
                managerStarter.stop();
            } catch (Exception e) {
                LOGGER.error("Caught error during shutdown! ", e);
            }
        }
    });

    try {
        managerStarter.start();
    } catch (Exception e) {
        LOGGER.error("Cannot start uReplicator-Manager: ", e);
    }
}

From source file:edu.usc.pgroup.floe.client.commands.Signal.java

/**
 * Entry point for Scale command./*from  w  w  w  . java2 s. com*/
 * @param args command line arguments sent by the floe.py script.
 */
public static void main(final String[] args) {

    Options options = new Options();

    Option appOption = OptionBuilder.withArgName("name").hasArg().isRequired()
            .withDescription("Application Name").create("app");

    Option pelletNameOption = OptionBuilder.withArgName("name").hasArg().isRequired()
            .withDescription("Pellet Name").create("pellet");

    Option signalOption = OptionBuilder.withArgName("data").hasArg().withType(new String())
            .withDescription("signal data to send to the pellet").create("data");

    options.addOption(appOption);
    options.addOption(pelletNameOption);
    options.addOption(signalOption);

    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("scale options", options);
        return;
    }

    String app = line.getOptionValue("app");
    String pellet = line.getOptionValue("pellet");
    String data = line.getOptionValue("data");

    LOGGER.info("Application: {}", app);
    LOGGER.info("Pellet: {}", pellet);
    LOGGER.info("data: {}", data);

    byte[] datab = Utils.serialize(data);
    try {
        TSignal signal = new TSignal();
        signal.set_destApp(app);
        signal.set_destPellet(pellet);
        signal.set_data(datab);
        FloeClient.getInstance().getClient().signal(signal);
    } catch (TException e) {
        LOGGER.error("Error while connecting to the coordinator: {}", e);
    }
}

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

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(/*from  w w  w.  j  a va  2s  .c o m*/
            OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_OPTION));
    options.addOption(
            OptionBuilder.withArgName("num").hasArg().withDescription("article id").create(ID_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("article title").create(TITLE_OPTION));

    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(ID_OPTION) || cmdline.hasOption(TITLE_OPTION))
            || !cmdline.hasOption(INDEX_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(FetchWikipediaArticle.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);
    }

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

    if (cmdline.hasOption(ID_OPTION)) {
        int id = Integer.parseInt(cmdline.getOptionValue(ID_OPTION));
        Document doc = searcher.getArticle(id);

        if (doc == null) {
            System.err.print("id " + id + " doesn't exist!\n");
        } else {
            out.println(doc.getField(IndexField.TEXT.name).stringValue());
        }
    } else {
        String title = cmdline.getOptionValue(TITLE_OPTION);
        Document doc = searcher.getArticle(title);

        if (doc == null) {
            System.err.print("article \"" + title + "\" doesn't exist!\n");
        } else {
            out.println(doc.getField(IndexField.TEXT.name).stringValue());
        }
    }

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

From source file:com.chip8java.emulator.Runner.java

/**
 * Runs the emulator with the specified command line options.
 * /*from  ww w  .  j a va2  s  .  c o m*/
 * @param argv
 *            The set of options passed to the emulator
 */
public static void main(String[] argv) {
    CommandLine commandLine = parseCommandLineOptions(argv);
    Emulator.Builder emulatorBuilder = new Emulator.Builder();

    if (commandLine.hasOption(HELP_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("emulator", generateOptions());
        System.exit(0);
    }

    if (commandLine.hasOption(SCALE_OPTION)) {
        int scale = Integer.parseInt(commandLine.getOptionValue(SCALE_OPTION));
        emulatorBuilder.setScale(scale);
    }

    String[] args = commandLine.getArgs();
    if (args.length != 0) {
        emulatorBuilder.setRom(args[0]);
    }

    if (commandLine.hasOption(TRACE_OPTION)) {
        emulatorBuilder.setTrace();
    }

    if (commandLine.hasOption(DELAY_OPTION)) {
        int delay = Integer.parseInt(commandLine.getOptionValue(DELAY_OPTION));
        emulatorBuilder.setCycleTime((long) delay);
    }

    Emulator emulator = emulatorBuilder.build();
    emulator.start();
}