List of usage examples for org.apache.commons.cli Parser parse
public CommandLine parse(Options options, String[] arguments) throws ParseException
arguments
based on the specifed Options . From source file:de.stz.bt.nanopubsub.StandaloneBroker.java
/** * Main Method for running the standalone Broker * /* w ww . java 2s . com*/ * @param args * @author jseitter */ public static void main(String[] args) { Options options = new Options(); options.addOption( OptionBuilder.hasArg(true).withArgName("port").withDescription("broker port number").create('p')); Parser parser = new PosixParser(); CommandLine cmdLine = null; try { cmdLine = parser.parse(options, args); } catch (ParseException e) { printHelp(options); } if (cmdLine == null) printHelp(options); new StandaloneBroker(cmdLine); }
From source file:com.thoughtworks.xstream.benchmark.cache.CacheBenchmark.java
public static void main(String[] args) { int counter = 10000; Product product = null;/*from ww w .j a v a 2 s . c o m*/ Options options = new Options(); options.addOption("p", "product", true, "Class name of the product to use for benchmark"); options.addOption("n", true, "Number of repetitions"); Parser parser = new PosixParser(); try { CommandLine commandLine = parser.parse(options, args); if (commandLine.hasOption('p')) { product = (Product) Class.forName(commandLine.getOptionValue('p')).newInstance(); } if (commandLine.hasOption('n')) { counter = Integer.parseInt(commandLine.getOptionValue('n')); } } catch (ParseException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } Harness harness = new Harness(); // harness.addMetric(new SerializationSpeedMetric(1) { // public String toString() { // return "Initial run serialization"; // } // }); // harness.addMetric(new DeserializationSpeedMetric(1, false) { // public String toString() { // return "Initial run deserialization"; // } // }); harness.addMetric(new SerializationSpeedMetric(counter)); harness.addMetric(new DeserializationSpeedMetric(counter, false)); if (product == null) { harness.addProduct(new NoCache()); harness.addProduct(new Cache122()); harness.addProduct(new RealClassCache()); harness.addProduct(new SerializedClassCache()); harness.addProduct(new AliasedAttributeCache()); harness.addProduct(new DefaultImplementationCache()); harness.addProduct(new NoCache()); } else { harness.addProduct(product); } harness.addTarget(new BasicTarget()); harness.addTarget(new ExtendedTarget()); harness.addTarget(new ReflectionTarget()); harness.addTarget(new SerializableTarget()); harness.run(new TextReporter(new PrintWriter(System.out, true))); System.out.println("Done."); }
From source file:com.thoughtworks.xstream.tools.benchmark.parsers.ParserBenchmark.java
public static void main(String[] args) { int counter = 1000; Options options = new Options(); options.addOption("p", "product", true, "Class name of the product to use for benchmark"); options.addOption("n", true, "Number of repetitions"); Harness harness = new Harness(); harness.addMetric(new DeserializationSpeedMetric(0, false) { public String toString() { return "Initial run deserialization"; }/*from www.j a v a2s.c o m*/ }); Parser parser = new PosixParser(); try { CommandLine commandLine = parser.parse(options, args); String name = null; if (commandLine.hasOption('p')) { name = commandLine.getOptionValue('p'); } if (name == null || name.equals("DOM")) { harness.addProduct(new XStreamDom()); } if (name == null || name.equals("JDOM")) { harness.addProduct(new XStreamJDom()); } if (name == null || name.equals("DOM4J")) { harness.addProduct(new XStreamDom4J()); } if (name == null || name.equals("XOM")) { harness.addProduct(new XStreamXom()); } if (name == null || name.equals("BEAStAX")) { harness.addProduct(new XStreamBEAStax()); } if (name == null || name.equals("Woodstox")) { harness.addProduct(new XStreamWoodstox()); } if (JVM.is16() && (name == null || name.equals("SJSXP"))) { harness.addProduct(new XStreamSjsxp()); } if (name == null || name.equals("Xpp3")) { harness.addProduct(new XStreamXpp3()); } if (name == null || name.equals("kXML2")) { harness.addProduct(new XStreamKXml2()); } if (name == null || name.equals("Xpp3DOM")) { harness.addProduct(new XStreamXpp3DOM()); } if (name == null || name.equals("kXML2DOM")) { harness.addProduct(new XStreamKXml2DOM()); } if (commandLine.hasOption('n')) { counter = Integer.parseInt(commandLine.getOptionValue('n')); } } catch (ParseException e) { e.printStackTrace(); } harness.addMetric(new DeserializationSpeedMetric(counter, false)); harness.addTarget(new BasicTarget()); harness.addTarget(new ExtendedTarget()); harness.addTarget(new ReflectionTarget()); harness.addTarget(new SerializableTarget()); harness.addTarget(new JavaBeanTarget()); if (false) { harness.addTarget(new FieldReflection()); harness.addTarget(new HierarchyLevelReflection()); harness.addTarget(new InnerClassesReflection()); harness.addTarget(new StaticInnerClassesReflection()); } harness.run(new TextReporter(new PrintWriter(System.out, true))); System.out.println("Done."); }
From source file:Homework4Execute.java
/** * @param args/*from w w w . j av a2 s .co m*/ */ public static void main(String[] args) { Parser parser = new GnuParser(); Options options = getCommandLineOptions(); String task = null; String host = null; String dir = null; CommandLine commandLine = null; try { commandLine = parser.parse(options, args); task = (String) commandLine.getOptionValue("task"); if ("traceroute".equals(task) || "cmdWinTrace".equals(task)) { host = (String) commandLine.getOptionValue("host"); if (host == null) { System.err.println("--host parameter required at this task!"); System.exit(-1); } } if ("cmdWinDir".equals(task)) { dir = (String) commandLine.getOptionValue("dir"); if (dir == null) { System.err.println("--dir parameter required at this task!"); System.exit(-1); } } } catch (ParseException e) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar homework4execute.jar", options); System.exit(-1); } if (task != null) { switch (task) { case "enviroment": PrintEnviroment.printEnviroment(); break; case "traceroute": RedirectOutput2Pipe.traceroute(host); break; case "cmdWinTrace": ProcessBuilderExecute.cmdWinTrace(host); break; case "cmdWinDir": RuntimeExecute.cmdWinDir(dir); break; case "uname": RedirectOutput2File.getUname(); break; } } else { RunWithThread.executeCommand("javac Teszt.java"); RunWithThread.executeCommand("java -cp ./ Teszt"); } }
From source file:jamm.tools.JammCleaner.java
/** * Our main method/*from ww w . j a v a 2 s. c om*/ * * @param argv command line arguments */ public static final void main(String argv[]) { Options opts = getOptions(); CommandLine cmdl = null; Parser parser = new GnuParser(); boolean sane = true; BasicConfigurator.configure(); try { cmdl = parser.parse(opts, argv); } catch (MissingOptionException e) { LOG.error("Missing required options." + e.toString()); sane = false; } catch (MissingArgumentException e) { LOG.error("Missing required Arguments." + e.toString()); sane = false; } catch (ParseException e) { LOG.error("Error parsing command line", e); sane = false; } // Load properties first loadProperties(); // Allow command line args to override properties file parseArgs(opts, cmdl); sane = sane && sanityCheck(); if (!sane) { printHelp(opts); System.exit(1); } AccountCleaner ac = new AccountCleaner(); ac.cleanUp(); DomainCleaner dc = new DomainCleaner(); dc.cleanUp(); }
From source file:com.jbrisbin.groovy.mqdsl.RabbitMQDsl.java
public static void main(String[] argv) { // Parse command line arguments CommandLine args = null;//from w w w .j av a2 s .co m try { Parser p = new BasicParser(); args = p.parse(cliOpts, argv); } catch (ParseException e) { log.error(e.getMessage(), e); } // Check for help if (args.hasOption('?')) { printUsage(); return; } // Runtime properties Properties props = System.getProperties(); // Check for ~/.rabbitmqrc File userSettings = new File(System.getProperty("user.home"), ".rabbitmqrc"); if (userSettings.exists()) { try { props.load(new FileInputStream(userSettings)); } catch (IOException e) { log.error(e.getMessage(), e); } } // Load Groovy builder file StringBuffer script = new StringBuffer(); BufferedInputStream in = null; String filename = "<STDIN>"; if (args.hasOption("f")) { filename = args.getOptionValue("f"); try { in = new BufferedInputStream(new FileInputStream(filename)); } catch (FileNotFoundException e) { log.error(e.getMessage(), e); } } else { in = new BufferedInputStream(System.in); } // Read script if (null != in) { byte[] buff = new byte[4096]; try { for (int read = in.read(buff); read > -1;) { script.append(new String(buff, 0, read)); read = in.read(buff); } } catch (IOException e) { log.error(e.getMessage(), e); } } else { System.err.println("No script file to evaluate..."); } PrintStream stdout = System.out; PrintStream out = null; if (args.hasOption("o")) { try { out = new PrintStream(new FileOutputStream(args.getOptionValue("o")), true); System.setOut(out); } catch (FileNotFoundException e) { log.error(e.getMessage(), e); } } String[] includes = (System.getenv().containsKey("MQDSL_INCLUDE") ? System.getenv("MQDSL_INCLUDE").split(String.valueOf(File.pathSeparatorChar)) : new String[] { System.getenv("HOME") + File.separator + ".mqdsl.d" }); try { // Setup RabbitMQ String username = (args.hasOption("U") ? args.getOptionValue("U") : props.getProperty("mq.user", "guest")); String password = (args.hasOption("P") ? args.getOptionValue("P") : props.getProperty("mq.password", "guest")); String virtualHost = (args.hasOption("v") ? args.getOptionValue("v") : props.getProperty("mq.virtualhost", "/")); String host = (args.hasOption("h") ? args.getOptionValue("h") : props.getProperty("mq.host", "localhost")); int port = Integer.parseInt( args.hasOption("p") ? args.getOptionValue("p") : props.getProperty("mq.port", "5672")); CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host); connectionFactory.setPort(port); connectionFactory.setUsername(username); connectionFactory.setPassword(password); if (null != virtualHost) { connectionFactory.setVirtualHost(virtualHost); } // The DSL builder RabbitMQBuilder builder = new RabbitMQBuilder(); builder.setConnectionFactory(connectionFactory); // Our execution environment Binding binding = new Binding(args.getArgs()); binding.setVariable("mq", builder); String fileBaseName = filename.replaceAll("\\.groovy$", ""); binding.setVariable("log", LoggerFactory.getLogger(fileBaseName.substring(fileBaseName.lastIndexOf("/") + 1))); if (null != out) { binding.setVariable("out", out); } // Include helper files GroovyShell shell = new GroovyShell(binding); for (String inc : includes) { File f = new File(inc); if (f.isDirectory()) { File[] files = f.listFiles(new FilenameFilter() { @Override public boolean accept(File file, String s) { return s.endsWith(".groovy"); } }); for (File incFile : files) { run(incFile, shell, binding); } } else { run(f, shell, binding); } } run(script.toString(), shell, binding); while (builder.isActive()) { try { Thread.sleep(500); } catch (InterruptedException e) { log.error(e.getMessage(), e); } } if (null != out) { out.close(); System.setOut(stdout); } } finally { System.exit(0); } }
From source file:kellinwood.zipsigner.cmdline.Main.java
public static void main(String[] args) { try {// w ww. j a v a2 s .c om Options options = new Options(); CommandLine cmdLine = null; Option helpOption = new Option("h", "help", false, "Display usage information"); Option modeOption = new Option("m", "keymode", false, "Keymode one of: auto, auto-testkey, auto-none, media, platform, shared, testkey, none"); modeOption.setArgs(1); Option keyOption = new Option("k", "key", false, "PCKS#8 encoded private key file"); keyOption.setArgs(1); Option pwOption = new Option("p", "keypass", false, "Private key password"); pwOption.setArgs(1); Option certOption = new Option("c", "cert", false, "X.509 public key certificate file"); certOption.setArgs(1); Option sbtOption = new Option("t", "template", false, "Signature block template file"); sbtOption.setArgs(1); Option keystoreOption = new Option("s", "keystore", false, "Keystore file"); keystoreOption.setArgs(1); Option aliasOption = new Option("a", "alias", false, "Alias for key/cert in the keystore"); aliasOption.setArgs(1); options.addOption(helpOption); options.addOption(modeOption); options.addOption(keyOption); options.addOption(certOption); options.addOption(sbtOption); options.addOption(pwOption); options.addOption(keystoreOption); options.addOption(aliasOption); Parser parser = new BasicParser(); try { cmdLine = parser.parse(options, args); } catch (MissingOptionException x) { System.out.println("One or more required options are missing: " + x.getMessage()); usage(options); } catch (ParseException x) { System.out.println(x.getClass().getName() + ": " + x.getMessage()); usage(options); } if (cmdLine.hasOption(helpOption.getOpt())) usage(options); Properties log4jProperties = new Properties(); log4jProperties.load(new FileReader("log4j.properties")); PropertyConfigurator.configure(log4jProperties); LoggerManager.setLoggerFactory(new Log4jLoggerFactory()); List<String> argList = cmdLine.getArgList(); if (argList.size() != 2) usage(options); ZipSigner signer = new ZipSigner(); signer.addAutoKeyObserver(new Observer() { @Override public void update(Observable observable, Object o) { System.out.println("Signing with key: " + o); } }); Class bcProviderClass = Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider"); Provider bcProvider = (Provider) bcProviderClass.newInstance(); KeyStoreFileManager.setProvider(bcProvider); signer.loadProvider("org.spongycastle.jce.provider.BouncyCastleProvider"); PrivateKey privateKey = null; if (cmdLine.hasOption(keyOption.getOpt())) { if (!cmdLine.hasOption(certOption.getOpt())) { System.out.println("Certificate file is required when specifying a private key"); usage(options); } String keypw = null; if (cmdLine.hasOption(pwOption.getOpt())) keypw = pwOption.getValue(); else { keypw = new String(readPassword("Key password")); if (keypw.equals("")) keypw = null; } URL privateKeyUrl = new File(keyOption.getValue()).toURI().toURL(); privateKey = signer.readPrivateKey(privateKeyUrl, keypw); } X509Certificate cert = null; if (cmdLine.hasOption(certOption.getOpt())) { if (!cmdLine.hasOption(keyOption.getOpt())) { System.out.println("Private key file is required when specifying a certificate"); usage(options); } URL certUrl = new File(certOption.getValue()).toURI().toURL(); cert = signer.readPublicKey(certUrl); } byte[] sigBlockTemplate = null; if (cmdLine.hasOption(sbtOption.getOpt())) { URL sbtUrl = new File(sbtOption.getValue()).toURI().toURL(); sigBlockTemplate = signer.readContentAsBytes(sbtUrl); } if (cmdLine.hasOption(keyOption.getOpt())) { signer.setKeys("custom", cert, privateKey, sigBlockTemplate); signer.signZip(argList.get(0), argList.get(1)); } else if (cmdLine.hasOption(modeOption.getOpt())) { signer.setKeymode(modeOption.getValue()); signer.signZip(argList.get(0), argList.get(1)); } else if (cmdLine.hasOption((keystoreOption.getOpt()))) { String alias = null; if (!cmdLine.hasOption(aliasOption.getOpt())) { KeyStore keyStore = KeyStoreFileManager.loadKeyStore(keystoreOption.getValue(), (char[]) null); for (Enumeration<String> e = keyStore.aliases(); e.hasMoreElements();) { alias = e.nextElement(); System.out.println("Signing with key: " + alias); break; } } else alias = aliasOption.getValue(); String keypw = null; if (cmdLine.hasOption(pwOption.getOpt())) keypw = pwOption.getValue(); else { keypw = new String(readPassword("Key password")); if (keypw.equals("")) keypw = null; } CustomKeySigner.signZip(signer, keystoreOption.getValue(), null, alias, keypw.toCharArray(), "SHA1withRSA", argList.get(0), argList.get(1)); } else { signer.setKeymode("auto-testkey"); signer.signZip(argList.get(0), argList.get(1)); } } catch (Throwable t) { t.printStackTrace(); } }
From source file:edu.cornell.med.icb.R.RUtils.java
public static void main(final String[] args) throws ParseException, ConfigurationException { final Options options = new Options(); final Option helpOption = new Option("h", "help", false, "Print this message"); options.addOption(helpOption);/* w w w. j ava2s .c o m*/ final Option startupOption = new Option(Mode.startup.name(), Mode.startup.name(), false, "Start Rserve process"); final Option shutdownOption = new Option(Mode.shutdown.name(), Mode.shutdown.name(), false, "Shutdown Rserve process"); final Option validateOption = new Option(Mode.validate.name(), Mode.validate.name(), false, "Validate that Rserve processes are running"); final OptionGroup optionGroup = new OptionGroup(); optionGroup.addOption(startupOption); optionGroup.addOption(shutdownOption); optionGroup.addOption(validateOption); optionGroup.setRequired(true); options.addOptionGroup(optionGroup); final Option portOption = new Option("port", "port", true, "Use specified port to communicate with the Rserve process"); portOption.setArgName("port"); portOption.setType(int.class); options.addOption(portOption); final Option hostOption = new Option("host", "host", true, "Communicate with the Rserve process on the given host"); hostOption.setArgName("hostname"); hostOption.setType(String.class); options.addOption(hostOption); final Option userOption = new Option("u", "username", true, "Username to send to the Rserve process"); userOption.setArgName("username"); userOption.setType(String.class); options.addOption(userOption); final Option passwordOption = new Option("p", "password", true, "Password to send to the Rserve process"); passwordOption.setArgName("password"); passwordOption.setType(String.class); options.addOption(passwordOption); final Option configurationOption = new Option("c", "configuration", true, "Configuration file or url to read from"); configurationOption.setArgName("configuration"); configurationOption.setType(String.class); options.addOption(configurationOption); final Parser parser = new BasicParser(); final CommandLine commandLine; try { commandLine = parser.parse(options, args); } catch (ParseException e) { usage(options); throw e; } int exitStatus = 0; if (commandLine.hasOption("h")) { usage(options); } else { Mode mode = null; for (final Mode potentialMode : Mode.values()) { if (commandLine.hasOption(potentialMode.name())) { mode = potentialMode; break; } } final ExecutorService threadPool = Executors.newCachedThreadPool(); if (commandLine.hasOption("configuration")) { final String configurationFile = commandLine.getOptionValue("configuration"); LOG.info("Reading configuration from " + configurationFile); XMLConfiguration configuration; try { final URL configurationURL = new URL(configurationFile); configuration = new XMLConfiguration(configurationURL); } catch (MalformedURLException e) { // resource is not a URL: attempt to get the resource from a file LOG.debug("Configuration is not a valid url"); configuration = new XMLConfiguration(configurationFile); } configuration.setValidating(true); final int numberOfRServers = configuration.getMaxIndex("RConfiguration.RServer") + 1; boolean failed = false; for (int i = 0; i < numberOfRServers; i++) { final String server = "RConfiguration.RServer(" + i + ")"; final String host = configuration.getString(server + "[@host]"); final int port = configuration.getInt(server + "[@port]", RConfigurationUtils.DEFAULT_RSERVE_PORT); final String username = configuration.getString(server + "[@username]"); final String password = configuration.getString(server + "[@password]"); final String command = configuration.getString(server + "[@command]", DEFAULT_RSERVE_COMMAND); if (executeMode(mode, threadPool, host, port, username, password, command) != 0) { failed = true; // we have other hosts to check so keep a failed state } } if (failed) { exitStatus = 3; } } else { final String host = commandLine.getOptionValue("host", "localhost"); final int port = Integer.valueOf(commandLine.getOptionValue("port", "6311")); final String username = commandLine.getOptionValue("username"); final String password = commandLine.getOptionValue("password"); exitStatus = executeMode(mode, threadPool, host, port, username, password, null); } threadPool.shutdown(); } System.exit(exitStatus); }
From source file:com.hurence.logisland.runner.StreamProcessingRunner.java
/** * main entry point// ww w .j ava 2 s . c om * * @param args */ public static void main(String[] args) { logger.info("starting StreamProcessingRunner"); ////////////////////////////////////////// // Commande lien management Parser parser = new GnuParser(); Options options = new Options(); String helpMsg = "Print this message."; Option help = new Option("help", helpMsg); options.addOption(help); OptionBuilder.withArgName("conf"); OptionBuilder.withLongOpt("config-file"); OptionBuilder.isRequired(); OptionBuilder.hasArg(); OptionBuilder.withDescription("config file path"); Option conf = OptionBuilder.create("conf"); options.addOption(conf); Optional<EngineContext> engineInstance = Optional.empty(); try { System.out.println(BannerLoader.loadBanner()); // parse the command line arguments CommandLine line = parser.parse(options, args); String configFile = line.getOptionValue("conf"); // load the YAML config LogislandConfiguration sessionConf = ConfigReader.loadConfig(configFile); // instantiate engine and all the processor from the config engineInstance = ComponentFactory.getEngineContext(sessionConf.getEngine()); if (!engineInstance.isPresent()) { throw new IllegalArgumentException("engineInstance could not be instantiated"); } if (!engineInstance.get().isValid()) { throw new IllegalArgumentException("engineInstance is not valid with input configuration !"); } logger.info("starting Logisland session version {}", sessionConf.getVersion()); logger.info(sessionConf.getDocumentation()); } catch (Exception e) { logger.error("unable to launch runner", e); System.exit(-1); } String engineName = engineInstance.get().getEngine().getIdentifier(); try { // start the engine EngineContext engineContext = engineInstance.get(); logger.info("start engine {}", engineName); engineInstance.get().getEngine().start(engineContext); logger.info("awaitTermination for engine {}", engineName); engineContext.getEngine().awaitTermination(engineContext); System.exit(0); } catch (Exception e) { logger.error("something went bad while running the job {} : {}", engineName, e); System.exit(-1); } }
From source file:com.jolira.testing.CachingRESTProxy.java
/** * @param args//from w w w. j a va2 s. c o m * @throws Exception */ public static void main(final String[] args) throws Exception { final Parser parser = new GnuParser(); final HelpFormatter formatter = new HelpFormatter(); final Options options = new Options(); options.addOption("c", CACHE, true, "chache directory (mandatory!)"); options.addOption("s", SERVER, true, "server name and port number as server:port"); options.addOption("x", USE_SSL, false, "use ssl"); options.addOption("?", HELP, false, "display help"); final CommandLine cli = parser.parse(options, args); final String server = cli.getOptionValue(SERVER); final String cache = cli.getOptionValue(CACHE); final boolean ssl = cli.hasOption(USE_SSL); if (cli.hasOption(HELP) || cache == null) { formatter.printHelp(CachingRESTProxy.class.getName(), options); return; } final CachingRESTProxy proxy = new CachingRESTProxy(ssl, server, new File(cache)); proxy.start(); }