List of usage examples for org.apache.commons.cli CommandLine hasOption
public boolean hasOption(char opt)
From source file:com.ibm.crail.storage.StorageServer.java
public static void main(String[] args) throws Exception { Logger LOG = CrailUtils.getLogger(); CrailConfiguration conf = new CrailConfiguration(); CrailConstants.updateConstants(conf); CrailConstants.printConf();// w w w .j a v a 2 s . c o m CrailConstants.verify(); int splitIndex = 0; for (String param : args) { if (param.equalsIgnoreCase("--")) { break; } splitIndex++; } //default values StringTokenizer tokenizer = new StringTokenizer(CrailConstants.STORAGE_TYPES, ","); if (!tokenizer.hasMoreTokens()) { throw new Exception("No storage types defined!"); } String storageName = tokenizer.nextToken(); int storageType = 0; HashMap<String, Integer> storageTypes = new HashMap<String, Integer>(); storageTypes.put(storageName, storageType); for (int type = 1; tokenizer.hasMoreElements(); type++) { String name = tokenizer.nextToken(); storageTypes.put(name, type); } int storageClass = -1; //custom values if (args != null) { Option typeOption = Option.builder("t").desc("storage type to start").hasArg().build(); Option classOption = Option.builder("c").desc("storage class the server will attach to").hasArg() .build(); Options options = new Options(); options.addOption(typeOption); options.addOption(classOption); CommandLineParser parser = new DefaultParser(); try { CommandLine line = parser.parse(options, Arrays.copyOfRange(args, 0, splitIndex)); if (line.hasOption(typeOption.getOpt())) { storageName = line.getOptionValue(typeOption.getOpt()); storageType = storageTypes.get(storageName).intValue(); } if (line.hasOption(classOption.getOpt())) { storageClass = Integer.parseInt(line.getOptionValue(classOption.getOpt())); } } catch (ParseException e) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Storage tier", options); System.exit(-1); } } if (storageClass < 0) { storageClass = storageType; } StorageTier storageTier = StorageTier.createInstance(storageName); if (storageTier == null) { throw new Exception("Cannot instantiate datanode of type " + storageName); } String extraParams[] = null; splitIndex++; if (args.length > splitIndex) { extraParams = new String[args.length - splitIndex]; for (int i = splitIndex; i < args.length; i++) { extraParams[i - splitIndex] = args[i]; } } storageTier.init(conf, extraParams); storageTier.printConf(LOG); RpcClient rpcClient = RpcClient.createInstance(CrailConstants.NAMENODE_RPC_TYPE); rpcClient.init(conf, args); rpcClient.printConf(LOG); ConcurrentLinkedQueue<InetSocketAddress> namenodeList = CrailUtils.getNameNodeList(); ConcurrentLinkedQueue<RpcConnection> connectionList = new ConcurrentLinkedQueue<RpcConnection>(); while (!namenodeList.isEmpty()) { InetSocketAddress address = namenodeList.poll(); RpcConnection connection = rpcClient.connect(address); connectionList.add(connection); } RpcConnection rpcConnection = connectionList.peek(); if (connectionList.size() > 1) { rpcConnection = new RpcDispatcher(connectionList); } LOG.info("connected to namenode(s) " + rpcConnection.toString()); StorageServer server = storageTier.launchServer(); StorageRpcClient storageRpc = new StorageRpcClient(storageType, CrailStorageClass.get(storageClass), server.getAddress(), rpcConnection); HashMap<Long, Long> blockCount = new HashMap<Long, Long>(); long sumCount = 0; while (server.isAlive()) { StorageResource resource = server.allocateResource(); if (resource == null) { break; } else { storageRpc.setBlock(resource.getAddress(), resource.getLength(), resource.getKey()); DataNodeStatistics stats = storageRpc.getDataNode(); long newCount = stats.getFreeBlockCount(); long serviceId = stats.getServiceId(); long oldCount = 0; if (blockCount.containsKey(serviceId)) { oldCount = blockCount.get(serviceId); } long diffCount = newCount - oldCount; blockCount.put(serviceId, newCount); sumCount += diffCount; LOG.info("datanode statistics, freeBlocks " + sumCount); } } while (server.isAlive()) { DataNodeStatistics stats = storageRpc.getDataNode(); long newCount = stats.getFreeBlockCount(); long serviceId = stats.getServiceId(); long oldCount = 0; if (blockCount.containsKey(serviceId)) { oldCount = blockCount.get(serviceId); } long diffCount = newCount - oldCount; blockCount.put(serviceId, newCount); sumCount += diffCount; LOG.info("datanode statistics, freeBlocks " + sumCount); Thread.sleep(2000); } }
From source file:ca.uqac.info.trace.XML.Hadoop.HadoopTraceGenerator.java
public static void main(String[] args) { String generator_name = ""; boolean FileGenerated = false; int verbosity = 0; // Parse command line arguments Options options = setupOptions();/*from w ww. j a v a 2 s .com*/ CommandLine c_line = setupCommandLine(args, options); if (c_line.hasOption("h")) { showUsage(options); System.exit(ERR_OK); } //Contains a generator if (c_line.hasOption("g")) { generator_name = c_line.getOptionValue("generator"); } else { System.err.println("No Generator in Arguments"); System.exit(ERR_ARGUMENTS); } //Get the MessageFeeder for the generator MessageFeeder mf = instantiateFeeder(generator_name); //Contains a FileWriter if (c_line.hasOption("f")) { mf.SetOutputFile(c_line.getOptionValue("FileWriter")); } else { System.err.println("No FileWriter in Arguments"); System.exit(ERR_ARGUMENTS); } //Contains a size for the output file if (c_line.hasOption("s")) { int size = Integer.parseInt(c_line.getOptionValue("Size")); mf.setSizeOutputFile(size); } else { System.err.println("No size for the Output File in Arguments"); System.exit(ERR_ARGUMENTS); } //Contains the type of the variables if (c_line.hasOption("t")) { mf.setTypeTrace(c_line.getOptionValue("Type")); } else { System.err.println("No type in Arguments"); System.exit(ERR_ARGUMENTS); } //Contains conditions for the generation of the XML's Trace if (c_line.hasOption("c")) { try { mf.setConditionsFile(c_line.getOptionValue("Conditions")); } catch (FileNotFoundException e) { System.out.println("The file of the conditions wasn't found !!!"); e.printStackTrace(); } catch (SAXException e) { System.out.println("SAXException : XML Exeception !!!"); e.printStackTrace(); } catch (IOException e) { System.out.println("IOException : Input/Ouput Exception !!!"); e.printStackTrace(); } } //Contains the depth for the Traces if (c_line.hasOption("d")) { mf.setDepthTrace(Integer.parseInt(c_line.getOptionValue("Depth"))); } else { System.err.println("No Depth in Arguments"); System.exit(ERR_ARGUMENTS); } //Contains the variable depth if (c_line.hasOption("v")) { mf.setDepthVar(Integer.parseInt(c_line.getOptionValue("VariableDepth"))); } else { System.err.println("No variable depth in Arguments"); System.exit(ERR_ARGUMENTS); } //Contains the value depth if (c_line.hasOption("w")) { mf.setDepthValue(Integer.parseInt(c_line.getOptionValue("DepthValue"))); } else { System.err.println("No value depth in Arguments"); System.exit(ERR_ARGUMENTS); } if (c_line.hasOption("verbosity")) { verbosity = Integer.parseInt(c_line.getOptionValue("verbosity")); } FileGenerated = mf.getFileGenerated(); System.out.println("-----------------------------------------------"); System.out.println("The generation of the Trace is start !!!"); System.out.println("-----------------------------------------------"); //Displays the Output File Tree if (verbosity > 0) { System.out.println("The output file is : " + c_line.getOptionValue("FileWriter")); System.out.println("-----------------------------------------------"); } while (FileGenerated != true) { //Get The current XML Trace String message = mf.next(); //Displays all of the messages (all of the Traces) if (verbosity >= 3) { System.out.println(message); } //Update the State of the generation FileGenerated = mf.getFileGenerated(); //Displays end if ((FileGenerated == true) && (verbosity < 3)) { System.out.println(message); } } System.out.println("-----------------------------------------------"); }
From source file:edu.ksu.cis.indus.staticanalyses.concurrency.escape.EscapeAndReadWriteCLI.java
/** * The entry point to this class./*from w w w.j a v a 2s . com*/ * * @param args command line arguments. * @throws RuntimeException when escape information and side-effect information calculation fails. */ public static void main(final String[] args) { final Options _options = new Options(); Option _option = new Option("h", "help", false, "Display message."); _option.setOptionalArg(false); _options.addOption(_option); _option = new Option("p", "soot-classpath", false, "Prepend this to soot class path."); _option.setArgs(1); _option.setArgName("classpath"); _option.setOptionalArg(false); _options.addOption(_option); _option = new Option("S", "scope", true, "The scope that should be analyzed."); _option.setArgs(1); _option.setArgName("scope"); _option.setRequired(false); _options.addOption(_option); final CommandLineParser _parser = new GnuParser(); try { final CommandLine _cl = _parser.parse(_options, args); if (_cl.hasOption("h")) { final String _cmdLineSyn = "java " + EscapeAndReadWriteCLI.class.getName() + " <options> <classnames>"; (new HelpFormatter()).printHelp(_cmdLineSyn, _options); System.exit(1); } if (_cl.getArgList().isEmpty()) { throw new MissingArgumentException("Please specify atleast one class."); } final EscapeAndReadWriteCLI _cli = new EscapeAndReadWriteCLI(); if (_cl.hasOption('p')) { _cli.addToSootClassPath(_cl.getOptionValue('p')); } if (_cl.hasOption('S')) { _cli.setScopeSpecFile(_cl.getOptionValue('S')); } _cli.setClassNames(_cl.getArgList()); _cli.<ITokens>execute(); } catch (final ParseException _e) { LOGGER.error("Error while parsing command line.", _e); System.out.println("Error while parsing command line." + _e); final String _cmdLineSyn = "java " + EscapeAndReadWriteCLI.class.getName() + " <options> <classnames>"; (new HelpFormatter()).printHelp(_cmdLineSyn, "Options are:", _options, ""); } catch (final Throwable _e) { LOGGER.error("Beyond our control. May day! May day!", _e); throw new RuntimeException(_e); } }
From source file:edu.msu.cme.rdp.multicompare.Reprocess.java
/** * This class reprocesses the classification results (allrank output) and print out hierarchy output file, based on the confidence cutoff; * and print out only the detail classification results with assignment at certain rank with confidence above the cutoff or/and matching a given taxon. * @param args//from w w w . ja v a 2 s .co m * @throws Exception */ public static void main(String[] args) throws Exception { PrintWriter assign_out = new PrintWriter(new NullWriter()); float conf = 0.8f; PrintStream heir_out = null; String hier_out_filename = null; ClassificationResultFormatter.FORMAT format = ClassificationResultFormatter.FORMAT.allRank; String rank = null; String taxonFilterFile = null; String train_propfile = null; String gene = null; List<MCSample> samples = new ArrayList(); try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption(CmdOptions.HIER_OUTFILE_SHORT_OPT)) { hier_out_filename = line.getOptionValue(CmdOptions.HIER_OUTFILE_SHORT_OPT); heir_out = new PrintStream(hier_out_filename); } else { throw new Exception( "It make sense to provide output filename for " + CmdOptions.HIER_OUTFILE_LONG_OPT); } if (line.hasOption(CmdOptions.OUTFILE_SHORT_OPT)) { assign_out = new PrintWriter(line.getOptionValue(CmdOptions.OUTFILE_SHORT_OPT)); } if (line.hasOption(CmdOptions.RANK_SHORT_OPT)) { rank = line.getOptionValue(CmdOptions.RANK_SHORT_OPT); } if (line.hasOption(CmdOptions.TAXON_SHORT_OPT)) { taxonFilterFile = line.getOptionValue(CmdOptions.TAXON_SHORT_OPT); } if (line.hasOption(CmdOptions.BOOTSTRAP_SHORT_OPT)) { conf = Float.parseFloat(line.getOptionValue(CmdOptions.BOOTSTRAP_SHORT_OPT)); if (conf < 0 || conf > 1) { throw new IllegalArgumentException("Confidence must be in the range [0,1]"); } } if (line.hasOption(CmdOptions.FORMAT_SHORT_OPT)) { String f = line.getOptionValue(CmdOptions.FORMAT_SHORT_OPT); if (f.equalsIgnoreCase("allrank")) { format = ClassificationResultFormatter.FORMAT.allRank; } else if (f.equalsIgnoreCase("fixrank")) { format = ClassificationResultFormatter.FORMAT.fixRank; } else if (f.equalsIgnoreCase("db")) { format = ClassificationResultFormatter.FORMAT.dbformat; } else if (f.equalsIgnoreCase("filterbyconf")) { format = ClassificationResultFormatter.FORMAT.filterbyconf; } else { throw new IllegalArgumentException( "Not valid output format, only allrank, fixrank, filterbyconf and db allowed"); } } if (line.hasOption(CmdOptions.TRAINPROPFILE_SHORT_OPT)) { if (gene != null) { throw new IllegalArgumentException( "Already specified the gene from the default location. Can not specify train_propfile"); } else { train_propfile = line.getOptionValue(CmdOptions.TRAINPROPFILE_SHORT_OPT); } } if (line.hasOption(CmdOptions.GENE_SHORT_OPT)) { if (train_propfile != null) { throw new IllegalArgumentException( "Already specified train_propfile. Can not specify gene any more"); } gene = line.getOptionValue(CmdOptions.GENE_SHORT_OPT).toLowerCase(); if (!gene.equals(ClassifierFactory.RRNA_16S_GENE) && !gene.equals(ClassifierFactory.FUNGALLSU_GENE) && !gene.equals(ClassifierFactory.FUNGALITS_warcup_GENE) && !gene.equals(ClassifierFactory.FUNGALITS_unite_GENE)) { throw new IllegalArgumentException(gene + " is NOT valid, only allows " + ClassifierFactory.RRNA_16S_GENE + ", " + ClassifierFactory.FUNGALLSU_GENE + ", " + ClassifierFactory.FUNGALITS_warcup_GENE + " and " + ClassifierFactory.FUNGALITS_unite_GENE); } } args = line.getArgs(); if (args.length < 1) { throw new Exception("Incorrect number of command line arguments"); } for (String arg : args) { String[] inFileNames = arg.split(","); String inputFile = inFileNames[0]; File idmappingFile = null; if (inFileNames.length == 2) { idmappingFile = new File(inFileNames[1]); if (!idmappingFile.exists()) { System.err.println("Failed to find input file \"" + inFileNames[1] + "\""); return; } } MCSample nextSample = new MCSampleResult(inputFile, idmappingFile); samples.add(nextSample); } } catch (Exception e) { System.out.println("Command Error: " + e.getMessage()); new HelpFormatter().printHelp(120, "Reprocess [options] <Classification_allrank_result>[,idmappingfile] ...", "", options, ""); return; } if (train_propfile == null && gene == null) { gene = ClassifierFactory.RRNA_16S_GENE; } HashSet<String> taxonFilter = null; if (taxonFilterFile != null) { taxonFilter = readTaxonFilterFile(taxonFilterFile); } MultiClassifier multiClassifier = new MultiClassifier(train_propfile, gene); DefaultPrintVisitor printVisitor = new DefaultPrintVisitor(heir_out, samples); MultiClassifierResult result = multiClassifier.multiClassificationParser(samples, conf, assign_out, format, rank, taxonFilter); result.getRoot().topDownVisit(printVisitor); assign_out.close(); heir_out.close(); if (multiClassifier.hasCopyNumber()) { // print copy number corrected counts File cn_corrected_s = new File(new File(hier_out_filename).getParentFile(), "cncorrected_" + hier_out_filename); PrintStream cn_corrected_hier_out = new PrintStream(cn_corrected_s); printVisitor = new DefaultPrintVisitor(cn_corrected_hier_out, samples, true); result.getRoot().topDownVisit(printVisitor); cn_corrected_hier_out.close(); } }
From source file:net.cliftonsnyder.svgchart.Main.java
public static void main(String[] args) { Options options = new Options(); options.addOption("c", "stylesheet", true, "CSS stylesheet (default: " + SVGChart.DEFAULT_STYLESHEET + ")"); options.addOption("h", "height", true, "chart height"); options.addOption("i", "input-file", true, "input file [default: stdin]"); options.addOption("o", "output-file", true, "output file [default: stdout]"); options.addOption("w", "width", true, "chart width"); options.addOption("?", "help", false, "print a brief help message"); Option type = new Option("t", "type", true, "chart type " + Arrays.toString(SVGChart.TYPES)); type.setRequired(true);/*w ww .j a v a2s .com*/ options.addOption(type); CommandLineParser parser = new GnuParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine line = null; try { // parse the command line arguments line = parser.parse(options, args); if (line.hasOption("help")) { formatter.printHelp(USAGE, options); System.exit(0); } } catch (ParseException exp) { // oops, something went wrong System.err.println("unable to parse command line: " + exp.getMessage()); formatter.printHelp(USAGE, options); System.exit(1); } SVGChart chart = null; String tmp = line.getOptionValue("type"); Matcher m = null; for (Pattern p : SVGChart.TYPE_PATTERNS) { if ((m = p.matcher(tmp)).matches()) { switch (m.group().charAt(0)) { case 'l': // DEBUG System.err.println("line"); break; case 'b': System.err.println("bar"); chart = new BarChart(); break; case 'p': System.err.println("pie"); break; default: System.err.println("unknown or unimplemented chart type: '" + tmp + "'"); System.exit(1); } } } try { chart.setWidth(Double.parseDouble(line.getOptionValue("width", "" + SVGChart.DEFAULT_WIDTH))); } catch (NumberFormatException e) { System.err.println( "unable to parse command line: invalid width value '" + line.getOptionValue("width") + "'"); System.exit(1); } try { chart.setHeight(Double.parseDouble(line.getOptionValue("height", "" + SVGChart.DEFAULT_HEIGHT))); } catch (NumberFormatException e) { System.err.println( "unable to parse command line: invalid height value '" + line.getOptionValue("height") + "'"); System.exit(1); } InputStream in = System.in; tmp = line.getOptionValue("input-file", "-"); if ("-".equals(tmp)) { in = System.in; } else { try { in = new FileInputStream(tmp); } catch (FileNotFoundException e) { System.err.println("input file not found: '" + tmp + "'"); System.exit(1); } } PrintStream out = System.out; tmp = line.getOptionValue("output-file", "-"); if ("-".equals(tmp)) { out = System.out; } else { try { out = new PrintStream(new FileOutputStream(tmp)); } catch (FileNotFoundException e) { System.err.println("output file not found: '" + tmp + "'"); System.exit(1); } } tmp = line.getOptionValue("stylesheet", SVGChart.DEFAULT_STYLESHEET); chart.setStyleSheet(tmp); try { chart.parseInput(in); } catch (IOException e) { System.err.println("I/O error while reading input"); System.exit(1); } catch (net.cliftonsnyder.svgchart.parse.ParseException e) { System.err.println("error parsing input: " + e.getMessage()); } chart.createChart(); try { chart.printChart(out, true); } catch (IOException e) { System.err.println("error serializing output"); System.exit(1); } }
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; boolean printHelp = false; try {//from w ww .java 2 s.c om 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.mozilla.bagheera.consumer.KafkaHBaseConsumer.java
public static void main(String[] args) { OptionFactory optFactory = OptionFactory.getInstance(); Options options = KafkaConsumer.getOptions(); options.addOption(optFactory.create("tbl", "table", true, "HBase table name.").required()); options.addOption(optFactory.create("f", "family", true, "Column family.")); options.addOption(optFactory.create("q", "qualifier", true, "Column qualifier.")); options.addOption(/*w w w .j ava 2 s . c o m*/ optFactory.create("b", "batchsize", true, "Batch size (number of messages per HBase flush).")); options.addOption(optFactory.create("pd", "prefixdate", false, "Prefix key with salted date.")); 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"))); } if (cmd.hasOption("batchsize")) { sinkConfig.setInt("hbasesink.hbase.batchsize", Integer.parseInt(cmd.getOptionValue("batchsize"))); } sinkConfig.setString("hbasesink.hbase.tablename", cmd.getOptionValue("table")); sinkConfig.setString("hbasesink.hbase.column.family", cmd.getOptionValue("family", "data")); sinkConfig.setString("hbasesink.hbase.column.qualifier", cmd.getOptionValue("qualifier", "json")); sinkConfig.setBoolean("hbasesink.hbase.rowkey.prefixdate", cmd.hasOption("prefixdate")); KeyValueSinkFactory sinkFactory = KeyValueSinkFactory.getInstance(HBaseSink.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(KafkaHBaseConsumer.class.getName(), options); } }
From source file:cc.wikitools.lucene.FindWikipediaArticleId.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(// w w w .j a v a 2 s . co m OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_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(TITLE_OPTION) || !cmdline.hasOption(INDEX_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(FindWikipediaArticleId.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 title = cmdline.getOptionValue(TITLE_OPTION); PrintStream out = new PrintStream(System.out, true, "UTF-8"); WikipediaSearcher searcher = new WikipediaSearcher(indexLocation); int id = searcher.getArticleId(title); out.println(title + ": id = " + id); searcher.close(); out.close(); }
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 w ww. j a v a 2s.co 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.denimgroup.threadfix.cli.CommandLineParser.java
public static void main(String[] args) { Options options = getOptions();/*from w w w . j a v a 2s. com*/ PosixParser parser = new PosixParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar tfcli.jar", options); } else if (cmd.hasOption("s")) { String[] setArgs = cmd.getOptionValues("s"); if (setArgs == null || setArgs.length != 2) { throw new ParseException("Bad arguments for set."); } if ("url".equals(setArgs[0])) { System.out.println("Setting URL to " + setArgs[1]); client.setUrl(setArgs[1]); } else if ("key".equals(setArgs[0])) { System.out.println("Setting API Key to " + setArgs[1]); client.setKey(setArgs[1]); } else { throw new ParseException("First argument to set must be url or key"); } } else if (cmd.hasOption("ct")) { String[] createArgs = cmd.getOptionValues("ct"); if (createArgs.length != 1) { throw new ParseException("Wrong number of arguments."); } System.out.println("Creating a Team with the name " + createArgs[0] + "."); System.out.println(client.createTeam(createArgs[0])); } else if (cmd.hasOption("cw")) { String[] createArgs = cmd.getOptionValues("cw"); if (createArgs.length != 2) { throw new ParseException("Wrong number of arguments."); } System.out.println("Creating a Waf with the name " + createArgs[0] + "."); System.out.println(client.createWaf(createArgs[0], createArgs[1])); } else if (cmd.hasOption("ca")) { String[] createArgs = cmd.getOptionValues("ca"); if (createArgs.length != 3) { throw new ParseException("Wrong number of arguments."); } System.out.println("Creating an Application with the name " + createArgs[1] + "."); System.out.println(client.createApplication(createArgs[0], createArgs[1], createArgs[2])); } else if (cmd.hasOption("teams")) { System.out.println("Getting all teams."); System.out.println(client.getAllTeams()); } else if (cmd.hasOption("u")) { String[] uploadArgs = cmd.getOptionValues("u"); // Upload a scan if (uploadArgs.length != 2) { throw new ParseException("Wrong number of arguments."); } System.out.println("Uploading " + uploadArgs[1] + " to Application " + uploadArgs[0] + "."); System.out.println(client.uploadScan(uploadArgs[0], uploadArgs[1])); } else if (cmd.hasOption("st")) { String[] searchArgs = cmd.getOptionValues("st"); if (searchArgs.length != 2) { throw new ParseException("Wrong number of arguments."); } if ("id".equals(searchArgs[0])) { System.out.println("Searching for team with the id " + searchArgs[1] + "."); System.out.println(client.searchForTeamById(searchArgs[1])); } else if ("name".equals(searchArgs[0])) { System.out.println("Searching for team with the name " + searchArgs[1] + "."); System.out.println(client.searchForTeamByName(searchArgs[1])); } else { System.out.println("Unknown property argument. Try either id or name."); return; } } else if (cmd.hasOption("sw")) { String[] searchArgs = cmd.getOptionValues("sw"); if (searchArgs.length != 4) { throw new ParseException("Wrong number of arguments."); } if ("id".equals(searchArgs[0])) { System.out.println("Searching for WAF with the id " + searchArgs[1] + "."); System.out.println(client.searchForWafById(searchArgs[1])); } else if ("name".equals(searchArgs[0])) { System.out.println("Searching for WAF with the name " + searchArgs[1] + "."); System.out.println(client.searchForWafByName(searchArgs[1])); } else { throw new ParseException("Unknown property argument. Try either id or name."); } } else if (cmd.hasOption("sa")) { String[] searchArgs = cmd.getOptionValues("sa"); if ("id".equals(searchArgs[0])) { if (searchArgs.length != 2) { System.out.println("Wrong number of arguments."); return; } System.out.println("Searching for application with the id " + searchArgs[1] + "."); System.out.println(client.searchForApplicationById(searchArgs[1])); } else if ("name".equals(searchArgs[0])) { if (searchArgs.length != 3) { System.out.println( "Wrong number of arguments. You need to input application name and team name as well."); return; } System.out.println("Searching for application with the name " + searchArgs[1] + " of team " + searchArgs[2]); System.out.println(client.searchForApplicationByName(searchArgs[1], searchArgs[2])); } else { System.out.println("Unknown property argument. Try either id or name."); return; } } else if (cmd.hasOption("r")) { String[] ruleArgs = cmd.getOptionValues("r"); if (ruleArgs.length != 1) { System.out.println("Wrong number of arguments.'"); } System.out.println("Downloading rules from WAF with ID " + ruleArgs[0] + "."); System.out.println(client.getRules(ruleArgs[0])); } else { throw new ParseException("No arguments found."); } } catch (ParseException e) { if (e.getMessage() != null) { System.out.println(e.getMessage()); } HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar tfcli.jar", options); } }