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.redhat.akashche.keystoregen.Launcher.java

public static void main(String[] args) throws Exception {
    try {/*from   w ww  . j  av a  2s . c  om*/
        CommandLine cline = new GnuParser().parse(OPTIONS, args);
        if (cline.hasOption(VERSION_OPTION)) {
            out.println(VERSION);
        } else if (cline.hasOption(HELP_OPTION)) {
            throw new ParseException("Printing help page:");
        } else if (0 == cline.getArgs().length && cline.hasOption(CONFIG_OPTION)
                && cline.hasOption(OUTPUT_OPTION)) {
            KeystoreConfig conf = parseConf(cline.getOptionValue(CONFIG_OPTION));
            KeyStore ks = new KeystoreGenerator().generate(conf);
            writeKeystore(conf, ks, cline.getOptionValue(OUTPUT_OPTION));
        } else {
            throw new ParseException("Incorrect arguments received!");
        }
    } catch (ParseException e) {
        HelpFormatter formatter = new HelpFormatter();
        out.println(e.getMessage());
        out.println(VERSION);
        formatter.printHelp("java -jar keystoregen.jar -c config.json -o output.p12", OPTIONS);
    }
}

From source file:com.khubla.jvmbasic.jvmbasicwww.JVMBASICWWW.java

public static void main(String[] args) {
    try {/*from   w w w.  j a v a  2s. co m*/
        System.out.println("khubla.com jvmBasic www server");
        /*
         * options
         */
        final Options options = new Options();
        Option oo = Option.builder().argName(SOURCEDIR_OPTION).longOpt(SOURCEDIR_OPTION).type(String.class)
                .hasArg().required(false).desc("source dir").build();
        options.addOption(oo);
        oo = Option.builder().argName(CLASSDIR_OPTION).longOpt(CLASSDIR_OPTION).type(String.class).hasArg()
                .required(false).desc("class dir").build();
        options.addOption(oo);
        oo = Option.builder().argName(PORT_OPTION).longOpt(PORT_OPTION).type(String.class).hasArg()
                .required(false).desc("TCP port").build();
        options.addOption(oo);
        /*
         * parse
         */
        final CommandLineParser parser = new DefaultParser();
        CommandLine cmd = null;
        try {
            cmd = parser.parse(options, args);
        } catch (final Exception e) {
            final HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("posix", options);
            System.exit(0);
        }
        /*
         * input dir
         */
        final String sourceDir = cmd.getOptionValue(SOURCEDIR_OPTION, SOURCEDIR_DEFAULT);
        /*
         * class dir
         */
        final String classdir = cmd.getOptionValue(CLASSDIR_OPTION, CLASSDIR_DEFAULT);
        /*
         * port
         */
        int port = Integer.parseInt(cmd.getOptionValue(PORT_OPTION, PORT_DEFAULT));
        /*
         * output the config
         */
        System.out.println("Source directory: " + sourceDir);
        System.out.println("Class directory: " + classdir);
        System.out.println("HTTP port: " + port);
        /*
         * configuration
         */
        final ServerConfiguration serverConfiguration = new ServerConfiguration(sourceDir, classdir, port);
        /*
         * server
         */
        final JVMBasicWebServer jvmBasicWebServer = new JVMBasicWebServer(serverConfiguration);
        jvmBasicWebServer.listen();
    } catch (final Exception e) {
        e.printStackTrace();
    }
}

From source file:it.tizianofagni.sparkboost.BoostClassifierExe.java

public static void main(String[] args) {

    Options options = new Options();
    options.addOption("b", "binaryProblem", false,
            "Indicate if the input dataset contains a binary problem and not a multilabel one");
    options.addOption("z", "labels0based", false,
            "Indicate if the labels IDs in the dataset to classifyLibSvmWithResults are already assigned in the range [0, numLabels-1] included");
    options.addOption("l", "enableSparkLogging", false, "Enable logging messages of Spark");
    options.addOption("w", "windowsLocalModeFix", true,
            "Set the directory containing the winutils.exe command");
    options.addOption("p", "parallelismDegree", true,
            "Set the parallelism degree (default: number of available cores in the Spark runtime");

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;//w  w w  . j av  a2 s  .  c  om
    String[] remainingArgs = null;
    try {
        cmd = parser.parse(options, args);
        remainingArgs = cmd.getArgs();
        if (remainingArgs.length != 3)
            throw new ParseException("You need to specify all mandatory parameters");
    } catch (ParseException e) {
        System.out.println("Parsing failed.  Reason: " + e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(
                BoostClassifierExe.class.getSimpleName() + " [OPTIONS] <inputFile> <inputModel> <outputFile>",
                options);
        System.exit(-1);
    }

    boolean binaryProblem = false;
    if (cmd.hasOption("b"))
        binaryProblem = true;
    boolean labels0Based = false;
    if (cmd.hasOption("z"))
        labels0Based = true;
    boolean enablingSparkLogging = false;
    if (cmd.hasOption("l"))
        enablingSparkLogging = true;

    if (cmd.hasOption("w")) {
        System.setProperty("hadoop.home.dir", cmd.getOptionValue("w"));
    }

    String inputFile = remainingArgs[0];
    String inputModel = remainingArgs[1];
    String outputFile = remainingArgs[2];

    long startTime = System.currentTimeMillis();

    // Disable Spark logging.
    if (!enablingSparkLogging) {
        Logger.getLogger("org").setLevel(Level.OFF);
        Logger.getLogger("akka").setLevel(Level.OFF);
    }

    // Create and configure Spark context.
    SparkConf conf = new SparkConf().setAppName("Spark MPBoost classifier");
    JavaSparkContext sc = new JavaSparkContext(conf);

    // Load boosting classifier from disk.
    BoostClassifier classifier = DataUtils.loadModel(sc, inputModel);

    // Get the parallelism degree.
    int parallelismDegree = sc.defaultParallelism();
    if (cmd.hasOption("p")) {
        parallelismDegree = Integer.parseInt(cmd.getOptionValue("p"));
    }

    // Classify documents available on specified input file.
    classifier.classifyLibSvm(sc, inputFile, parallelismDegree, labels0Based, binaryProblem, outputFile);
    long endTime = System.currentTimeMillis();
    System.out.println("Execution time: " + (endTime - startTime) + " milliseconds.");
}

From source file:Compiler.java

/** A command line entry point to the mini Java compiler.
 *//* w  w w .  j  a v  a 2  s . c  o  m*/
public static void main(String[] args) {
    CommandLineParser parser = new BasicParser();
    Options options = new Options();

    options.addOption("L", "LLVM", true, "LLVM Bitcode Output Location.");
    options.addOption("x", "x86", true, "x86 Output File Location");
    options.addOption("l", "llvm", false, "Dump Human Readable LLVM Code.");
    options.addOption("i", "input", true, "Compile to x86 Assembly.");
    options.addOption("I", "interp", false, "Run the interpreter.");
    options.addOption("h", "help", false, "Print this help message.");
    options.addOption("V", "version", false, "Version information.");

    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("v")) {
            System.out.println("MiniJava Compiler");
            System.out.println("Written By Mark Jones http://web.cecs.pdx.edu/~mpj/");
            System.out.println("Extended for LLVM by Mitch Souders and Mark Smith");
        }
        if (cmd.hasOption("h")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("java -jar mjc.jar -i <INPUT> (--x86 <OUT>|--LLVM <OUT>|--llvm)", options);
            System.exit(0);
        }
        int errors = 0;
        if (!cmd.hasOption("i")) {
            System.out.println("-i|--input requires a MiniJava input file");
            System.out.println("--help for more info.");
            errors++;
        }
        if (!cmd.hasOption("x") && !cmd.hasOption("l") && !cmd.hasOption("L") && !cmd.hasOption("I")) {
            System.out.println("--x86|--llvm|--LLVM|--interp required for some sort of output.");
            System.out.println("--help for more info.");
            errors++;
        }

        if (errors > 0) {
            System.exit(1);
        }
        String inputFile = cmd.getOptionValue("i");
        compile(inputFile, cmd);
    } catch (ParseException exp) {
        System.out.println("Argument Error: " + exp.getMessage());
    }
}

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(//from   ww  w  . ja v  a  2s  .  c  o  m
            OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_OPTION));
    options.addOption(
            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:at.tfr.securefs.client.SecurefsFileServiceClient.java

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

    SecurefsFileServiceClient client = new SecurefsFileServiceClient();
    try {//w  ww .ja v  a  2s  .c o  m
        client.parse(args);

        if (client.asyncTest) {
            ExecutorService executor = Executors.newFixedThreadPool(client.threads);
            for (int i = 0; i < client.threads; i++) {
                executor.submit(client);
            }
            executor.shutdown();
            executor.awaitTermination(10, TimeUnit.MINUTES);
        } else {
            client.run();
        }

    } catch (Throwable e) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp(SecurefsFileServiceClient.class.getSimpleName(), client.options);
        e.printStackTrace();
    }
}

From source file:lapispaste.Main.java

public static void main(String[] args) throws Exception {
    // create Options object
    Options options = new Options();
    String version;//from w w  w  . j  a  v a2  s  .c o  m

    version = "0.1";

    // populate Options with.. well options :P
    options.addOption("v", false, "Display version");
    options.addOption("f", true, "File to paste");

    // non-critical options
    options.addOption("t", true, "Code language");
    options.addOption("p", false, "Read from pipe");

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

    // assemble a map of values
    final Map<String, String> pastemap = new HashMap<String, String>();

    if (cmd.hasOption("t"))
        pastemap.put("format", cmd.getOptionValue("t").toString());
    else
        pastemap.put("format", "text");

    // critical options
    if (cmd.hasOption("v"))
        System.out.println("lapispaste version " + version);
    else if (cmd.hasOption("f")) {
        File file = new File(cmd.getOptionValue("f"));
        StringBuffer pdata = readData(new FileReader(file));
        paster(pastemap, pdata);
    } else if (cmd.hasOption("p")) {
        StringBuffer pdata = readData(new InputStreamReader(System.in));
        paster(pastemap, pdata);
    } else {
        // Did not recieve what was expected
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("lapispaste [OPTIONS] [FILE]", options);
    }

}

From source file:com.canyapan.randompasswordgenerator.cli.Main.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption("h", false, "prints help");
    options.addOption("def", false, "generates 8 character password with default options");
    options.addOption("p", true, "password length (default 8)");
    options.addOption("l", false, "include lower case characters");
    options.addOption("u", false, "include upper case characters");
    options.addOption("d", false, "include digits");
    options.addOption("s", false, "include symbols");
    options.addOption("lc", true, "minimum lower case character count (default 0)");
    options.addOption("uc", true, "minimum upper case character count (default 0)");
    options.addOption("dc", true, "minimum digit count (default 0)");
    options.addOption("sc", true, "minimum symbol count (default 0)");
    options.addOption("a", false, "avoid ambiguous characters");
    options.addOption("f", false, "force every character type");
    options.addOption("c", false, "continuous password generation");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;/*from w  w w. j a va2  s .  com*/
    boolean printHelp = false;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        printHelp = true;
    }

    if (printHelp || args.length == 0 || cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(
                "java -jar RandomPasswordGenerator.jar [-p <arg>] [-l] [-u] [-s] [-d] [-dc <arg>] [-a] [-f]",
                options);
        return;
    }

    RandomPasswordGenerator rpg = new RandomPasswordGenerator();

    if (cmd.hasOption("def")) {
        rpg.withDefault().withPasswordLength(Integer.parseInt(cmd.getOptionValue("p", "8")));
    } else {
        rpg.withPasswordLength(Integer.parseInt(cmd.getOptionValue("p", "8")))
                .withLowerCaseCharacters(cmd.hasOption("l")).withUpperCaseCharacters(cmd.hasOption("u"))
                .withDigits(cmd.hasOption("d")).withSymbols(cmd.hasOption("s"))
                .withAvoidAmbiguousCharacters(cmd.hasOption("a"))
                .withForceEveryCharacterType(cmd.hasOption("f"));

        if (cmd.hasOption("lc")) {
            rpg.withMinLowerCaseCharacterCount(Integer.parseInt(cmd.getOptionValue("lc", "0")));
        }

        if (cmd.hasOption("uc")) {
            rpg.withMinUpperCaseCharacterCount(Integer.parseInt(cmd.getOptionValue("uc", "0")));
        }

        if (cmd.hasOption("dc")) {
            rpg.withMinDigitCount(Integer.parseInt(cmd.getOptionValue("dc", "0")));
        }

        if (cmd.hasOption("sc")) {
            rpg.withMinSymbolCount(Integer.parseInt(cmd.getOptionValue("sc", "0")));
        }
    }

    Scanner scanner = new Scanner(System.in);

    try {
        do {
            final String password = rpg.generate();
            final PasswordMeter.Result result = PasswordMeter.check(password);
            System.out.printf("%s%nScore: %s%%%nComplexity: %s%n%n", password, result.getScore(),
                    result.getComplexity());

            if (cmd.hasOption("c")) {
                System.out.print("Another? y/N: ");
            }
        } while (cmd.hasOption("c") && scanner.nextLine().matches("^(?i:y(?:es)?)$"));
    } catch (RandomPasswordGeneratorException e) {
        System.err.println(e.getMessage());
    } catch (PasswordMeterException e) {
        System.err.println(e.getMessage());
    }
}

From source file:eu.optimis.monitoring.amazoncollector.Collector.java

public static void main(String[] args) {

    Collector collector = new Collector();
    Options options = new Options();
    Option id = OptionBuilder.withArgName("id").hasArg().withDescription("use given collector ID")
            .create(ID_OPT);//w  w w. j  av  a2 s .c o  m
    Option conf = OptionBuilder.withArgName("configuration path").hasArg().withDescription("Configuration path")
            .create(PATH_OPT);
    options.addOption(id);
    options.addOption(conf);

    CommandLineParser parser = new GnuParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Incorrect parameters: " + exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("collector", options);
        System.exit(2); //Incorrect usage
    }

    if (line.hasOption(ID_OPT)) {
        String cid = line.getOptionValue(ID_OPT);
        Measurement.setDefCollectorId(cid);
        System.out.println("Using Collector ID: " + cid);
    } else {
        System.out.println("Using default Collector ID: " + DEFAULT_ID + " (To use custom ID use -i argument)");
        Measurement.setDefCollectorId(DEFAULT_ID);
    }

    if (line.hasOption(PATH_OPT)) {
        collector.propertiesPath = line.getOptionValue(PATH_OPT);
        System.out.println("Using Properties file: " + collector.propertiesPath);
    } else {
        System.out.println("Using default Configuration file: " + DEFAULT_PROPERTIES_PATH
                + " (To use custom path use -c argument)");
        collector.propertiesPath = DEFAULT_PROPERTIES_PATH;
    }

    collector.getProperties();

    MeasurementsHelper helper = new MeasurementsHelper(collector.accessKey, collector.secretKey);
    List<Measurement> measurements = helper.getMeasurements();

    String xmlData = XMLHelper.createDocument(measurements);
    RESTHelper rest = new RESTHelper(collector.aggregatorURL);
    rest.sendDocument(xmlData);
}

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

/**
 * Entry point for the flake.//  www .  ja  va2s  .  c o m
 *
 * @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;
    }
}