List of usage examples for org.apache.commons.cli HelpFormatter printHelp
public void printHelp(String cmdLineSyntax, Options options)
options
with the specified command line syntax. From source file:com.netflix.aegisthus.tools.SSTableExport.java
@SuppressWarnings("rawtypes") public static void main(String[] args) throws IOException { String usage = String.format("Usage: %s <sstable>", SSTableExport.class.getName()); CommandLineParser parser = new PosixParser(); try {/*from w w w . ja va 2 s . c o m*/ cmd = parser.parse(options, args); } catch (ParseException e1) { System.err.println(e1.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(usage, options); System.exit(1); } if (cmd.getArgs().length != 1) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(usage, options); System.exit(1); } Map<String, AbstractType> convertors = null; if (cmd.hasOption(COLUMN_NAME_TYPE)) { try { convertors = new HashMap<String, AbstractType>(); convertors.put(SSTableScanner.COLUMN_NAME_KEY, TypeParser.parse(cmd.getOptionValue(COLUMN_NAME_TYPE))); } catch (ConfigurationException e) { System.err.println(e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(usage, options); System.exit(1); } catch (SyntaxException e) { System.err.println(e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(usage, options); System.exit(1); } } Descriptor.Version version = null; if (cmd.hasOption(OPT_VERSION)) { version = new Descriptor.Version(cmd.getOptionValue(OPT_VERSION)); } if (cmd.hasOption(INDEX_SPLIT)) { String ssTableFileName; DataInput input = null; if ("-".equals(cmd.getArgs()[0])) { ssTableFileName = System.getProperty("aegisthus.file.name"); input = new DataInputStream(new BufferedInputStream(System.in, 65536 * 10)); } else { ssTableFileName = new File(cmd.getArgs()[0]).getAbsolutePath(); input = new DataInputStream( new BufferedInputStream(new FileInputStream(ssTableFileName), 65536 * 10)); } exportIndexSplit(ssTableFileName, input); } else if (cmd.hasOption(INDEX)) { String ssTableFileName = new File(cmd.getArgs()[0]).getAbsolutePath(); exportIndex(ssTableFileName); } else if (cmd.hasOption(ROWSIZE)) { String ssTableFileName = new File(cmd.getArgs()[0]).getAbsolutePath(); exportRowSize(ssTableFileName); } else if ("-".equals(cmd.getArgs()[0])) { if (version == null) { System.err.println("when streaming must supply file version"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(usage, options); System.exit(1); } exportStream(version); } else { String ssTableFileName = new File(cmd.getArgs()[0]).getAbsolutePath(); FileInputStream fis = new FileInputStream(ssTableFileName); InputStream inputStream = new DataInputStream(new BufferedInputStream(fis, 65536 * 10)); long end = -1; if (cmd.hasOption(END)) { end = Long.valueOf(cmd.getOptionValue(END)); } if (cmd.hasOption(OPT_COMP)) { CompressionMetadata cm = new CompressionMetadata( new BufferedInputStream(new FileInputStream(cmd.getOptionValue(OPT_COMP)), 65536), fis.getChannel().size()); inputStream = new CompressionInputStream(inputStream, cm); end = cm.getDataLength(); } DataInputStream input = new DataInputStream(inputStream); if (version == null) { version = Descriptor.fromFilename(ssTableFileName).version; } SSTableScanner scanner = new SSTableScanner(input, convertors, end, version); if (cmd.hasOption(OPT_MAX_COLUMN_SIZE)) { scanner.setMaxColSize(Long.parseLong(cmd.getOptionValue(OPT_MAX_COLUMN_SIZE))); } export(scanner); if (cmd.hasOption(OPT_MAX_COLUMN_SIZE)) { if (scanner.getErrorRowCount() > 0) { System.err.println(String.format("%d rows were too large", scanner.getErrorRowCount())); } } } }
From source file:io.anserini.index.IndexGov2.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 a2s .c om*/ OptionBuilder.withArgName("path").hasArg().withDescription("input data path").create(INPUT_OPTION)); options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("output index path") .create(INDEX_OPTION)); options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of indexer threads") .create(THREADS_OPTION)); options.addOption(OptionBuilder.withArgName("num").hasArg() .withDescription("max number of documents to index (-1 to index everything)") .create(DOCLIMIT_OPTION)); options.addOption(POSITIONS_OPTION, false, "index positions"); options.addOption(OPTIMIZE_OPTION, false, "merge all index segments"); 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(INPUT_OPTION) || !cmdline.hasOption(INDEX_OPTION) || !cmdline.hasOption(THREADS_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(100); formatter.printHelp(IndexGov2.class.getCanonicalName(), options); System.exit(-1); } final String dirPath = cmdline.getOptionValue(INDEX_OPTION); final String dataDir = cmdline.getOptionValue(INPUT_OPTION); final int docCountLimit = cmdline.hasOption(DOCLIMIT_OPTION) ? Integer.parseInt(cmdline.getOptionValue(DOCLIMIT_OPTION)) : -1; final int numThreads = Integer.parseInt(cmdline.getOptionValue(THREADS_OPTION)); final boolean doUpdate = cmdline.hasOption(UPDATE_OPTION); final boolean positions = cmdline.hasOption(POSITIONS_OPTION); final boolean optimize = cmdline.hasOption(OPTIMIZE_OPTION); final Analyzer a = new EnglishAnalyzer(); final TrecContentSource trecSource = createGov2Source(dataDir); final Directory dir = FSDirectory.open(Paths.get(dirPath)); LOG.info("Index path: " + dirPath); LOG.info("Doc limit: " + (docCountLimit == -1 ? "all docs" : "" + docCountLimit)); LOG.info("Threads: " + numThreads); LOG.info("Positions: " + positions); LOG.info("Optimize (merge segments): " + optimize); final IndexWriterConfig config = new IndexWriterConfig(a); if (doUpdate) { config.setOpenMode(IndexWriterConfig.OpenMode.APPEND); } else { config.setOpenMode(IndexWriterConfig.OpenMode.CREATE); } final IndexWriter writer = new IndexWriter(dir, config); Gov2IndexThreads threads = new Gov2IndexThreads(writer, positions, trecSource, numThreads, docCountLimit); LOG.info("Indexer: start"); final long t0 = System.currentTimeMillis(); threads.start(); while (!threads.done()) { Thread.sleep(100); } threads.stop(); final long t1 = System.currentTimeMillis(); LOG.info("Indexer: indexing done (" + (t1 - t0) / 1000.0 + " sec); total " + writer.maxDoc() + " docs"); if (!doUpdate && docCountLimit != -1 && writer.maxDoc() != docCountLimit) { throw new RuntimeException("w.maxDoc()=" + writer.maxDoc() + " but expected " + docCountLimit); } if (threads.failed.get()) { throw new RuntimeException("exceptions during indexing"); } final long t2; t2 = System.currentTimeMillis(); final Map<String, String> commitData = new HashMap<String, String>(); commitData.put("userData", "multi"); writer.setCommitData(commitData); writer.commit(); final long t3 = System.currentTimeMillis(); LOG.info("Indexer: commit multi (took " + (t3 - t2) / 1000.0 + " sec)"); if (optimize) { LOG.info("Indexer: merging all segments"); writer.forceMerge(1); final long t4 = System.currentTimeMillis(); LOG.info("Indexer: segments merged (took " + (t4 - t3) / 1000.0 + " sec)"); } LOG.info("Indexer: at close: " + writer.segString()); final long tCloseStart = System.currentTimeMillis(); writer.close(); LOG.info("Indexer: close took " + (System.currentTimeMillis() - tCloseStart) / 1000.0 + " sec"); dir.close(); final long tFinal = System.currentTimeMillis(); LOG.info("Indexer: finished (" + (tFinal - t0) / 1000.0 + " sec)"); LOG.info("Indexer: net bytes indexed " + threads.getBytesIndexed()); LOG.info("Indexer: " + (threads.getBytesIndexed() / 1024. / 1024. / 1024. / ((tFinal - t0) / 3600000.)) + " GB/hour plain text"); }
From source file:com.controlj.experiment.bulktrend.trendclient.Main.java
public static void main(String args[]) { Options options = setupCLOptions();/*w w w . ja v a 2s . c om*/ CommandLineParser parser = new GnuParser(); CommandLine line = null; try { line = parser.parse(options, args); } catch (ParseException e) { System.err.println("Command line parsing failed: " + e.getMessage()); System.exit(-1); } if (line.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("trendclient", options); printConfigHelp(); System.exit(0); } // dir option - read config files File baseDir = new File(""); if (line.hasOption(PARAM_DIR)) { baseDir = new File(line.getOptionValue(PARAM_DIR)); } Properties props = getProperties(baseDir); String server = getProperty(props, PROP_SERVER); String parserName = getProperty(props, PROP_PARSER); String handlerName = getProperty(props, PROP_HANDLER); String user = getProperty(props, PROP_USER); String pw = getProperty(props, PROP_PASSWORD); TrendClient tc = new TrendClient(server, getIDs(baseDir), user, pw, handlerName, parserName); String defaultDigitsString = props.getProperty(PROP_DIGITS); if (defaultDigitsString != null) { try { tc.setDefaultDigits(Integer.parseInt(defaultDigitsString)); } catch (NumberFormatException e) { System.err.println("Invalid valid for property " + PROP_DIGITS + ":" + defaultDigitsString); } } //testfile if (line.hasOption(PARAM_TESTFILE)) { String fileName = line.getOptionValue(PARAM_TESTFILE); if (fileName == null) { fileName = "response.dump"; } try { tc.setAlternateInput(new FileInputStream(new File(fileName))); System.out.println("Reading trends from file: " + fileName); } catch (FileNotFoundException e) { System.err.println("Error, " + PARAM_TESTFILE + " '" + fileName + "' not found"); } } else { System.out.println("Reading trends from " + server); System.out.println("Parser=" + parserName); System.out.println("Handler=" + handlerName); } // Start/End Date start = parseDateOption(PARAM_START, line); Date end = parseDateOption(PARAM_END, line); if (start == null) { start = TrendClient.getYesterday().getTime(); } if (end == null) { end = TrendClient.getYesterday().getTime(); } tc.setStart(start); tc.setEnd(end); System.out.println("From " + start + " to " + end); // nozip if (line.hasOption(PARAM_NOZIP)) { tc.setZip(false); } tc.go(); }
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);//from w w w . jav a2 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:gpframework.RunExperiment.java
/** * Application's entry point.//from w w w . ja va 2 s . c om * * @param args * @throws ParseException * @throws ParameterException */ public static void main(String[] args) throws ParseException, ParameterException { // Failsafe parameters if (args.length == 0) { args = new String[] { "-f", "LasSortednessFunction", "-n", "5", "-ff", "JoinFactory", "-tf", "SortingElementFactory", "-pf", "SortingProgramFactory", "-s", "SMOGPSelection", "-a", "SMOGP", "-t", "50", "-e", "1000000000", "-mf", "SingleMutationFactory", "-d", "-bn", "other" }; } // Create options Options options = new Options(); setupOptions(options); // Read options from the command line CommandLineParser parser = new PosixParser(); CommandLine cmd; // Print help if parameter requirements are not met try { cmd = parser.parse(options, args); } // If some parameters are missing, print help catch (MissingOptionException e) { HelpFormatter hf = new HelpFormatter(); hf.printHelp("java -jar GPFramework \n", options); System.out.println(); System.out.println("Missing parameters: " + e.getMissingOptions()); return; } // Re-initialize PRNG long seed = System.currentTimeMillis(); Utils.random = new Random(seed); // Set the problem size int problemSize = Integer.parseInt(cmd.getOptionValue("n")); // Set debug mode and cluster mode Utils.debug = cmd.hasOption("d"); RunExperiment.cluster = cmd.hasOption("c"); // Initialize fitness function and some factories FitnessFunction fitnessFunction = fromName(cmd.getOptionValue("f"), problemSize); MutationFactory mutationFactory = fromName(cmd.getOptionValue("mf")); Selection selectionCriterion = fromName(cmd.getOptionValue("s")); FunctionFactory functionFactory = fromName(cmd.getOptionValue("ff")); TerminalFactory terminalFactory = fromName(cmd.getOptionValue("tf"), problemSize); ProgramFactory programFactory = fromName(cmd.getOptionValue("pf"), functionFactory, terminalFactory); // Initialize algorithm Algorithm algorithm = fromName(cmd.getOptionValue("a"), mutationFactory, selectionCriterion); algorithm.setParameter("evaluationsBudget", cmd.getOptionValue("e")); algorithm.setParameter("timeBudget", cmd.getOptionValue("t")); // Initialize problem Problem problem = new Problem(programFactory, fitnessFunction); Program solution = algorithm.solve(problem); Utils.debug("Population results: "); Utils.debug(algorithm.getPopulation().toString()); Utils.debug(algorithm.getPopulation().parse()); Map<String, Object> entry = new HashMap<String, Object>(); // Copy algorithm setup for (Object o : options.getRequiredOptions()) { Option option = options.getOption(o.toString()); entry.put(option.getLongOpt(), cmd.getOptionValue(option.getOpt())); } entry.put("seed", seed); // Copy results entry.put("bestProgram", solution.toString()); entry.put("bestSolution", fitnessFunction.normalize(solution)); // Copy all statistics entry.putAll(algorithm.getStatistics()); Utils.debug("Maximum encountered population size: " + algorithm.getStatistics().get("maxPopulationSizeToCompleteFront")); Utils.debug("Maximum encountered tree size: " + algorithm.getStatistics().get("maxProgramComplexityToCompleteFront")); Utils.debug("Solution complexity: " + solution.complexity() + "/" + (2 * problemSize - 1)); }
From source file:de.prozesskraft.pkraft.Createmap.java
public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException { // try/* ww w . j a va 2 s . c om*/ // { // if (args.length != 3) // { // System.out.println("Please specify processdefinition file (xml) and an outputfilename"); // } // // } // catch (ArrayIndexOutOfBoundsException e) // { // System.out.println("***ArrayIndexOutOfBoundsException: Please specify processdefinition.xml, openoffice_template.od*, newfile_for_processdefinitions.odt\n" + e.toString()); // } /*---------------------------- get options from ini-file ----------------------------*/ File inifile = new java.io.File( WhereAmI.getInstallDirectoryAbsolutePath(Createmap.class) + "/" + "../etc/pkraft-createmap.ini"); if (inifile.exists()) { try { ini = new Ini(inifile); } catch (InvalidFileFormatException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else { System.err.println("ini file does not exist: " + inifile.getAbsolutePath()); System.exit(1); } /*---------------------------- create boolean options ----------------------------*/ Option ohelp = new Option("help", "print this message"); /*---------------------------- create argument options ----------------------------*/ Option ooutput = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[mandatory; default: process.dot] file for generated map.") // .isRequired() .create("output"); Option odefinition = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[mandatory] process definition file.") // .isRequired() .create("definition"); /*---------------------------- create options object ----------------------------*/ Options options = new Options(); options.addOption(ohelp); options.addOption(ooutput); options.addOption(odefinition); /*---------------------------- create the parser ----------------------------*/ CommandLineParser parser = new GnuParser(); try { // parse the command line arguments commandline = parser.parse(options, args); } catch (Exception exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); exiter(); } /*---------------------------- usage/help ----------------------------*/ if (commandline.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("createmap", options); System.out.println(""); System.out.println("author: " + author + " | version: " + version + " | date: " + date); System.exit(0); } /*---------------------------- ueberpruefen ob eine schlechte kombination von parametern angegeben wurde ----------------------------*/ if (!(commandline.hasOption("definition"))) { System.err.println("option -definition is mandatory."); exiter(); } if (!(commandline.hasOption("output"))) { System.err.println("option -output is mandatory."); exiter(); } /*---------------------------- die lizenz ueberpruefen und ggf abbrechen ----------------------------*/ // check for valid license ArrayList<String> allPortAtHost = new ArrayList<String>(); allPortAtHost.add(ini.get("license-server", "license-server-1")); allPortAtHost.add(ini.get("license-server", "license-server-2")); allPortAtHost.add(ini.get("license-server", "license-server-3")); MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1"); // lizenz-logging ausgeben for (String actLine : (ArrayList<String>) lic.getLog()) { System.err.println(actLine); } // abbruch, wenn lizenz nicht valide if (!lic.isValid()) { System.exit(1); } /*---------------------------- die eigentliche business logic ----------------------------*/ Process p1 = new Process(); java.io.File output = new java.io.File(commandline.getOptionValue("output")); if (output.exists()) { System.err.println("warn: already exists: " + output.getCanonicalPath()); exiter(); } p1.setInfilexml(commandline.getOptionValue("definition")); System.err.println("info: reading process definition " + commandline.getOptionValue("definition")); // dummy process Process p2 = null; try { p2 = p1.readXml(); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); System.err.println("error"); exiter(); } // den wrapper process generieren ArrayList<String> dot = p2.getProcessAsDotGraph(); // dot file rausschreiben writeFile.writeFile(output, dot); }
From source file:com.marketplace.Main.java
public static void main(String args[]) { Options options = new CLI().getOptions(); if (args.length == 0) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("android-marketplace-crawler", options); } else {// w ww . j a va 2s . c o m new Main().resolveArgs(options, args); } }
From source file:com.maxpowered.amazon.advertising.api.app.App.java
public static void main(final String... args) throws FileNotFoundException, IOException, JAXBException, XMLStreamException, InterruptedException { try (ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("application-context.xml")) { /*/* w w w . j ava 2 s . c o m*/ * Get default options based on spring configs */ final String inputDefault = getOptionDefaultBasedOnSpringProperty(ctx, PROPERTY_APP_INPUT, STD_IN_STR); final String processedDefault = inputDefault.equals(STD_IN_STR) ? DEFAULT_PROCESSED_FILE_BASE : inputDefault + PROCESSED_EXT; final String outputDefault = getOptionDefaultBasedOnSpringProperty(ctx, PROPERTY_APP_OUTPUT, STD_OUT_STR); int throttleDefault = Integer.valueOf(getOptionDefaultBasedOnSpringProperty(ctx, PROPERTY_APP_THROTTLE, String.valueOf(DEFAULT_APP_THROTTLE))); // Maximum of 25000 requests per hour throttleDefault = Math.min(throttleDefault, MAX_APP_THROTTLE); /* * Get options from the CLI args */ final Options options = new Options(); options.addOption("h", false, "Display this help."); options.addOption("i", true, "Set the file to read ASINs from. " + DEFAULT_STR + inputDefault); options.addOption("p", true, "Set the file to store processed ASINs in. " + DEFAULT_STR + processedDefault + " or '" + PROCESSED_EXT + "' appended to the input file name."); // Add a note that the output depends on the configured processors. If none are configured, it defaults to a // std.out processor options.addOption("o", true, "Set the file to write fetched info xml to via FileProcessor. " + DEFAULT_STR + outputDefault); options.addOption("1", false, "Override output file and always output fetched info xml to std.out."); options.addOption("t", true, "Set the requests per hour throttle (max of " + MAX_APP_THROTTLE + "). " + DEFAULT_STR + throttleDefault); final CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; boolean needsHelp = false; try { cmd = parser.parse(options, args); } catch (final ParseException e) { needsHelp = true; } if (cmd.hasOption("h") || needsHelp) { final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("App", options); return; } // Get throttle rate final int throttle = Math.min( cmd.hasOption("t") ? Integer.valueOf(cmd.getOptionValue("t")) : throttleDefault, MAX_APP_THROTTLE); LOG.debug("Throttle (default {}) is {} requests per hour", throttleDefault, throttle); // We don't want to hit our limit, just under an hour worth of milliseconds final int requestWait = 3540000 / throttle; // Get input stream String input; if (cmd.hasOption("i")) { input = cmd.getOptionValue("i"); } else { input = inputDefault; } LOG.debug("Input name (default {}) is {}", inputDefault, input); // Get processed file String processed; if (cmd.hasOption("p")) { processed = cmd.getOptionValue("p"); } else { processed = input + PROCESSED_EXT; } LOG.debug("Processed file name (default {}) is {}", processedDefault, processed); final File processedFile = new File(processed); processedFile.createNewFile(); try (final InputStream inputStream = getInputStream(input)) { // Get output stream String output; if (cmd.hasOption("o")) { output = cmd.getOptionValue("o"); } else { output = outputDefault; } if (cmd.hasOption("1")) { output = STD_OUT_STR; } LOG.debug("Output (default {}) name is {}", outputDefault, output); // Special logic to set the FileProcessor output if (output.equals(STD_OUT_STR)) { final FileProcessor fileProcessor = ctx.getBeanFactory().getBean(FileProcessor.class); fileProcessor.setOutputStream(System.out); } else if (!output.equals(outputDefault)) { final FileProcessor fileProcessor = ctx.getBeanFactory().getBean(FileProcessor.class); fileProcessor.setOutputFile(output); } // This could be easily configured through CLI or properties final List<String> responseGroups = Lists.newArrayList(); for (final ResponseGroup responseGroup : new ResponseGroup[] { ResponseGroup.IMAGES, ResponseGroup.ITEM_ATTRIBUTES }) { responseGroups.add(responseGroup.getResponseGroupName()); } final String responseGroupString = Joiner.on(",").join(responseGroups); // Search the list of remaining ASINs final ProductFetcher fetcher = ctx.getBeanFactory().getBean(ProductFetcher.class); fetcher.setProcessedFile(processedFile); fetcher.setRequestWait(requestWait); fetcher.setInputStream(inputStream); fetcher.setResponseGroups(responseGroupString); // This ensures that statistics of processed asins should almost always get printed at the end Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { fetcher.logStatistics(); } }); fetcher.fetchProductInformation(); } } }
From source file:createSod.java
/** * @param args/*from ww w . j a v a2 s . co m*/ * @throws CMSException */ public static void main(String[] args) throws Exception { try { CommandLine options = verifyArgs(args); String privateKeyLocation = options.getOptionValue("privatekey"); String keyPassword = options.getOptionValue("keypass"); String certificate = options.getOptionValue("certificate"); String sodContent = options.getOptionValue("content"); String sod = ""; if (options.hasOption("out")) { sod = options.getOptionValue("out"); } // CHARGEMENT DU FICHIER PKCS#12 KeyStore ks = null; char[] password = null; Security.addProvider(new BouncyCastleProvider()); try { ks = KeyStore.getInstance("PKCS12"); // Password pour le fichier personnal_nyal.p12 password = keyPassword.toCharArray(); ks.load(new FileInputStream(privateKeyLocation), password); } catch (Exception e) { System.out.println("Erreur: fichier " + privateKeyLocation + " n'est pas un fichier pkcs#12 valide ou passphrase incorrect"); return; } // RECUPERATION DU COUPLE CLE PRIVEE/PUBLIQUE ET DU CERTIFICAT PUBLIQUE X509Certificate cert = null; PrivateKey privatekey = null; PublicKey publickey = null; try { Enumeration en = ks.aliases(); String ALIAS = ""; Vector vectaliases = new Vector(); while (en.hasMoreElements()) vectaliases.add(en.nextElement()); String[] aliases = (String[]) (vectaliases.toArray(new String[0])); for (int i = 0; i < aliases.length; i++) if (ks.isKeyEntry(aliases[i])) { ALIAS = aliases[i]; break; } privatekey = (PrivateKey) ks.getKey(ALIAS, password); cert = (X509Certificate) ks.getCertificate(ALIAS); publickey = ks.getCertificate(ALIAS).getPublicKey(); } catch (Exception e) { e.printStackTrace(); return; } // Chargement du certificat partir du fichier InputStream inStream = new FileInputStream(certificate); CertificateFactory cf = CertificateFactory.getInstance("X.509"); cert = (X509Certificate) cf.generateCertificate(inStream); inStream.close(); // Chargement du fichier qui va tre sign File file_to_sign = new File(sodContent); byte[] buffer = new byte[(int) file_to_sign.length()]; DataInputStream in = new DataInputStream(new FileInputStream(file_to_sign)); in.readFully(buffer); in.close(); // Chargement des certificats qui seront stocks dans le fichier .p7 // Ici, seulement le certificat personnal_nyal.cer sera associ. // Par contre, la chane des certificats non. ArrayList certList = new ArrayList(); certList.add(cert); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); CMSSignedDataGenerator signGen = new CMSSignedDataGenerator(); // privatekey correspond notre cl prive rcupre du fichier PKCS#12 // cert correspond au certificat publique personnal_nyal.cer // Le dernier argument est l'algorithme de hachage qui sera utilis signGen.addSigner(privatekey, cert, CMSSignedDataGenerator.DIGEST_SHA1); signGen.addCertificatesAndCRLs(certs); CMSProcessable content = new CMSProcessableByteArray(buffer); // Generation du fichier CMS/PKCS#7 // L'argument deux permet de signifier si le document doit tre attach avec la signature // Valeur true: le fichier est attach (c'est le cas ici) // Valeur false: le fichier est dtach CMSSignedData signedData = signGen.generate(content, true, "BC"); byte[] signeddata = signedData.getEncoded(); // Ecriture du buffer dans un fichier. if (sod.equals("")) { System.out.print(signeddata.toString()); } else { FileOutputStream envfos = new FileOutputStream(sod); envfos.write(signeddata); envfos.close(); } } catch (OptionException oe) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(NAME, getOptions()); System.exit(-1); } catch (Exception e) { e.printStackTrace(); return; } }
From source file:com.ingby.socbox.bischeck.cli.CacheCli.java
public static void main(String[] args) throws ConfigurationException, CacheException, IOException, ParseException { CommandLineParser cmdParser = new GnuParser(); CommandLine line = null;// w ww. ja va 2 s . co m // create the Options Options options = new Options(); options.addOption("u", "usage", false, "show usage"); options.addOption("p", "pipemode", false, "read from stdin"); options.addOption("T", "notime", false, "do not show execution time"); options.addOption("P", "noparse", false, "do not show parsed expression"); try { line = cmdParser.parse(options, args); } catch (org.apache.commons.cli.ParseException e) { System.out.println("Command parse error:" + e.getMessage()); Util.ShellExit(1); } if (line.hasOption("usage")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(PROGRAMNAME, options); Util.ShellExit(0); } try { ConfigurationManager.getInstance(); } catch (java.lang.IllegalStateException e) { ConfigurationManager.init(); ConfigurationManager.getInstance(); } Boolean supportNull = false; if ("true".equalsIgnoreCase( ConfigurationManager.getInstance().getProperties().getProperty("notFullListParse", "false"))) { supportNull = true; } CacheFactory.init(); if (line.hasOption("notime")) { showtime = false; } if (line.hasOption("noparse")) { showparse = false; } if (line.hasOption("pipemode")) { pipe(); } else { cli(supportNull); } }