List of usage examples for org.apache.commons.cli GnuParser GnuParser
GnuParser
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 w ww .j a va2 s . 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: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);//from ww w .j ava 2 s.co m 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.evolveum.midpoint.tools.gui.Main.java
public static void main(String[] args) throws Exception { Options options = new Options(); Option propertiesLocaleDelimiter = new Option("d", "delimiter", true, "Delimiter for locale name in properties file. Default is '_' (underscore)."); options.addOption(propertiesLocaleDelimiter); Option targetFolder = new Option("t", "targetFolder", true, "Target folder where properties file is generated."); targetFolder.setRequired(true);//from ww w .j a v a2s. c o m options.addOption(targetFolder); Option baseFolder = new Option("b", "baseFolder", true, "Base folder used for properties files searching."); baseFolder.setRequired(true); options.addOption(baseFolder); Option localesToCheck = new Option("l", "locale", true, "Locales to check."); localesToCheck.setRequired(true); options.addOption(localesToCheck); Option recursiveFolderToCheck = new Option("r", "folderRecursive", true, "Folder used for recursive search for properties files."); options.addOption(recursiveFolderToCheck); Option nonRecursiveFolderToCheck = new Option("n", "folderNonRecursive", true, "Folder used for non recursive search for properties files."); options.addOption(nonRecursiveFolderToCheck); Option help = new Option("h", "help", false, "Print this help."); options.addOption(help); Option disableBackup = new Option("db", "disableBackup", false, "Disable backuping property files."); options.addOption(disableBackup); try { CommandLineParser parser = new GnuParser(); CommandLine line = parser.parse(options, args); if (line.hasOption(help.getOpt())) { printHelp(options); return; } if (!line.hasOption(recursiveFolderToCheck.getOpt()) && !line.hasOption(nonRecursiveFolderToCheck.getOpt())) { printHelp(options); return; } GeneratorConfiguration config = new GeneratorConfiguration(); if (line.hasOption(baseFolder.getOpt())) { config.setBaseFolder(new File(line.getOptionValue(baseFolder.getOpt()))); } if (line.hasOption(targetFolder.getOpt())) { config.setTargetFolder(new File(line.getOptionValue(targetFolder.getOpt()))); } if (line.hasOption(propertiesLocaleDelimiter.getOpt())) { config.setPropertiesLocaleDelimiter(line.getOptionValue(propertiesLocaleDelimiter.getOpt())); } if (line.hasOption(recursiveFolderToCheck.getOpt())) { String[] recursives = line.getOptionValues(recursiveFolderToCheck.getOpt()); if (recursives != null && recursives.length > 0) { for (String recursive : recursives) { config.getRecursiveFolderToCheck().add(recursive); } } } if (line.hasOption(nonRecursiveFolderToCheck.getOpt())) { String[] nonRecursives = line.getOptionValues(nonRecursiveFolderToCheck.getOpt()); if (nonRecursives != null && nonRecursives.length > 0) { for (String nonRecursive : nonRecursives) { config.getNonRecursiveFolderToCheck().add(nonRecursive); } } } if (line.hasOption(localesToCheck.getOpt())) { String[] locales = line.getOptionValues(localesToCheck.getOpt()); for (String locale : locales) { config.getLocalesToCheck().add(getLocaleFromString(locale)); } } if (line.hasOption(disableBackup.getOpt())) { config.setDisableBackup(true); } PropertiesGenerator generator = new PropertiesGenerator(config); generator.generate(); } catch (ParseException ex) { System.out.println("Error: " + ex.getMessage()); printHelp(options); } catch (Exception ex) { System.out.println("Something is broken."); ex.printStackTrace(); } }
From source file:com.rabbitmq.examples.MulticastMain.java
public static void main(String[] args) { Options options = getOptions();/* w w w.j a v a 2 s.c o m*/ CommandLineParser parser = new GnuParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption('?')) { usage(options); System.exit(0); } String exchangeType = strArg(cmd, 't', "direct"); String exchangeName = strArg(cmd, 'e', exchangeType); String queueName = strArg(cmd, 'u', ""); int samplingInterval = intArg(cmd, 'i', 1); int rateLimit = intArg(cmd, 'r', 0); int producerCount = intArg(cmd, 'x', 1); int consumerCount = intArg(cmd, 'y', 1); int producerTxSize = intArg(cmd, 'm', 0); int consumerTxSize = intArg(cmd, 'n', 0); long confirm = intArg(cmd, 'c', -1); boolean autoAck = cmd.hasOption('a'); int prefetchCount = intArg(cmd, 'q', 0); int minMsgSize = intArg(cmd, 's', 0); int timeLimit = intArg(cmd, 'z', 0); List<?> flags = lstArg(cmd, 'f'); int frameMax = intArg(cmd, 'M', 0); int heartbeat = intArg(cmd, 'b', 0); String uri = strArg(cmd, 'h', "amqp://localhost"); boolean exclusive = "".equals(queueName); boolean autoDelete = !exclusive; //setup String id = UUID.randomUUID().toString(); Stats stats = new Stats(1000L * samplingInterval); ConnectionFactory factory = new ConnectionFactory(); factory.setUri(uri); factory.setRequestedFrameMax(frameMax); factory.setRequestedHeartbeat(heartbeat); Thread[] consumerThreads = new Thread[consumerCount]; Connection[] consumerConnections = new Connection[consumerCount]; for (int i = 0; i < consumerCount; i++) { System.out.println("starting consumer #" + i); Connection conn = factory.newConnection(); consumerConnections[i] = conn; Channel channel = conn.createChannel(); if (consumerTxSize > 0) channel.txSelect(); channel.exchangeDeclare(exchangeName, exchangeType); String qName = channel .queueDeclare(queueName, flags.contains("persistent"), exclusive, autoDelete, null) .getQueue(); if (prefetchCount > 0) channel.basicQos(prefetchCount); channel.queueBind(qName, exchangeName, id); Thread t = new Thread(new Consumer(channel, id, qName, consumerTxSize, autoAck, stats, timeLimit)); consumerThreads[i] = t; t.start(); } Thread[] producerThreads = new Thread[producerCount]; Connection[] producerConnections = new Connection[producerCount]; Channel[] producerChannels = new Channel[producerCount]; for (int i = 0; i < producerCount; i++) { System.out.println("starting producer #" + i); Connection conn = factory.newConnection(); producerConnections[i] = conn; Channel channel = conn.createChannel(); producerChannels[i] = channel; if (producerTxSize > 0) channel.txSelect(); if (confirm >= 0) channel.confirmSelect(); channel.exchangeDeclare(exchangeName, exchangeType); final Producer p = new Producer(channel, exchangeName, id, flags, producerTxSize, 1000L * samplingInterval, rateLimit, minMsgSize, timeLimit, confirm); channel.addReturnListener(p); channel.addConfirmListener(p); Thread t = new Thread(p); producerThreads[i] = t; t.start(); } for (int i = 0; i < producerCount; i++) { producerThreads[i].join(); producerChannels[i].clearReturnListeners(); producerChannels[i].clearConfirmListeners(); producerConnections[i].close(); } for (int i = 0; i < consumerCount; i++) { consumerThreads[i].join(); consumerConnections[i].close(); } } catch (ParseException exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); usage(options); } catch (Exception e) { System.err.println("Main thread caught exception: " + e); e.printStackTrace(); System.exit(1); } }
From source file:gdv.xport.Main.java
/** * Diese Main-Klasse dient hautpsaechlich zu Demo-Zwecken. Werden keine Optionen angegeben, wird von der * Standard-Eingabe (System.in) gelesen und das Ergebnis nach System.out geschrieben. <br/> * Mit "-help" bekommt man eine kleine Uebersicht der Optionen. * * @param args/*from w w w . ja v a 2s . co m*/ * die verschiendene Argumente (z.B. -import * http://www.gdv-online.de/vuvm/musterdatei_bestand/musterdatei_041222.txt -validate -xml) * @throws IOException * falls der Import oder Export schief gegangen ist * @throws XMLStreamException * falls bei der XML-Generierung was schief gelaufen ist. */ public static void main(final String[] args) throws IOException, XMLStreamException { Options options = createOptions(); CommandLineParser parser = new GnuParser(); try { CommandLine cmd = parser.parse(options, args); // Option "-help" if (cmd.hasOption("help")) { printHelp(options); System.exit(0); } Datenpaket datenpaket = importDatenpaket(cmd); formatDatenpaket(cmd, datenpaket); // Option "-validate" if (cmd.hasOption("validate")) { printViolations(datenpaket.validate()); } } catch (ParseException ex) { LOG.log(Level.SEVERE, "Cannot parse " + Arrays.toString(args), ex); System.err.println("Fehler beim Aufruf von " + Main.class); printHelp(options); System.exit(1); } }
From source file:com.gsma.iariauth.validator.util.IARIValidatorMain.java
public static void main(String[] args) { String formatstr = "IARIValidator [-d <authorization document>] [-n <package name>] [-ps <package signer fingerprint>] [-pk <package signer keystore>] [-pa <package signer certificate alias>] [-pp <package signer keystore password>] -k <keystore> -p <password> [-v]"; HelpFormatter formatter = new HelpFormatter(); GnuParser parser = new GnuParser(); Options opts = new Options(); opts.addOption(new ArgOption("d", "document", "IARI Authorization document")); opts.addOption(new ArgOption("pkgname", "package-name", "package name")); opts.addOption(new ArgOption("pkgsigner", "package-signer", "package signer fingerprint")); opts.addOption(new ArgOption("pkgkeystore", "package-keystore", "package signing keystore")); opts.addOption(new ArgOption("pkgalias", "package-key-alias", "package signing certificate alias")); opts.addOption(new ArgOption("pkgstorepass", "package-keystore-pass", "package signing keystore password")); opts.addOption(new Option("v", "verbose", false, "verbose output")); CommandLine cli = null;/* www . java 2 s . c o m*/ try { cli = parser.parse(opts, args); } catch (ParseException e) { formatter.printHelp(formatstr, opts); return; } boolean verbose = cli.hasOption("v"); String packageName = cli.getOptionValue("pkgname"); String packageSigner = cli.getOptionValue("pkgsigner"); if (packageSigner == null) { String packageSignerKeystore = cli.getOptionValue("pkgkeystore"); String packageSignerKeystoreAlias = cli.getOptionValue("pkgalias"); String packageSignerKeystorePasswd = cli.getOptionValue("pkgstorepass"); if (packageSignerKeystore != null) { if (packageSignerKeystoreAlias == null) { System.err.println("No alias given for package signing certificate"); System.exit(1); } if (packageSignerKeystorePasswd == null) { System.err.println("No password given for package signing keystore"); System.exit(1); } KeyStore packageKeystore = loadKeyStore(packageSignerKeystore, packageSignerKeystorePasswd); if (packageKeystore == null) { System.err.println("Unable to read package keystore"); System.exit(1); } try { X509Certificate c = (X509Certificate) packageKeystore .getCertificate(packageSignerKeystoreAlias); if (c == null) { System.err.println("Unable to access package signing certificate"); System.exit(1); } packageSigner = getFingerprint(c); } catch (KeyStoreException e) { System.err.println("Unable to access package signing certificate"); System.exit(1); } catch (CertificateEncodingException e) { e.printStackTrace(); System.err.println("Unable to read package signing certificate"); System.exit(1); } } } String authDocumentPath = cli.getOptionValue("d"); if (authDocumentPath == null) { System.err.println("No auth document specified"); System.exit(1); } File authDocument = new File(authDocumentPath); if (!authDocument.exists() || !authDocument.isFile()) { System.err.println("Unable to read specified auth document"); System.exit(1); } PackageProcessor processor = new PackageProcessor(packageName, packageSigner); ProcessingResult result = processor.processIARIauthorization(authDocument); if (result.getStatus() != ProcessingResult.STATUS_OK) { System.err.println("Error validating authDocument:"); System.err.println(result.getError().toString()); System.exit(1); } if (verbose) { System.out.println(result.getAuthDocument().toString()); } System.exit(0); }
From source file:com.mozilla.bagheera.consumer.KafkaSequenceFileConsumer.java
public static void main(String[] args) { OptionFactory optFactory = OptionFactory.getInstance(); Options options = KafkaConsumer.getOptions(); options.addOption(optFactory.create("o", "output", true, "HDFS base path for output.")); options.addOption(optFactory.create("df", "dateformat", true, "Date format for the date subdirectories.")); options.addOption(optFactory.create("fs", "filesize", true, "Max file size for output files.")); options.addOption(/*from ww w. ja v a 2s . c o m*/ optFactory.create("b", "usebytes", false, "Use BytesWritable for value rather than Text.")); options.addOption(optFactory.create("ts", "addtimestamp", false, "Adds bagheera timestamp to the json")); 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(); sinkConfig.setString("hdfssink.hdfs.basedir.path", cmd.getOptionValue("output", "/bagheera")); sinkConfig.setString("hdfssink.hdfs.date.format", cmd.getOptionValue("dateformat", "yyyy-MM-dd")); sinkConfig.setLong("hdfssink.hdfs.max.filesize", Long.parseLong(cmd.getOptionValue("filesize", "536870912"))); sinkConfig.setBoolean("hdfssink.hdfs.usebytes", cmd.hasOption("usebytes")); sinkConfig.setBoolean("hdfssink.hdfs.addtimestamp", cmd.hasOption("addtimestamp")); KeyValueSinkFactory sinkFactory = KeyValueSinkFactory.getInstance(SequenceFileSink.class, sinkConfig); sh.addLast(sinkFactory); // Set the sink for consumer storage consumer.setSinkFactory(sinkFactory); // Initialize metrics collection, reporting, etc. final MetricsManager manager = MetricsManager.getDefaultMetricsManager(); prepareHealthChecks(); // Begin polling consumer.poll(); } catch (ParseException e) { LOG.error("Error parsing command line options", e); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(KafkaSequenceFileConsumer.class.getName(), options); } catch (NumberFormatException e) { LOG.error("Failed to parse filesize option", 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(/*from w ww.ja v a2 s . c o 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.rapleaf.hank.cli.AddDomain.java
public static void main(String[] args) throws InterruptedException, ParseException, IOException, InvalidConfigurationException { Options options = new Options(); options.addOption("n", "name", true, "the name of the domain to be created"); options.addOption("p", "num-parts", true, "the number of partitions for this domain"); options.addOption("f", "storage-engine-factory", true, "class name of the storage engine factory used by this domain"); options.addOption("o", "storage-engine-options", true, "path to a yaml file containing the options for the storage engine"); options.addOption("t", "partitioner", true, "class name of the partition used by this domain"); options.addOption("v", "initial-version", true, "initial version number of this domain"); options.addOption("c", "config", true, "path of a valid config file with coordinator connection information"); try {/*from www .j ava2s .c o m*/ CommandLine line = new GnuParser().parse(options, args); CommandLineChecker.check(line, options, new String[] { "name", "num-parts", "storage-engine-factory", "storage-engine-options", "partitioner", "initial-version" }, AddDomain.class); Configurator configurator = new YamlClientConfigurator(line.getOptionValue("config")); addDomain(configurator, line.getOptionValue("name"), line.getOptionValue("num-parts"), line.getOptionValue("storage-engine-factory"), line.getOptionValue("storage-engine-options"), line.getOptionValue("partitioner"), line.getOptionValue("initial-version")); } catch (ParseException e) { new HelpFormatter().printHelp("add_domain", options); throw e; } }
From source file:cc.wikitools.lucene.SearchWikipedia.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(//from ww w .j av a2s . c om OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_OPTION)); options.addOption( OptionBuilder.withArgName("string").hasArg().withDescription("query text").create(QUERY_OPTION)); options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of results to return") .create(NUM_RESULTS_OPTION)); options.addOption(new Option(VERBOSE_OPTION, "print out complete document")); options.addOption(new Option(TITLE_OPTION, "search title")); options.addOption(new Option(ARTICLE_OPTION, "search article")); 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(QUERY_OPTION) || !cmdline.hasOption(INDEX_OPTION) || !cmdline.hasOption(QUERY_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(SearchWikipedia.class.getName(), options); System.exit(-1); } File indexLocation = new File(cmdline.getOptionValue(INDEX_OPTION)); if (!indexLocation.exists()) { System.err.println("Error: " + indexLocation + " does not exist!"); System.exit(-1); } String queryText = cmdline.getOptionValue(QUERY_OPTION); int numResults = cmdline.hasOption(NUM_RESULTS_OPTION) ? Integer.parseInt(cmdline.getOptionValue(NUM_RESULTS_OPTION)) : DEFAULT_NUM_RESULTS; boolean verbose = cmdline.hasOption(VERBOSE_OPTION); boolean searchArticle = !cmdline.hasOption(TITLE_OPTION); PrintStream out = new PrintStream(System.out, true, "UTF-8"); WikipediaSearcher searcher = new WikipediaSearcher(indexLocation); TopDocs rs = null; if (searchArticle) { rs = searcher.searchArticle(queryText, numResults); } else { rs = searcher.searchTitle(queryText, numResults); } int i = 1; for (ScoreDoc scoreDoc : rs.scoreDocs) { Document hit = searcher.doc(scoreDoc.doc); out.println(String.format("%d. %s (wiki id = %s, lucene id = %d) %f", i, hit.getField(IndexField.TITLE.name).stringValue(), hit.getField(IndexField.ID.name).stringValue(), scoreDoc.doc, scoreDoc.score)); if (verbose) { out.println("# " + hit.toString().replaceAll("[\\n\\r]+", " ")); } i++; } searcher.close(); out.close(); }