List of usage examples for org.apache.commons.cli CommandLine hasOption
public boolean hasOption(char opt)
From source file:com.google.cloud.speech.grpc.demos.NonStreamingRecognizeClient.java
public static void main(String[] args) throws Exception { String audioFile = ""; String host = "speech.googleapis.com"; Integer port = 443;/* w ww. ja va 2 s . c o m*/ Integer sampling = 16000; CommandLineParser parser = new DefaultParser(); Options options = new Options(); options.addOption(OptionBuilder.withLongOpt("uri").withDescription("path to audio uri").hasArg() .withArgName("FILE_PATH").create()); options.addOption( OptionBuilder.withLongOpt("host").withDescription("endpoint for api, e.g. speech.googleapis.com") .hasArg().withArgName("ENDPOINT").create()); options.addOption(OptionBuilder.withLongOpt("port").withDescription("SSL port, usually 443").hasArg() .withArgName("PORT").create()); options.addOption(OptionBuilder.withLongOpt("sampling").withDescription("Sampling Rate, i.e. 16000") .hasArg().withArgName("RATE").create()); try { CommandLine line = parser.parse(options, args); if (line.hasOption("uri")) { audioFile = line.getOptionValue("uri"); } else { System.err.println("An Audio uri must be specified (e.g. file:///foo/baz.raw)."); System.exit(1); } if (line.hasOption("host")) { host = line.getOptionValue("host"); } else { System.err.println("An API enpoint must be specified (typically speech.googleapis.com)."); System.exit(1); } if (line.hasOption("port")) { port = Integer.parseInt(line.getOptionValue("port")); } else { System.err.println("An SSL port must be specified (typically 443)."); System.exit(1); } if (line.hasOption("sampling")) { sampling = Integer.parseInt(line.getOptionValue("sampling")); } else { System.err.println("An Audio sampling rate must be specified."); System.exit(1); } } catch (ParseException exp) { System.err.println("Unexpected exception:" + exp.getMessage()); System.exit(1); } NonStreamingRecognizeClient client = new NonStreamingRecognizeClient(host, port, URI.create(audioFile), sampling); try { client.recognize(); } finally { client.shutdown(); } }
From source file:com.datatorrent.stram.StreamingAppMaster.java
/** * @param args/*from w ww .j av a 2s.c o m*/ * Command line args * @throws Throwable */ public static void main(final String[] args) throws Throwable { StdOutErrLog.tieSystemOutAndErrToLog(); LOG.info("Master starting with classpath: {}", System.getProperty("java.class.path")); LOG.info("version: {}", VersionInfo.APEX_VERSION.getBuildVersion()); StringWriter sw = new StringWriter(); for (Map.Entry<String, String> e : System.getenv().entrySet()) { sw.append("\n").append(e.getKey()).append("=").append(e.getValue()); } LOG.info("appmaster env:" + sw.toString()); Options opts = new Options(); opts.addOption("app_attempt_id", true, "App Attempt ID. Not to be used unless for testing purposes"); opts.addOption("help", false, "Print usage"); CommandLine cliParser = new GnuParser().parse(opts, args); // option "help" overrides and cancels any run if (cliParser.hasOption("help")) { new HelpFormatter().printHelp("ApplicationMaster", opts); return; } Map<String, String> envs = System.getenv(); ApplicationAttemptId appAttemptID = Records.newRecord(ApplicationAttemptId.class); if (!envs.containsKey(Environment.CONTAINER_ID.name())) { if (cliParser.hasOption("app_attempt_id")) { String appIdStr = cliParser.getOptionValue("app_attempt_id", ""); appAttemptID = ConverterUtils.toApplicationAttemptId(appIdStr); } else { throw new IllegalArgumentException("Application Attempt Id not set in the environment"); } } else { ContainerId containerId = ConverterUtils.toContainerId(envs.get(Environment.CONTAINER_ID.name())); appAttemptID = containerId.getApplicationAttemptId(); } boolean result = false; StreamingAppMasterService appMaster = null; try { appMaster = new StreamingAppMasterService(appAttemptID); LOG.info("Initializing Application Master."); Configuration conf = new YarnConfiguration(); appMaster.init(conf); appMaster.start(); result = appMaster.run(); } catch (Throwable t) { LOG.error("Exiting Application Master", t); System.exit(1); } finally { if (appMaster != null) { appMaster.stop(); } } if (result) { LOG.info("Application Master completed."); System.exit(0); } else { LOG.info("Application Master failed."); System.exit(2); } }
From source file:com.flaptor.indextank.storage.IndexesLogServer.java
public static void main(String[] args) throws IOException, InterruptedException { // create the parser CommandLineParser parser = new PosixParser(); int readerPort, managerPort; try {//from w w w . j av a2s.c o m // parse the command line arguments CommandLine line = parser.parse(getOptions(), args); if (line.hasOption("help")) { printHelp(getOptions(), null); System.exit(1); return; } String val = null; val = line.getOptionValue("reader_port", null); if (null != val) { readerPort = Integer.valueOf(val); } else { printHelp(getOptions(), "Must specify a server port"); System.exit(1); return; } val = null; val = line.getOptionValue("manager_port", null); if (null != val) { managerPort = Integer.valueOf(val); } else { printHelp(getOptions(), "Must specify a server port"); System.exit(1); return; } } catch (ParseException exp) { printHelp(getOptions(), exp.getMessage()); System.exit(1); return; } new IndexesLogServer(readerPort, managerPort).start(); }
From source file:com.haulmont.yarg.console.ConsoleRunner.java
public static void main(String[] args) { Options options = createOptions();//from w ww . ja v a 2 s .co m CommandLineParser parser = new PosixParser(); CommandLine cmd; try { cmd = parser.parse(options, args); if (!cmd.hasOption(REPORT_PATH) || !cmd.hasOption(OUTPUT_PATH)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("report", options); System.exit(-1); } String templateCode = cmd.getOptionValue(TEMPLATE_CODE, ReportTemplate.DEFAULT_TEMPLATE_CODE); PropertiesLoader propertiesLoader = new DefaultPropertiesLoader( cmd.getOptionValue(PROPERTIES_PATH, DefaultPropertiesLoader.DEFAULT_PROPERTIES_PATH)); Reporting reporting = createReportingEngine(propertiesLoader); XmlReader xmlReader = new DefaultXmlReader(); Report report = xmlReader .parseXml(FileUtils.readFileToString(new File(cmd.getOptionValue(REPORT_PATH)))); Map<String, Object> params = parseReportParams(cmd, report); reporting.runReport(new RunParams(report).templateCode(templateCode).params(params), new FileOutputStream(cmd.getOptionValue(OUTPUT_PATH))); if (doExitWhenFinished) { System.exit(0); } } catch (Exception e) { e.printStackTrace(); if (doExitWhenFinished) { System.exit(-1); } } }
From source file:jlite.cli.JobCancel.java
public static void main(String[] args) { System.out.println(); // extra line CommandLineParser parser = new GnuParser(); Options options = setupOptions();/* w w w . j a va 2s . co m*/ HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.setSyntaxPrefix("Usage: "); CommandLine line = null; try { line = parser.parse(options, args); if (line.hasOption("help")) { helpFormatter.printHelp(100, COMMAND, "\noptions:", options, "\n" + CLI.FOOTER, false); System.out.println(); // extra line System.exit(0); } else { if (line.hasOption("xml")) { System.out.println("<output>"); } run(line.getArgs(), line); } } catch (ParseException e) { System.err.println(e.getMessage() + "\n"); helpFormatter.printHelp(100, COMMAND, "\noptions:", options, "\n" + CLI.FOOTER, false); System.out.println(); // extra line System.exit(-1); } catch (Exception e) { if (line.hasOption("xml")) { System.out.println("<error>" + e.getMessage() + "</error>"); } else { System.err.println(e.getMessage()); } } finally { if (line.hasOption("xml")) { System.out.println("</output>"); } } System.out.println(); // extra line }
From source file:bboss.org.artofsolving.jodconverter.cli.Convert.java
public static void main(String[] arguments) throws ParseException, JSONException, IOException { CommandLineParser commandLineParser = new PosixParser(); CommandLine commandLine = commandLineParser.parse(OPTIONS, arguments); String outputFormat = null;//w w w . ja v a 2 s . c o m if (commandLine.hasOption(OPTION_OUTPUT_FORMAT.getOpt())) { outputFormat = commandLine.getOptionValue(OPTION_OUTPUT_FORMAT.getOpt()); } int port = DEFAULT_OFFICE_PORT; if (commandLine.hasOption(OPTION_PORT.getOpt())) { port = Integer.parseInt(commandLine.getOptionValue(OPTION_PORT.getOpt())); } String[] fileNames = commandLine.getArgs(); if ((outputFormat == null && fileNames.length != 2) || fileNames.length < 1) { String syntax = "java -jar jodconverter-core.jar [options] input-file output-file\n" + "or [options] -o output-format input-file [input-file...]"; HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp(syntax, OPTIONS); System.exit(STATUS_INVALID_ARGUMENTS); } DocumentFormatRegistry registry; if (commandLine.hasOption(OPTION_REGISTRY.getOpt())) { File registryFile = new File(commandLine.getOptionValue(OPTION_REGISTRY.getOpt())); registry = new JsonDocumentFormatRegistry(FileUtils.readFileToString(registryFile)); } else { registry = new DefaultDocumentFormatRegistry(); } DefaultOfficeManagerConfiguration configuration = new DefaultOfficeManagerConfiguration(); configuration.setPortNumber(port); if (commandLine.hasOption(OPTION_TIMEOUT.getOpt())) { int timeout = Integer.parseInt(commandLine.getOptionValue(OPTION_TIMEOUT.getOpt())); configuration.setTaskExecutionTimeout(timeout * 1000); } if (commandLine.hasOption(OPTION_USER_PROFILE.getOpt())) { String templateProfileDir = commandLine.getOptionValue(OPTION_USER_PROFILE.getOpt()); configuration.setTemplateProfileDir(new File(templateProfileDir)); } OfficeManager officeManager = configuration.buildOfficeManager(); officeManager.start(); OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager, registry); try { if (outputFormat == null) { File inputFile = new File(fileNames[0]); File outputFile = new File(fileNames[1]); converter.convert(inputFile, outputFile); } else { for (int i = 0; i < fileNames.length; i++) { File inputFile = new File(fileNames[i]); String outputName = FilenameUtils.getBaseName(fileNames[i]) + "." + outputFormat; File outputFile = new File(FilenameUtils.getFullPath(fileNames[i]) + outputName); converter.convert(inputFile, outputFile); } } } finally { officeManager.stop(); } }
From source file:com.linkedin.helix.tools.ZKDumper.java
public static void main(String[] args) throws Exception { if (args == null || args.length == 0) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("java " + ZKDumper.class.getName(), options); System.exit(1);//ww w .j a v a 2s.c om } CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); cmd.hasOption("zkSvr"); boolean download = cmd.hasOption("download"); boolean upload = cmd.hasOption("upload"); boolean del = cmd.hasOption("delete"); String zkAddress = cmd.getOptionValue("zkSvr"); String zkPath = cmd.getOptionValue("zkpath"); String fsPath = cmd.getOptionValue("fspath"); ZKDumper zkDump = new ZKDumper(zkAddress); if (download) { if (cmd.hasOption("addSuffix")) { zkDump.suffix = cmd.getOptionValue("addSuffix"); } zkDump.download(zkPath, fsPath + zkPath); } if (upload) { if (cmd.hasOption("removeSuffix")) { zkDump.removeSuffix = true; } zkDump.upload(zkPath, fsPath); } if (del) { zkDump.delete(zkPath); } }
From source file:name.wagners.fssp.Main.java
/** * @param args// ww w. ja v a2 s. c o m * command-line arguments */ public static void main(final String[] args) { // create the command line parser CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); options.addOption(OptionBuilder.hasArg().withArgName("gn").withLongOpt("generations") .withDescription("Number of generations [default: 50]").withType(Integer.valueOf(0)).create("g")); options.addOption(OptionBuilder.hasArg().withArgName("mp").withLongOpt("mutation") .withDescription("Mutation propability [default: 0.5]").withType(Double.valueOf(0)).create("m")); options.addOption(OptionBuilder.hasArg().withArgName("ps").withLongOpt("populationsize") .withDescription("Size of population [default: 20]").withType(Integer.valueOf(0)).create("p")); options.addOption(OptionBuilder.hasArg().withArgName("rp").withLongOpt("recombination") .withDescription("Recombination propability [default: 0.8]").withType(Double.valueOf(0)) .create("r")); options.addOption(OptionBuilder.hasArg().withArgName("sp").withLongOpt("selectionpressure") .withDescription("Selection pressure [default: 4]").withType(Integer.valueOf(0)).create("s")); options.addOption(OptionBuilder.withLongOpt("help").withDescription("print this message").create("h")); options.addOption(OptionBuilder.hasArg().withArgName("filename").isRequired().withLongOpt("file") .withDescription("Problem file [default: \"\"]").withType(String.valueOf("")).create("f")); options.addOptionGroup(new OptionGroup() .addOption(OptionBuilder.withLongOpt("verbose").withDescription("be extra verbose").create("v")) .addOption(OptionBuilder.withLongOpt("quiet").withDescription("be extra quiet").create("q"))); options.addOption(OptionBuilder.withLongOpt("version") .withDescription("print the version information and exit").create("V")); try { // parse the command line arguments CommandLine line = parser.parse(options, args); // validate that block-size has been set if (line.hasOption("h")) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fssp", options); } } catch (MissingOptionException exp) { log.info("An option was missing:" + exp.getMessage(), exp); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fssp", options); } catch (MissingArgumentException exp) { log.info("An argument was missing:" + exp.getMessage(), exp); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fssp", options); } catch (AlreadySelectedException exp) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fssp", options); } catch (ParseException exp) { log.info("Unexpected exception:" + exp.getMessage(), exp); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fssp", options); System.exit(1); } // Ausgabe der eingestellten Optionen log.info("Configuration"); // log.info(" Datafile: {}", fname); }
From source file:fr.inria.edelweiss.kgdqp.core.FedQueryingCLI.java
@SuppressWarnings("unchecked") public static void main(String args[]) throws ParseException, EngineException { List<String> endpoints = new ArrayList<String>(); String queryPath = null;/* w w w. j ava 2s .com*/ int slice = -1; Options options = new Options(); Option helpOpt = new Option("h", "help", false, "print this message"); Option queryOpt = new Option("q", "query", true, "specify the sparql query file"); Option endpointOpt = new Option("e", "endpoints", true, "the list of federated sparql endpoint URLs"); Option groupingOpt = new Option("g", "grouping", true, "triple pattern optimisation"); Option slicingOpt = new Option("s", "slicing", true, "size of the slicing parameter"); Option versionOpt = new Option("v", "version", false, "print the version information and exit"); options.addOption(queryOpt); options.addOption(endpointOpt); options.addOption(helpOpt); options.addOption(versionOpt); options.addOption(groupingOpt); options.addOption(slicingOpt); String header = "Corese/KGRAM DQP command line interface"; String footer = "\nPlease report any issue to alban.gaignard@cnrs.fr"; CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("kgdqp", header, options, footer, true); System.exit(0); } if (!cmd.hasOption("e")) { logger.info("You must specify at least the URL of one sparql endpoint !"); System.exit(0); } else { endpoints = new ArrayList<String>(Arrays.asList(cmd.getOptionValues("e"))); } if (!cmd.hasOption("q")) { logger.info("You must specify a path for a sparql query !"); System.exit(0); } else { queryPath = cmd.getOptionValue("q"); } if (cmd.hasOption("s")) { try { slice = Integer.parseInt(cmd.getOptionValue("s")); } catch (NumberFormatException ex) { logger.warn(cmd.getOptionValue("s") + " is not formatted as number for the slicing parameter"); logger.warn("Slicing disabled"); } } if (cmd.hasOption("v")) { logger.info("version 3.0.4-SNAPSHOT"); System.exit(0); } ///////////////// Graph graph = Graph.create(); QueryProcessDQP exec = QueryProcessDQP.create(graph); exec.setGroupingEnabled(cmd.hasOption("g")); if (slice > 0) { exec.setSlice(slice); } Provider sProv = ProviderImplCostMonitoring.create(); exec.set(sProv); for (String url : endpoints) { try { exec.addRemote(new URL(url), WSImplem.REST); } catch (MalformedURLException ex) { logger.error(url + " is not a well-formed URL"); System.exit(1); } } StringBuffer fileData = new StringBuffer(1000); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(queryPath)); } catch (FileNotFoundException ex) { logger.error("Query file " + queryPath + " not found !"); System.exit(1); } char[] buf = new char[1024]; int numRead = 0; try { while ((numRead = reader.read(buf)) != -1) { String readData = String.valueOf(buf, 0, numRead); fileData.append(readData); buf = new char[1024]; } reader.close(); } catch (IOException ex) { logger.error("Error while reading query file " + queryPath); System.exit(1); } String sparqlQuery = fileData.toString(); // Query q = exec.compile(sparqlQuery, null); // System.out.println(q); StopWatch sw = new StopWatch(); sw.start(); Mappings map = exec.query(sparqlQuery); int dqpSize = map.size(); System.out.println("--------"); long time = sw.getTime(); System.out.println(time + " " + dqpSize); }
From source file:BasApp.java
public static void main(String[] args) throws Exception { Options options = getOptions();/*from w ww . j a v a2 s . c o m*/ CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { showHelp(options); return; // only show help and exit } final VOConfig cfg; if (cmd.hasOption("config")) { Serializer serializer = new Persister(); final String config = cmd.getOptionValue("config"); FileInputStream fis = new FileInputStream(config); cfg = serializer.read(VOConfig.class, fis); fis.close(); } else { cfg = new VOConfig(); } cfg.setCmd(cmd); CipherProvider dataCipherProvider = new CipherProvider(); dataCipherProvider.setPassword(cmd.getOptionValue("passwd", null)); CipherProvider metaCipherProvider = new CipherProvider(); metaCipherProvider.setPassword(cmd.getOptionValue("passwd-meta", null)); String repoPathStr = cfg.getRepository(); Repository repository = new Repository(repoPathStr, dataCipherProvider, metaCipherProvider); if (cmd.hasOption("dump-config")) { Serializer serializer = new Persister(); final FileOutputStream fos = new FileOutputStream(cmd.getOptionValue("dump-config")); serializer.write(cfg, fos); fos.close(); } if (cmd.hasOption("backup")) { BackupService backup = new BackupService(cfg, repository); backup.run(); } if (cmd.hasOption("restore")) { //noinspection unchecked String restoreTo = null; if (cmd.hasOption("restore-to")) { restoreTo = cmd.getOptionValue("restore-to"); } RestoreService restore = new RestoreService(cmd.getOptionValue("r"), repository, cmd.getArgList(), restoreTo); restore.run(); } if (cmd.hasOption("check")) { CheckService check = new CheckService(cmd.getOptionValue("check"), repository); check.run(); } }