List of usage examples for org.apache.commons.cli CommandLine hasOption
public boolean hasOption(char opt)
From source file:client.MultiplexingClient.java
public static void main(String[] args) throws Exception { // Prepare to parse the command line Options options = new Options(); Option sslOpt = new Option("s", "ssl", false, "Use SSL"); Option debugOpt = new Option("d", true, "Debug level (NONE, FINER, FINE, CONFIG, INFO, WARNING, SEVERE. Default INFO."); Option numConnectionsOpt = new Option("n", true, "Number of connections to establish. [Default: 1]"); Option numPcktOpt = new Option("p", true, "Number of packets to send in each connection. [Default: 20]"); Option pcktMaxSizeOpt = new Option("m", true, "Maximum size of packets. [Default: 4096]"); Option help = new Option("h", "print this message"); options.addOption(help);/*w ww. j a v a2 s . co m*/ options.addOption(debugOpt); options.addOption(numConnectionsOpt); options.addOption(numPcktOpt); options.addOption(pcktMaxSizeOpt); options.addOption(sslOpt); CommandLineParser parser = new PosixParser(); // parse the command line arguments CommandLine line = parser.parse(options, args); if (line.hasOption(help.getOpt()) || line.getArgs().length < 1) { showUsage(options); return; } if (line.hasOption(sslOpt.getOpt())) { channelFactory = new SSLChannelFactory(true, TRUSTSTORE, TRUSTSTORE_PASSWORD); } else { channelFactory = new PlainChannelFactory(); } if (line.hasOption(numConnectionsOpt.getOpt())) { connectionCount = Integer.parseInt(line.getOptionValue(numConnectionsOpt.getOpt())); } else { connectionCount = 1; } if (line.hasOption(numPcktOpt.getOpt())) { packetsToSend = Integer.parseInt(line.getOptionValue(numPcktOpt.getOpt())); } else { packetsToSend = 20; } if (line.hasOption(pcktMaxSizeOpt.getOpt())) { maxPcktSize = Integer.parseInt(line.getOptionValue(pcktMaxSizeOpt.getOpt())); } else { maxPcktSize = 4096; } InetSocketAddress remotePoint; try { String host = line.getArgs()[0]; int colonIndex = host.indexOf(':'); remotePoint = new InetSocketAddress(host.substring(0, colonIndex), Integer.parseInt(host.substring(colonIndex + 1))); } catch (Exception e) { showUsage(options); return; } // Setups the logging context for Log4j // NDC.push(Thread.currentThread().getName()); st = new SelectorThread(); for (int i = 0; i < connectionCount; i++) { new MultiplexingClient(remotePoint); // Must sleep for a while between opening connections in order // to give the remote host enough time to handle them. Otherwise, // the remote host backlog will get full and the connection // attemps will start to be refused. Thread.sleep(100); } }
From source file:cc.twittertools.index.ExtractTermStatisticsFromIndex.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(OptionBuilder.withArgName("dir").hasArg().withDescription("index").create(INDEX_OPTION)); options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("min").create(MIN_OPTION)); CommandLine cmdline = null; CommandLineParser parser = new GnuParser(); try {//from w w w . ja v a 2 s .com cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (!cmdline.hasOption(INDEX_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(ExtractTermStatisticsFromIndex.class.getName(), options); System.exit(-1); } String indexLocation = cmdline.getOptionValue(INDEX_OPTION); int min = cmdline.hasOption(MIN_OPTION) ? Integer.parseInt(cmdline.getOptionValue(MIN_OPTION)) : 1; PrintStream out = new PrintStream(System.out, true, "UTF-8"); IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(indexLocation))); Terms terms = SlowCompositeReaderWrapper.wrap(reader).terms(StatusField.TEXT.name); TermsEnum termsEnum = terms.iterator(TermsEnum.EMPTY); long missingCnt = 0; int skippedTerms = 0; BytesRef bytes = new BytesRef(); while ((bytes = termsEnum.next()) != null) { byte[] buf = new byte[bytes.length]; System.arraycopy(bytes.bytes, 0, buf, 0, bytes.length); String term = new String(buf, "UTF-8"); int df = termsEnum.docFreq(); long cf = termsEnum.totalTermFreq(); if (df < min) { skippedTerms++; missingCnt += cf; continue; } out.println(term + "\t" + df + "\t" + cf); } reader.close(); out.close(); System.err.println("skipped terms: " + skippedTerms + ", cnt: " + missingCnt); }
From source file:com.google.endpoints.examples.bookstore.BookstoreServer.java
public static void main(String[] args) throws Exception { Options options = createOptions();/*from w w w. j a va 2s . c o m*/ CommandLineParser parser = new DefaultParser(); CommandLine line; try { line = parser.parse(options, args); } catch (ParseException e) { System.err.println("Invalid command line: " + e.getMessage()); printUsage(options); return; } int port = DEFAULT_PORT; if (line.hasOption("port")) { String portOption = line.getOptionValue("port"); try { port = Integer.parseInt(portOption); } catch (java.lang.NumberFormatException e) { System.err.println("Invalid port number: " + portOption); printUsage(options); return; } } final BookstoreData data = initializeBookstoreData(); final BookstoreServer server = new BookstoreServer(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { System.out.println("Shutting down"); server.stop(); } catch (Exception e) { e.printStackTrace(); } } }); server.start(port, data); System.out.format("Bookstore service listening on %d\n", port); server.blockUntilShutdown(); }
From source file:edu.msu.cme.rdp.abundstats.cli.AbundMain.java
public static void main(String[] args) throws IOException { File inputFile;/*from w w w . ja v a 2s.c o m*/ File resultDir = new File("."); RPlotter plotter = null; boolean isClusterFile = true; List<AbundStatsCalculator> statCalcs = new ArrayList(); double clustCutoffFrom = Double.MIN_VALUE, clustCutoffTo = Double.MAX_VALUE; String usage = "Main [options] <cluster file>"; try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption("result-dir")) { resultDir = new File(line.getOptionValue("result-dir")); if (!resultDir.exists() && !resultDir.mkdirs()) { throw new Exception( "Result directory " + resultDir + " does not exist and could not be created"); } } if (line.hasOption("R-location")) { plotter = new RPlotter(); plotter.setCommandTemplate(rplotterTemplate); plotter.setRPath(line.getOptionValue("R-location")); plotter.setOutFileExt(".png"); if (!new File(plotter.getRPath()).canExecute()) { throw new Exception(plotter.getRPath() + " does not exist or is not exectuable"); } } if (line.hasOption("lower-cutoff")) { clustCutoffFrom = Double.valueOf(line.getOptionValue("lower-cutoff")); } if (line.hasOption("upper-cutoff")) { clustCutoffTo = Double.valueOf(line.getOptionValue("upper-cutoff")); } if (line.hasOption("jaccard")) { statCalcs.add(new Jaccard(true)); } if (line.hasOption("sorensen")) { statCalcs.add(new Sorensen(true)); } if (line.hasOption("otu-table")) { isClusterFile = false; } if (statCalcs.isEmpty()) { throw new Exception("Must specify at least one stat to compute (jaccard, sorensen)"); } args = line.getArgs(); if (args.length != 1) { throw new Exception("Unexpected number of command line arguments"); } inputFile = new File(args[0]); } catch (Exception e) { new HelpFormatter().printHelp(usage, options); System.err.println("Error: " + e.getMessage()); return; } if (isClusterFile) { RDPClustParser parser; parser = new RDPClustParser(inputFile); try { if (parser.getClusterSamples().size() == 1) { throw new IOException("Cluster file must have more than one sample"); } List<Cutoff> cutoffs = parser.getCutoffs(clustCutoffFrom, clustCutoffTo); if (cutoffs.isEmpty()) { throw new IOException( "No cutoffs in cluster file in range [" + clustCutoffFrom + "-" + clustCutoffTo + "]"); } for (Cutoff cutoff : cutoffs) { List<Sample> samples = new ArrayList(); for (ClusterSample clustSample : parser.getClusterSamples()) { Sample s = new Sample(clustSample.getName()); for (Cluster clust : cutoff.getClusters().get(clustSample.getName())) { s.addSpecies(clust.getNumberOfSeqs()); } samples.add(s); } processSamples(samples, statCalcs, resultDir, cutoff.getCutoff() + "_", plotter); } } finally { parser.close(); } } else { List<Sample> samples = new ArrayList(); BufferedReader reader = new BufferedReader(new FileReader(inputFile)); String line = reader.readLine(); if (line == null || line.split("\\s+").length < 2) { throw new IOException("Must be 2 or more samples for abundance statistic calculations!"); } int numSamples = line.split("\\s+").length; boolean header = true; try { Integer.valueOf(line.split("\\s+")[0]); header = false; } catch (Exception e) { } if (header) { for (String s : line.split("\\s+")) { samples.add(new Sample(s)); } } else { int sample = 0; for (String s : line.split("\\s+")) { samples.add(new Sample("" + sample)); samples.get(sample).addSpecies(Integer.valueOf(s)); sample++; } } int lineno = 2; while ((line = reader.readLine()) != null) { if (line.trim().equals("")) { continue; } int sample = 0; if (line.split("\\s+").length != numSamples) { System.err.println( "Line number " + lineno + " didn't have the expected number of samples (contained " + line.split("\\s+").length + ", expected " + numSamples + ")"); } for (String s : line.split("\\s+")) { samples.get(sample).addSpecies(Integer.valueOf(s)); sample++; } lineno++; } processSamples(samples, statCalcs, resultDir, inputFile.getName(), plotter); } }
From source file:cz.muni.fi.pa165.creatures.rest.client.CreaturesRESTClient.java
public static void main(String[] args) { CommandLineParser parser = new PosixParser(); Options options = OptionsProvider.getInstance().getOptions(); try {/*from w w w . j ava2s . c o m*/ CommandLine line = parser.parse(options, args); if (!CommandLineValidator.validate(line)) { throw new ParseException("Command line arguments are not valid. Please refer the help"); } if (line.hasOption("h")) { CreaturesRESTClient.printHelp(options); System.exit(0); } CRUDService crudService; String operation = line.getOptionValue("o"); String uri; if (line.hasOption("u")) { uri = normalizeURI(line.getOptionValue("u")); } else { uri = DEFAULT_URI; } // weapon mode if (line.hasOption("w")) { crudService = new WeaponCRUDServiceImpl(uri + WEAPON_URI_PART); if (operation.equals("C")) { WeaponDTO dto = (WeaponDTO) DTOBuilder.get(WeaponDTO.class, line); crudService.create(dto); } else if (operation.equals("R")) { Long id = Long.parseLong(line.getOptionValue("i")); crudService.getById(id); } else if (operation.equals("U")) { WeaponDTO dto = (WeaponDTO) DTOBuilder.get(WeaponDTO.class, line); crudService.update(dto); } else if (operation.equals("D")) { Long id = Long.parseLong(line.getOptionValue("i")); crudService.delete(id); } else if (operation.equals("A")) { crudService.getAll(); } else if (operation.equals("N")) { crudService.getCount(); } // region mode } else if (line.hasOption("r")) { crudService = new RegionCRUDServiceImpl(uri + REGION_URI_PART); if (operation.equals("C")) { RegionDTO dto = (RegionDTO) DTOBuilder.get(RegionDTO.class, line); crudService.create(dto); } else if (operation.equals("R")) { Long id = Long.parseLong(line.getOptionValue("i")); crudService.getById(id); } else if (operation.equals("U")) { RegionDTO dto = (RegionDTO) DTOBuilder.get(RegionDTO.class, line); crudService.update(dto); } else if (operation.equals("D")) { Long id = Long.parseLong(line.getOptionValue("i")); crudService.delete(id); } else if (operation.equals("A")) { crudService.getAll(); } else if (operation.equals("N")) { crudService.getCount(); } } } catch (ParseException ex) { CreaturesRESTClient.printHelp(options); System.exit(1); } catch (IllegalArgumentException ex) { System.exit(1); } catch (JAXBException ex) { System.exit(1); } catch (Exception ex) { System.exit(1); } }
From source file:cc.wikitools.lucene.FetchWikipediaArticle.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(/* w ww . j a v a 2 s . c om*/ OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_OPTION)); options.addOption( OptionBuilder.withArgName("num").hasArg().withDescription("article id").create(ID_OPTION)); options.addOption( OptionBuilder.withArgName("string").hasArg().withDescription("article title").create(TITLE_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(ID_OPTION) || cmdline.hasOption(TITLE_OPTION)) || !cmdline.hasOption(INDEX_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(FetchWikipediaArticle.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); } WikipediaSearcher searcher = new WikipediaSearcher(indexLocation); PrintStream out = new PrintStream(System.out, true, "UTF-8"); if (cmdline.hasOption(ID_OPTION)) { int id = Integer.parseInt(cmdline.getOptionValue(ID_OPTION)); Document doc = searcher.getArticle(id); if (doc == null) { System.err.print("id " + id + " doesn't exist!\n"); } else { out.println(doc.getField(IndexField.TEXT.name).stringValue()); } } else { String title = cmdline.getOptionValue(TITLE_OPTION); Document doc = searcher.getArticle(title); if (doc == null) { System.err.print("article \"" + title + "\" doesn't exist!\n"); } else { out.println(doc.getField(IndexField.TEXT.name).stringValue()); } } searcher.close(); out.close(); }
From source file:com.trendmicro.hdfs.webdav.Main.java
public static void main(String[] args) { HDFSWebDAVServlet servlet = HDFSWebDAVServlet.getServlet(); Configuration conf = servlet.getConfiguration(); // Process command line Options options = new Options(); options.addOption("d", "debug", false, "Enable debug logging"); options.addOption("p", "port", true, "Port to bind to [default: 8080]"); options.addOption("b", "bind-address", true, "Address or hostname to bind to [default: 0.0.0.0]"); options.addOption("g", "ganglia", true, "Send Ganglia metrics to host:port [default: none]"); CommandLine cmd = null; try {//from ww w . ja va 2s . c o m cmd = new PosixParser().parse(options, args); } catch (ParseException e) { printUsageAndExit(options, -1); } if (cmd.hasOption('d')) { Logger rootLogger = Logger.getLogger("com.trendmicro"); rootLogger.setLevel(Level.DEBUG); } if (cmd.hasOption('b')) { conf.set("hadoop.webdav.bind.address", cmd.getOptionValue('b')); } if (cmd.hasOption('p')) { conf.setInt("hadoop.webdav.port", Integer.valueOf(cmd.getOptionValue('p'))); } String gangliaHost = null; int gangliaPort = 8649; if (cmd.hasOption('g')) { String val = cmd.getOptionValue('g'); if (val.indexOf(':') != -1) { String[] split = val.split(":"); gangliaHost = split[0]; gangliaPort = Integer.valueOf(split[1]); } else { gangliaHost = val; } } InetSocketAddress addr = getAddress(conf); // Log in the server principal from keytab UserGroupInformation.setConfiguration(conf); if (UserGroupInformation.isSecurityEnabled()) try { SecurityUtil.login(conf, "hadoop.webdav.server.kerberos.keytab", "hadoop.webdav.server.kerberos.principal", addr.getHostName()); } catch (IOException e) { LOG.fatal("Could not log in", e); System.err.println("Could not log in"); System.exit(-1); } // Set up embedded Jetty Server server = new Server(); server.setSendServerVersion(false); server.setSendDateHeader(false); server.setStopAtShutdown(true); // Set up connector Connector connector = new SelectChannelConnector(); connector.setPort(addr.getPort()); connector.setHost(addr.getHostName()); server.addConnector(connector); LOG.info("Listening on " + addr); // Set up context Context context = new Context(server, "/", Context.SESSIONS); // WebDAV servlet ServletHolder servletHolder = new ServletHolder(servlet); servletHolder.setInitParameter("authenticate-header", "Basic realm=\"Hadoop WebDAV Server\""); context.addServlet(servletHolder, "/*"); // metrics instrumentation filter context.addFilter(new FilterHolder(new DefaultWebappMetricsFilter()), "/*", 0); // auth filter context.addFilter(new FilterHolder(new AuthFilter(conf)), "/*", 0); server.setHandler(context); // Set up Ganglia metrics reporting if (gangliaHost != null) { GangliaReporter.enable(1, TimeUnit.MINUTES, gangliaHost, gangliaPort); } // Start and join the server thread try { server.start(); server.join(); } catch (Exception e) { LOG.fatal("Failed to start Jetty", e); System.err.println("Failed to start Jetty"); System.exit(-1); } }
From source file:net.iridiant.hdfs.webdav.Main.java
public static void main(String[] args) { HDFSWebDAVServlet servlet = HDFSWebDAVServlet.getServlet(); Configuration conf = servlet.getConfiguration(); // Process command line Options options = new Options(); options.addOption("d", "debug", false, "Enable debug logging"); options.addOption("p", "port", true, "Port to bind to [default: 8080]"); options.addOption("b", "bind-address", true, "Address or hostname to bind to [default: 0.0.0.0]"); options.addOption("g", "ganglia", true, "Send Ganglia metrics to host:port [default: none]"); CommandLine cmd = null; try {//from ww w . j a v a2s . com cmd = new PosixParser().parse(options, args); } catch (ParseException e) { printUsageAndExit(options, -1); } if (cmd.hasOption('d')) { Logger rootLogger = Logger.getLogger("net.iridiant"); rootLogger.setLevel(Level.DEBUG); } if (cmd.hasOption('b')) { conf.set("hadoop.webdav.bind.address", cmd.getOptionValue('b')); } if (cmd.hasOption('p')) { conf.setInt("hadoop.webdav.port", Integer.valueOf(cmd.getOptionValue('p'))); } String gangliaHost = null; int gangliaPort = 8649; if (cmd.hasOption('g')) { String val = cmd.getOptionValue('g'); if (val.indexOf(':') != -1) { String[] split = val.split(":"); gangliaHost = split[0]; gangliaPort = Integer.valueOf(split[1]); } else { gangliaHost = val; } } InetSocketAddress addr = getAddress(conf); // Log in the server principal from keytab UserGroupInformation.setConfiguration(conf); if (UserGroupInformation.isSecurityEnabled()) try { SecurityUtil.login(conf, "hadoop.webdav.server.kerberos.keytab", "hadoop.webdav.server.kerberos.principal", addr.getHostName()); } catch (IOException e) { LOG.fatal("Could not log in", e); System.err.println("Could not log in"); System.exit(-1); } // Set up embedded Jetty Server server = new Server(); server.setSendServerVersion(false); server.setSendDateHeader(false); server.setStopAtShutdown(true); // Set up connector Connector connector = new SelectChannelConnector(); connector.setPort(addr.getPort()); connector.setHost(addr.getHostName()); server.addConnector(connector); LOG.info("Listening on " + addr); // Set up context Context context = new Context(server, "/", Context.SESSIONS); // WebDAV servlet ServletHolder servletHolder = new ServletHolder(servlet); servletHolder.setInitParameter("authenticate-header", "Basic realm=\"Hadoop WebDAV Server\""); context.addServlet(servletHolder, "/*"); // metrics instrumentation filter context.addFilter(new FilterHolder(new DefaultWebappMetricsFilter()), "/*", 0); // auth filter context.addFilter(new FilterHolder(new AuthFilter(conf)), "/*", 0); server.setHandler(context); // Set up Ganglia metrics reporting if (gangliaHost != null) { GangliaReporter.enable(1, TimeUnit.MINUTES, gangliaHost, gangliaPort); } // Start and join the server thread try { server.start(); server.join(); } catch (Exception e) { LOG.fatal("Failed to start Jetty", e); System.err.println("Failed to start Jetty"); System.exit(-1); } }
From source file:com.navercorp.client.Main.java
public static void main(String[] args) { Client clnt = null;//from w ww.j a v a2 s . co m try { CommandLine cmd = new DefaultParser() .parse(new Options().addOption("z", true, "zookeeper address (ip:port,ip:port,...)") .addOption("t", true, "zookeeper connection timeout") .addOption("c", true, "command and arguments"), args); final String connectionString = cmd.hasOption("z") ? cmd.getOptionValue("z") : "127.0.0.1:2181"; final int timeout = cmd.hasOption("t") ? Integer.valueOf(cmd.getOptionValue("t")) : 10000; clnt = new Client(connectionString, timeout); String command; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while ((command = in.readLine()) != null) { printResult(clnt.execute(command.split(" "))); } System.exit(Code.OK.n()); } catch (ParseException e) { e.printStackTrace(System.err); System.err.println(Client.getUsage()); System.exit(INVALID_ARGUMENT.n()); } catch (IOException e) { e.printStackTrace(System.err); System.exit(ZK_CONNECTION_LOSS.n()); } catch (InterruptedException e) { e.printStackTrace(System.err); System.exit(INTERNAL_ERROR.n()); } finally { if (clnt != null) { try { clnt.close(); } catch (Exception e) { ; // nothing to do } } } }
From source file:com.obidea.semantika.cli.Main.java
public static void main(String[] args) { @SuppressWarnings("unchecked") List<Logger> loggers = Collections.list(LogManager.getCurrentLoggers()); loggers.add(LogManager.getRootLogger()); normal(loggers);/*from w w w .j a v a 2s . c om*/ try { CommandLineParser parser = new GnuParser(); CommandLine optionLine = parser.parse(sOptions, args); if (optionLine.hasOption(Environment.VERSION)) { printVersion(); System.exit(0); } if (optionLine.hasOption(Environment.HELP)) { printUsage(); System.exit(0); } String operation = determineOperation(args); if (StringUtils.isEmpty(operation)) { printUsage(); } else { setupLoggers(optionLine, loggers); executeOperation(operation, optionLine); } } catch (Exception e) { System.err.println("Unexpected exception:" + e.getMessage()); //$NON-NLS-1$ System.exit(1); } }