List of usage examples for org.apache.commons.cli CommandLineParser parse
CommandLine parse(Options options, String[] arguments) throws ParseException;
From source file:com.mosso.client.cloudfiles.sample.FilesRemove.java
public static void main(String args[]) throws NoSuchAlgorithmException, FilesException { //Build the command line options Options options = addCommandLineOptions(); if (args.length <= 0) printHelp(options);//from w w w . j av a2 s .co m CommandLineParser parser = new GnuParser(); try { // parse the command line arguments CommandLine line = parser.parse(options, args); if (line.hasOption("help")) { printHelp(options); System.exit(0); } if (line.hasOption("container")) { String containerName = null; containerName = line.getOptionValue("container"); removeContainer(containerName, line.hasOption('r')); } //if (line.hasOption("container")) if (line.hasOption("object")) { String ObjectNameWithPath = null; ObjectNameWithPath = line.getOptionValue("object"); removeObject(ObjectNameWithPath); } //if (line.hasOption("container")) } //end try catch (ParseException err) { logger.fatal("Parsing exception on the command line: " + err); System.err.println("Please see the logs for more details. Error Message: " + err.getMessage()); err.printStackTrace(System.err); } //catch( ParseException err ) catch (IOException err) { logger.fatal("IOException : " + err); System.err.println("Please see the logs for more details. Error Message: " + err.getMessage()); } //catch ( IOException err) }
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(//from ww w. ja v a 2s . c om 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:com.rackspacecloud.client.cloudfiles.sample.FilesRemove.java
public static void main(String args[]) throws NoSuchAlgorithmException, FilesException { //Build the command line options Options options = addCommandLineOptions(); if (args.length <= 0) printHelp(options);/*from w w w . j a v a 2 s . co m*/ CommandLineParser parser = new GnuParser(); try { // parse the command line arguments CommandLine line = parser.parse(options, args); if (line.hasOption("help")) { printHelp(options); System.exit(0); } if (line.hasOption("container")) { String containerName = null; containerName = line.getOptionValue("container"); removeContainer(containerName, line.hasOption('r')); } //if (line.hasOption("container")) if (line.hasOption("object")) { String ObjectNameWithPath = null; ObjectNameWithPath = line.getOptionValue("object"); removeObject(ObjectNameWithPath); } //if (line.hasOption("container")) } //end try catch (ParseException err) { logger.fatal("Parsing exception on the command line: " + err); System.err.println("Please see the logs for more details. Error Message: " + err.getMessage()); err.printStackTrace(System.err); } //catch( ParseException err ) catch (Exception err) { logger.fatal("Exception : " + err); System.err.println("Please see the logs for more details. Error Message: " + err.getMessage()); } //catch ( IOException err) }
From source file:BasApp.java
public static void main(String[] args) throws Exception { Options options = getOptions();/*from w w w. ja v a2 s .c o m*/ CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { showHelp(options); return; // only show help and exit } final VOConfig cfg; if (cmd.hasOption("config")) { Serializer serializer = new Persister(); final String config = cmd.getOptionValue("config"); FileInputStream fis = new FileInputStream(config); cfg = serializer.read(VOConfig.class, fis); fis.close(); } else { cfg = new VOConfig(); } cfg.setCmd(cmd); CipherProvider dataCipherProvider = new CipherProvider(); dataCipherProvider.setPassword(cmd.getOptionValue("passwd", null)); CipherProvider metaCipherProvider = new CipherProvider(); metaCipherProvider.setPassword(cmd.getOptionValue("passwd-meta", null)); String repoPathStr = cfg.getRepository(); Repository repository = new Repository(repoPathStr, dataCipherProvider, metaCipherProvider); if (cmd.hasOption("dump-config")) { Serializer serializer = new Persister(); final FileOutputStream fos = new FileOutputStream(cmd.getOptionValue("dump-config")); serializer.write(cfg, fos); fos.close(); } if (cmd.hasOption("backup")) { BackupService backup = new BackupService(cfg, repository); backup.run(); } if (cmd.hasOption("restore")) { //noinspection unchecked String restoreTo = null; if (cmd.hasOption("restore-to")) { restoreTo = cmd.getOptionValue("restore-to"); } RestoreService restore = new RestoreService(cmd.getOptionValue("r"), repository, cmd.getArgList(), restoreTo); restore.run(); } if (cmd.hasOption("check")) { CheckService check = new CheckService(cmd.getOptionValue("check"), repository); check.run(); } }
From source file:com.gordcorp.jira2db.App.java
public static void main(String[] args) throws Exception { File log4jFile = new File("log4j.xml"); if (log4jFile.exists()) { DOMConfigurator.configure("log4j.xml"); }// w w w.j a v a 2 s . c o m Option help = new Option("h", "help", false, "print this message"); @SuppressWarnings("static-access") Option project = OptionBuilder.withLongOpt("project").withDescription("Only sync Jira project PROJECT") .hasArg().withArgName("PROJECT").create(); @SuppressWarnings("static-access") Option property = OptionBuilder.withArgName("property=value").hasArgs(2).withValueSeparator() .withDescription("use value for given property").create("D"); @SuppressWarnings("static-access") Option testJira = OptionBuilder.withLongOpt("test-jira") .withDescription("Test the connection to Jira and print the results").create(); @SuppressWarnings("static-access") Option forever = OptionBuilder.withLongOpt("forever") .withDescription("Will continue polling Jira and syncing forever").create(); Options options = new Options(); options.addOption(help); options.addOption(project); options.addOption(property); options.addOption(testJira); options.addOption(forever); CommandLineParser parser = new GnuParser(); try { CommandLine line = parser.parse(options, args); if (line.hasOption(help.getOpt())) { printHelp(options); return; } // Overwrite the properties file with command line arguments if (line.hasOption("D")) { String[] values = line.getOptionValues("D"); for (int i = 0; i < values.length; i = i + 2) { String key = values[i]; // If user does not provide a value for this property, use // an empty string String value = ""; if (i + 1 < values.length) { value = values[i + 1]; } log.info("Setting key=" + key + " value=" + value); PropertiesWrapper.set(key, value); } } if (line.hasOption("test-jira")) { testJira(); } else { JiraSynchroniser jira = new JiraSynchroniser(); if (line.hasOption("project")) { jira.setProjects(Arrays.asList(new String[] { line.getOptionValue("project") })); } if (line.hasOption("forever")) { jira.syncForever(); } else { jira.syncAll(); } } } catch (ParseException exp) { log.error("Parsing failed: " + exp.getMessage()); } catch (Exception e) { log.error(e.getMessage(), e); } }
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(/* w w w. ja v a 2 s. c om*/ 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.booktrack.vader.Main.java
/** * main entry point and demo case for Vader * @param args the arguments - explained below in the code * @throws Exception anything goes wrong - except *//*from w w w . ja v a 2 s .c o m*/ public static void main(String[] args) throws Exception { // create Options object for command line parsing Options options = new Options(); options.addOption("file", true, "input text-file (-file) to read and analyse using Vader"); CommandLineParser cmdParser = new DefaultParser(); CommandLine line = null; try { // parse the command line arguments line = cmdParser.parse(options, args); } catch (ParseException exp) { // oops, something went wrong logger.error("invalid command line: " + exp.getMessage()); System.exit(0); } // get the command line argument -file String inputFile = line.getOptionValue("file"); if (inputFile == null) { help(options); System.exit(0); } if (!new File(inputFile).exists()) { logger.error("file does not exist: " + inputFile); System.exit(0); } // example use of the classes // read the entire input file String fileText = new String(Files.readAllBytes(Paths.get(inputFile))); // setup Vader Vader vader = new Vader(); vader.init(); // load vader // setup nlp processor VaderNLP vaderNLP = new VaderNLP(); vaderNLP.init(); // load open-nlp // parse the text into a set of sentences List<List<Token>> sentenceList = vaderNLP.parse(fileText); // apply vader analysis to each sentence for (List<Token> sentence : sentenceList) { VScore vaderScore = vader.analyseSentence(sentence); logger.info("sentence:" + Token.tokenListToString(sentence)); logger.info("Vader score:" + vaderScore.toString()); } }
From source file:edu.cmu.lti.oaqa.knn4qa.apps.BuildInMemFwdIndexApp.java
public static void main(String[] args) { Options options = new Options(); options.addOption(CommonParams.ROOT_DIR_PARAM, null, true, CommonParams.ROOT_DIR_DESC); options.addOption(CommonParams.SUB_DIR_TYPE_PARAM, null, true, CommonParams.SUB_DIR_TYPE_DESC); options.addOption(CommonParams.MAX_NUM_REC_PARAM, null, true, CommonParams.MAX_NUM_REC_DESC); options.addOption(CommonParams.SOLR_FILE_NAME_PARAM, null, true, CommonParams.SOLR_FILE_NAME_DESC); options.addOption(CommonParams.OUT_INDEX_PARAM, null, true, CommonParams.OUT_MINDEX_DESC); options.addOption(EXCLUDE_FIELDS_PARAM, null, true, EXCLUDE_FIELDS_DESC); CommandLineParser parser = new org.apache.commons.cli.GnuParser(); try {/*from w ww .j a v a2 s .c o m*/ CommandLine cmd = parser.parse(options, args); String rootDir = null; rootDir = cmd.getOptionValue(CommonParams.ROOT_DIR_PARAM); if (null == rootDir) Usage("Specify: " + CommonParams.ROOT_DIR_DESC, options); String outPrefix = cmd.getOptionValue(CommonParams.OUT_INDEX_PARAM); if (null == outPrefix) Usage("Specify: " + CommonParams.OUT_MINDEX_DESC, options); String subDirTypeList = cmd.getOptionValue(CommonParams.SUB_DIR_TYPE_PARAM); if (null == subDirTypeList || subDirTypeList.isEmpty()) Usage("Specify: " + CommonParams.SUB_DIR_TYPE_DESC, options); String solrFileName = cmd.getOptionValue(CommonParams.SOLR_FILE_NAME_PARAM); if (null == solrFileName) Usage("Specify: " + CommonParams.SOLR_FILE_NAME_DESC, options); int maxNumRec = Integer.MAX_VALUE; String tmp = cmd.getOptionValue(CommonParams.MAX_NUM_REC_PARAM); if (tmp != null) { try { maxNumRec = Integer.parseInt(tmp); if (maxNumRec <= 0) { Usage("The maximum number of records should be a positive integer", options); } } catch (NumberFormatException e) { Usage("The maximum number of records should be a positive integer", options); } } String[] exclFields = new String[0]; tmp = cmd.getOptionValue(EXCLUDE_FIELDS_PARAM); if (null != tmp) { exclFields = tmp.split(","); } String[] subDirs = subDirTypeList.split(","); for (int k = 0; k < FeatureExtractor.mFieldNames.length; ++k) { String field = FeatureExtractor.mFieldsSOLR[k]; String fieldName = FeatureExtractor.mFieldNames[k]; boolean bOk = !StringUtilsLeo.isInArrayNoCase(fieldName, exclFields); if (bOk) System.out.println("Processing field: " + field); else { System.out.println("Skipping field: " + field); continue; } String[] fileNames = new String[subDirs.length]; for (int i = 0; i < fileNames.length; ++i) fileNames[i] = rootDir + "/" + subDirs[i] + "/" + solrFileName; InMemForwardIndex indx = new InMemForwardIndex(field, fileNames, maxNumRec); indx.save(InMemIndexFeatureExtractor.indexFileName(outPrefix, fieldName)); } } catch (ParseException e) { Usage("Cannot parse arguments", options); } catch (Exception e) { e.printStackTrace(); System.err.println("Terminating due to an exception: " + e); System.exit(1); } }
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;/* ww w. j ava 2s . co m*/ 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:com.act.lcms.db.io.LoadTSVIntoDB.java
public static void main(String[] args) throws Exception { Options opts = new Options(); opts.addOption(Option.builder("t").argName("type") .desc("The type of TSV data to read, options are: " + StringUtils.join(TSV_TYPE.values(), ", ")) .hasArg().required().longOpt("table-type").build()); opts.addOption(Option.builder("i").argName("path").desc("The TSV file to read").hasArg().required() .longOpt("input-file").build()); // DB connection options. opts.addOption(Option.builder().argName("database url") .desc("The url to use when connecting to the LCMS db").hasArg().longOpt("db-url").build()); opts.addOption(Option.builder("u").argName("database user").desc("The LCMS DB user").hasArg() .longOpt("db-user").build()); opts.addOption(Option.builder("p").argName("database password").desc("The LCMS DB password").hasArg() .longOpt("db-pass").build()); opts.addOption(Option.builder("H").argName("database host") .desc(String.format("The LCMS DB host (default = %s)", DB.DEFAULT_HOST)).hasArg().longOpt("db-host") .build());/*from w w w . j a va2s .c o m*/ opts.addOption(Option.builder("P").argName("database port") .desc(String.format("The LCMS DB port (default = %d)", DB.DEFAULT_PORT)).hasArg().longOpt("db-port") .build()); opts.addOption(Option.builder("N").argName("database name") .desc(String.format("The LCMS DB name (default = %s)", DB.DEFAULT_DB_NAME)).hasArg() .longOpt("db-name").build()); // Everybody needs a little help from their friends. opts.addOption( Option.builder("h").argName("help").desc("Prints this help message").longOpt("help").build()); CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { System.err.format("Argument parsing failed: %s\n", e.getMessage()); HelpFormatter fmt = new HelpFormatter(); fmt.printHelp(LoadTSVIntoDB.class.getCanonicalName(), opts, true); System.exit(1); } if (cl.hasOption("help")) { new HelpFormatter().printHelp(LoadTSVIntoDB.class.getCanonicalName(), opts, true); return; } File inputFile = new File(cl.getOptionValue("input-file")); if (!inputFile.exists()) { System.err.format("Unable to find input file at %s\n", cl.getOptionValue("input-file")); new HelpFormatter().printHelp(LoadTSVIntoDB.class.getCanonicalName(), opts, true); System.exit(1); } TSV_TYPE contentType = null; try { contentType = TSV_TYPE.valueOf(cl.getOptionValue("table-type")); } catch (IllegalArgumentException e) { System.err.format("Unrecognized TSV type '%s'\n", cl.getOptionValue("table-type")); new HelpFormatter().printHelp(LoadTSVIntoDB.class.getCanonicalName(), opts, true); System.exit(1); } DB db; if (cl.hasOption("db-url")) { db = new DB().connectToDB(cl.getOptionValue("db-url")); } else { Integer port = null; if (cl.getOptionValue("P") != null) { port = Integer.parseInt(cl.getOptionValue("P")); } db = new DB().connectToDB(cl.getOptionValue("H"), port, cl.getOptionValue("N"), cl.getOptionValue("u"), cl.getOptionValue("p")); } try { db.getConn().setAutoCommit(false); TSVParser parser = new TSVParser(); parser.parse(inputFile); List<Pair<Integer, DB.OPERATION_PERFORMED>> results = null; switch (contentType) { case CURATED_CHEMICAL: results = CuratedChemical.insertOrUpdateCuratedChemicalsFromTSV(db, parser); break; case CONSTRUCT: results = ConstructEntry.insertOrUpdateCompositionMapEntriesFromTSV(db, parser); break; case CHEMICAL_OF_INTEREST: results = ChemicalOfInterest.insertOrUpdateChemicalOfInterestsFromTSV(db, parser); break; default: throw new RuntimeException(String.format("Unsupported TSV type: %s", contentType)); } if (results != null) { for (Pair<Integer, DB.OPERATION_PERFORMED> r : results) { System.out.format("%d: %s\n", r.getLeft(), r.getRight()); } } // If we didn't encounter an exception, commit the transaction. db.getConn().commit(); } catch (Exception e) { System.err.format("Caught exception when trying to load plate composition, rolling back. %s\n", e.getMessage()); db.getConn().rollback(); throw (e); } finally { db.getConn().close(); } }