List of usage examples for java.lang Integer parseInt
public static int parseInt(String s) throws NumberFormatException
From source file:com.microsoft.kafkaavailability.App.java
public static void main(String[] args) throws IOException, MetaDataManagerException, InterruptedException { System.out.println("Starting KafkaAvailability Tool"); IPropertiesManager appPropertiesManager = new PropertiesManager<AppProperties>("appProperties.json", AppProperties.class); appProperties = (AppProperties) appPropertiesManager.getProperties(); Options options = new Options(); options.addOption("r", "run", true, "Number of runs. Don't use this argument if you want to run infintely."); options.addOption("s", "sleep", true, "Time (in milliseconds) to sleep between each run. Default is 300000"); Option clusterOption = Option.builder("c").hasArg().required(true).longOpt("cluster") .desc("(REQUIRED) Cluster name").build(); options.addOption(clusterOption);/*from w w w . ja va 2s.c o m*/ CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); try { // parse the command line arguments CommandLine line = parser.parse(options, args); int howManyRuns; m_cluster = line.getOptionValue("cluster"); MDC.put("cluster", m_cluster); if (line.hasOption("sleep")) { m_sleepTime = Integer.parseInt(line.getOptionValue("sleep")); } if (line.hasOption("run")) { howManyRuns = Integer.parseInt(line.getOptionValue("run")); for (int i = 0; i < howManyRuns; i++) { InitMetrics(); RunOnce(); Thread.sleep(m_sleepTime); } } else { while (true) { InitMetrics(); RunOnce(); Thread.sleep(m_sleepTime); } } } catch (ParseException exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); formatter.printHelp("KafkaAvailability", options); } }
From source file:com.mozilla.bagheera.consumer.KafkaReplayConsumer.java
public static void main(String[] args) { OptionFactory optFactory = OptionFactory.getInstance(); Options options = KafkaConsumer.getOptions(); options.addOption(/* w w w . j a v a 2 s. co m*/ optFactory.create("k", "copy-keys", true, "Whether or not to copy keys from the source data")); options.addOption(optFactory.create("d", "dest", true, "Destination host / url pattern (include '" + ReplaySink.KEY_PLACEHOLDER + "' for key placeholder)") .required()); options.addOption(optFactory.create("s", "sample", true, "Rate at which to sample the source data (defaults to using all data)")); options.addOption( optFactory.create("D", "delete", true, "Also replay deletes (using the source keys by necessity)")); CommandLineParser parser = new GnuParser(); ShutdownHook sh = ShutdownHook.getInstance(); try { // Parse command line options CommandLine cmd = parser.parse(options, args); final KafkaConsumer consumer = KafkaConsumer.fromOptions(cmd); sh.addFirst(consumer); // Create a sink for storing data SinkConfiguration sinkConfig = new SinkConfiguration(); if (cmd.hasOption("numthreads")) { sinkConfig.setInt("hbasesink.hbase.numthreads", Integer.parseInt(cmd.getOptionValue("numthreads"))); } sinkConfig.setString("replaysink.keys", cmd.getOptionValue("copy-keys", "true")); sinkConfig.setString("replaysink.dest", cmd.getOptionValue("dest", "http://bogus:8080/submit/endpoint/" + ReplaySink.KEY_PLACEHOLDER)); sinkConfig.setString("replaysink.sample", cmd.getOptionValue("sample", "1")); sinkConfig.setString("replaysink.delete", cmd.getOptionValue("delete", "true")); KeyValueSinkFactory sinkFactory = KeyValueSinkFactory.getInstance(ReplaySink.class, sinkConfig); sh.addLast(sinkFactory); // Set the sink factory for consumer storage consumer.setSinkFactory(sinkFactory); prepareHealthChecks(); // Initialize metrics collection, reporting, etc. final MetricsManager manager = MetricsManager.getDefaultMetricsManager(); // Begin polling consumer.poll(); } catch (ParseException e) { LOG.error("Error parsing command line options", e); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(KafkaReplayConsumer.class.getName(), options); } }
From source file:edu.cmu.lti.oaqa.annographix.apps.SolrIndexApp.java
public static void main(String[] args) { Options options = new Options(); options.addOption("t", null, true, "Text File"); options.addOption("a", null, true, "Annotation File"); options.addOption("u", null, true, "Solr URI"); options.addOption("n", null, true, "Batch size"); options.addOption(//www. j av a2 s . c o m OptionBuilder.withLongOpt(TEXT_FIELD_ARG).withDescription("Text field name").hasArg().create()); options.addOption(OptionBuilder.withLongOpt(ANNOT_FIELD_ARG).withDescription("Annotation field name") .hasArg().create()); CommandLineParser parser = new org.apache.commons.cli.GnuParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("t")) { docTextFile = cmd.getOptionValue("t"); } else { Usage("Specify Text File"); } if (cmd.hasOption("a")) { docAnnotFile = cmd.getOptionValue("a"); } else { Usage("Specify Annotation File"); } if (cmd.hasOption("u")) { solrURI = cmd.getOptionValue("u"); } else { Usage("Specify Solr URI"); } if (cmd.hasOption("n")) { batchQty = Integer.parseInt(cmd.getOptionValue("n")); } String textFieldName = UtilConst.DEFAULT_TEXT4ANNOT_FIELD; String annotFieldName = UtilConst.DEFAULT_ANNOT_FIELD; if (cmd.hasOption(TEXT_FIELD_ARG)) { textFieldName = cmd.getOptionValue(TEXT_FIELD_ARG); } if (cmd.hasOption(ANNOT_FIELD_ARG)) { annotFieldName = cmd.getOptionValue(ANNOT_FIELD_ARG); } System.out.println(String.format("Annotated text field: '%s', annotation field: '%s'", textFieldName, annotFieldName)); // Ignoring return value here SolrUtils.parseAndCheckConfig(solrURI, textFieldName, annotFieldName); System.out.println("Config is fine!"); DocumentReader.readDoc(docTextFile, textFieldName, docAnnotFile, batchQty, new SolrDocumentIndexer(solrURI, textFieldName, annotFieldName)); } catch (ParseException e) { Usage("Cannot parse arguments"); } catch (Exception e) { System.err.println("Terminating due to an exception: " + e); System.exit(1); } }
From source file:io.s4.tools.loadgenerator.LoadGenerator.java
public static void main(String args[]) { Options options = new Options(); boolean warmUp = false; options.addOption(/*from ww w . j a v a 2 s. c om*/ OptionBuilder.withArgName("rate").hasArg().withDescription("Rate (events per second)").create("r")); options.addOption(OptionBuilder.withArgName("display_rate").hasArg() .withDescription("Display Rate at specified second boundary").create("d")); options.addOption(OptionBuilder.withArgName("adapter_address").hasArg() .withDescription("Address of client adapter").create("a")); options.addOption(OptionBuilder.withArgName("listener_application_name").hasArg() .withDescription("Listener application name").create("g")); options.addOption( OptionBuilder.withArgName("sleep_overhead").hasArg().withDescription("Sleep overhead").create("o")); options.addOption(new Option("w", "Warm-up")); CommandLineParser parser = new GnuParser(); CommandLine line = null; try { // parse the command line arguments line = parser.parse(options, args); } catch (ParseException exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); System.exit(1); } int expectedRate = 250; if (line.hasOption("r")) { try { expectedRate = Integer.parseInt(line.getOptionValue("r")); } catch (Exception e) { System.err.println("Bad expected rate specified " + line.getOptionValue("r")); System.exit(1); } } int displayRateIntervalSeconds = 20; if (line.hasOption("d")) { try { displayRateIntervalSeconds = Integer.parseInt(line.getOptionValue("d")); } catch (Exception e) { System.err.println("Bad display rate value specified " + line.getOptionValue("d")); System.exit(1); } } int updateFrequency = 0; if (line.hasOption("f")) { try { updateFrequency = Integer.parseInt(line.getOptionValue("f")); } catch (Exception e) { System.err.println("Bad query udpdate frequency specified " + line.getOptionValue("f")); System.exit(1); } System.out.printf("Update frequency is %d\n", updateFrequency); } String clientAdapterAddress = null; String clientAdapterHost = null; int clientAdapterPort = -1; if (line.hasOption("a")) { clientAdapterAddress = line.getOptionValue("a"); String[] parts = clientAdapterAddress.split(":"); if (parts.length != 2) { System.err.println("Bad adapter address specified " + clientAdapterAddress); System.exit(1); } clientAdapterHost = parts[0]; try { clientAdapterPort = Integer.parseInt(parts[1]); } catch (NumberFormatException nfe) { System.err.println("Bad adapter address specified " + clientAdapterAddress); System.exit(1); } } long sleepOverheadMicros = -1; if (line.hasOption("o")) { try { sleepOverheadMicros = Long.parseLong(line.getOptionValue("o")); } catch (NumberFormatException e) { System.err.println("Bad sleep overhead specified " + line.getOptionValue("o")); System.exit(1); } System.out.printf("Specified sleep overhead is %d\n", sleepOverheadMicros); } if (line.hasOption("w")) { warmUp = true; } List loArgs = line.getArgList(); if (loArgs.size() < 1) { System.err.println("No input file specified"); System.exit(1); } String inputFilename = (String) loArgs.get(0); LoadGenerator loadGenerator = new LoadGenerator(); loadGenerator.setInputFilename(inputFilename); loadGenerator.setDisplayRateInterval(displayRateIntervalSeconds); loadGenerator.setExpectedRate(expectedRate); loadGenerator.setClientAdapterHost(clientAdapterHost); loadGenerator.setClientAdapterPort(clientAdapterPort); loadGenerator.run(); System.exit(0); }
From source file:com.redhat.poc.jdg.bankofchina.function.TestCase411RemoteMultiThreadsCustomMarshal.java
public static void main(String[] args) throws Exception { CommandLine commandLine;// ww w . j av a 2 s . c o m Options options = new Options(); options.addOption("s", true, "The start csv file number option"); options.addOption("e", true, "The end csv file number option"); BasicParser parser = new BasicParser(); parser.parse(options, args); commandLine = parser.parse(options, args); if (commandLine.getOptions().length > 0) { if (commandLine.hasOption("s")) { String start = commandLine.getOptionValue("s"); if (start != null && start.length() > 0) { csvFileStart = Integer.parseInt(start); } } if (commandLine.hasOption("e")) { String end = commandLine.getOptionValue("e"); if (end != null && end.length() > 0) { csvFileEnd = Integer.parseInt(end); } } } System.out.println( "%%%%%%%%% csv ?, ?, ?(ms)," + new Date().getTime()); for (int i = csvFileStart; i <= csvFileEnd; i++) { new TestCase411RemoteMultiThreadsCustomMarshal(i).start(); } }
From source file:edu.uci.ics.crawler4j.weatherCrawler.BasicCrawlController.java
public static void main(String[] args) { String folder = ConfigUtils.getFolder(); String crawlerCount = ConfigUtils.getCrawlerCount(); args = new String[2]; if (StringUtils.isBlank(folder) || StringUtils.isBlank(crawlerCount)) { args[0] = "weather"; args[1] = "10"; System.out.println("No parameters in config.properties ......."); System.out.println("[weather] will be used as rootFolder (it will contain intermediate crawl data)"); System.out.println("[10] will be used as numberOfCralwers (number of concurrent threads)"); } else {/*from w w w. j a v a 2s.c o m*/ args[0] = folder; args[1] = crawlerCount; } /* * crawlStorageFolder is a folder where intermediate crawl data is * stored. */ String crawlStorageFolder = args[0]; /* * numberOfCrawlers shows the number of concurrent threads that should * be initiated for crawling. */ int numberOfCrawlers = Integer.parseInt(args[1]); CrawlConfig config = new CrawlConfig(); if (crawlStorageFolder != null && IO.deleteFolderContents(new File(crawlStorageFolder))) System.out.println(""); config.setCrawlStorageFolder(crawlStorageFolder + "/d" + System.currentTimeMillis()); /* * Be polite: Make sure that we don't send more than 1 request per * second (1000 milliseconds between requests). */ config.setPolitenessDelay(1000); config.setConnectionTimeout(1000 * 60); // config1.setPolitenessDelay(1000); /* * You can set the maximum crawl depth here. The default value is -1 for * unlimited depth */ config.setMaxDepthOfCrawling(StringUtils.isBlank(ConfigUtils.getCrawlerDepth()) ? 40 : Integer.valueOf(ConfigUtils.getCrawlerDepth())); // config1.setMaxDepthOfCrawling(0); /* * You can set the maximum number of pages to crawl. The default value * is -1 for unlimited number of pages */ config.setMaxPagesToFetch(100000); // config1.setMaxPagesToFetch(10000); /* * Do you need to set a proxy? If so, you can use: * config.setProxyHost("proxyserver.example.com"); * config.setProxyPort(8080); * * If your proxy also needs authentication: * config.setProxyUsername(username); config.getProxyPassword(password); */ if (ConfigUtils.getValue("useProxy", "false").equalsIgnoreCase("true")) { System.out.println("?============"); List<ProxySetting> proxys = ConfigUtils.getProxyList(); ProxySetting proxy = proxys.get(RandomUtils.nextInt(proxys.size() - 1)); /* test the proxy is alaviable or not */ while (!TestProxy.testProxyAvailable(proxy)) { proxy = proxys.get(RandomUtils.nextInt(proxys.size() - 1)); } System.out.println("??" + proxy.getIp() + ":" + proxy.getPort()); config.setProxyHost(proxy.getIp()); config.setProxyPort(proxy.getPort()); // config.setProxyHost("127.0.0.1"); // config.setProxyPort(8087); } else { System.out.println("??============"); } /* * This config parameter can be used to set your crawl to be resumable * (meaning that you can resume the crawl from a previously * interrupted/crashed crawl). Note: if you enable resuming feature and * want to start a fresh crawl, you need to delete the contents of * rootFolder manually. */ config.setResumableCrawling(false); // config1.setResumableCrawling(false); /* * Instantiate the controller for this crawl. */ PageFetcher pageFetcher = new PageFetcher(config); // PageFetcher pageFetcher1 = new PageFetcher(config1); RobotstxtConfig robotstxtConfig = new RobotstxtConfig(); RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher); try { /* * For each crawl, you need to add some seed urls. These are the * first URLs that are fetched and then the crawler starts following * links which are found in these pages */ CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer); controller.addSeed(StringUtils.isBlank(ConfigUtils.getSeed()) ? "http://www.tianqi.com/chinacity.html" : ConfigUtils.getSeed()); // controller.addSeed("http://www.ics.uci.edu/~lopes/"); // controller.addSeed("http://www.ics.uci.edu/~welling/"); /* * Start the crawl. This is a blocking operation, meaning that your * code will reach the line after this only when crawling is * finished. */ String isDaily = null; isDaily = ConfigUtils.getValue("isDaily", "true"); System.out .println("?=======" + ConfigUtils.getValue("table", "weather_data") + "======="); if (isDaily.equalsIgnoreCase("true")) { System.out.println("???=============="); controller.start(BasicDailyCrawler.class, numberOfCrawlers); } else { System.out.println("???=============="); controller.start(BasicCrawler.class, numberOfCrawlers); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:org.ala.harvester.HarvestRunner.java
/** * Main method//w ww . j a va2 s . c o m * * @param args */ public static void main(String[] args) { // Get Spring context context = new ClassPathXmlApplicationContext("classpath*:spring.xml"); //InfoSourceDAO infoSourceDAORO = (InfoSourceDAO) context.getBean("infoSourceDao"); HarvestRunner hr = (HarvestRunner) context.getBean("harvestRunner"); if (args.length < 1) { System.out.println( "Please enter an info source ID to harvest OR enter \"all\" " + "to harvest all info sources"); System.exit(-1); } else if (args.length < 2 && args[0].equalsIgnoreCase("all")) { logger.info("Harvesting all info sources..."); List<Integer> infoSourceIds = hr.getAllIds(); hr.harvest(infoSourceIds); } else if (args.length < 2) { try { Integer infoSourceId = Integer.parseInt(args[0]); List<Integer> infoSourceIds = new ArrayList<Integer>(); infoSourceIds.add(infoSourceId); hr.harvest(infoSourceIds); } catch (NumberFormatException ex) { logger.error("info source id was not recognised as a number: " + ex.getMessage()); } } else if (args.length < 3 && args[0].equalsIgnoreCase("all")) { try { Integer timeGap = Integer.parseInt(args[1]); logger.info("Harvesting all info sources..."); List<Integer> infoSourceIds = hr.getAllIds(); hr.harvest(infoSourceIds, timeGap); } catch (NumberFormatException ex) { logger.error("time gap was not recognised as a number: " + ex.getMessage()); } } else if (args.length < 3) { try { Integer infoSourceId = Integer.parseInt(args[0]); Integer timeGap = Integer.parseInt(args[1]); List<Integer> infoSourceIds = new ArrayList<Integer>(); infoSourceIds.add(infoSourceId); hr.harvest(infoSourceIds, timeGap); } catch (NumberFormatException ex) { logger.error("info source id was not recognised as a number: " + ex.getMessage()); } } }
From source file:com.betfair.cougar.test.socket.app.SocketCompatibilityTestingApp.java
public static void main(String[] args) throws Exception { Parser parser = new PosixParser(); Options options = new Options(); options.addOption("r", "repo", true, "Repository type to search: local|central"); options.addOption("c", "client-concurrency", true, "Max threads to allow each client tester to run tests, defaults to 10"); options.addOption("t", "test-concurrency", true, "Max client testers to run concurrently, defaults to 5"); options.addOption("m", "max-time", true, "Max time (in minutes) to allow tests to complete, defaults to 10"); options.addOption("v", "version", false, "Print version and exit"); options.addOption("h", "help", false, "This help text"); CommandLine commandLine = parser.parse(options, args); if (commandLine.hasOption("h")) { System.out.println(options); System.exit(0);/*from ww w. jav a 2 s .c om*/ } if (commandLine.hasOption("v")) { System.out.println("How the hell should I know?"); System.exit(0); } // 1. Find all testers in given repos List<RepoSearcher> repoSearchers = new ArrayList<>(); for (String repo : commandLine.getOptionValues("r")) { if ("local".equals(repo.toLowerCase())) { repoSearchers.add(new LocalRepoSearcher()); } else if ("central".equals(repo.toLowerCase())) { repoSearchers.add(new CentralRepoSearcher()); } else { System.err.println("Unrecognized repo: " + repo); System.err.println(options); System.exit(1); } } int clientConcurrency = 10; if (commandLine.hasOption("c")) { try { clientConcurrency = Integer.parseInt(commandLine.getOptionValue("c")); } catch (NumberFormatException nfe) { System.err.println( "client-concurrency is not a valid integer: '" + commandLine.getOptionValue("c") + "'"); System.exit(1); } } int testConcurrency = 5; if (commandLine.hasOption("t")) { try { testConcurrency = Integer.parseInt(commandLine.getOptionValue("t")); } catch (NumberFormatException nfe) { System.err.println( "test-concurrency is not a valid integer: '" + commandLine.getOptionValue("t") + "'"); System.exit(1); } } int maxMinutes = 10; if (commandLine.hasOption("m")) { try { maxMinutes = Integer.parseInt(commandLine.getOptionValue("m")); } catch (NumberFormatException nfe) { System.err.println("max-time is not a valid integer: '" + commandLine.getOptionValue("m") + "'"); System.exit(1); } } Properties clientProps = new Properties(); clientProps.setProperty("client.concurrency", String.valueOf(clientConcurrency)); File baseRunDir = new File(System.getProperty("user.dir") + "/run"); baseRunDir.mkdirs(); File tmpDir = new File(baseRunDir, "jars"); tmpDir.mkdirs(); List<ServerRunner> serverRunners = new ArrayList<>(); List<ClientRunner> clientRunners = new ArrayList<>(); for (RepoSearcher searcher : repoSearchers) { List<File> jars = searcher.findAndCache(tmpDir); for (File f : jars) { ServerRunner serverRunner = new ServerRunner(f, baseRunDir); System.out.println("Found tester: " + serverRunner.getVersion()); serverRunners.add(serverRunner); clientRunners.add(new ClientRunner(f, baseRunDir, clientProps)); } } // 2. Start servers and collect ports System.out.println(); System.out.println("Starting " + serverRunners.size() + " servers..."); for (ServerRunner server : serverRunners) { server.startServer(); } System.out.println(); List<TestCombo> tests = new ArrayList<>(serverRunners.size() * clientRunners.size()); for (ServerRunner server : serverRunners) { for (ClientRunner client : clientRunners) { tests.add(new TestCombo(server, client)); } } System.out.println("Enqueued " + tests.size() + " test combos to run..."); long startTime = System.currentTimeMillis(); // 3. Run every client against every server, collecting results BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue(serverRunners.size() * clientRunners.size()); ThreadPoolExecutor service = new ThreadPoolExecutor(testConcurrency, testConcurrency, 5000, TimeUnit.MILLISECONDS, workQueue); service.prestartAllCoreThreads(); workQueue.addAll(tests); while (!workQueue.isEmpty()) { Thread.sleep(1000); } service.shutdown(); service.awaitTermination(maxMinutes, TimeUnit.MINUTES); long endTime = System.currentTimeMillis(); long totalTimeSecs = Math.round((endTime - startTime) / 1000.0); for (ServerRunner server : serverRunners) { server.shutdownServer(); } System.out.println(); System.out.println("======="); System.out.println("Results"); System.out.println("-------"); // print a summary int totalTests = 0; int totalSuccess = 0; for (TestCombo combo : tests) { String clientVer = combo.getClientVersion(); String serverVer = combo.getServerVersion(); String results = combo.getClientResults(); ObjectMapper mapper = new ObjectMapper(new JsonFactory()); JsonNode node = mapper.reader().readTree(results); JsonNode resultsArray = node.get("results"); int numTests = resultsArray.size(); int numSuccess = 0; for (int i = 0; i < numTests; i++) { if ("success".equals(resultsArray.get(i).get("result").asText())) { numSuccess++; } } totalSuccess += numSuccess; totalTests += numTests; System.out.println(clientVer + "/" + serverVer + ": " + numSuccess + "/" + numTests + " succeeded - took " + String.format("%2f", combo.getRunningTime()) + " seconds"); } System.out.println("-------"); System.out.println( "Overall: " + totalSuccess + "/" + totalTests + " succeeded - took " + totalTimeSecs + " seconds"); FileWriter out = new FileWriter("results.json"); PrintWriter pw = new PrintWriter(out); // 4. Output full results pw.println("{\n \"results\": ["); for (TestCombo combo : tests) { combo.emitResults(pw, " "); } pw.println(" ],"); pw.println(" \"servers\": ["); for (ServerRunner server : serverRunners) { server.emitInfo(pw, " "); } pw.println(" ],"); pw.close(); }
From source file:org.zaizi.sensefy.auth.AuthServerApplication.java
public static void main(String[] args) { SpringApplication.run(AuthServerApplication.class, args); int port = Integer.parseInt(System.getProperty("jetty.port", "8080")); int requestHeaderSize = Integer.parseInt(System.getProperty("jetty.header.size", "65536")); Server server = new Server(port); server.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize", -1); ProtectionDomain domain = AuthServerApplication.class.getProtectionDomain(); URL location = domain.getCodeSource().getLocation(); // Set request header size // server.getConnectors()[0].setRequestHeaderSize(requestHeaderSize); WebAppContext webapp = new WebAppContext(); webapp.setContextPath("/auth"); webapp.setDescriptor(location.toExternalForm() + "/WEB-INF/web.xml"); webapp.setServer(server);/*from w ww.j av a 2 s . co m*/ webapp.setWar(location.toExternalForm()); // (Optional) Set the directory the war will extract to. // If not set, java.io.tmpdir will be used, which can cause problems // if the temp directory gets cleaned periodically. // Your build scripts should remove this directory between deployments // webapp.setTempDirectory(new File("/path/to/webapp-directory")); server.setHandler(webapp); try { server.start(); server.join(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:dhtaccess.tools.Put.java
public static void main(String[] args) { byte[] secret = null; int ttl = 3600; // parse properties Properties prop = System.getProperties(); String gateway = prop.getProperty("dhtaccess.gateway"); if (gateway == null || gateway.length() <= 0) { gateway = DEFAULT_GATEWAY;//from ww w . jav a 2 s. c o m } // 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("s", "secret", true, "can be used to remove the value later"); options.addOption("t", "ttl", true, "how long (in seconds) to store the value"); 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; } optVal = cmd.getOptionValue('s'); if (optVal != null) { try { secret = optVal.getBytes(ENCODE); } catch (UnsupportedEncodingException e) { // NOTREACHED } } optVal = cmd.getOptionValue('t'); if (optVal != null) { ttl = Integer.parseInt(optVal); } args = cmd.getArgs(); // parse arguments if (args.length < 2) { usage(COMMAND); System.exit(1); } for (int index = 0; index + 1 < args.length; index += 2) { byte[] key = null, value = null; try { key = args[index].getBytes(ENCODE); value = args[index + 1].getBytes(ENCODE); } catch (UnsupportedEncodingException e1) { // NOTREACHED } // prepare for RPC DHTAccessor accessor = null; try { accessor = new DHTAccessor(gateway); } catch (MalformedURLException e) { e.printStackTrace(); System.exit(1); } // RPC int res = accessor.put(key, value, ttl, secret); String resultString; switch (res) { case 0: resultString = "Success"; break; case 1: resultString = "Capacity"; break; case 2: resultString = "Again"; break; default: resultString = "???"; } System.out.println(resultString + ": " + args[index] + ", " + args[index + 1]); } }