List of usage examples for org.apache.commons.cli CommandLineParser parse
CommandLine parse(Options options, String[] arguments) throws ParseException;
From source file:com.alexoree.jenkins.Main.java
public static void main(String[] args) throws Exception { // create Options object Options options = new Options(); options.addOption("t", false, "throttle the downloads, waits 5 seconds in between each d/l"); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("jenkins-sync", options); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); boolean throttle = cmd.hasOption("t"); String plugins = "https://updates.jenkins-ci.org/latest/"; List<String> ps = new ArrayList<String>(); Document doc = Jsoup.connect(plugins).get(); for (Element file : doc.select("td a")) { //System.out.println(file.attr("href")); if (file.attr("href").endsWith(".hpi") || file.attr("href").endsWith(".war")) { ps.add(file.attr("href")); }//from w w w. ja v a 2 s . c o m } File root = new File("."); //https://updates.jenkins-ci.org/latest/AdaptivePlugin.hpi new File("./latest").mkdirs(); //output zip file String zipFile = "jenkinsSync.zip"; // create byte buffer byte[] buffer = new byte[1024]; FileOutputStream fos = new FileOutputStream(zipFile); ZipOutputStream zos = new ZipOutputStream(fos); //download the plugins for (int i = 0; i < ps.size(); i++) { System.out.println("[" + i + "/" + ps.size() + "] downloading " + plugins + ps.get(i)); String outputFile = download(root.getAbsolutePath() + "/latest/" + ps.get(i), plugins + ps.get(i)); FileInputStream fis = new FileInputStream(outputFile); // begin writing a new ZIP entry, positions the stream to the start of the entry data zos.putNextEntry(new ZipEntry(outputFile.replace(root.getAbsolutePath(), "") .replace("updates.jenkins-ci.org/", "").replace("https:/", ""))); int length; while ((length = fis.read(buffer)) > 0) { zos.write(buffer, 0, length); } zos.closeEntry(); fis.close(); if (throttle) Thread.sleep(WAIT); new File(root.getAbsolutePath() + "/latest/" + ps.get(i)).deleteOnExit(); } //download the json metadata plugins = "https://updates.jenkins-ci.org/"; ps = new ArrayList<String>(); doc = Jsoup.connect(plugins).get(); for (Element file : doc.select("td a")) { //System.out.println(file.attr("href")); if (file.attr("href").endsWith(".json")) { ps.add(file.attr("href")); } } for (int i = 0; i < ps.size(); i++) { download(root.getAbsolutePath() + "/" + ps.get(i), plugins + ps.get(i)); FileInputStream fis = new FileInputStream(root.getAbsolutePath() + "/" + ps.get(i)); // begin writing a new ZIP entry, positions the stream to the start of the entry data zos.putNextEntry(new ZipEntry(plugins + ps.get(i))); int length; while ((length = fis.read(buffer)) > 0) { zos.write(buffer, 0, length); } zos.closeEntry(); fis.close(); new File(root.getAbsolutePath() + "/" + ps.get(i)).deleteOnExit(); if (throttle) Thread.sleep(WAIT); } // close the ZipOutputStream zos.close(); }
From source file:com.dustindoloff.s3websitedeploy.Main.java
public static void main(final String[] args) { final Options options = buildOptions(); final CommandLineParser parser = new DefaultParser(); final CommandLine commandLine; try {/*from w w w . jav a 2 s .c o m*/ commandLine = parser.parse(options, args); } catch (final ParseException e) { System.out.println(e.getMessage()); new HelpFormatter().printHelp("s3WebsiteDeploy", options); System.exit(1); return; } final File websiteZip = new File(commandLine.getOptionValue(ARG_WEBSITE_ZIP)); final String s3Bucket = commandLine.getOptionValue(ARG_BUCKET); final String awsAccessKey = commandLine.getOptionValue(ARG_AWS_ACCESS_KEY); final String awsSecretKey = commandLine.getOptionValue(ARG_AWS_SECRET_KEY); final ZipFile zipFile = getAsValidZip(websiteZip); if (zipFile == null) { System.out.println("Invalid zip file passed in"); System.exit(2); return; } System.out.println("Running S3 Website Deploy"); final AmazonS3 s3Client = new AmazonS3Client(new BasicAWSCredentials(awsAccessKey, awsSecretKey)); final Region bucketRegion = getBucketRegion(s3Client, s3Bucket); if (bucketRegion == null) { System.out.println("Unable to get the region for the bucket."); System.exit(3); return; } s3Client.setRegion(bucketRegion); if (!emptyBucket(s3Client, s3Bucket)) { System.out.println("Unable to upload to empty bucket."); System.exit(4); return; } if (!upload(s3Client, s3Bucket, zipFile)) { System.out.println("Unable to upload to S3."); System.exit(5); return; } System.out.println("Deployment Complete"); }
From source file:com.twentyn.bioreactor.pH.ControlSystem.java
public static void main(String[] args) throws Exception { Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());/*from w w w . j av a 2s. c om*/ } CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { LOGGER.error(String.format("Argument parsing failed: %s\n", e.getMessage())); HELP_FORMATTER.printHelp(ControlSystem.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(ControlSystem.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } SOLUTION solution = null; String acidOrBase = cl.getOptionValue(OPTION_CONTROL_SOLUTION); if (acidOrBase.equals(SOLUTION.ACID.name())) { solution = SOLUTION.ACID; } if (acidOrBase.equals(SOLUTION.BASE.name())) { solution = SOLUTION.BASE; } if (solution == null) { LOGGER.error("Input solution is neither %s or %s", SOLUTION.ACID.name(), SOLUTION.BASE.name()); return; } Double targetPH = Double.parseDouble(cl.getOptionValue(OPTION_TARGET_PH)); File sensorReadingDataFile = new File( cl.getOptionValue(OPTION_SENSOR_READING_FILE_LOCATION, SENSOR_READING_FILE_LOCATION)); MotorPinConfiguration motorPinConfiguration = new MotorPinConfiguration( MotorPinConfiguration.PinNumberingScheme.BOARD); motorPinConfiguration.initializeGPIOPinsAndSetConfigToStartState(); ControlSystem controlSystem = new ControlSystem(motorPinConfiguration, solution, targetPH, sensorReadingDataFile); controlSystem.registerModuleForObjectMapper(new JodaModule()); try { controlSystem.run(); } finally { LOGGER.info("Shutting down"); controlSystem.shutdownFermentation(); } }
From source file:cz.muni.fi.mir.mathmlunificator.MathMLUnificatorCommandLineTool.java
/** * Main (starting) method of the command line application. * * @param argv Array of command line arguments that are expected to be * filesystem paths to input XML documents with MathML to be unified. * @throws ParserConfigurationException If a XML DOM builder cannot be * created with the configuration requested. */// ww w . j a v a 2s . c o m public static void main(String argv[]) throws ParserConfigurationException { final Options options = new Options(); options.addOption("p", "operator-unification", false, "unify operator in addition to other types of nodes"); options.addOption("h", "help", false, "print help"); final CommandLineParser parser = new DefaultParser(); CommandLine line = null; try { line = parser.parse(options, argv); } catch (ParseException ex) { printHelp(options); System.exit(1); } if (line != null) { if (line.hasOption('h')) { printHelp(options); System.exit(0); } operatorUnification = line.hasOption('p'); final List<String> arguments = Arrays.asList(line.getArgs()); if (arguments.size() > 0) { Document outerDocument = DOMBuilder.getDocumentBuilder().newDocument(); Node rootNode = outerDocument.createElementNS(UNIFIED_MATHML_NS, UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_BATCH_OUTPUT_ROOT_ELEM); outerDocument.appendChild(rootNode); for (String filepath : arguments) { try { Document doc = DOMBuilder.buildDocFromFilepath(filepath); MathMLUnificator.unifyMathML(doc, operatorUnification); if (arguments.size() == 1) { xmlStdoutSerializer(doc); } else { Node itemNode = rootNode.getOwnerDocument().createElementNS(UNIFIED_MATHML_NS, UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_BATCH_OUTPUT_ITEM_ELEM); Attr filenameAttr = itemNode.getOwnerDocument().createAttributeNS(UNIFIED_MATHML_NS, UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_BATCH_OUTPUT_ITEM_FILEPATH_ATTR); filenameAttr.setTextContent(String.valueOf(filepath)); ((Element) itemNode).setAttributeNodeNS(filenameAttr); itemNode.appendChild( rootNode.getOwnerDocument().importNode(doc.getDocumentElement(), true)); rootNode.appendChild(itemNode); } } catch (SAXException | IOException ex) { Logger.getLogger(MathMLUnificatorCommandLineTool.class.getName()).log(Level.SEVERE, "Failed processing of file: " + filepath, ex); } } if (rootNode.getChildNodes().getLength() > 0) { xmlStdoutSerializer(rootNode.getOwnerDocument()); } } else { printHelp(options); System.exit(0); } } }
From source file:io.anserini.search.SearchTweets.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(new Option(RM3_OPTION, "apply relevance feedback with rm3")); options.addOption(/*from ww w . j a va 2s . c o m*/ OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_OPTION)); options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of results to return") .create(NUM_RESULTS_OPTION)); options.addOption(OptionBuilder.withArgName("file").hasArg() .withDescription("file containing topics in TREC format").create(QUERIES_OPTION)); options.addOption(OptionBuilder.withArgName("similarity").hasArg() .withDescription("similarity to use (BM25, LM)").create(SIMILARITY_OPTION)); options.addOption( OptionBuilder.withArgName("string").hasArg().withDescription("runtag").create(RUNTAG_OPTION)); CommandLine cmdline = null; CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (!cmdline.hasOption(QUERIES_OPTION) || !cmdline.hasOption(INDEX_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(SearchTweets.class.getName(), options); System.exit(-1); } File indexLocation = new File(cmdline.getOptionValue(INDEX_OPTION)); if (!indexLocation.exists()) { System.err.println("Error: " + indexLocation + " does not exist!"); System.exit(-1); } String runtag = cmdline.hasOption(RUNTAG_OPTION) ? cmdline.getOptionValue(RUNTAG_OPTION) : DEFAULT_RUNTAG; String topicsFile = cmdline.getOptionValue(QUERIES_OPTION); int numResults = 1000; try { if (cmdline.hasOption(NUM_RESULTS_OPTION)) { numResults = Integer.parseInt(cmdline.getOptionValue(NUM_RESULTS_OPTION)); } } catch (NumberFormatException e) { System.err.println("Invalid " + NUM_RESULTS_OPTION + ": " + cmdline.getOptionValue(NUM_RESULTS_OPTION)); System.exit(-1); } String similarity = "LM"; if (cmdline.hasOption(SIMILARITY_OPTION)) { similarity = cmdline.getOptionValue(SIMILARITY_OPTION); } PrintStream out = new PrintStream(System.out, true, "UTF-8"); IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(indexLocation.getAbsolutePath()))); IndexSearcher searcher = new IndexSearcher(reader); if (similarity.equalsIgnoreCase("BM25")) { searcher.setSimilarity(new BM25Similarity()); } else if (similarity.equalsIgnoreCase("LM")) { searcher.setSimilarity(new LMDirichletSimilarity(2500.0f)); } MicroblogTopicSet topics = MicroblogTopicSet.fromFile(new File(topicsFile)); for (MicroblogTopic topic : topics) { Filter filter = NumericRangeFilter.newLongRange(StatusField.ID.name, 0L, topic.getQueryTweetTime(), true, true); Query query = AnalyzerUtils.buildBagOfWordsQuery(StatusField.TEXT.name, IndexTweets.ANALYZER, topic.getQuery()); TopDocs rs = searcher.search(query, filter, numResults); RerankerContext context = new RerankerContext(searcher, query, topic.getQuery(), filter); RerankerCascade cascade = new RerankerCascade(context); if (cmdline.hasOption(RM3_OPTION)) { cascade.add(new Rm3Reranker(IndexTweets.ANALYZER, StatusField.TEXT.name)); cascade.add(new RemoveRetweetsTemporalTiebreakReranker()); } else { cascade.add(new RemoveRetweetsTemporalTiebreakReranker()); } ScoredDocuments docs = cascade.run(ScoredDocuments.fromTopDocs(rs, searcher)); for (int i = 0; i < docs.documents.length; i++) { String qid = topic.getId().replaceFirst("^MB0*", ""); out.println(String.format("%s Q0 %s %d %f %s", qid, docs.documents[i].getField(StatusField.ID.name).numericValue(), (i + 1), docs.scores[i], runtag)); } } reader.close(); out.close(); }
From source file:com.example.geomesa.authorizations.GeoServerAuthorizationsTutorial.java
/** * Main entry point. Executes queries against an existing GDELT dataset. * * @param args//from ww w. j a v a 2 s . c o m * * @throws Exception */ public static void main(String[] args) throws Exception { // read command line options - this contains the path to geoserver and the data store to query CommandLineParser parser = new BasicParser(); Options options = SetupUtil.getWfsOptions(); CommandLine cmd = parser.parse(options, args); String geoserverHost = cmd.getOptionValue(SetupUtil.GEOSERVER_URL); if (!geoserverHost.endsWith("/")) { geoserverHost += "/"; } // create the URL to GeoServer. Note that we need to point to the 'GetCapabilities' request, // and that we are using WFS version 1.0.0 String geoserverUrl = geoserverHost + "wfs?request=GetCapabilities&version=1.0.0"; // create the geotools configuration for a WFS data store Map<String, String> configuration = new HashMap<String, String>(); configuration.put(WFSDataStoreFactory.URL.key, geoserverUrl); configuration.put(WFSDataStoreFactory.WFS_STRATEGY.key, "geoserver"); configuration.put(WFSDataStoreFactory.TIMEOUT.key, cmd.getOptionValue(SetupUtil.TIMEOUT, "99999")); System.out.println("Executing query against '" + geoserverHost + "' with client keystore '" + System.getProperty("javax.net.ssl.keyStore") + "'"); // verify we have gotten the correct datastore WFSDataStore wfsDataStore = (WFSDataStore) DataStoreFinder.getDataStore(configuration); assert wfsDataStore != null; // the geoserver data store to query String geoserverDataStore = cmd.getOptionValue(SetupUtil.FEATURE_STORE); executeQuery(geoserverDataStore, wfsDataStore); }
From source file:dhtaccess.tools.Put.java
public static void main(String[] args) { byte[] secret = null; int ttl = 3600; // parse properties Properties prop = System.getProperties(); String gateway = prop.getProperty("dhtaccess.gateway"); if (gateway == null || gateway.length() <= 0) { gateway = DEFAULT_GATEWAY;/*from ww w . j ava2 s . c om*/ } // parse options Options options = new Options(); options.addOption("h", "help", false, "print help"); options.addOption("g", "gateway", true, "gateway URI, list at http://opendht.org/servers.txt"); options.addOption("s", "secret", true, "can be used to remove the value later"); options.addOption("t", "ttl", true, "how long (in seconds) to store the value"); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println("There is an invalid option."); e.printStackTrace(); System.exit(1); } String optVal; if (cmd.hasOption('h')) { usage(COMMAND); System.exit(1); } optVal = cmd.getOptionValue('g'); if (optVal != null) { gateway = optVal; } optVal = cmd.getOptionValue('s'); if (optVal != null) { try { secret = optVal.getBytes(ENCODE); } catch (UnsupportedEncodingException e) { // NOTREACHED } } optVal = cmd.getOptionValue('t'); if (optVal != null) { ttl = Integer.parseInt(optVal); } args = cmd.getArgs(); // parse arguments if (args.length < 2) { usage(COMMAND); System.exit(1); } for (int index = 0; index + 1 < args.length; index += 2) { byte[] key = null, value = null; try { key = args[index].getBytes(ENCODE); value = args[index + 1].getBytes(ENCODE); } catch (UnsupportedEncodingException e1) { // NOTREACHED } // prepare for RPC DHTAccessor accessor = null; try { accessor = new DHTAccessor(gateway); } catch (MalformedURLException e) { e.printStackTrace(); System.exit(1); } // RPC int res = accessor.put(key, value, ttl, secret); String resultString; switch (res) { case 0: resultString = "Success"; break; case 1: resultString = "Capacity"; break; case 2: resultString = "Again"; break; default: resultString = "???"; } System.out.println(resultString + ": " + args[index] + ", " + args[index + 1]); } }
From source file:com.aleggeup.util.App.java
public static void main(final String[] args) { final CommandLineParser parser = new PosixParser(); final Options options = buildOptions(); File sourceFile = null;// w w w . j ava 2 s . c o m File targetFile = null; try { final CommandLine commandLine = parser.parse(options, args); if (commandLine.getOptions().length == 0 || commandLine.hasOption('h')) { printHelp(options); System.exit(0); } if (commandLine.hasOption('s')) { sourceFile = new File(commandLine.getOptionValue('s')).getCanonicalFile(); } if (commandLine.hasOption('t')) { targetFile = new File(commandLine.getOptionValue('t')).getCanonicalFile(); } } catch (final ParseException e) { printHelp(options); System.exit(-1); } catch (final IOException e) { e.printStackTrace(); } }
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"; }// w w w . jav a 2s . c o 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:illarion.compile.Compiler.java
public static void main(final String[] args) { ByteArrayOutputStream stdOutBuffer = new ByteArrayOutputStream(); PrintStream orgStdOut = System.out; System.setOut(new PrintStream(stdOutBuffer)); SLF4JBridgeHandler.removeHandlersForRootLogger(); SLF4JBridgeHandler.install();//from w w w .j a va 2s. co m Options options = new Options(); final Option npcDir = new Option("n", "npc-dir", true, "The place where the compiled NPC files are stored."); npcDir.setArgs(1); npcDir.setArgName("directory"); npcDir.setRequired(false); options.addOption(npcDir); final Option questDir = new Option("q", "quest-dir", true, "The place where the compiled Quest files are stored."); questDir.setArgs(1); questDir.setArgName("directory"); questDir.setRequired(false); options.addOption(questDir); final Option type = new Option("t", "type", true, "This option is used to set what kind of parser is supposed to be used in case" + " the content of standard input is processed."); type.setArgs(1); type.setArgName("type"); type.setRequired(false); options.addOption(type); CommandLineParser parser = new GnuParser(); try { CommandLine cmd = parser.parse(options, args); String[] files = cmd.getArgs(); if (files.length > 0) { System.setOut(orgStdOut); stdOutBuffer.writeTo(orgStdOut); processFileMode(cmd); } else { System.setOut(orgStdOut); processStdIn(cmd); } } catch (final ParseException e) { final HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("java -jar compiler.jar [Options] File", options, true); System.exit(-1); } catch (final IOException e) { LOGGER.error(e.getLocalizedMessage()); System.exit(-1); } }