List of usage examples for org.apache.commons.cli OptionBuilder withDescription
public static OptionBuilder withDescription(String newDescription)
From source file:mx.unam.fesa.mss.MSSMain.java
/** * @param args//from ww w . j a v a 2s. co m */ @SuppressWarnings("static-access") public static void main(String[] args) { // // managing command line options using commons-cli // Options options = new Options(); // help option // options.addOption( OptionBuilder.withDescription("Prints this message.").withLongOpt("help").create(OPT_HELP)); // port option // options.addOption(OptionBuilder.withDescription("The port in which the MineSweeperServer will listen to.") .hasArg().withType(new Integer(0)).withArgName("PORT").withLongOpt("port").create(OPT_PORT)); // parsing options // int port = DEFAULT_PORT; try { // using GNU standard // CommandLine line = new GnuParser().parse(options, args); if (line.hasOption(OPT_HELP)) { new HelpFormatter().printHelp("mss [options]", options); return; } if (line.hasOption(OPT_PORT)) { try { port = (Integer) line.getOptionObject(OPT_PORT); } catch (Exception e) { } } } catch (ParseException e) { System.err.println("Could not parse command line options correctly: " + e.getMessage()); return; } // // configuring logging services // try { LogManager.getLogManager() .readConfiguration(ClassLoader.getSystemResourceAsStream(DEFAULT_LOGGING_CONFIG_FILE)); } catch (Exception e) { throw new Error("Could not load logging properties file", e); } // // setting up UDP server // try { new MSServer(port); } catch (Exception e) { LoggerFactory.getLogger(MSSMain.class).error("Could not execute MineSweeper server: ", e); } }
From source file:com.hurence.logisland.runner.StreamProcessingRunner.java
/** * main entry point/* w w w . j a v a 2 s .c o m*/ * * @param args */ public static void main(String[] args) { logger.info("starting StreamProcessingRunner"); ////////////////////////////////////////// // Commande lien management Parser parser = new GnuParser(); Options options = new Options(); String helpMsg = "Print this message."; Option help = new Option("help", helpMsg); options.addOption(help); OptionBuilder.withArgName("conf"); OptionBuilder.withLongOpt("config-file"); OptionBuilder.isRequired(); OptionBuilder.hasArg(); OptionBuilder.withDescription("config file path"); Option conf = OptionBuilder.create("conf"); options.addOption(conf); Optional<EngineContext> engineInstance = Optional.empty(); try { System.out.println(BannerLoader.loadBanner()); // parse the command line arguments CommandLine line = parser.parse(options, args); String configFile = line.getOptionValue("conf"); // load the YAML config LogislandConfiguration sessionConf = ConfigReader.loadConfig(configFile); // instantiate engine and all the processor from the config engineInstance = ComponentFactory.getEngineContext(sessionConf.getEngine()); if (!engineInstance.isPresent()) { throw new IllegalArgumentException("engineInstance could not be instantiated"); } if (!engineInstance.get().isValid()) { throw new IllegalArgumentException("engineInstance is not valid with input configuration !"); } logger.info("starting Logisland session version {}", sessionConf.getVersion()); logger.info(sessionConf.getDocumentation()); } catch (Exception e) { logger.error("unable to launch runner", e); System.exit(-1); } String engineName = engineInstance.get().getEngine().getIdentifier(); try { // start the engine EngineContext engineContext = engineInstance.get(); logger.info("start engine {}", engineName); engineInstance.get().getEngine().start(engineContext); logger.info("awaitTermination for engine {}", engineName); engineContext.getEngine().awaitTermination(engineContext); System.exit(0); } catch (Exception e) { logger.error("something went bad while running the job {} : {}", engineName, e); System.exit(-1); } }
From source file:mx.unam.fesa.isoo.msp.MSPMain.java
/** * @param args/*from w ww . ja v a 2 s. co m*/ * @throws Exception */ @SuppressWarnings("static-access") public static void main(String[] args) { // // creating options // Options options = new Options(); // help option // options.addOption( OptionBuilder.withDescription("Prints this message.").withLongOpt("help").create(OPT_HELP)); // server option // options.addOption(OptionBuilder.withDescription("The server this MineSweeperPlayer will connect to.") .hasArg().withArgName("SERVER").withLongOpt("server").create(OPT_SERVER)); // port option // options.addOption(OptionBuilder.withDescription("The port this MineSweeperPlayer will connect to.").hasArg() .withType(new Integer(0)).withArgName("PORT").withLongOpt("port").create(OPT_PORT)); // parsing options // String hostname = DEFAULT_SERVER; int port = DEFAULT_PORT; try { // using GNU standard // CommandLine line = new GnuParser().parse(options, args); if (line.hasOption(OPT_HELP)) { new HelpFormatter().printHelp("msc [options]", options); return; } if (line.hasOption(OPT_PORT)) { try { port = (Integer) line.getOptionObject(OPT_PORT); } catch (Exception e) { } } if (line.hasOption(OPT_SERVER)) { hostname = line.getOptionValue(OPT_PORT); } } catch (ParseException e) { System.err.println("Could not parse command line options correctly: " + e.getMessage()); return; } // // configuring logging services // try { LogManager.getLogManager() .readConfiguration(ClassLoader.getSystemResourceAsStream(DEFAULT_LOGGING_CONFIG_FILE)); } catch (Exception e) { throw new Error("Could not load logging properties file.", e); } // // setting up Mine Sweeper client // try { new MSClient(hostname, port); } catch (Exception e) { System.err.println("Could not execute MineSweeper client: " + e.getMessage()); } }
From source file:com.servioticy.dispatcher.DispatcherTopology.java
/** * @param args/*from ww w . j a v a 2s . c om*/ * @throws InvalidTopologyException * @throws AlreadyAliveException * @throws InterruptedException */ public static void main(String[] args) throws AlreadyAliveException, InvalidTopologyException, InterruptedException, ParseException { Options options = new Options(); options.addOption( OptionBuilder.withArgName("file").hasArg().withDescription("Config file path.").create("f")); options.addOption(OptionBuilder.withArgName("topology").hasArg() .withDescription("Name of the topology in storm. If no name is given it will run in local mode.") .create("t")); options.addOption(OptionBuilder.withDescription("Enable debugging").create("d")); CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(options, args); String path = null; if (cmd.hasOption("f")) { path = cmd.getOptionValue("f"); } DispatcherContext dc = new DispatcherContext(); dc.loadConf(path); TopologyBuilder builder = new TopologyBuilder(); // TODO Auto-assign workers to the spout in function of the number of Kestrel IPs builder.setSpout("updates", new KestrelThriftSpout(Arrays.asList(dc.updatesAddresses), dc.updatesPort, dc.updatesQueue, new UpdateDescriptorScheme())); builder.setSpout("actions", new KestrelThriftSpout(Arrays.asList(dc.actionsAddresses), dc.actionsPort, dc.actionsQueue, new ActuationScheme())); builder.setBolt("prepare", new PrepareBolt(dc)).shuffleGrouping("updates"); builder.setBolt("actuationdispatcher", new ActuationDispatcherBolt(dc)).shuffleGrouping("actions"); builder.setBolt("subretriever", new SubscriptionRetrieveBolt(dc)).shuffleGrouping("prepare", "subscription"); builder.setBolt("externaldispatcher", new ExternalDispatcherBolt(dc)).fieldsGrouping("subretriever", "externalSub", new Fields("subid")); builder.setBolt("internaldispatcher", new InternalDispatcherBolt(dc)).fieldsGrouping("subretriever", "internalSub", new Fields("subid")); builder.setBolt("streamdispatcher", new StreamDispatcherBolt(dc)) .shuffleGrouping("subretriever", "streamSub").shuffleGrouping("prepare", "stream"); builder.setBolt("streamprocessor", new StreamProcessorBolt(dc)).shuffleGrouping("streamdispatcher", "default"); if (dc.benchmark) { builder.setBolt("benchmark", new BenchmarkBolt(dc)).shuffleGrouping("streamdispatcher", "benchmark") .shuffleGrouping("subretriever", "benchmark").shuffleGrouping("streamprocessor", "benchmark") .shuffleGrouping("prepare", "benchmark"); } Config conf = new Config(); conf.setDebug(cmd.hasOption("d")); if (cmd.hasOption("t")) { StormSubmitter.submitTopology(cmd.getOptionValue("t"), conf, builder.createTopology()); } else { conf.setMaxTaskParallelism(4); LocalCluster cluster = new LocalCluster(); cluster.submitTopology("dispatcher", conf, builder.createTopology()); } }
From source file:apps.classification.LearnSVMPerf.java
public static void main(String[] args) throws IOException { String cmdLineSyntax = LearnSVMPerf.class.getName() + " [OPTIONS] <path to svm_perf> <trainingIndexDirectory>"; Options options = new Options(); OptionBuilder.withArgName("c"); OptionBuilder.withDescription("The c value for svm_perf (default 0.01)"); OptionBuilder.withLongOpt("c"); OptionBuilder.isRequired(false);// w w w . j ava 2 s .com OptionBuilder.hasArg(); 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("l"); OptionBuilder.withDescription("The loss function to optimize (default 2):\n" + " 0 Zero/one loss: 1 if vector of predictions contains error, 0 otherwise.\n" + " 1 F1: 100 minus the F1-score in percent.\n" + " 2 Errorrate: Percentage of errors in prediction vector.\n" + " 3 Prec/Rec Breakeven: 100 minus PRBEP in percent.\n" + " 4 Prec@p: 100 minus precision at p in percent.\n" + " 5 Rec@p: 100 minus recall at p in percent.\n" + " 10 ROCArea: Percentage of swapped pos/neg pairs (i.e. 100 - ROCArea)."); OptionBuilder.withLongOpt("l"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("w"); OptionBuilder.withDescription("Choice of structural learning algorithm (default 9):\n" + " 0: n-slack algorithm described in [2]\n" + " 1: n-slack algorithm with shrinking heuristic\n" + " 2: 1-slack algorithm (primal) described in [5]\n" + " 3: 1-slack algorithm (dual) described in [5]\n" + " 4: 1-slack algorithm (dual) with constraint cache [5]\n" + " 9: custom algorithm in svm_struct_learn_custom.c"); OptionBuilder.withLongOpt("w"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("p"); OptionBuilder.withDescription("The value of p used by the prec@p and rec@p loss functions (default 0)"); OptionBuilder.withLongOpt("p"); 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()); SvmPerfLearnerCustomizer classificationLearnerCustomizer = null; GnuParser parser = new GnuParser(); String[] remainingArgs = null; try { CommandLine line = parser.parse(options, args); remainingArgs = line.getArgs(); classificationLearnerCustomizer = new SvmPerfLearnerCustomizer(remainingArgs[0]); if (line.hasOption("c")) classificationLearnerCustomizer.setC(Float.parseFloat(line.getOptionValue("c"))); if (line.hasOption("w")) classificationLearnerCustomizer.setW(Integer.parseInt(line.getOptionValue("w"))); if (line.hasOption("p")) classificationLearnerCustomizer.setP(Integer.parseInt(line.getOptionValue("p"))); if (line.hasOption("l")) classificationLearnerCustomizer.setL(Integer.parseInt(line.getOptionValue("l"))); if (line.hasOption("v")) classificationLearnerCustomizer.printSvmPerfOutput(true); if (line.hasOption("s")) classificationLearnerCustomizer.setDeleteTrainingFiles(false); if (line.hasOption("t")) classificationLearnerCustomizer.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 != 2) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(cmdLineSyntax, options); System.exit(-1); } String indexFile = remainingArgs[1]; File file = new File(indexFile); String indexName = file.getName(); String indexPath = file.getParent(); // LEARNING SvmPerfLearner classificationLearner = new SvmPerfLearner(); classificationLearner.setRuntimeCustomizer(classificationLearnerCustomizer); FileSystemStorageManager storageManager = new FileSystemStorageManager(indexPath, false); storageManager.open(); IIndex training = TroveReadWriteHelper.readIndex(storageManager, indexName, TroveContentDBType.Full, TroveClassificationDBType.Full); storageManager.close(); IClassifier classifier = classificationLearner.build(training); File executableFile = new File(classificationLearnerCustomizer.getSvmPerfLearnPath()); SvmPerfDataManager dataManager = new SvmPerfDataManager(new SvmPerfClassifierCustomizer( executableFile.getParentFile().getAbsolutePath() + Os.pathSeparator() + "svm_perf_classify")); String description = "_SVMPerf_C-" + classificationLearnerCustomizer.getC() + "_W-" + classificationLearnerCustomizer.getW() + "_L-" + classificationLearnerCustomizer.getL(); if (classificationLearnerCustomizer.getL() == 4 || classificationLearnerCustomizer.getL() == 5) description += "_P-" + classificationLearnerCustomizer.getP(); if (classificationLearnerCustomizer.getAdditionalParameters().length() > 0) description += "_" + classificationLearnerCustomizer.getAdditionalParameters(); storageManager = new FileSystemStorageManager(indexPath, false); storageManager.open(); dataManager.write(storageManager, indexName + description, classifier); storageManager.close(); }
From source file:com.zarkonnen.longan.Main.java
public static void main(String[] args) throws IOException { // Use Apache Commons CLI (packaged into the Jar) to parse command line options. Options options = new Options(); Option helpO = OptionBuilder.withDescription("print help").create("h"); Option versionO = OptionBuilder.withDescription("print version").create("v"); Option outputO = OptionBuilder.withDescription("output file").withLongOpt("out").hasArg() .withArgName("file").create("o"); Option formatO = OptionBuilder .withDescription("output format: one of plaintext (default) and visualize (debug output in png)") .hasArg().withArgName("format").withLongOpt("format").create(); Option serverO = OptionBuilder.withDescription("launches server mode: Server mode reads " + "command line strings one per line exactly as above. If no output file is " + "specified, returns a line containing the number of output lines before the " + "output. If there is an error, returns a single line with the error message. " + "Shut down server by sending \"quit\".").withLongOpt("server").create(); Option openCLO = OptionBuilder .withDescription(/*from www. jav a2 s.c o m*/ "enables use of the graphics card to " + "support the OCR system. Defaults to true.") .withLongOpt("enable-opencl").hasArg().withArgName("enabled").create(); options.addOption(helpO); options.addOption(versionO); options.addOption(outputO); options.addOption(formatO); options.addOption(serverO); options.addOption(openCLO); CommandLineParser clp = new GnuParser(); try { CommandLine line = clp.parse(options, args); if (line.hasOption("h")) { new HelpFormatter().printHelp(INVOCATION, options); System.exit(0); } if (line.hasOption("v")) { System.out.println(Longan.VERSION); System.exit(0); } boolean enableOpenCL = true; if (line.hasOption("enable-opencl")) { enableOpenCL = line.getOptionValue("enable-opencl").toLowerCase().equals("true") || line.getOptionValue("enable-opencl").equals("1"); } if (line.hasOption("server")) { Longan longan = Longan.getDefaultImplementation(enableOpenCL); BufferedReader inputR = new BufferedReader(new InputStreamReader(System.in)); while (true) { String input = inputR.readLine(); if (input.trim().equals("quit")) { return; } String[] args2 = splitInput(input); Options o2 = new Options(); o2.addOption(outputO); o2.addOption(formatO); try { line = clp.parse(o2, args2); File outFile = null; if (line.hasOption("o")) { outFile = new File(line.getOptionValue("o")); } ResultConverter format = FORMATS.get(line.getOptionValue("format", "plaintext")); if (format != DEFAULT_FORMAT && outFile == null) { System.out.println("You must specify an output file for non-plaintext output."); continue; } if (line.getArgList().isEmpty()) { System.out.println("Please specify an input image."); continue; } if (line.getArgList().size() > 1) { System.err.println("Please specify one input image at a time"); continue; } File inFile = new File((String) line.getArgList().get(0)); if (!inFile.exists()) { System.out.println("The input image does not exist."); continue; } try { Result result = longan.process(ImageIO.read(inFile)); if (outFile == null) { String txt = DEFAULT_FORMAT.convert(result); System.out.println(numNewlines(txt) + 1); System.out.print(txt); } else { if (outFile.getAbsoluteFile().getParentFile() != null && !outFile.getAbsoluteFile().getParentFile().exists()) { outFile.getParentFile().mkdirs(); } FileOutputStream fos = new FileOutputStream(outFile); try { format.write(result, fos); } finally { fos.close(); } } } catch (Exception e) { System.out.println("Processing error: " + exception(e)); } } catch (ParseException e) { System.out.println("Input not recognized: " + exception(e)); } } // End server loop } else { // Single invocation File outFile = null; if (line.hasOption("o")) { outFile = new File(line.getOptionValue("o")); } ResultConverter format = FORMATS.get(line.getOptionValue("format", "plaintext")); if (format != DEFAULT_FORMAT && outFile == null) { System.err.println("You must specify an output file for non-plaintext output."); System.exit(1); } if (line.getArgList().isEmpty()) { System.err.println("Please specify an input image."); new HelpFormatter().printHelp(INVOCATION, options); System.exit(1); } if (line.getArgList().size() > 1) { System.err.println("Please specify one input image only. To process multiple " + "images, use server mode."); System.exit(1); } File inFile = new File((String) line.getArgList().get(0)); if (!inFile.exists()) { System.err.println("The input image does not exist."); System.exit(1); } try { Result result = Longan.getDefaultImplementation(enableOpenCL).process(ImageIO.read(inFile)); if (outFile == null) { String txt = DEFAULT_FORMAT.convert(result); System.out.print(txt); } else { if (outFile.getAbsoluteFile().getParentFile() != null && !outFile.getAbsoluteFile().getParentFile().exists()) { outFile.getParentFile().mkdirs(); } FileOutputStream fos = new FileOutputStream(outFile); try { format.write(format.convert(result), fos); } finally { fos.close(); } } } catch (Exception e) { System.err.println("Processing error: " + exception(e)); System.exit(1); } } } catch (ParseException e) { System.err.println("Parsing command line input failed: " + exception(e)); System.exit(1); } }
From source file:eu.fbk.utils.twm.FormPageSearcher.java
public static void main(final String args[]) throws Exception { String logConfig = System.getProperty("log-config"); if (logConfig == null) { logConfig = "configuration/log-config.txt"; }/*from w w w .j a v a 2 s. co m*/ PropertyConfigurator.configure(logConfig); final Options options = new Options(); try { OptionBuilder.withArgName("index"); OptionBuilder.hasArg(); OptionBuilder.withDescription("open an index with the specified name"); OptionBuilder.isRequired(); OptionBuilder.withLongOpt("index"); final Option indexNameOpt = OptionBuilder.create("i"); OptionBuilder.withArgName("interactive-mode"); OptionBuilder.withDescription("enter in the interactive mode"); OptionBuilder.withLongOpt("interactive-mode"); final Option interactiveModeOpt = OptionBuilder.create("t"); OptionBuilder.withArgName("search"); OptionBuilder.hasArg(); OptionBuilder.withDescription("search for the specified key"); OptionBuilder.withLongOpt("search"); final Option searchOpt = OptionBuilder.create("s"); OptionBuilder.withArgName("key-freq"); OptionBuilder.hasArg(); OptionBuilder.withDescription("read the keys' frequencies from the specified file"); OptionBuilder.withLongOpt("key-freq"); final Option freqFileOpt = OptionBuilder.create("f"); OptionBuilder.withArgName("minimum-freq"); // Option keyFieldNameOpt = // OptionBuilder.withArgName("key-field-name").hasArg().withDescription("use the specified name for the field key").withLongOpt("key-field-name").create("k"); // Option valueFieldNameOpt = // OptionBuilder.withArgName("value-field-name").hasArg().withDescription("use the specified name for the field value").withLongOpt("value-field-name").create("v"); final Option minimumKeyFreqOpt = OptionBuilder.hasArg() .withDescription("minimum key frequency of cached values (default is " + DEFAULT_MIN_FREQ + ")") .withLongOpt("minimum-freq").create("m"); OptionBuilder.withArgName("int"); final Option notificationPointOpt = OptionBuilder.hasArg() .withDescription( "receive notification every n pages (default is " + DEFAULT_NOTIFICATION_POINT + ")") .withLongOpt("notification-point").create("b"); options.addOption("h", "help", false, "print this message"); options.addOption("v", "version", false, "output version information and exit"); options.addOption(indexNameOpt); options.addOption(interactiveModeOpt); options.addOption(searchOpt); options.addOption(freqFileOpt); // options.addOption(keyFieldNameOpt); // options.addOption(valueFieldNameOpt); options.addOption(minimumKeyFreqOpt); options.addOption(notificationPointOpt); final CommandLineParser parser = new PosixParser(); final CommandLine line = parser.parse(options, args); if (line.hasOption("help") || line.hasOption("version")) { throw new ParseException(""); } int minFreq = DEFAULT_MIN_FREQ; if (line.hasOption("minimum-freq")) { minFreq = Integer.parseInt(line.getOptionValue("minimum-freq")); } int notificationPoint = DEFAULT_NOTIFICATION_POINT; if (line.hasOption("notification-point")) { notificationPoint = Integer.parseInt(line.getOptionValue("notification-point")); } final FormPageSearcher pageFormSearcher = new FormPageSearcher(line.getOptionValue("index")); pageFormSearcher.setNotificationPoint(notificationPoint); /* * logger.debug(line.getOptionValue("key-field-name") + "\t" + * line.getOptionValue("value-field-name")); if (line.hasOption("key-field-name")) { * pageFormSearcher.setKeyFieldName(line.getOptionValue("key-field-name")); } if * (line.hasOption("value-field-name")) { * pageFormSearcher.setValueFieldName(line.getOptionValue("value-field-name")); } */ if (line.hasOption("key-freq")) { pageFormSearcher.loadCache(line.getOptionValue("key-freq"), minFreq); } if (line.hasOption("search")) { logger.debug("searching " + line.getOptionValue("search") + "..."); final FreqSetSearcher.Entry[] result = pageFormSearcher.search(line.getOptionValue("search")); logger.info(Arrays.toString(result)); } if (line.hasOption("interactive-mode")) { pageFormSearcher.interactive(); } } catch (final ParseException e) { // oops, something went wrong if (e.getMessage().length() > 0) { System.out.println("Parsing failed: " + e.getMessage() + "\n"); } final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(400, "java -cp dist/thewikimachine.jar org.fbk.cit.hlt.thewikimachine.index.FormPageSearcher", "\n", options, "\n", true); } }
From source file:com.browseengine.bobo.index.MakeBobo.java
/** * @param args//w w w.j a v a 2s . c o m */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub Option help = new Option("help", false, "print this message"); OptionBuilder.withArgName("path"); OptionBuilder.hasArg(); OptionBuilder.withDescription("data source - required"); Option src = OptionBuilder.create("source"); src.setRequired(true); OptionBuilder.withArgName("path"); OptionBuilder.hasArg(); OptionBuilder.withDescription("index to create - required"); Option index = OptionBuilder.create("index"); index.setRequired(true); OptionBuilder.withArgName("file"); OptionBuilder.hasArg(); OptionBuilder.withDescription("field configuration - optional"); Option conf = OptionBuilder.create("conf"); OptionBuilder.withArgName("class"); OptionBuilder.hasArg(); OptionBuilder.withDescription("class name of the data digester - default: xml digester"); Option digesterOpt = OptionBuilder.create("digester"); OptionBuilder.withArgName("name"); OptionBuilder.hasArg(); OptionBuilder.withDescription("character set name - default: UTF-8"); Option charset = OptionBuilder.create("charset"); OptionBuilder.withArgName("maxdocs"); OptionBuilder.hasArg(); OptionBuilder.withDescription("maximum number of documents - default: 100"); Option maxdocs = OptionBuilder.create("maxdocs"); Options options = new Options(); options.addOption(help); options.addOption(conf); options.addOption(index); options.addOption(src); options.addOption(charset); options.addOption(digesterOpt); options.addOption(maxdocs); // create the parser CommandLineParser parser = new BasicParser(); try { // parse the command line arguments CommandLine line = parser.parse(options, args); String output = line.getOptionValue("index"); File data = new File(line.getOptionValue("source")); Class digesterClass; if (line.hasOption("digester")) digesterClass = Class.forName(line.getOptionValue("digester")); else throw new RuntimeException("digester not specified"); Charset chset; if (line.hasOption("charset")) { chset = Charset.forName(line.getOptionValue("charset")); } else { chset = Charset.forName("UTF-8"); } int maxDocs; try { maxDocs = Integer.parseInt(line.getOptionValue("maxdocs")); } catch (Exception e) { maxDocs = 100; } FileDigester digester; try { Constructor constructor = digesterClass.getConstructor(new Class[] { File.class }); digester = (FileDigester) constructor.newInstance(new Object[] { data }); digester.setCharset(chset); digester.setMaxDocs(maxDocs); } catch (Exception e) { throw new RuntimeException("Invalid digester class.", e); } BoboIndexer indexer = new BoboIndexer(digester, FSDirectory.open(new File(output))); indexer.index(); } catch (ParseException exp) { exp.printStackTrace(); usage(options); } catch (ClassNotFoundException e) { System.out.println("Invalid digester class."); usage(options); } }
From source file:com.google.testing.pogen.PageObjectGenerator.java
@SuppressWarnings("static-access") public static void main(String[] args) { if (args.length == 0) { printUsage(System.out);//from w ww . j a v a2 s .c om return; } String commandName = args[0]; // @formatter:off Options options = new Options() .addOption(OptionBuilder.withDescription( "Attribute name to be assigned in tagas containing template variables (default is 'id').") .hasArg().withLongOpt("attr").create('a')) .addOption(OptionBuilder.withDescription("Print help for this command.").withLongOpt("help") .create('h')) .addOption(OptionBuilder.withDescription("Print processed files verbosely.").withLongOpt("verbose") .create('v')); // @formatter:on String helpMessage = null; if (commandName.equals(GENERATE_COMMAND)) { // @formatter:off options.addOption(OptionBuilder.withDescription("Package name of generating skeleton test code.") .hasArg().isRequired().withLongOpt("package").create('p')) .addOption(OptionBuilder.withDescription("Output directory of generating skeleton test code.") .hasArg().isRequired().withLongOpt("out").create('o')) .addOption(OptionBuilder.withDescription( "Root input directory of html template files for analyzing the suffixes of the package name.") .hasArg().isRequired().withLongOpt("in").create('i')) .addOption(OptionBuilder.withDescription("Regex for finding html template files.").hasArg() .withLongOpt("regex").create('e')) .addOption(OptionBuilder.withDescription("Option for finding html template files recursively.") .withLongOpt("recursive").create('r')); // @formatter:on helpMessage = "java PageObjectGenerator generate -o <test_out_dir> -p <package_name> -i <root_directory> " + " [OPTIONS] <template_file1> <template_file2> ...\n" + "e.g. java PageObjectGenerator generate -a class -o PageObjectGeneratorTest/src/test/java/com/google/testing/pogen/pages" + " -i PageObjectGeneratorTest/src/main/resources -p com.google.testing.pogen.pages -e (.*)\\.html -v"; } else if (commandName.equals(MEASURE_COMMAND)) { helpMessage = "java PageObjectGenerator measure [OPTIONS] <template_file1> <template_file2> ..."; } else if (commandName.equals(LIST_COMMAND)) { helpMessage = "java PageObjectGenerator list <template_file1> <template_file2> ..."; } else { System.err.format("'%s' is not a PageObjectGenerator command.", commandName); printUsage(System.err); System.exit(-1); } BasicParser cmdParser = new BasicParser(); HelpFormatter f = new HelpFormatter(); try { CommandLine cl = cmdParser.parse(options, Arrays.copyOfRange(args, 1, args.length)); if (cl.hasOption('h')) { f.printHelp(helpMessage, options); return; } Command command = null; String[] templatePaths = cl.getArgs(); String attributeName = cl.getOptionValue('a'); attributeName = attributeName != null ? attributeName : "id"; if (commandName.equals(GENERATE_COMMAND)) { String rootDirectoryPath = cl.getOptionValue('i'); String templateFilePattern = cl.getOptionValue('e'); boolean isRecusive = cl.hasOption('r'); command = new GenerateCommand(templatePaths, cl.getOptionValue('o'), cl.getOptionValue('p'), attributeName, cl.hasOption('v'), rootDirectoryPath, templateFilePattern, isRecusive); } else if (commandName.equals(MEASURE_COMMAND)) { command = new MeasureCommand(templatePaths, attributeName, cl.hasOption('v')); } else if (commandName.equals(LIST_COMMAND)) { command = new ListCommand(templatePaths, attributeName); } try { command.execute(); return; } catch (FileProcessException e) { System.err.println(e.getMessage()); } catch (IOException e) { System.err.println("Errors occur in processing files."); System.err.println(e.getMessage()); } } catch (ParseException e) { System.err.println("Errors occur in parsing the command arguments."); System.err.println(e.getMessage()); f.printHelp(helpMessage, options); } System.exit(-1); }
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 w w. j av a 2 s .co 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); } }