List of usage examples for org.apache.commons.cli GnuParser GnuParser
GnuParser
From source file:de.uni_koblenz.west.splendid.tools.NQuadSourceAggregator.java
public static void main(String[] args) { try {/* w w w . j a v a2 s .c o m*/ // parse the command line arguments CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(OPTIONS, args); // print help message if (cmd.hasOption("h") || cmd.hasOption("help")) { new HelpFormatter().printHelp(USAGE, OPTIONS); System.exit(0); } // get input files (from option -i or all remaining parameters) String[] inputFiles = cmd.getOptionValues("i"); if (inputFiles == null) inputFiles = cmd.getArgs(); if (inputFiles.length == 0) { System.out.println("need at least one input file."); new HelpFormatter().printUsage(new PrintWriter(System.out, true), 80, USAGE); System.exit(1); } String outputFile = cmd.getOptionValue("o"); // process all input files new NQuadSourceAggregator().process(outputFile, inputFiles); } catch (ParseException exp) { // print parse error and display usage message System.out.println(exp.getMessage()); new HelpFormatter().printUsage(new PrintWriter(System.out, true), 80, USAGE, OPTIONS); } }
From source file:com.linkedin.restli.tools.snapshot.gen.RestLiSnapshotExporterCmdLineApp.java
/** * @param args restliexporter -sourcepath sourcepath -resourcepackages packagenames [-name api_name] [-outdir outdir] *///from w w w. ja va2 s. c om public static void main(String[] args) { CommandLine cl = null; try { final CommandLineParser parser = new GnuParser(); cl = parser.parse(OPTIONS, args); } catch (ParseException e) { System.err.println("Invalid arguments: " + e.getMessage()); final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "restliexporter -sourcepath sourcepath [-resourcepackages packagenames] [-resourceclasses classnames]" + "[-name api_name] [-outdir outdir]", OPTIONS); System.exit(0); } final String resolverPath = System.getProperty(AbstractGenerator.GENERATOR_RESOLVER_PATH); try { final RestLiSnapshotExporter exporter = new RestLiSnapshotExporter(); exporter.setResolverPath(resolverPath); exporter.export(cl.getOptionValue("name"), null, cl.getOptionValues("sourcepath"), cl.getOptionValues("resourcepackages"), cl.getOptionValues("resourceClasses"), cl.getOptionValue("outdir", "."), AdditionalDocProvidersUtil.findDocProviders(log, cl.hasOption("loadAdditionalDocProviders"))); } catch (Throwable e) { log.error("Error writing Snapshot files", e); System.out.println("Error writing Snapshot files:\n" + e); System.exit(1); } }
From source file:cc.twittertools.search.local.RunQueries.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(/*from 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("num").hasArg().withDescription("number of results to return") .create(NUM_RESULTS_OPTION)); options.addOption(OptionBuilder.withArgName("file").hasArg() .withDescription("file containing topics in TREC format").create(QUERIES_OPTION)); options.addOption(OptionBuilder.withArgName("similarity").hasArg() .withDescription("similarity to use (BM25, LM)").create(SIMILARITY_OPTION)); options.addOption( OptionBuilder.withArgName("string").hasArg().withDescription("runtag").create(RUNTAG_OPTION)); options.addOption(new Option(VERBOSE_OPTION, "print out complete document")); 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(QUERIES_OPTION) || !cmdline.hasOption(INDEX_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(RunQueries.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 runtag = cmdline.hasOption(RUNTAG_OPTION) ? cmdline.getOptionValue(RUNTAG_OPTION) : DEFAULT_RUNTAG; String topicsFile = cmdline.getOptionValue(QUERIES_OPTION); int numResults = 1000; try { if (cmdline.hasOption(NUM_RESULTS_OPTION)) { numResults = Integer.parseInt(cmdline.getOptionValue(NUM_RESULTS_OPTION)); } } catch (NumberFormatException e) { System.err.println("Invalid " + NUM_RESULTS_OPTION + ": " + cmdline.getOptionValue(NUM_RESULTS_OPTION)); System.exit(-1); } String similarity = "LM"; if (cmdline.hasOption(SIMILARITY_OPTION)) { similarity = cmdline.getOptionValue(SIMILARITY_OPTION); } boolean verbose = cmdline.hasOption(VERBOSE_OPTION); PrintStream out = new PrintStream(System.out, true, "UTF-8"); IndexReader reader = DirectoryReader.open(FSDirectory.open(indexLocation)); IndexSearcher searcher = new IndexSearcher(reader); if (similarity.equalsIgnoreCase("BM25")) { searcher.setSimilarity(new BM25Similarity()); } else if (similarity.equalsIgnoreCase("LM")) { searcher.setSimilarity(new LMDirichletSimilarity(2500.0f)); } QueryParser p = new QueryParser(Version.LUCENE_43, StatusField.TEXT.name, IndexStatuses.ANALYZER); TrecTopicSet topics = TrecTopicSet.fromFile(new File(topicsFile)); for (TrecTopic topic : topics) { Query query = p.parse(topic.getQuery()); Filter filter = NumericRangeFilter.newLongRange(StatusField.ID.name, 0L, topic.getQueryTweetTime(), true, true); TopDocs rs = searcher.search(query, filter, numResults); int i = 1; for (ScoreDoc scoreDoc : rs.scoreDocs) { Document hit = searcher.doc(scoreDoc.doc); out.println(String.format("%s Q0 %s %d %f %s", topic.getId(), hit.getField(StatusField.ID.name).numericValue(), i, scoreDoc.score, runtag)); if (verbose) { out.println("# " + hit.toString().replaceAll("[\\n\\r]+", " ")); } i++; } } reader.close(); out.close(); }
From source file:de.topobyte.osm4j.pbf.executables.EntitySplitBlockwise.java
public static void main(String[] args) throws IOException { // @formatter:off Options options = new Options(); OptionHelper.add(options, OPTION_INPUT, true, true, "input file"); OptionHelper.add(options, OPTION_OUTPUT_NODES, true, false, "the file to write nodes to"); OptionHelper.add(options, OPTION_OUTPUT_WAYS, true, false, "the file to write ways to"); OptionHelper.add(options, OPTION_OUTPUT_RELATIONS, true, false, "the file to write relations to"); // @formatter:on CommandLine line = null;/* w w w . jav a 2 s . co m*/ try { line = new GnuParser().parse(options, args); } catch (ParseException e) { System.out.println("unable to parse command line: " + e.getMessage()); new HelpFormatter().printHelp(HELP_MESSAGE, options); System.exit(1); } if (line == null) { return; } String inputPath = line.getOptionValue(OPTION_INPUT); File file = new File(inputPath); PbfFile pbfFile = new PbfFile(file); OutputStream outNodes = null, outWays = null, outRelations = null; if (line.hasOption(OPTION_OUTPUT_NODES)) { String path = line.getOptionValue(OPTION_OUTPUT_NODES); FileOutputStream fos = new FileOutputStream(path); outNodes = new BufferedOutputStream(fos); } if (line.hasOption(OPTION_OUTPUT_WAYS)) { String path = line.getOptionValue(OPTION_OUTPUT_WAYS); FileOutputStream fos = new FileOutputStream(path); outWays = new BufferedOutputStream(fos); } if (line.hasOption(OPTION_OUTPUT_RELATIONS)) { String path = line.getOptionValue(OPTION_OUTPUT_RELATIONS); FileOutputStream fos = new FileOutputStream(path); outRelations = new BufferedOutputStream(fos); } if (outNodes == null && outWays == null && outRelations == null) { System.out.println("You should specify an output for at least one entity"); System.exit(1); } EntitySplitBlockwise task = new EntitySplitBlockwise(pbfFile, outNodes, outWays, outRelations); task.execute(); }
From source file:de.tudarmstadt.lt.lm.app.GenerateNgrams.java
@SuppressWarnings("static-access") public static void main(String[] args) { Options opts = new Options(); opts.addOption(OptionBuilder.withLongOpt("help").withDescription("Display help message.").create("?")); opts.addOption(OptionBuilder.withLongOpt("ptype").withArgName("class").hasArg().withDescription( "specify the instance of the language model provider that you want to use: {LtSegProvider, BreakIteratorStringProvider, UimaStringProvider, PreTokenizedStringProvider} (default: LtSegProvider)") .create("p")); opts.addOption(OptionBuilder.withLongOpt("cardinality").withArgName("ngram-order").hasArg().withDescription( "Specify the cardinality of the ngrams (min. 1). Specify a range using 'from-to'. (Examples: 5 = extract 5grams; 1-5 = extract 1grams, 2grams, ..., 5grams; default: 1-5).") .create("n")); opts.addOption(OptionBuilder.withLongOpt("dir").withArgName("directory").isRequired().hasArg() .withDescription(// www . j av a 2 s. c o m "specify the directory that contains '.txt' files that are used as source for generating ngrams.") .create("d")); opts.addOption(OptionBuilder.withLongOpt("overwrite").withDescription("Overwrite existing ngram file.") .create("w")); CommandLine cli = null; try { cli = new GnuParser().parse(opts, args); } catch (Exception e) { print_usage(opts, e.getMessage()); } if (cli.hasOption("?")) print_usage(opts, null); AbstractStringProvider prvdr = null; try { prvdr = StartLM .getStringProviderInstance(cli.getOptionValue("ptype", LtSegProvider.class.getSimpleName())); } catch (Exception e) { print_usage(opts, String.format("Could not instantiate LmProvider '%s': %s", cli.getOptionValue("ptype", LtSegProvider.class.getSimpleName()), e.getMessage())); } String n_ = cli.getOptionValue("cardinality", "1-5"); int dash_index = n_.indexOf('-'); int n_e = Integer.parseInt(n_.substring(dash_index + 1, n_.length()).trim()); int n_b = n_e; if (dash_index == 0) n_b = 1; if (dash_index > 0) n_b = Math.max(1, Integer.parseInt(n_.substring(0, dash_index).trim())); final File src_dir = new File(cli.getOptionValue("dir")); boolean overwrite = Boolean.parseBoolean(cli.getOptionValue("overwrite", "false")); generateNgrams(src_dir, prvdr, n_b, n_e, overwrite); }
From source file:io.anserini.search.SearchTweets.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(new Option(RM3_OPTION, "apply relevance feedback with rm3")); options.addOption(// w ww .java 2 s . c o m OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_OPTION)); options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of results to return") .create(NUM_RESULTS_OPTION)); options.addOption(OptionBuilder.withArgName("file").hasArg() .withDescription("file containing topics in TREC format").create(QUERIES_OPTION)); options.addOption(OptionBuilder.withArgName("similarity").hasArg() .withDescription("similarity to use (BM25, LM)").create(SIMILARITY_OPTION)); options.addOption( OptionBuilder.withArgName("string").hasArg().withDescription("runtag").create(RUNTAG_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(QUERIES_OPTION) || !cmdline.hasOption(INDEX_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(SearchTweets.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 runtag = cmdline.hasOption(RUNTAG_OPTION) ? cmdline.getOptionValue(RUNTAG_OPTION) : DEFAULT_RUNTAG; String topicsFile = cmdline.getOptionValue(QUERIES_OPTION); int numResults = 1000; try { if (cmdline.hasOption(NUM_RESULTS_OPTION)) { numResults = Integer.parseInt(cmdline.getOptionValue(NUM_RESULTS_OPTION)); } } catch (NumberFormatException e) { System.err.println("Invalid " + NUM_RESULTS_OPTION + ": " + cmdline.getOptionValue(NUM_RESULTS_OPTION)); System.exit(-1); } String similarity = "LM"; if (cmdline.hasOption(SIMILARITY_OPTION)) { similarity = cmdline.getOptionValue(SIMILARITY_OPTION); } PrintStream out = new PrintStream(System.out, true, "UTF-8"); IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(indexLocation.getAbsolutePath()))); IndexSearcher searcher = new IndexSearcher(reader); if (similarity.equalsIgnoreCase("BM25")) { searcher.setSimilarity(new BM25Similarity()); } else if (similarity.equalsIgnoreCase("LM")) { searcher.setSimilarity(new LMDirichletSimilarity(2500.0f)); } MicroblogTopicSet topics = MicroblogTopicSet.fromFile(new File(topicsFile)); for (MicroblogTopic topic : topics) { Filter filter = NumericRangeFilter.newLongRange(StatusField.ID.name, 0L, topic.getQueryTweetTime(), true, true); Query query = AnalyzerUtils.buildBagOfWordsQuery(StatusField.TEXT.name, IndexTweets.ANALYZER, topic.getQuery()); TopDocs rs = searcher.search(query, filter, numResults); RerankerContext context = new RerankerContext(searcher, query, topic.getQuery(), filter); RerankerCascade cascade = new RerankerCascade(context); if (cmdline.hasOption(RM3_OPTION)) { cascade.add(new Rm3Reranker(IndexTweets.ANALYZER, StatusField.TEXT.name)); cascade.add(new RemoveRetweetsTemporalTiebreakReranker()); } else { cascade.add(new RemoveRetweetsTemporalTiebreakReranker()); } ScoredDocuments docs = cascade.run(ScoredDocuments.fromTopDocs(rs, searcher)); for (int i = 0; i < docs.documents.length; i++) { String qid = topic.getId().replaceFirst("^MB0*", ""); out.println(String.format("%s Q0 %s %d %f %s", qid, docs.documents[i].getField(StatusField.ID.name).numericValue(), (i + 1), docs.scores[i], runtag)); } } reader.close(); out.close(); }
From source file:apps.classification.ClassifySVMPerf.java
public static void main(String[] args) throws IOException { boolean dumpConfidences = false; String cmdLineSyntax = ClassifySVMPerf.class.getName() + " [OPTIONS] <path to svm_perf_classify> <testIndexDirectory> <modelDirectory>"; Options options = new Options(); OptionBuilder.withArgName("d"); OptionBuilder.withDescription("Dump confidences file"); OptionBuilder.withLongOpt("d"); OptionBuilder.isRequired(false);/* w ww.jav a 2 s .c o m*/ OptionBuilder.hasArg(false); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("t"); OptionBuilder.withDescription("Path for temporary files"); OptionBuilder.withLongOpt("t"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("v"); OptionBuilder.withDescription("Verbose output"); OptionBuilder.withLongOpt("v"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(false); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("s"); OptionBuilder.withDescription("Don't delete temporary training file in svm_perf format (default: delete)"); OptionBuilder.withLongOpt("s"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(false); options.addOption(OptionBuilder.create()); SvmPerfClassifierCustomizer customizer = null; GnuParser parser = new GnuParser(); String[] remainingArgs = null; try { CommandLine line = parser.parse(options, args); remainingArgs = line.getArgs(); customizer = new SvmPerfClassifierCustomizer(remainingArgs[0]); if (line.hasOption("d")) dumpConfidences = true; if (line.hasOption("v")) customizer.printSvmPerfOutput(true); if (line.hasOption("s")) { customizer.setDeleteTestFiles(false); customizer.setDeletePredictionsFiles(false); } if (line.hasOption("t")) customizer.setTempPath(line.getOptionValue("t")); } catch (Exception exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(cmdLineSyntax, options); System.exit(-1); } if (remainingArgs.length != 3) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(cmdLineSyntax, options); System.exit(-1); } String testFile = remainingArgs[1]; File file = new File(testFile); String testName = file.getName(); String testPath = file.getParent(); String classifierFile = remainingArgs[2]; file = new File(classifierFile); String classifierName = file.getName(); String classifierPath = file.getParent(); FileSystemStorageManager storageManager = new FileSystemStorageManager(testPath, false); storageManager.open(); IIndex test = TroveReadWriteHelper.readIndex(storageManager, testName, TroveContentDBType.Full, TroveClassificationDBType.Full); storageManager.close(); SvmPerfDataManager dataManager = new SvmPerfDataManager(customizer); storageManager = new FileSystemStorageManager(classifierPath, false); storageManager.open(); SvmPerfClassifier classifier = (SvmPerfClassifier) dataManager.read(storageManager, classifierName); storageManager.close(); classifier.setRuntimeCustomizer(customizer); // CLASSIFICATION String classificationName = testName + "_" + classifierName; Classifier classifierModule = new Classifier(test, classifier, dumpConfidences); classifierModule.setClassificationMode(ClassificationMode.PER_CATEGORY); classifierModule.exec(); IClassificationDB testClassification = classifierModule.getClassificationDB(); storageManager = new FileSystemStorageManager(testPath, false); storageManager.open(); TroveReadWriteHelper.writeClassification(storageManager, testClassification, classificationName + ".cla", true); storageManager.close(); if (dumpConfidences) { ClassificationScoreDB confidences = classifierModule.getConfidences(); ClassificationScoreDB.write(testPath + Os.pathSeparator() + classificationName + ".confidences", confidences); } }
From source file:com.evolveum.midpoint.tools.ninja.Main.java
public static void main(String[] args) { Options options = new Options(); options.addOption(help);//from w w w . j a v a 2 s.c o m options.addOption(validate); options.addOption(create); options.addOption(importOp); options.addOption(schemaOp); options.addOption(exportOp); options.addOption(driver); options.addOption(url); options.addOption(username); options.addOption(password); options.addOption(Password); options.addOption(keyStore); options.addOption(trans); options.addOption(outputFormat); options.addOption(outputDirectory); options.addOption(input); try { CommandLineParser parser = new GnuParser(); CommandLine line = parser.parse(options, args); if (line.getOptions().length == 0 || line.hasOption(help.getOpt())) { printHelp(options); return; } //repository validation, if proper option is present boolean valid = validate(line, options); //import DDL, if proper option is present if (line.hasOption(create.getOpt())) { ImportDDL ddl = new ImportDDL(createDDLConfig(line)); if (!ddl.execute()) { System.out.println("DLL import was unsuccessful, skipping other steps."); return; } //repository validation after DDL import, if proper option is present valid = validate(line, options); } //import objects, only if repository validation didn't fail (in case it was tested) if (valid && line.hasOption(importOp.getOpt())) { String path = line.getOptionValue(importOp.getOpt()); boolean validateSchema = line.hasOption(schemaOp.getOpt()); ImportObjects objects = new ImportObjects(path, validateSchema); objects.execute(); } if (valid && line.hasOption(exportOp.getOpt())) { String path = line.getOptionValue(exportOp.getOpt()); ExportObjects objects = new ExportObjects(path); objects.execute(); } if (line.hasOption(keyStore.getOpt())) { KeyStoreDumper keyStoreDumper = new KeyStoreDumper(); keyStoreDumper.execute(); } if (line.hasOption(trans.getOpt())) { if (!checkCommand(line)) { return; } FileTransformer transformer = new FileTransformer(); configureTransformer(transformer, line); transformer.execute(); } } catch (ParseException ex) { System.out.println("Error: " + ex.getMessage()); printHelp(options); } catch (Exception ex) { System.out.println("Exception occurred, reason: " + ex.getMessage()); ex.printStackTrace(); } }
From source file:is.iclt.icenlp.runner.RunLemmald.java
public static void main(String[] args) { CommandLineParser parser = new GnuParser(); try {/*w ww . ja v a 2 s. c o m*/ // parse the command line arguments CommandLine cmdLine = parser.parse(options, args); if (cmdLine.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("lemmatize.sh", options); } else { runConsole(cmdLine); } } catch (ParseException exp) { // oops, something went wrong System.err.println("Could not parse command line arguments. Reason: " + exp.getMessage()); } }
From source file:de.uni_koblenz.west.splendid.tools.NXVoidGenerator.java
public static void main(String[] args) { try {/*from w w w. j av a 2 s. c o m*/ // parse the command line arguments CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(OPTIONS, args); // print help message if (cmd.hasOption("h") || cmd.hasOption("help")) { new HelpFormatter().printHelp(USAGE, OPTIONS); System.exit(0); } // get input files (from option -i or all remaining parameters) String[] inputFiles = cmd.getOptionValues("i"); if (inputFiles == null) inputFiles = cmd.getArgs(); if (inputFiles.length == 0) { System.out.println("need at least one input file."); new HelpFormatter().printUsage(new PrintWriter(System.out, true), 80, USAGE); System.exit(1); } String outputFile = cmd.getOptionValue("o"); // process all input files new NXVoidGenerator().process(outputFile, inputFiles); } catch (ParseException exp) { // print parse error and display usage message System.out.println(exp.getMessage()); new HelpFormatter().printUsage(new PrintWriter(System.out, true), 80, USAGE, OPTIONS); } }