List of usage examples for org.apache.commons.cli CommandLine getOptionValue
public String getOptionValue(char opt)
From source file:ee.ria.xroad.opmonitordaemon.OperationalDataRecordsGenerator.java
/** * Main function.//from ww w . j a v a2s . com * @param args args * @throws Exception if something goes wrong. */ public static void main(String args[]) throws Exception { CommandLine cmd = parseCommandLine(args); if (cmd.hasOption("help")) { usage(); System.exit(0); } long startTimestamp = cmd.getOptionValue("timestamp") != null ? Long.parseLong(cmd.getOptionValue("timestamp")) : DEFAULT_FIRST_TIMESTAMP; int batchSize = cmd.getOptionValue("batch-size") != null ? Integer.parseInt(cmd.getOptionValue("batch-size")) : DEFAULT_BATCH_SIZE; int batchCount = cmd.getOptionValue("batch-count") != null ? Integer.parseInt(cmd.getOptionValue("batch-count")) : DEFAULT_BATCH_COUNT; String longString = cmd.getOptionValue("long-string-length") != null ? getDummyStr(Integer.parseInt(cmd.getOptionValue("long-string-length"))) : getDummyStr(DEFAULT_LONG_STRING_LENGTH); String shortString = cmd.getOptionValue("short-string-length") != null ? getDummyStr(Integer.parseInt(cmd.getOptionValue("short-string-length"))) : getDummyStr(DEFAULT_SHORT_LONG_STRING_LENGTH); log.info("first timestamp: {}, batch-size: {}, batch-count: {}", startTimestamp, batchSize, batchCount); for (int i = 0; i < batchCount; ++i) { storeRecords(batchSize, startTimestamp++, longString, shortString); } log.info("{} records generated", batchCount * batchSize); }
From source file:edu.cwru.jpdg.JPDG.java
public static void main(String[] argv) throws pDG_Builder.Error { final Option helpOpt = new Option("h", "help", false, "print this message"); final Option outputOpt = new Option("o", "output", true, "output file location"); final Option baseOpt = new Option("b", "base-dir", true, "base directory to analyze"); final Option excludeOpt = new Option("e", "exclude", true, "exclude these directories"); final Option classOpt = new Option("c", "classpath", true, "classpath for soot"); final Option labelOpt = new Option("l", "label-type", true, "label type, valid choices are: expr-tree, inst"); final org.apache.commons.cli.Options options = new org.apache.commons.cli.Options(); options.addOption(helpOpt);/*w w w .j ava 2s . c o m*/ options.addOption(outputOpt); options.addOption(baseOpt); options.addOption(classOpt); options.addOption(labelOpt); options.addOption(excludeOpt); String cp = null; String base_dir = null; String label_type = "expr-tree"; String output_file = null; List<String> excluded = new ArrayList<String>(); try { GnuParser parser = new GnuParser(); CommandLine line = parser.parse(options, argv); if (line.hasOption(helpOpt.getLongOpt())) { Usage(options); } cp = line.getOptionValue(classOpt.getLongOpt()); base_dir = line.getOptionValue(baseOpt.getLongOpt()); label_type = line.getOptionValue(labelOpt.getLongOpt()); output_file = line.getOptionValue(outputOpt.getLongOpt()); String[] ex = line.getOptionValues(excludeOpt.getLongOpt()); if (ex != null) { excluded = Arrays.asList(ex); } } catch (final MissingOptionException e) { System.err.println(e.getMessage()); Usage(options); } catch (final UnrecognizedOptionException e) { System.err.println(e.getMessage()); Usage(options); } catch (final ParseException e) { System.err.println(e.getMessage()); System.exit(1); } List<String> dirs = new ArrayList<String>(); dirs.add(base_dir); soot.Scene S = runSoot(cp, dirs, excluded); writeGraph(build_PDG(S, excluded, label_type), output_file); }
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);/* w w w. ja v a 2 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:com.zimbra.cs.db.MySQL.java
public static void main(String args[]) { // command line argument parsing Options options = new Options(); CommandLine cl = Versions.parseCmdlineArgs(args, options); String outputDir = cl.getOptionValue("o"); File outFile = new File(outputDir, "versions-init.sql"); outFile.delete();// www . j a va2 s . com try { String redoVer = com.zimbra.cs.redolog.Version.latest().toString(); String outStr = "-- AUTO-GENERATED .SQL FILE - Generated by the MySQL versions tool\n" + "USE zimbra;\n" + "INSERT INTO zimbra.config(name, value, description) VALUES\n" + "\t('db.version', '" + Versions.DB_VERSION + "', 'db schema version'),\n" + "\t('index.version', '" + Versions.INDEX_VERSION + "', 'index version'),\n" + "\t('redolog.version', '" + redoVer + "', 'redolog version')\n" + ";\nCOMMIT;\n"; Writer output = new BufferedWriter(new FileWriter(outFile)); output.write(outStr); if (output != null) output.close(); } catch (IOException e) { System.out.println("ERROR - caught exception at\n"); e.printStackTrace(); System.exit(-1); } }
From source file:benchmarkio.controlcenter.LaunchRocket.java
public static void main(final String[] args) throws Exception { // create the parser final CommandLineParser parser = new BasicParser(); // parse the command line arguments final CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("u")) { displayHelp();/*w w w. j a v a 2s . c o m*/ } final String host = cmd.getOptionValue("host"); final int port = Integer.parseInt(cmd.getOptionValue("port")); final BrokerType brokerType = BrokerType.valueOf(cmd.getOptionValue("broker-type")); final int numConsumers = Integer.parseInt(cmd.getOptionValue("num-consumers")); final int numProducers = Integer.parseInt(cmd.getOptionValue("num-producers")); final int totalNumberOfMessages = Integer.parseInt(cmd.getOptionValue("total-number-of-messages")); final double msgSizeInKB = Double.parseDouble(cmd.getOptionValue("msg-size-in-kb")); // Optional options final Optional<String> optionalBenchmarkType = Optional.fromNullable(cmd.getOptionValue("benchmark-type")); final Optional<String> optionalDurable = Optional.fromNullable(cmd.getOptionValue("durable")); // Kafka Specific final Optional<String> optionalZookeeper = Optional.fromNullable(cmd.getOptionValue("zookeeper")); Optional<String> optionalKafkaProducerType = Optional .fromNullable(cmd.getOptionValue("kafka-producer-type")); BenchmarkType benchmarkType; if (optionalBenchmarkType.isPresent()) { benchmarkType = BenchmarkType.valueOf(optionalBenchmarkType.get()); } else { log.info("Benchmark type was not specified, defaulting to: {}", BenchmarkType.PRODUCER_AND_CONSUMER); benchmarkType = BenchmarkType.PRODUCER_AND_CONSUMER; } boolean durable = false; if (optionalDurable.isPresent()) { durable = Boolean.valueOf(optionalDurable.get()); } else { log.info("Durable parameter was not specified, defaulting to: FALSE"); } if (brokerType == BrokerType.KAFKA) { if (!optionalZookeeper.isPresent()) { log.error("zookeeper is missing, it is a required property for KAFKA broker"); System.exit(0); } if (!optionalKafkaProducerType.isPresent()) { log.info("kafka-producer-type is not specified, defaulting to sync"); optionalKafkaProducerType = Optional.of("sync"); } else if (!optionalKafkaProducerType.get().equals("sync") && !optionalKafkaProducerType.get().equals("async")) { log.warn("kafka-producer-type is not one of the accepted sync | async values, defaulting to sync"); optionalKafkaProducerType = Optional.of("sync"); } } log.info("destination (topic or queue): {}", Consts.DESTINATION_NAME); log.info("host: {}", host); log.info("port: {}", port); log.info("broker-type: {}", brokerType); log.info("benchmark-type: {}", benchmarkType); log.info("durable: {}", durable); log.info("num-consumers: {}", numConsumers); log.info("num-producers: {}", numProducers); log.info("total-number-of-messages: {}", totalNumberOfMessages); log.info("msg-size-in-kb: {}", msgSizeInKB); if (brokerType == BrokerType.KAFKA) { log.info("zookeeper: {}", optionalZookeeper.get()); log.info("kafka-producer-type: {}", optionalKafkaProducerType.get()); } LaunchRocket.start(brokerType, benchmarkType, durable, host, port, numConsumers, numProducers, totalNumberOfMessages, msgSizeInKB, optionalZookeeper, optionalKafkaProducerType); System.exit(0); }
From source file:edu.msu.cme.rdp.classifier.ClassifierCmd.java
/** * This is the main method to do classification. * <p>Usage: java ClassifierCmd queryFile outputFile [property file]. * <br>//from w w w . j a v a2 s. com * queryFile can be one of the following formats: Fasta, Genbank and EMBL. * <br> * outputFile will be used to save the classification output. * <br> * property file contains the mapping of the training files. * <br> * Note: the training files and the property file should be in the same directory. * The default property file is set to data/classifier/16srrna/rRNAClassifier.properties. */ public static void main(String[] args) throws Exception { String queryFile = null; String outputFile = null; String propFile = null; String gene = null; ClassificationResultFormatter.FORMAT format = CmdOptions.DEFAULT_FORMAT; int min_bootstrap_words = Classifier.MIN_BOOTSTRSP_WORDS; try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption(CmdOptions.OUTFILE_SHORT_OPT)) { outputFile = line.getOptionValue(CmdOptions.OUTFILE_SHORT_OPT); } else { throw new Exception("outputFile must be specified"); } 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 { propFile = line.getOptionValue(CmdOptions.TRAINPROPFILE_SHORT_OPT); } } 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("filterbyconf")) { format = ClassificationResultFormatter.FORMAT.filterbyconf; } else if (f.equalsIgnoreCase("db")) { format = ClassificationResultFormatter.FORMAT.dbformat; } else { throw new IllegalArgumentException( "Not valid output format, only allrank, fixrank, filterbyconf and db allowed"); } } if (line.hasOption(CmdOptions.GENE_SHORT_OPT)) { if (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)) { throw new IllegalArgumentException(gene + " is NOT valid, only allows " + ClassifierFactory.RRNA_16S_GENE + " and " + ClassifierFactory.FUNGALLSU_GENE); } } if (line.hasOption(CmdOptions.MIN_BOOTSTRAP_WORDS_SHORT_OPT)) { min_bootstrap_words = Integer .parseInt(line.getOptionValue(CmdOptions.MIN_BOOTSTRAP_WORDS_SHORT_OPT)); if (min_bootstrap_words < Classifier.MIN_BOOTSTRSP_WORDS) { throw new IllegalArgumentException(CmdOptions.MIN_BOOTSTRAP_WORDS_LONG_OPT + " must be at least " + Classifier.MIN_BOOTSTRSP_WORDS); } } args = line.getArgs(); if (args.length != 1) { throw new Exception("Expect one query file"); } queryFile = args[0]; } catch (Exception e) { System.out.println("Command Error: " + e.getMessage()); new HelpFormatter().printHelp(120, "ClassifierCmd [options] <samplefile>\nNote this is the legacy command for one sample classification ", "", options, ""); return; } if (propFile == null && gene == null) { gene = CmdOptions.DEFAULT_GENE; } ClassifierCmd classifierCmd = new ClassifierCmd(); printLicense(); classifierCmd.doClassify(queryFile, outputFile, propFile, format, gene, min_bootstrap_words); }
From source file:ca.uhn.hunit.run.TestRunner.java
/** * @param args/*from w w w.j a v a 2 s . co m*/ * @throws URISyntaxException * @throws JAXBException * @throws ConfigurationException * @throws InterfaceWontStartException * @throws FileNotFoundException * @throws ParseException */ public static void main(String[] theArgs) throws URISyntaxException, JAXBException, InterfaceWontStartException, ConfigurationException, FileNotFoundException, ParseException { Options options = new Options(); OptionGroup fileOptionGroup = new OptionGroup(); fileOptionGroup.setRequired(false); Option option = new Option("f", "file", true, "The path to the file to load the test battery from"); option.setValueSeparator('='); fileOptionGroup.addOption(option); option = new Option("c", "classpath", true, "The classpath path to the file to load the test battery from"); option.setValueSeparator('='); fileOptionGroup.addOption(option); options.addOptionGroup(fileOptionGroup); OptionGroup uiOptionGroup = new OptionGroup(); option = new Option("g", "gui", false, "Start hUnit in GUI mode (default)"); uiOptionGroup.addOption(option); option = new Option("x", "text", false, "Start hUnit in Text mode"); uiOptionGroup.addOption(option); options.addOptionGroup(uiOptionGroup); option = new Option("t", "tests", true, "A comma separated list of tests to execute (default is all)"); option.setValueSeparator('='); option.setRequired(false); options.addOption(option); Resource defFile = null; CommandLine parser; boolean textMode = false; try { parser = new PosixParser().parse(options, theArgs); if (parser.hasOption("f")) { defFile = new FileSystemResource(parser.getOptionValue("f")); } else if (parser.hasOption("c")) { defFile = new ClassPathResource(parser.getOptionValue("c")); } if (parser.hasOption("x")) { textMode = true; } } catch (Exception e) { HelpFormatter hf = new HelpFormatter(); hf.printHelp("java -jar hunit-[version]-jar-with-dependencies.jar [-c FILE|-f FILE] [options]", options); return; } String[] testsToExecute = null; if (parser.hasOption("t")) { testsToExecute = parser.getOptionValue("t").split(","); } if (textMode) { executeInTextMode(defFile, testsToExecute); } else { executeInGuiMode(defFile, testsToExecute); } }
From source file:edu.cmu.lti.oaqa.knn4qa.apps.FilterTranTable.java
public static void main(String[] args) { Options options = new Options(); options.addOption(INPUT_PARAM, null, true, INPUT_DESC); options.addOption(OUTPUT_PARAM, null, true, OUTPUT_DESC); options.addOption(CommonParams.MEM_FWD_INDEX_PARAM, null, true, CommonParams.MEM_FWD_INDEX_DESC); options.addOption(CommonParams.GIZA_ITER_QTY_PARAM, null, true, CommonParams.GIZA_ITER_QTY_PARAM); options.addOption(CommonParams.GIZA_ROOT_DIR_PARAM, null, true, CommonParams.GIZA_ROOT_DIR_PARAM); options.addOption(CommonParams.MIN_PROB_PARAM, null, true, CommonParams.MIN_PROB_DESC); options.addOption(CommonParams.MAX_WORD_QTY_PARAM, null, true, CommonParams.MAX_WORD_QTY_PARAM); CommandLineParser parser = new org.apache.commons.cli.GnuParser(); try {//from w w w . j a v a 2s. c o m CommandLine cmd = parser.parse(options, args); String outputFile = null; outputFile = cmd.getOptionValue(OUTPUT_PARAM); if (null == outputFile) { Usage("Specify 'A name of the output file'", options); } String gizaRootDir = cmd.getOptionValue(CommonParams.GIZA_ROOT_DIR_PARAM); if (null == gizaRootDir) { Usage("Specify '" + CommonParams.GIZA_ROOT_DIR_DESC + "'", options); } String gizaIterQty = cmd.getOptionValue(CommonParams.GIZA_ITER_QTY_PARAM); if (null == gizaIterQty) { Usage("Specify '" + CommonParams.GIZA_ITER_QTY_DESC + "'", options); } float minProb = 0; String tmpf = cmd.getOptionValue(CommonParams.MIN_PROB_PARAM); if (tmpf != null) { minProb = Float.parseFloat(tmpf); } int maxWordQty = Integer.MAX_VALUE; String tmpi = cmd.getOptionValue(CommonParams.MAX_WORD_QTY_PARAM); if (null != tmpi) { maxWordQty = Integer.parseInt(tmpi); } String memFwdIndxName = cmd.getOptionValue(CommonParams.MEM_FWD_INDEX_PARAM); if (null == memFwdIndxName) { Usage("Specify '" + CommonParams.MEM_FWD_INDEX_DESC + "'", options); } System.out.println("Filtering index: " + memFwdIndxName + " max # of frequent words: " + maxWordQty + " min. probability:" + minProb); VocabularyFilterAndRecoder filter = new FrequentIndexWordFilterAndRecoder(memFwdIndxName, maxWordQty); String srcVocFile = CompressUtils.findFileVariant(gizaRootDir + "/source.vcb"); System.out.println("Source vocabulary file: " + srcVocFile); GizaVocabularyReader srcVoc = new GizaVocabularyReader(srcVocFile, filter); String dstVocFile = CompressUtils.findFileVariant(gizaRootDir + "/target.vcb"); System.out.println("Target vocabulary file: " + dstVocFile); GizaVocabularyReader dstVoc = new GizaVocabularyReader(CompressUtils.findFileVariant(dstVocFile), filter); String inputFile = CompressUtils.findFileVariant(gizaRootDir + "/output.t1." + gizaIterQty); BufferedReader finp = new BufferedReader( new InputStreamReader(CompressUtils.createInputStream(inputFile))); BufferedWriter fout = new BufferedWriter( new OutputStreamWriter(CompressUtils.createOutputStream(outputFile))); try { String line; int prevSrcId = -1; int wordQty = 0; long addedQty = 0; long totalQty = 0; boolean isNotFiltered = false; for (totalQty = 0; (line = finp.readLine()) != null;) { ++totalQty; // Skip empty lines line = line.trim(); if (line.isEmpty()) continue; GizaTranRec rec = new GizaTranRec(line); if (rec.mSrcId != prevSrcId) { ++wordQty; } if (totalQty % REPORT_INTERVAL_QTY == 0) { System.out.println(String.format( "Processed %d lines (%d source word entries) from '%s', added %d lines", totalQty, wordQty, inputFile, addedQty)); } // isNotFiltered should be set after procOneWord if (rec.mSrcId != prevSrcId) { if (rec.mSrcId == 0) isNotFiltered = true; else { String wordSrc = srcVoc.getWord(rec.mSrcId); isNotFiltered = filter == null || (wordSrc != null && filter.checkWord(wordSrc)); } } prevSrcId = rec.mSrcId; if (rec.mProb >= minProb && isNotFiltered) { String wordDst = dstVoc.getWord(rec.mDstId); if (filter == null || (wordDst != null && filter.checkWord(wordDst))) { fout.write(String.format(rec.mSrcId + " " + rec.mDstId + " " + rec.mProb)); fout.newLine(); addedQty++; } } } System.out.println( String.format("Processed %d lines (%d source word entries) from '%s', added %d lines", totalQty, wordQty, inputFile, addedQty)); } finally { finp.close(); fout.close(); } } 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:act.installer.reachablesexplorer.WordCloudGenerator.java
public static void main(String[] args) { CLIUtil cliUtil = new CLIUtil(Loader.class, HELP_MESSAGE, OPTION_BUILDERS); CommandLine cl = cliUtil.parseCommandLine(args); // TODO add possibility to run wordcloud generation as a post processing step, from a loaded reachables database File inchisFile = new File(cl.getOptionValue(OPTION_INPUT_INCHIS)); L2InchiCorpus inchiCorpus = new L2InchiCorpus(); try {//from w ww. java2s . c o m inchiCorpus.loadCorpus(inchisFile); } catch (IOException e) { cliUtil.failWithMessage("Could not load inchi corpus from input file %s", inchisFile.getAbsolutePath()); } WordCloudGenerator wordCloudGenerator = new WordCloudGenerator( cl.getOptionValue(OPTION_DB_HOST, DEFAULT_HOST), Integer.parseInt(cl.getOptionValue(OPTION_DB_PORT, DEFAULT_PORT)), cl.getOptionValue(OPTION_INSTALLER_SOURCE_DB, DEFAULT_CHEMICALS_DATABASE), cl.getOptionValue(OPTION_RENDERING_CACHE, DEFAULT_ASSETS_LOCATION), cl.getOptionValue(OPTION_RSCRIPT_EXE_PATH, RSCRIPT_EXE_PATH)); inchiCorpus.getInchiList().forEach(wordCloudGenerator::generateWordCloud); }
From source file:de.fischer.thotti.core.runner.TargetURLGenerator.java
public static final void main(String[] args) { String accessKey = null;/*from w ww . j a va 2 s. c om*/ String secretKey = null; Options options = createCommandLineOption(); CommandLineParser parser = new GnuParser(); try { // parse the command line arguments CommandLine line = parser.parse(options, args); if (!line.hasOption("ak")) { throw new ParseException("AWS Accress Key is missing."); } if (!line.hasOption("sk")) { throw new ParseException("AWS Secret Key is missing."); } accessKey = line.getOptionValue("ak"); secretKey = line.getOptionValue("sk"); } catch (ParseException exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); System.exit(1); } TargetURLGenerator generator = new TargetURLGenerator(); generator.setAccessKey(accessKey); generator.setSecretKey(secretKey); generator.run(); }