List of usage examples for org.apache.commons.cli PosixParser PosixParser
PosixParser
From source file:com.genentech.struchk.sdfNormalizer.java
public static void main(String[] args) { long start = System.currentTimeMillis(); int nMessages = 0; int nErrors = 0; int nStruct = 0; // create command line Options object Options options = new Options(); Option opt = new Option("in", true, "input file [.ism,.sdf,...]"); opt.setRequired(true);/*from w w w.j av a2 s. c o m*/ options.addOption(opt); opt = new Option("out", true, "output file"); opt.setRequired(true); options.addOption(opt); opt = new Option("mol", true, "molFile used for output: ORIGINAL(def)|NORMALIZED|TAUTOMERIC"); opt.setRequired(false); options.addOption(opt); opt = new Option("shortMessage", false, "Limit message to first 80 characters to conform with sdf file specs."); opt.setRequired(false); options.addOption(opt); CommandLineParser parser = new PosixParser(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException e) { exitWithHelp(options, e.getMessage()); throw new Error(e); // avoid compiler errors } args = cmd.getArgs(); if (args.length != 0) { System.err.print("Unknown options: " + args + "\n\n"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("sdfNormalizer", options); System.exit(1); } String molOpt = cmd.getOptionValue("mol"); OUTMolFormat outMol = OUTMolFormat.ORIGINAL; if (molOpt == null || "original".equalsIgnoreCase(molOpt)) outMol = OUTMolFormat.ORIGINAL; else if ("NORMALIZED".equalsIgnoreCase(molOpt)) outMol = OUTMolFormat.NORMALIZED; else if ("TAUTOMERIC".equalsIgnoreCase(molOpt)) outMol = OUTMolFormat.TAUTOMERIC; else { System.err.printf("Unkown option for -mol: %s\n", molOpt); System.exit(1); } String inFile = cmd.getOptionValue("in"); String outFile = cmd.getOptionValue("out"); boolean limitMessage = cmd.hasOption("shortMessage"); try { oemolistream ifs = new oemolistream(inFile); oemolostream ofs = new oemolostream(outFile); URL cFile = OEStruchk.getResourceURL(OEStruchk.class, "Struchk.xml"); // create OEStruchk from config file OEStruchk strchk = new OEStruchk(cFile, CHECKConfig.ASSIGNStructFlag, false); OEGraphMol mol = new OEGraphMol(); StringBuilder sb = new StringBuilder(2000); while (oechem.OEReadMolecule(ifs, mol)) { if (!strchk.applyRules(mol, null)) nErrors++; switch (outMol) { case NORMALIZED: mol.Clear(); oechem.OEAddMols(mol, strchk.getTransformedMol("parent")); break; case TAUTOMERIC: mol.Clear(); oechem.OEAddMols(mol, strchk.getTransformedMol(null)); break; case ORIGINAL: break; } oechem.OESetSDData(mol, "CTISMILES", strchk.getTransformedIsoSmiles(null)); oechem.OESetSDData(mol, "CTSMILES", strchk.getTransformedSmiles(null)); oechem.OESetSDData(mol, "CISMILES", strchk.getTransformedIsoSmiles("parent")); oechem.OESetSDData(mol, "Strutct_Flag", strchk.getStructureFlag().getName()); List<Message> msgs = strchk.getStructureMessages(null); nMessages += msgs.size(); for (Message msg : msgs) sb.append(String.format("\t%s:%s", msg.getLevel(), msg.getText())); if (limitMessage) sb.setLength(Math.min(sb.length(), 80)); oechem.OESetSDData(mol, "NORM_MESSAGE", sb.toString()); oechem.OEWriteMolecule(ofs, mol); sb.setLength(0); nStruct++; } strchk.delete(); mol.delete(); ifs.close(); ifs.delete(); ofs.close(); ofs.delete(); } catch (Exception e) { throw new Error(e); } finally { System.err.printf("sdfNormalizer: Checked %d structures %d errors, %d messages in %dsec\n", nStruct, nErrors, nMessages, (System.currentTimeMillis() - start) / 1000); } }
From source file:com.aerospike.utility.SetDelete.java
public static void main(String[] args) throws ParseException { Options options = new Options(); options.addOption("h", "host", true, "Server hostname (default: localhost)"); options.addOption("p", "port", true, "Server port (default: 3000)"); options.addOption("n", "namespace", true, "Namespace (default: test)"); options.addOption("s", "set", true, "Set to delete (default: test)"); options.addOption("u", "usage", false, "Print usage."); CommandLineParser parser = new PosixParser(); CommandLine cl = parser.parse(options, args, false); if (args.length == 0 || cl.hasOption("u")) { logUsage(options);//from ww w.j av a 2 s. c o m return; } String host = cl.getOptionValue("h", "127.0.0.1"); String portString = cl.getOptionValue("p", "3000"); int port = Integer.parseInt(portString); String set = cl.getOptionValue("s", "test"); String namespace = cl.getOptionValue("n", "test"); log.info("Host: " + host); log.info("Port: " + port); log.info("Name space: " + namespace); log.info("Set: " + set); if (set == null) { log.error("You must specify a set"); return; } try { final AerospikeClient client = new AerospikeClient(host, port); ScanPolicy scanPolicy = new ScanPolicy(); scanPolicy.includeBinData = false; scanPolicy.concurrentNodes = true; scanPolicy.priority = Priority.HIGH; /* * scan the entire Set using scannAll(). This will scan each node * in the cluster and return the record Digest to the call back object */ client.scanAll(scanPolicy, namespace, set, new ScanCallback() { public void scanCallback(Key key, Record record) throws AerospikeException { /* * for each Digest returned, delete it using delete() */ if (client.delete(null, key)) count++; /* * after 25,000 records delete, return print the count. */ if (count % 25000 == 0) { log.info("Deleted " + count); } } }, new String[] {}); log.info("Deleted " + count + " records from set " + set); } catch (AerospikeException e) { int resultCode = e.getResultCode(); log.info(ResultCode.getResultString(resultCode)); log.debug("Error details: ", e); } }
From source file:brut.apktool.Main.java
public static void main(String[] args) throws IOException, InterruptedException, BrutException { // set verbosity default Verbosity verbosity = Verbosity.NORMAL; // cli parser CommandLineParser parser = new PosixParser(); CommandLine commandLine = null;//from w w w.j av a 2 s .co m // load options _Options(); try { commandLine = parser.parse(allOptions, args, false); } catch (ParseException ex) { System.err.println(ex.getMessage()); usage(commandLine); return; } // check for verbose / quiet if (commandLine.hasOption("-v") || commandLine.hasOption("--verbose")) { verbosity = Verbosity.VERBOSE; } else if (commandLine.hasOption("-q") || commandLine.hasOption("--quiet")) { verbosity = Verbosity.QUIET; } setupLogging(verbosity); // check for advance mode if (commandLine.hasOption("advance") || commandLine.hasOption("advanced")) { setAdvanceMode(true); } // @todo use new ability of apache-commons-cli to check hasOption for non-prefixed items boolean cmdFound = false; for (String opt : commandLine.getArgs()) { if (opt.equalsIgnoreCase("d") || opt.equalsIgnoreCase("decode")) { cmdDecode(commandLine); cmdFound = true; } else if (opt.equalsIgnoreCase("b") || opt.equalsIgnoreCase("build")) { cmdBuild(commandLine); cmdFound = true; } else if (opt.equalsIgnoreCase("if") || opt.equalsIgnoreCase("install-framework")) { cmdInstallFramework(commandLine); cmdFound = true; } else if (opt.equalsIgnoreCase("publicize-resources")) { cmdPublicizeResources(commandLine); cmdFound = true; } } // if no commands ran, run the version / usage check. if (cmdFound == false) { if (commandLine.hasOption("version") || commandLine.hasOption("version")) { _version(); } else { usage(commandLine); } } }
From source file:com.thoughtworks.xstream.benchmark.cache.CacheBenchmark.java
public static void main(String[] args) { int counter = 10000; Product product = null;/*w w w . j av a2 s .c om*/ 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:edu.msu.cme.rdp.probematch.cli.PrimerMatch.java
public static void main(String[] args) throws Exception { PrintStream out = new PrintStream(System.out); int maxDist = Integer.MAX_VALUE; try {//from w w w . j a v a 2 s. c o m CommandLine line = new PosixParser().parse(options, args); if (line.hasOption("outFile")) { out = new PrintStream(new File(line.getOptionValue("outFile"))); } if (line.hasOption("maxDist")) { maxDist = Integer.valueOf(line.getOptionValue("maxDist")); } args = line.getArgs(); if (args.length != 2) { throw new Exception("Unexpected number of command line arguments"); } } catch (Exception e) { System.err.println("Error: " + e.getMessage()); new HelpFormatter().printHelp("PrimerMatch <primer_list | primer_file> <seq_file>", options); return; } List<PatternBitMask64> primers = new ArrayList(); if (new File(args[0]).exists()) { File primerFile = new File(args[0]); SequenceFormat seqformat = SeqUtils.guessFileFormat(primerFile); if (seqformat.equals(SequenceFormat.FASTA)) { SequenceReader reader = new SequenceReader(primerFile); Sequence seq; while ((seq = reader.readNextSequence()) != null) { primers.add(new PatternBitMask64(seq.getSeqString(), true, seq.getSeqName())); } reader.close(); } else { BufferedReader reader = new BufferedReader(new FileReader(args[0])); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (!line.equals("")) { primers.add(new PatternBitMask64(line, true)); } } reader.close(); } } else { for (String primer : args[0].split(",")) { primers.add(new PatternBitMask64(primer, true)); } } SeqReader seqReader = new SequenceReader(new File(args[1])); Sequence seq; String primerRegion; out.println("#seqname\tdesc\tprimer_index\tprimer_name\tposition\tmismatches\tseq_primer_region"); while ((seq = seqReader.readNextSequence()) != null) { for (int index = 0; index < primers.size(); index++) { PatternBitMask64 primer = primers.get(index); BitVector64Result results = BitVector64.process(seq.getSeqString().toCharArray(), primer, maxDist); for (BitVector64Match result : results.getResults()) { primerRegion = seq.getSeqString().substring( Math.max(0, result.getPosition() - primer.getPatternLength()), result.getPosition()); if (result.getPosition() < primer.getPatternLength()) { for (int pad = result.getPosition(); pad < primer.getPatternLength(); pad++) { primerRegion = "x" + primerRegion; } } out.println(seq.getSeqName() + "\t" + seq.getDesc() + "\t" + (index + 1) + "\t" + primer.getPrimerName() + "\t" + result.getPosition() + "\t" + result.getScore() + "\t" + primerRegion); } } } out.close(); seqReader.close(); }
From source file:fr.jamgotchian.tuplegen.core.Main.java
public static void main(String[] args) { CommandLineParser parser = new PosixParser(); try {// w w w.j a v a 2s .c o m CommandLine line = parser.parse(OPTIONS, args); if (line.hasOption("h") || !line.hasOption("c") || !line.hasOption("d")) { usage(); } File genSrcDir = new File(line.getOptionValue("d")); if (!genSrcDir.exists()) { throw new IllegalArgumentException(genSrcDir + " does not exit"); } if (!genSrcDir.isDirectory()) { throw new IllegalArgumentException(genSrcDir + " should be a directory"); } File cfgFile = new File(line.getOptionValue("c")); if (!cfgFile.exists()) { throw new IllegalArgumentException(cfgFile + " does not exist"); } TupleGen generator = new TupleGen(); generator.generate(cfgFile, genSrcDir, false, LOGGER); } catch (Throwable t) { t.printStackTrace(); } }
From source file:com.aerospike.client.rest.AerospikeRESTfulService.java
public static void main(String[] args) throws ParseException { Options options = new Options(); options.addOption("h", "host", true, "Server hostname (default: localhost)"); options.addOption("p", "port", true, "Server port (default: 3000)"); // parse the command line args CommandLineParser parser = new PosixParser(); CommandLine cl = parser.parse(options, args, false); // set properties Properties as = System.getProperties(); String host = cl.getOptionValue("h", "localhost"); as.put("seedHost", host); String portString = cl.getOptionValue("p", "3000"); as.put("port", portString); // start app// w w w.ja v a 2 s . c om SpringApplication.run(AerospikeRESTfulService.class, args); }
From source file:bbs.monitor.ListNode.java
public static void main(String[] args) throws Exception { boolean printRawForm = false; String transport = null;/*from w w w. j a v a2s . co m*/ String selfAddressAndPort = null; // parse command-line arguments Options opts = new Options(); opts.addOption("h", "help", false, "print help"); opts.addOption("r", "raw", false, "print nodes in the raw form (hostname:port)"); opts.addOption("t", "transport", true, "transpoft, UDP or TCP"); opts.addOption("s", "selfipaddress", true, "self IP address (and port)"); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(opts, 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); } if (cmd.hasOption('r')) { printRawForm = true; } optVal = cmd.getOptionValue('t'); if (optVal != null) { transport = optVal; } optVal = cmd.getOptionValue('s'); if (optVal != null) { selfAddressAndPort = optVal; } args = cmd.getArgs(); // parse initial contact String contactHostAndPort = null; int contactPort = -1; if (args.length < 1) { usage(COMMAND); System.exit(1); } contactHostAndPort = args[0]; if (args.length >= 2) contactPort = Integer.parseInt(args[1]); // // prepare a NodeCollector and invoke it // // prepare StatConfiguration StatConfiguration config = StatFactory.getDefaultConfiguration(); config.setDoUPnPNATTraversal(false); if (transport != null) { config.setMessagingTransport(transport); } if (selfAddressAndPort != null) { MessagingUtility.HostAndPort hostAndPort = MessagingUtility.parseHostnameAndPort(selfAddressAndPort, config.getSelfPort()); config.setSelfAddress(hostAndPort.getHostName()); config.setSelfPort(hostAndPort.getPort()); } // prepare MessageReceiver and initial contact MessagingProvider provider = config.deriveMessagingProvider(); MessageReceiver receiver = config.deriveMessageReceiver(provider); MessagingAddress contact; try { contact = provider.getMessagingAddress(contactHostAndPort, contactPort); } catch (IllegalArgumentException e) { contact = provider.getMessagingAddress(contactHostAndPort, config.getContactPort()); } // prepare a callback NodeCollectorCallback cb; if (printRawForm) { cb = new NodeCollectorCallback() { public void addNode(ID id, MessagingAddress address) { System.out.println(new MessagingUtility.HostAndPort(address.getHostname(), address.getPort())); // <hostname>:<port> } public void removeNode(ID id) { } }; } else { cb = new NodeCollectorCallback() { public void addNode(ID id, MessagingAddress address) { //System.out.println(HTMLUtil.convertMessagingAddressToURL(address)); System.out.println("http://" + address.getHostAddress() + ":" + address.getPort() + "/"); // http://<hostname>:port/ } public void removeNode(ID id) { } }; } // instantiate and invoke a NodeCollector NodeCollector collector = StatFactory.getNodeCollector(config, contact, cb, receiver); collector.investigate(); // stop MessageReceiver to prevent // handling incoming messages and submissions to a thread pool receiver.stop(); }
From source file:com.yahoo.pasc.paxos.client.PaxosClient.java
public static void main(String[] args) throws Exception { CommandLineParser parser = new PosixParser(); Options options;//w w w. j ava 2s. c om { Option id = new Option("i", true, "client id"); Option clients = new Option("c", true, "number of clients"); Option host = new Option("l", true, "leader (hostname:port)"); Option servers = new Option("s", true, "number of servers"); Option quorum = new Option("q", true, "necesarry quorum at the client"); Option port = new Option("p", true, "port used by client"); Option buffer = new Option("b", true, "number of concurrent clients"); Option timeout = new Option("t", true, "timeout in milliseconds"); Option udp = new Option("u", false, "use UDP"); Option zookeeper = new Option("z", true, "zookeeper connection string"); Option warmup = new Option("w", true, "warmup messagges"); Option measuring = new Option("m", true, "measuring time"); Option request = new Option("r", true, "request size"); Option frequency = new Option("f", true, "frequency of throughput info"); Option anm = new Option("a", false, "use protection"); Option inlineThresh = new Option("n", true, "threshold for sending requests iNline with accepts "); Option asynSize = new Option("y", true, "size of async messages queue"); options = new Options(); options.addOption(id).addOption(host).addOption(servers).addOption(quorum).addOption(port) .addOption(warmup).addOption(buffer).addOption(timeout).addOption(udp).addOption(zookeeper) .addOption(clients).addOption(measuring).addOption(request).addOption(frequency).addOption(anm) .addOption(inlineThresh).addOption(asynSize); } CommandLine line = null; try { line = parser.parse(options, args); String host = line.hasOption('l') ? line.getOptionValue('l') : "localhost:20548,localhost:20748,localhost:20778"; String zkConnection = line.hasOption('z') ? line.getOptionValue('z') : "localhost:2181"; int clientIds = line.hasOption('i') ? Integer.parseInt(line.getOptionValue('i')) : 0; int servers = line.hasOption('s') ? Integer.parseInt(line.getOptionValue('s')) : 3; int quorum = line.hasOption('q') ? Integer.parseInt(line.getOptionValue('q')) : 1; int buffer = line.hasOption('b') ? Integer.parseInt(line.getOptionValue('b')) : 1; int timeout = line.hasOption('t') ? Integer.parseInt(line.getOptionValue('t')) : 5000; int clients = line.hasOption('c') ? Integer.parseInt(line.getOptionValue('c')) : 1; int requestSize = line.hasOption('r') ? Integer.parseInt(line.getOptionValue('r')) : 0; int inlineThreshold = line.hasOption('n') ? Integer.parseInt(line.getOptionValue('n')) : 1000; int asynSize = line.hasOption('y') ? Integer.parseInt(line.getOptionValue('y')) : 100; boolean protection = line.hasOption('a'); int threads = Runtime.getRuntime().availableProcessors() * 2; final ExecutionHandler executor = new ExecutionHandler(new OrderedMemoryAwareThreadPoolExecutor(threads, 1024 * 1024, 1024 * 1024 * 1024, 30, TimeUnit.SECONDS, Executors.defaultThreadFactory())); String[] serverHosts = host.split(","); ServerHelloHandler shello = new ServerHelloHandler(); ReplyHandler reply = new ReplyHandler(); SubmitHandler submit = new SubmitHandler(); TimeoutHandler tout = new TimeoutHandler(); AsyncMessageHandler asyncm = new AsyncMessageHandler(); ByeHandler bye = new ByeHandler(); HelloHandler hello = new HelloHandler(); Random rnd = new Random(); for (int i = 0; i < buffer; ++i) { ClientState clientState = new ClientState(servers, quorum, inlineThreshold, asynSize); final PascRuntime<ClientState> runtime = new PascRuntime<ClientState>(protection); runtime.setState(clientState); runtime.addHandler(ServerHello.class, shello); runtime.addHandler(Reply.class, reply); runtime.addHandler(Submit.class, submit); runtime.addHandler(Timeout.class, tout); runtime.addHandler(AsyncMessage.class, asyncm); runtime.addHandler(Bye.class, bye); runtime.addHandler(Hello.class, hello); final PaxosClientHandler handler = new PaxosClientHandler(runtime, new SimpleClient(requestSize), serverHosts, clients, timeout, zkConnection, executor); if (line.hasOption('w')) handler.setWarmup(Integer.parseInt(line.getOptionValue('w'))); if (line.hasOption('m')) handler.setMeasuringTime(Integer.parseInt(line.getOptionValue('m'))); if (line.hasOption('f')) handler.setPeriod(Integer.parseInt(line.getOptionValue('f'))); handler.start(); Thread.sleep(rnd.nextInt(200)); } } catch (Exception e) { System.err.println("Unexpected exception " + e); e.printStackTrace(); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Paxos", options); System.exit(-1); } }
From source file:dhtaccess.tools.Get.java
public static void main(String[] args) { boolean details = false; // parse properties Properties prop = System.getProperties(); String gateway = prop.getProperty("dhtaccess.gateway"); if (gateway == null || gateway.length() <= 0) { gateway = DEFAULT_GATEWAY;/*from w ww.jav a 2 s . com*/ } // 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("d", "details", false, "print secret hash and TTL"); 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; } if (cmd.hasOption('d')) { details = true; } args = cmd.getArgs(); // parse arguments if (args.length < 1) { usage(COMMAND); System.exit(1); } // prepare for RPC DHTAccessor accessor = null; try { accessor = new DHTAccessor(gateway); } catch (MalformedURLException e) { e.printStackTrace(); System.exit(1); } for (int index = 0; index < args.length; index++) { byte[] key = null; try { key = args[index].getBytes(ENCODE); } catch (UnsupportedEncodingException e1) { // NOTREACHED } // RPC if (args.length > 1) { System.out.println(args[index] + ":"); } if (details) { Set<DetailedGetResult> results = accessor.getDetails(key); for (DetailedGetResult r : results) { String valString = null; try { valString = new String((byte[]) r.getValue(), ENCODE); } catch (UnsupportedEncodingException e) { // NOTREACHED } BigInteger hashedSecure = new BigInteger(1, (byte[]) r.getHashedSecret()); System.out.println(valString + " " + r.getTTL() + " " + r.getHashType() + " 0x" + ("0000000" + hashedSecure.toString(16)).substring(0, 8)); } } else { Set<byte[]> results = accessor.get(key); for (byte[] valBytes : results) { try { System.out.println(new String((byte[]) valBytes, ENCODE)); } catch (UnsupportedEncodingException e) { // NOTREACHED } } } } // for (int index = 0... }