List of usage examples for org.apache.commons.cli CommandLine getOptionValue
public String getOptionValue(char opt)
From source file:edu.washington.data.sentimentreebank.StanfordNLPDict.java
public static void main(String args[]) { Options options = new Options(); options.addOption("d", "dict", true, "dictionary file."); options.addOption("s", "sentiment", true, "sentiment value file."); CommandLineParser parser = new GnuParser(); try {// ww w . ja va2 s .c o m CommandLine line = parser.parse(options, args); if (!line.hasOption("dict") && !line.hasOption("sentiment")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("StanfordNLPDict", options); return; } Path dictPath = Paths.get(line.getOptionValue("dict")); Path sentimentPath = Paths.get(line.getOptionValue("sentiment")); StanfordNLPDict snlp = new StanfordNLPDict(dictPath, sentimentPath); String sentence = "take off"; System.out.printf("sentence [%1$s] %2$s\n", sentence, String.valueOf(snlp.getPhraseSentiment(sentence))); } catch (ParseException exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("StanfordNLPDict", options); } catch (IOException ex) { Logger.getLogger(StanfordNLPDict.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:edu.cmu.lti.oaqa.knn4qa.apps.QueryGenNMSLIB.java
public static void main(String[] args) { Options options = new Options(); options.addOption(CommonParams.QUERY_FILE_PARAM, null, true, CommonParams.QUERY_FILE_DESC); options.addOption(CommonParams.MEMINDEX_PARAM, null, true, CommonParams.MEMINDEX_DESC); options.addOption(CommonParams.KNN_QUERIES_PARAM, null, true, CommonParams.KNN_QUERIES_DESC); options.addOption(CommonParams.NMSLIB_FIELDS_PARAM, null, true, CommonParams.NMSLIB_FIELDS_DESC); options.addOption(CommonParams.MAX_NUM_QUERY_PARAM, null, true, CommonParams.MAX_NUM_QUERY_DESC); options.addOption(CommonParams.SEL_PROB_PARAM, null, true, CommonParams.SEL_PROB_DESC); CommandLineParser parser = new org.apache.commons.cli.GnuParser(); BufferedWriter knnQueries = null; int maxNumQuery = Integer.MAX_VALUE; Float selProb = null;// w ww.ja va 2s .c om try { CommandLine cmd = parser.parse(options, args); String queryFile = null; if (cmd.hasOption(CommonParams.QUERY_FILE_PARAM)) { queryFile = cmd.getOptionValue(CommonParams.QUERY_FILE_PARAM); } else { Usage("Specify 'query file'", options); } String knnQueriesFile = cmd.getOptionValue(CommonParams.KNN_QUERIES_PARAM); if (null == knnQueriesFile) Usage("Specify '" + CommonParams.KNN_QUERIES_DESC + "'", options); String tmpn = cmd.getOptionValue(CommonParams.MAX_NUM_QUERY_PARAM); if (tmpn != null) { try { maxNumQuery = Integer.parseInt(tmpn); } catch (NumberFormatException e) { Usage("Maximum number of queries isn't integer: '" + tmpn + "'", options); } } String tmps = cmd.getOptionValue(CommonParams.NMSLIB_FIELDS_PARAM); if (null == tmps) Usage("Specify '" + CommonParams.NMSLIB_FIELDS_DESC + "'", options); String nmslibFieldList[] = tmps.split(","); knnQueries = new BufferedWriter(new FileWriter(knnQueriesFile)); knnQueries.write("isQueryFile=1"); knnQueries.newLine(); knnQueries.newLine(); String memIndexPref = cmd.getOptionValue(CommonParams.MEMINDEX_PARAM); if (null == memIndexPref) { Usage("Specify '" + CommonParams.MEMINDEX_DESC + "'", options); } String tmpf = cmd.getOptionValue(CommonParams.SEL_PROB_PARAM); if (tmpf != null) { try { selProb = Float.parseFloat(tmpf); } catch (NumberFormatException e) { Usage("A selection probability isn't a number in the range (0,1)'" + tmpf + "'", options); } if (selProb < Float.MIN_NORMAL || selProb + Float.MIN_NORMAL >= 1) Usage("A selection probability isn't a number in the range (0,1)'" + tmpf + "'", options); } BufferedReader inpText = new BufferedReader( new InputStreamReader(CompressUtils.createInputStream(queryFile))); String docText = XmlHelper.readNextXMLIndexEntry(inpText); NmslibQueryGenerator queryGen = new NmslibQueryGenerator(nmslibFieldList, memIndexPref); Random rnd = new Random(); for (int docNum = 1; docNum <= maxNumQuery && docText != null; ++docNum, docText = XmlHelper.readNextXMLIndexEntry(inpText)) { if (selProb != null) { if (rnd.nextFloat() > selProb) continue; } Map<String, String> docFields = null; try { docFields = XmlHelper.parseXMLIndexEntry(docText); String queryObjStr = queryGen.getStrObjForKNNService(docFields); knnQueries.append(queryObjStr); knnQueries.newLine(); } catch (SAXException e) { System.err.println("Parsing error, offending DOC:" + NL + docText + " doc # " + docNum); throw new Exception("Parsing error."); } } knnQueries.close(); } catch (ParseException e) { Usage("Cannot parse arguments", options); if (null != knnQueries) try { knnQueries.close(); } catch (IOException e1) { e1.printStackTrace(); } } catch (Exception e) { System.err.println("Terminating due to an exception: " + e); try { if (knnQueries != null) knnQueries.close(); } catch (IOException e1) { e1.printStackTrace(); } System.exit(1); } System.out.println("Terminated successfully!"); }
From source file:edu.usc.pgroup.floe.client.commands.KillApp.java
/** * Entry point for Scale command.// w ww .j a v a 2 s .c om * @param args command line arguments sent by the floe.py script. */ public static void main(final String[] args) { Options options = new Options(); Option appOption = OptionBuilder.withArgName("name").hasArg().isRequired() .withDescription("Application Name").create("app"); options.addOption(appOption); CommandLineParser parser = new BasicParser(); CommandLine line; try { line = parser.parse(options, args); } catch (ParseException e) { LOGGER.error("Invalid command: " + e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("scale options", options); return; } String app = line.getOptionValue("app"); LOGGER.info("Application: {}", app); try { FloeClient.getInstance().killApp(app); } catch (TException e) { LOGGER.error("Error while connecting to the coordinator: {}", e); } }
From source file:io.github.azige.whitespace.Cli.java
public static void main(String[] args) { Options options = new Options().addOption("h", "help", false, "??") .addOptionGroup(new OptionGroup() .addOption(new Option("p", "????????")) .addOption(new Option("c", "?????"))) .addOption(null, "szm", false, "????") .addOption("e", "encoding", true, "??" + DEFAULT_ENCODING); try {/* w w w . j a va2 s . com*/ CommandLineParser parser = new BasicParser(); CommandLine cl = parser.parse(options, args); if (cl.hasOption('h')) { printHelp(System.out, options); return; } if (cl.hasOption('e')) { encoding = Charset.forName(cl.getOptionValue('e')); } else { encoding = Charset.forName(DEFAULT_ENCODING); } if (cl.hasOption("szm")) { useSzm = true; } String[] fileArgs = cl.getArgs(); if (fileArgs.length != 1) { printHelp(System.err, options); return; } try (InputStream input = Files.newInputStream(Paths.get(fileArgs[0]))) { if (cl.hasOption('p')) { printPseudoCode(input); } else if (cl.hasOption('c')) { compile(input, fileArgs[0]); } else { execute(input, fileArgs[0]); } } } catch (ParseException ex) { ex.printStackTrace(); printHelp(System.err, options); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:com.adavr.player.Launcher.java
public static void main(String[] args) { CommandLine cl; try {/*from w w w. j a va2 s.com*/ cl = new BasicParser().parse(OPTIONS, args); } catch (ParseException ex) { showUsage(); return; } if (cl.hasOption("help")) { showUsage(); return; } ApplicationContext appCtx = (ApplicationContext) loadClass(cl.getOptionValue("context")); if (appCtx == null) { System.out.println("Failed to load App Context"); appCtx = new VLCApplication(); } if (cl.hasOption("source")) { String src = cl.getOptionValue("source"); appCtx.getMediaContext().setMedia(src); } Application application = new Application(appCtx); application.setVSync(cl.hasOption("vsync")); if (cl.hasOption("factory")) { String className = cl.getOptionValue("factory"); HMDRenderContextFactory factory = (HMDRenderContextFactory) loadClass(className); if (factory != null) { application.setHMDRenderContextFactory(factory); } } application.run(); }
From source file:com.linkedin.helix.examples.BootstrapProcess.java
public static void main(String[] args) throws Exception { String zkConnectString = "localhost:2181"; String clusterName = "storage-integration-cluster"; String instanceName = "localhost_8905"; String file = null;/* w w w. j av a 2s . com*/ String stateModelValue = "MasterSlave"; int delay = 0; boolean skipZeroArgs = true;// false is for dev testing if (!skipZeroArgs || args.length > 0) { CommandLine cmd = processCommandLineArgs(args); zkConnectString = cmd.getOptionValue(zkServer); clusterName = cmd.getOptionValue(cluster); String host = cmd.getOptionValue(hostAddress); String portString = cmd.getOptionValue(hostPort); int port = Integer.parseInt(portString); instanceName = host + "_" + port; file = cmd.getOptionValue(configFile); if (file != null) { File f = new File(file); if (!f.exists()) { System.err.println("static config file doesn't exist"); System.exit(1); } } stateModelValue = cmd.getOptionValue(stateModel); if (cmd.hasOption(transDelay)) { try { delay = Integer.parseInt(cmd.getOptionValue(transDelay)); if (delay < 0) { throw new Exception("delay must be positive"); } } catch (Exception e) { e.printStackTrace(); delay = 0; } } } // Espresso_driver.py will consume this System.out.println("Starting Process with ZK:" + zkConnectString); BootstrapProcess process = new BootstrapProcess(zkConnectString, clusterName, instanceName, file, stateModelValue, delay); process.start(); Thread.currentThread().join(); }
From source file:com.cws.esolutions.core.main.EmailUtility.java
public static final void main(final String[] args) { final String methodName = EmailUtility.CNAME + "#main(final String[] args)"; if (DEBUG) {/* ww w.j a v a2 s .c o m*/ DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", (Object) args); } if (args.length == 0) { HelpFormatter usage = new HelpFormatter(); usage.printHelp(EmailUtility.CNAME, options, true); return; } try { CommandLineParser parser = new PosixParser(); CommandLine commandLine = parser.parse(options, args); URL xmlURL = null; JAXBContext context = null; Unmarshaller marshaller = null; CoreConfigurationData configData = null; xmlURL = FileUtils.getFile(commandLine.getOptionValue("config")).toURI().toURL(); context = JAXBContext.newInstance(CoreConfigurationData.class); marshaller = context.createUnmarshaller(); configData = (CoreConfigurationData) marshaller.unmarshal(xmlURL); EmailMessage message = new EmailMessage(); message.setMessageTo(new ArrayList<String>(Arrays.asList(commandLine.getOptionValues("to")))); message.setMessageSubject(commandLine.getOptionValue("subject")); message.setMessageBody((String) commandLine.getArgList().get(0)); message.setEmailAddr((StringUtils.isNotEmpty(commandLine.getOptionValue("from"))) ? new ArrayList<String>(Arrays.asList(commandLine.getOptionValue("from"))) : new ArrayList<String>(Arrays.asList(configData.getMailConfig().getMailFrom()))); if (DEBUG) { DEBUGGER.debug("EmailMessage: {}", message); } try { EmailUtils.sendEmailMessage(configData.getMailConfig(), message, false); } catch (MessagingException mx) { System.err.println( "An error occurred while sending the requested message. Exception: " + mx.getMessage()); } } catch (ParseException px) { px.printStackTrace(); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(EmailUtility.CNAME, options, true); } catch (MalformedURLException mx) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(EmailUtility.CNAME, options, true); } catch (JAXBException jx) { jx.printStackTrace(); System.err.println("An error occurred while loading the provided configuration file. Cannot continue."); } }
From source file:com.discursive.jccook.cmdline.CliBasicExample.java
public static void main(String[] args) throws Exception { CommandLineParser parser = new BasicParser(); Options options = new Options(); options.addOption("h", "help", false, "Print this usage information"); options.addOption("v", "verbose", false, "Print out VERBOSE debugging information"); options.addOption("f", "file", true, "File to save program output to"); CommandLine commandLine = parser.parse(options, args); boolean verbose = false; String file = ""; if (commandLine.hasOption('h')) { System.out.println("Help Message"); System.exit(0);/* w ww . j av a 2 s . c o m*/ } if (commandLine.hasOption('v')) { verbose = true; } if (commandLine.hasOption('f')) { file = commandLine.getOptionValue('f'); } System.exit(0); }
From source file:at.ac.tuwien.dsg.comot.m.adapter.Main.java
public static void main(String[] args) { Options options = createOptions();// w w w .j a va 2s. c om try { CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("mh") && cmd.hasOption("ih") && cmd.hasOption("ip")) { Integer infoPort = null; try { infoPort = new Integer(cmd.getOptionValue("ip")); } catch (NumberFormatException e) { LOG.warn("infoPort must be a number"); showHelp(options); } AppContextAdapter.setBrokerHost(cmd.getOptionValue("mh")); AppContextAdapter.setInfoHost(cmd.getOptionValue("ih")); AppContextAdapter.setInfoPort(infoPort); context = new AnnotationConfigApplicationContext(AppContextAdapter.class); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { if (context != null) { context.close(); } } }); if (cmd.hasOption("m") || cmd.hasOption("r") || cmd.hasOption("s")) { Manager manager = context.getBean(EpsAdapterManager.class); String serviceId = getServiceInstanceId(); String participantId = context.getBean(InfoClient.class).getOsuInstanceByServiceId(serviceId) .getId(); if (cmd.hasOption("m")) { Monitoring processor = context.getBean(Monitoring.class); manager.start(participantId, processor); } else if (cmd.hasOption("r")) { Control processor = context.getBean(Control.class); manager.start(participantId, processor); } else if (cmd.hasOption("s")) { Deployment processor = context.getBean(Deployment.class); manager.start(participantId, processor); } } else { LOG.warn("No adapter type specified"); showHelp(options); } } else { LOG.warn("Required parameters were not specified."); showHelp(options); } } catch (Exception e) { LOG.error("{}", e); showHelp(options); } }
From source file:com.act.lcms.v2.fullindex.Searcher.java
public static void main(String args[]) throws Exception { CLIUtil cliUtil = new CLIUtil(Searcher.class, HELP_MESSAGE, OPTION_BUILDERS); CommandLine cl = cliUtil.parseCommandLine(args); File indexDir = new File(cl.getOptionValue(OPTION_INDEX_PATH)); if (!indexDir.exists() || !indexDir.isDirectory()) { cliUtil.failWithMessage("Unable to read index directory at %s", indexDir.getAbsolutePath()); }/* www .j a v a 2 s . c o m*/ if (!cl.hasOption(OPTION_MZ_RANGE) && !cl.hasOption(OPTION_TIME_RANGE)) { cliUtil.failWithMessage( "Extracting all readings is not currently supported; specify an m/z or time range"); } Pair<Double, Double> mzRange = extractRange(cl.getOptionValue(OPTION_MZ_RANGE)); Pair<Double, Double> timeRange = extractRange(cl.getOptionValue(OPTION_TIME_RANGE)); Searcher searcher = Factory.makeSearcher(indexDir); List<TMzI> results = searcher.searchIndexInRange(mzRange, timeRange); if (cl.hasOption(OPTION_OUTPUT_FILE)) { try (PrintWriter writer = new PrintWriter(new FileWriter(cl.getOptionValue(OPTION_OUTPUT_FILE)))) { Searcher.writeOutput(writer, results); } } else { // Don't close the print writer if we're writing to stdout. Searcher.writeOutput(new PrintWriter(new OutputStreamWriter(System.out)), results); } LOGGER.info("Done"); }