List of usage examples for org.apache.commons.cli HelpFormatter HelpFormatter
HelpFormatter
From source file:com.commonsware.android.gcm.cmd.GCM.java
@SuppressWarnings("static-access") public static void main(String[] args) { Option helpOpt = new Option("h", "help", false, "print this message"); Option apiKeyOpt = OptionBuilder.withArgName("key").hasArg().isRequired().withDescription("GCM API key") .withLongOpt("apiKey").create('a'); Option deviceOpt = OptionBuilder.withArgName("regId").hasArg().isRequired() .withDescription("device to send to").withLongOpt("device").create('d'); Option dataOpt = OptionBuilder.withArgName("key=value").hasArgs(2).withDescription("datum to send") .withValueSeparator().withLongOpt("data").create('D'); Options options = new Options(); options.addOption(apiKeyOpt);// ww w.j ava2 s .c o m options.addOption(deviceOpt); options.addOption(dataOpt); options.addOption(helpOpt); CommandLineParser parser = new PosixParser(); try { CommandLine line = parser.parse(options, args); if (line.hasOption('h') || !line.hasOption('a') || !line.hasOption('d')) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("gcm", options, true); } else { sendMessage(line.getOptionValue('a'), Arrays.asList(line.getOptionValues('d')), line.getOptionProperties("data")); } } catch (org.apache.commons.cli.MissingOptionException moe) { System.err.println("Invalid command syntax"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("gcm", options, true); } catch (Exception e) { e.printStackTrace(); } }
From source file:edu.ucsb.cs.eager.sa.cerebro.Cerebro.java
public static void main(String[] args) { Options options = new Options(); options.addOption("ccp", "cerebro-classpath", true, "Cerebro classpath"); options.addOption("c", "class", true, "Class to be used as the starting point"); options.addOption("dnc", "disable-nec-classes", false, "Disable loading of necessary classes"); options.addOption("wp", "whole-program", false, "Enable whole program mode"); CommandLine cmd;/* w w w .j a v a2 s . co m*/ try { CommandLineParser parser = new BasicParser(); cmd = parser.parse(options, args); } catch (ParseException e) { System.err.println("Error: " + e.getMessage() + "\n"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Cerebro", options); return; } String classPath = cmd.getOptionValue("ccp"); if (classPath == null) { System.err.println("Cerebro classpath (ccp) option is required"); return; } else { String[] paths = classPath.split(":"); for (String p : paths) { File file = new File(p); if (!file.exists()) { System.err.println("Path segment: " + p + " mentioned in classpath does not exist"); return; } } } String startingPoint = cmd.getOptionValue("c"); if (startingPoint == null) { System.err.println("Starting point class (c) option is required"); return; } Cerebro cerebro = new Cerebro(classPath, startingPoint); cerebro.setLoadNecessaryClasses(!cmd.hasOption("dnc")); cerebro.setWholeProgramMode(cmd.hasOption("wp")); cerebro.setVerbose(true); cerebro.analyze(); }
From source file:cc.twittertools.corpus.demo.ReadStatuses.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input directory or file") .create(INPUT_OPTION));/*from w w w . j ava2s. c o m*/ options.addOption(VERBOSE_OPTION, false, "print logging output every 10000 tweets"); options.addOption(DUMP_OPTION, false, "dump statuses"); 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(INPUT_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(ReadStatuses.class.getName(), options); System.exit(-1); } PrintStream out = new PrintStream(System.out, true, "UTF-8"); StatusStream stream; // Figure out if we're reading from HTML SequenceFiles or JSON. File file = new File(cmdline.getOptionValue(INPUT_OPTION)); if (!file.exists()) { System.err.println("Error: " + file + " does not exist!"); System.exit(-1); } if (file.isDirectory()) { stream = new JsonStatusCorpusReader(file); } else { stream = new JsonStatusBlockReader(file); } int cnt = 0; Status status; while ((status = stream.next()) != null) { if (cmdline.hasOption(DUMP_OPTION)) { String text = status.getText(); if (text != null) { text = text.replaceAll("\\s+", " "); text = text.replaceAll("\0", ""); } out.println(String.format("%d\t%s\t%s\t%s", status.getId(), status.getScreenname(), status.getCreatedAt(), text)); } cnt++; if (cnt % 10000 == 0 && cmdline.hasOption(VERBOSE_OPTION)) { LOG.info(cnt + " statuses read"); } } stream.close(); LOG.info(String.format("Total of %s statuses read.", cnt)); }
From source file:com.dhenton9000.screenshots.ScreenShotLauncher.java
/** * main launching method that takes command line arguments * * @param args/*from ww w . j a v a2s. c o m*/ */ public static void main(String[] args) { final String[] actions = { ACTIONS.source.toString(), ACTIONS.target.toString(), ACTIONS.compare.toString() }; final List actionArray = Arrays.asList(actions); Options options = new Options(); options.addOption(OptionBuilder.withLongOpt("action").hasArg().isRequired().withArgName("action").create()); HelpFormatter formatter = new HelpFormatter(); String header = "Process screenshots\n" + "--action=source create source screenshots\n" + "--action=target create the screenshots for comparison\n" + "--action=compare compare the images\n" + "%s\n\n"; String action = null; try { // parse the command line arguments CommandLineParser parser = new PosixParser(); CommandLine line = parser.parse(options, args); // validate that action option has been set if (line.hasOption("action")) { action = line.getOptionValue("action"); LOG.debug("action '" + action + "'"); if (!actionArray.contains(action)) { formatter.printHelp(ScreenShotLauncher.class.getName(), String.format(header, String.format("action option '%s' is invalid", action)), options, "\n\n", true); System.exit(1); } } else { formatter.printHelp(ScreenShotLauncher.class.getName(), String.format(header, "not found"), options, "\n\n", false); System.exit(1); } } catch (ParseException exp) { formatter.printHelp(ScreenShotLauncher.class.getName(), String.format(header, "problem " + exp.getMessage()), options, "\n\n", false); System.exit(1); } ACTIONS actionEnum = ACTIONS.valueOf(action); ScreenShotLauncher launcher = new ScreenShotLauncher(); try { launcher.handleRequest(actionEnum); } catch (Exception ex) { LOG.error(ex.getMessage(), ex); } }
From source file:mx.unam.fesa.mss.MSSMain.java
/** * @param args/*from w w w . j a v a 2s .com*/ */ @SuppressWarnings("static-access") public static void main(String[] args) { // // managing command line options using commons-cli // Options options = new Options(); // help option // options.addOption( OptionBuilder.withDescription("Prints this message.").withLongOpt("help").create(OPT_HELP)); // port option // options.addOption(OptionBuilder.withDescription("The port in which the MineSweeperServer will listen to.") .hasArg().withType(new Integer(0)).withArgName("PORT").withLongOpt("port").create(OPT_PORT)); // parsing options // int port = DEFAULT_PORT; try { // using GNU standard // CommandLine line = new GnuParser().parse(options, args); if (line.hasOption(OPT_HELP)) { new HelpFormatter().printHelp("mss [options]", options); return; } if (line.hasOption(OPT_PORT)) { try { port = (Integer) line.getOptionObject(OPT_PORT); } catch (Exception e) { } } } catch (ParseException e) { System.err.println("Could not parse command line options correctly: " + e.getMessage()); return; } // // configuring logging services // try { LogManager.getLogManager() .readConfiguration(ClassLoader.getSystemResourceAsStream(DEFAULT_LOGGING_CONFIG_FILE)); } catch (Exception e) { throw new Error("Could not load logging properties file", e); } // // setting up UDP server // try { new MSServer(port); } catch (Exception e) { LoggerFactory.getLogger(MSSMain.class).error("Could not execute MineSweeper server: ", e); } }
From source file:com.googlecode.hiberpcml.generator.Tool.java
public static void main(String arg[]) throws Exception { CommandLineParser parser = new PosixParser(); Options options = new Options(); Option destinyOpt = new Option("t", "target", true, "target of the generated classes"); destinyOpt.setArgName("target"); options.addOption(destinyOpt);//w ww. ja va 2 s.c o m Option packageOpt = new Option("p", "package", true, "Java Package of the generated classes"); packageOpt.setArgName("package"); options.addOption(packageOpt); Option webServiceOpt = new Option("w", "webservice", true, "build webservice classes"); webServiceOpt.setArgs(2); webServiceOpt.setArgName("serviceName service"); options.addOption(webServiceOpt); options.addOption(webServiceOpt); CommandLine cmd = parser.parse(options, arg); if (cmd.getArgs().length == 0) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("generator [options] FILE|DIRECTORY.", options); System.exit(1); } Pcml pcml; ArrayList<File> filesToParse = getFilesToParse(cmd.getArgs()[0]); JCodeModel cm = new JCodeModel(); JPackage _package = cm._package(cmd.getOptionValue("p", "")); Generator generator; WSGenerator wsGenerator = null; File targetFile = new File(cmd.getOptionValue("t", "./target")); targetFile.mkdirs(); if (cmd.hasOption("w")) { wsGenerator = new WSGenerator(_package, cmd.getOptionValues("w")[0], cmd.getOptionValues("w")[1]); } for (File file : filesToParse) { pcml = Util.load(file); if (cmd.hasOption("w")) { wsGenerator.addMethod(pcml); } else { generator = new Generator(); generator.generate(_package, pcml); } } cm.build(targetFile); }
From source file:cc.wikitools.lucene.ScoreWikipediaArticle.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(// w w w. jav a 2s . com 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)); options.addOption( OptionBuilder.withArgName("string").hasArg().withDescription("query text").create(QUERY_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) || !cmdline.hasOption(QUERY_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(ScoreWikipediaArticle.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); WikipediaSearcher searcher = new WikipediaSearcher(indexLocation); PrintStream out = new PrintStream(System.out, true, "UTF-8"); if (cmdline.hasOption(ID_OPTION)) { out.println("score: " + searcher.scoreArticle(queryText, Integer.parseInt(cmdline.getOptionValue(ID_OPTION)))); } else { out.println("score: " + searcher.scoreArticle(queryText, cmdline.getOptionValue(TITLE_OPTION))); } searcher.close(); out.close(); }
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;/* w w w . j a v a2 s. c o m*/ 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:com.google.api.codegen.SynchronizerTool.java
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption("h", "help", false, "show usage"); options.addOption(//from ww w .j a va2 s . com Option.builder().longOpt("source_path").desc("The directory which contains the final code.") .hasArg().argName("SOURCE-PATH").required(true).build()); options.addOption( Option.builder().longOpt("generated_path").desc("The directory which contains the generated code.") .hasArg().argName("GENERATED-PATH").build()); options.addOption(Option.builder().longOpt("baseline_path") .desc("The directory which contains the baseline code.").hasArg().argName("BASELINE-PATH").build()); options.addOption(Option.builder().longOpt("auto_merge") .desc("If set, no GUI will be launched if merge can be completed automatically.") .argName("AUTO-MERGE").build()); options.addOption(Option.builder().longOpt("auto_resolve") .desc("Whether to enable smart conflict resolution").argName("AUTO_RESOLVE").build()); options.addOption(Option.builder().longOpt("ignore_base") .desc("If true, the baseline will be ignored and two-way merge will be used.") .argName("IGNORE_BASE").build()); CommandLine cl = (new DefaultParser()).parse(options, args); if (cl.hasOption("help")) { HelpFormatter formater = new HelpFormatter(); formater.printHelp("CodeGeneratorTool", options); } synchronize(cl.getOptionValue("source_path"), cl.getOptionValue("generated_path"), cl.getOptionValue("baseline_path"), cl.hasOption("auto_merge"), cl.hasOption("auto_resolve"), cl.hasOption("ignore_base")); }
From source file:com.gsma.iariauth.validator.util.IARIValidatorMain.java
public static void main(String[] args) { String formatstr = "IARIValidator [-d <authorization document>] [-n <package name>] [-ps <package signer fingerprint>] [-pk <package signer keystore>] [-pa <package signer certificate alias>] [-pp <package signer keystore password>] -k <keystore> -p <password> [-v]"; HelpFormatter formatter = new HelpFormatter(); GnuParser parser = new GnuParser(); Options opts = new Options(); opts.addOption(new ArgOption("d", "document", "IARI Authorization document")); opts.addOption(new ArgOption("pkgname", "package-name", "package name")); opts.addOption(new ArgOption("pkgsigner", "package-signer", "package signer fingerprint")); opts.addOption(new ArgOption("pkgkeystore", "package-keystore", "package signing keystore")); opts.addOption(new ArgOption("pkgalias", "package-key-alias", "package signing certificate alias")); opts.addOption(new ArgOption("pkgstorepass", "package-keystore-pass", "package signing keystore password")); opts.addOption(new Option("v", "verbose", false, "verbose output")); CommandLine cli = null;//www . j a va 2 s .c om try { cli = parser.parse(opts, args); } catch (ParseException e) { formatter.printHelp(formatstr, opts); return; } boolean verbose = cli.hasOption("v"); String packageName = cli.getOptionValue("pkgname"); String packageSigner = cli.getOptionValue("pkgsigner"); if (packageSigner == null) { String packageSignerKeystore = cli.getOptionValue("pkgkeystore"); String packageSignerKeystoreAlias = cli.getOptionValue("pkgalias"); String packageSignerKeystorePasswd = cli.getOptionValue("pkgstorepass"); if (packageSignerKeystore != null) { if (packageSignerKeystoreAlias == null) { System.err.println("No alias given for package signing certificate"); System.exit(1); } if (packageSignerKeystorePasswd == null) { System.err.println("No password given for package signing keystore"); System.exit(1); } KeyStore packageKeystore = loadKeyStore(packageSignerKeystore, packageSignerKeystorePasswd); if (packageKeystore == null) { System.err.println("Unable to read package keystore"); System.exit(1); } try { X509Certificate c = (X509Certificate) packageKeystore .getCertificate(packageSignerKeystoreAlias); if (c == null) { System.err.println("Unable to access package signing certificate"); System.exit(1); } packageSigner = getFingerprint(c); } catch (KeyStoreException e) { System.err.println("Unable to access package signing certificate"); System.exit(1); } catch (CertificateEncodingException e) { e.printStackTrace(); System.err.println("Unable to read package signing certificate"); System.exit(1); } } } String authDocumentPath = cli.getOptionValue("d"); if (authDocumentPath == null) { System.err.println("No auth document specified"); System.exit(1); } File authDocument = new File(authDocumentPath); if (!authDocument.exists() || !authDocument.isFile()) { System.err.println("Unable to read specified auth document"); System.exit(1); } PackageProcessor processor = new PackageProcessor(packageName, packageSigner); ProcessingResult result = processor.processIARIauthorization(authDocument); if (result.getStatus() != ProcessingResult.STATUS_OK) { System.err.println("Error validating authDocument:"); System.err.println(result.getError().toString()); System.exit(1); } if (verbose) { System.out.println(result.getAuthDocument().toString()); } System.exit(0); }