List of usage examples for org.apache.commons.cli Option setRequired
public void setRequired(boolean required)
From source file:fr.inria.atlanmod.kyanos.benchmarks.KyanosGraphQueryLoop.java
public static void main(String[] args) { Options options = new Options(); Option inputOpt = OptionBuilder.create(IN); inputOpt.setArgName("INPUT"); inputOpt.setDescription("Input Kyanos resource directory"); inputOpt.setArgs(1);/*from ww w . jav a2s . c o m*/ inputOpt.setRequired(true); Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS); inClassOpt.setArgName("CLASS"); inClassOpt.setDescription("FQN of EPackage implementation class"); inClassOpt.setArgs(1); inClassOpt.setRequired(true); Option optFileOpt = OptionBuilder.create(OPTIONS_FILE); optFileOpt.setArgName("FILE"); optFileOpt.setDescription("Properties file holding the options to be used in the Kyanos Resource"); optFileOpt.setArgs(1); options.addOption(inputOpt); options.addOption(inClassOpt); options.addOption(optFileOpt); CommandLineParser parser = new PosixParser(); try { PersistenceBackendFactoryRegistry.getFactories().put(NeoBlueprintsURI.NEO_GRAPH_SCHEME, new BlueprintsPersistenceBackendFactory()); CommandLine commandLine = parser.parse(options, args); URI uri = NeoBlueprintsURI.createNeoGraphURI(new File(commandLine.getOptionValue(IN))); Class<?> inClazz = KyanosGraphQueryLoop.class.getClassLoader() .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS)); inClazz.getMethod("init").invoke(null); ResourceSet resourceSet = new ResourceSetImpl(); resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap() .put(NeoBlueprintsURI.NEO_GRAPH_SCHEME, PersistentResourceFactory.eINSTANCE); Resource resource = resourceSet.createResource(uri); Map<String, Object> loadOpts = new HashMap<String, Object>(); if (commandLine.hasOption(OPTIONS_FILE)) { Properties properties = new Properties(); properties.load(new FileInputStream(new File(commandLine.getOptionValue(OPTIONS_FILE)))); for (final Entry<Object, Object> entry : properties.entrySet()) { loadOpts.put((String) entry.getKey(), (String) entry.getValue()); } } resource.load(loadOpts); { LOG.log(Level.INFO, "Start query"); long begin = System.currentTimeMillis(); EList<MethodDeclaration> list = JavaQueries.getUnusedMethodsLoop(resource); long end = System.currentTimeMillis(); LOG.log(Level.INFO, "End query"); LOG.log(Level.INFO, MessageFormat.format("Query result (loops) contains {0} elements", list.size())); LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin))); } if (resource instanceof PersistentResourceImpl) { PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) resource); } else { resource.unload(); } } catch (ParseException e) { MessageUtil.showError(e.toString()); MessageUtil.showError("Current arguments: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar <this-file.jar>", options, true); } catch (Throwable e) { MessageUtil.showError(e.toString()); } }
From source file:fr.inria.atlanmod.kyanos.benchmarks.KyanosGraphQueryRenameAllMethods.java
public static void main(String[] args) { Options options = new Options(); Option inputOpt = OptionBuilder.create(IN); inputOpt.setArgName("INPUT"); inputOpt.setDescription("Input Kyanos resource directory"); inputOpt.setArgs(1);/*from w w w . jav a 2 s .c o m*/ inputOpt.setRequired(true); Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS); inClassOpt.setArgName("CLASS"); inClassOpt.setDescription("FQN of EPackage implementation class"); inClassOpt.setArgs(1); inClassOpt.setRequired(true); Option optFileOpt = OptionBuilder.create(OPTIONS_FILE); optFileOpt.setArgName("FILE"); optFileOpt.setDescription("Properties file holding the options to be used in the Kyanos Resource"); optFileOpt.setArgs(1); options.addOption(inputOpt); options.addOption(inClassOpt); options.addOption(optFileOpt); CommandLineParser parser = new PosixParser(); try { PersistenceBackendFactoryRegistry.getFactories().put(NeoBlueprintsURI.NEO_GRAPH_SCHEME, new BlueprintsPersistenceBackendFactory()); CommandLine commandLine = parser.parse(options, args); URI uri = NeoBlueprintsURI.createNeoGraphURI(new File(commandLine.getOptionValue(IN))); Class<?> inClazz = KyanosGraphQueryRenameAllMethods.class.getClassLoader() .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS)); inClazz.getMethod("init").invoke(null); ResourceSet resourceSet = new ResourceSetImpl(); resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap() .put(NeoBlueprintsURI.NEO_GRAPH_SCHEME, PersistentResourceFactory.eINSTANCE); Resource resource = resourceSet.createResource(uri); Map<String, Object> loadOpts = new HashMap<String, Object>(); if (commandLine.hasOption(OPTIONS_FILE)) { Properties properties = new Properties(); properties.load(new FileInputStream(new File(commandLine.getOptionValue(OPTIONS_FILE)))); for (final Entry<Object, Object> entry : properties.entrySet()) { loadOpts.put((String) entry.getKey(), (String) entry.getValue()); } } resource.load(loadOpts); String name = UUID.randomUUID().toString(); { LOG.log(Level.INFO, "Start query"); long begin = System.currentTimeMillis(); JavaQueries.renameAllMethods(resource, name); long end = System.currentTimeMillis(); resource.save(Collections.emptyMap()); LOG.log(Level.INFO, "End query"); LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin))); } if (resource instanceof PersistentResourceImpl) { PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) resource); } else { resource.unload(); } } catch (ParseException e) { MessageUtil.showError(e.toString()); MessageUtil.showError("Current arguments: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar <this-file.jar>", options, true); } catch (Throwable e) { MessageUtil.showError(e.toString()); } }
From source file:fr.inria.atlanmod.kyanos.benchmarks.KyanosGraphTraverser.java
public static void main(String[] args) { Options options = new Options(); Option inputOpt = OptionBuilder.create(IN); inputOpt.setArgName("INPUT"); inputOpt.setDescription("Input Kyanos resource directory"); inputOpt.setArgs(1);//w w w . j a va 2 s . com inputOpt.setRequired(true); Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS); inClassOpt.setArgName("CLASS"); inClassOpt.setDescription("FQN of EPackage implementation class"); inClassOpt.setArgs(1); inClassOpt.setRequired(true); Option optFileOpt = OptionBuilder.create(OPTIONS_FILE); optFileOpt.setArgName("FILE"); optFileOpt.setDescription("Properties file holding the options to be used in the Kyanos Resource"); optFileOpt.setArgs(1); options.addOption(inputOpt); options.addOption(inClassOpt); options.addOption(optFileOpt); CommandLineParser parser = new PosixParser(); try { PersistenceBackendFactoryRegistry.getFactories().put(NeoBlueprintsURI.NEO_GRAPH_SCHEME, new BlueprintsPersistenceBackendFactory()); CommandLine commandLine = parser.parse(options, args); URI uri = NeoBlueprintsURI.createNeoGraphURI(new File(commandLine.getOptionValue(IN))); Class<?> inClazz = KyanosGraphTraverser.class.getClassLoader() .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS)); inClazz.getMethod("init").invoke(null); ResourceSet resourceSet = new ResourceSetImpl(); resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap() .put(NeoBlueprintsURI.NEO_GRAPH_SCHEME, PersistentResourceFactory.eINSTANCE); Resource resource = resourceSet.createResource(uri); Map<String, Object> loadOpts = new HashMap<String, Object>(); if (commandLine.hasOption(OPTIONS_FILE)) { Properties properties = new Properties(); properties.load(new FileInputStream(new File(commandLine.getOptionValue(OPTIONS_FILE)))); for (final Entry<Object, Object> entry : properties.entrySet()) { loadOpts.put((String) entry.getKey(), (String) entry.getValue()); } } resource.load(loadOpts); LOG.log(Level.INFO, "Start counting"); int count = 0; long begin = System.currentTimeMillis(); for (Iterator<EObject> iterator = resource.getAllContents(); iterator.hasNext(); iterator .next(), count++) ; long end = System.currentTimeMillis(); LOG.log(Level.INFO, "End counting"); LOG.log(Level.INFO, MessageFormat.format("Resource {0} contains {1} elements", uri, count)); LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin))); if (resource instanceof PersistentResourceImpl) { PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) resource); } else { resource.unload(); } } catch (ParseException e) { MessageUtil.showError(e.toString()); MessageUtil.showError("Current arguments: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar <this-file.jar>", options, true); } catch (Throwable e) { MessageUtil.showError(e.toString()); } }
From source file:fr.inria.atlanmod.kyanos.benchmarks.CdoQueryRenameAllMethods.java
public static void main(String[] args) { Options options = new Options(); Option inputOpt = OptionBuilder.create(IN); inputOpt.setArgName("INPUT"); inputOpt.setDescription("Input CDO resource directory"); inputOpt.setArgs(1);/*www. jav a 2s .c o m*/ inputOpt.setRequired(true); Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS); inClassOpt.setArgName("CLASS"); inClassOpt.setDescription("FQN of EPackage implementation class"); inClassOpt.setArgs(1); inClassOpt.setRequired(true); Option repoOpt = OptionBuilder.create(REPO_NAME); repoOpt.setArgName("REPO_NAME"); repoOpt.setDescription("CDO Repository name"); repoOpt.setArgs(1); repoOpt.setRequired(true); options.addOption(inputOpt); options.addOption(inClassOpt); options.addOption(repoOpt); CommandLineParser parser = new PosixParser(); try { CommandLine commandLine = parser.parse(options, args); String repositoryDir = commandLine.getOptionValue(IN); String repositoryName = commandLine.getOptionValue(REPO_NAME); Class<?> inClazz = CdoQueryRenameAllMethods.class.getClassLoader() .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS)); inClazz.getMethod("init").invoke(null); EmbeddedCDOServer server = new EmbeddedCDOServer(repositoryDir, repositoryName); try { server.run(); CDOSession session = server.openSession(); ((CDONet4jSession) session).options().setCommitTimeout(50 * 1000); CDOTransaction transaction = session.openTransaction(); Resource resource = transaction.getRootResource(); String name = UUID.randomUUID().toString(); { LOG.log(Level.INFO, "Start query"); long begin = System.currentTimeMillis(); JavaQueries.renameAllMethods(resource, name); long end = System.currentTimeMillis(); transaction.commit(); LOG.log(Level.INFO, "End query"); LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin))); } // { // transaction.close(); // session.close(); // // session = server.openSession(); // transaction = session.openTransaction(); // resource = transaction.getRootResource(); // // EList<? extends EObject> methodList = JavaQueries.getAllInstances(resource, JavaPackage.eINSTANCE.getMethodDeclaration()); // int i = 0; // for (EObject eObject: methodList) { // MethodDeclaration method = (MethodDeclaration) eObject; // if (name.equals(method.getName())) { // i++; // } // } // LOG.log(Level.INFO, MessageFormat.format("Renamed {0} methods", i)); // } transaction.close(); session.close(); } finally { server.stop(); } } catch (ParseException e) { MessageUtil.showError(e.toString()); MessageUtil.showError("Current arguments: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar <this-file.jar>", options, true); } catch (Throwable e) { MessageUtil.showError(e.toString()); } }
From source file:fr.inria.atlanmod.kyanos.benchmarks.CdoCreator.java
public static void main(String[] args) { Options options = new Options(); Option inputOpt = OptionBuilder.create(IN); inputOpt.setArgName("INPUT"); inputOpt.setDescription("Input file"); inputOpt.setArgs(1);//from w w w.j a v a 2 s . co m inputOpt.setRequired(true); Option outputOpt = OptionBuilder.create(OUT); outputOpt.setArgName("OUTPUT"); outputOpt.setDescription("Output directory"); outputOpt.setArgs(1); outputOpt.setRequired(true); Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS); inClassOpt.setArgName("CLASS"); inClassOpt.setDescription("FQN of EPackage implementation class"); inClassOpt.setArgs(1); inClassOpt.setRequired(true); Option repoOpt = OptionBuilder.create(REPO_NAME); repoOpt.setArgName("REPO_NAME"); repoOpt.setDescription("CDO Repository name"); repoOpt.setArgs(1); repoOpt.setRequired(true); options.addOption(inputOpt); options.addOption(outputOpt); options.addOption(inClassOpt); options.addOption(repoOpt); CommandLineParser parser = new PosixParser(); try { CommandLine commandLine = parser.parse(options, args); URI sourceUri = URI.createFileURI(commandLine.getOptionValue(IN)); String outputDir = commandLine.getOptionValue(OUT); String repositoryName = commandLine.getOptionValue(REPO_NAME); Class<?> inClazz = CdoCreator.class.getClassLoader() .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS)); inClazz.getMethod("init").invoke(null); ResourceSet resourceSet = new ResourceSetImpl(); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi", new XMIResourceFactoryImpl()); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("zxmi", new XMIResourceFactoryImpl()); Resource sourceResource = resourceSet.createResource(sourceUri); Map<String, Object> loadOpts = new HashMap<String, Object>(); if ("zxmi".equals(sourceUri.fileExtension())) { loadOpts.put(XMIResource.OPTION_ZIP, Boolean.TRUE); } Runtime.getRuntime().gc(); long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); LOG.log(Level.INFO, MessageFormat.format("Used memory before loading: {0}", MessageUtil.byteCountToDisplaySize(initialUsedMemory))); LOG.log(Level.INFO, "Loading source resource"); sourceResource.load(loadOpts); LOG.log(Level.INFO, "Source resource loaded"); Runtime.getRuntime().gc(); long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); LOG.log(Level.INFO, MessageFormat.format("Used memory after loading: {0}", MessageUtil.byteCountToDisplaySize(finalUsedMemory))); LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}", MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory))); EmbeddedCDOServer server = new EmbeddedCDOServer(outputDir, repositoryName); try { server.run(); CDOSession session = server.openSession(); CDOTransaction transaction = session.openTransaction(); transaction.getRootResource().getContents().clear(); LOG.log(Level.INFO, "Start moving elements"); transaction.getRootResource().getContents().addAll(sourceResource.getContents()); LOG.log(Level.INFO, "End moving elements"); LOG.log(Level.INFO, "Commiting"); transaction.commit(); LOG.log(Level.INFO, "Commit done"); transaction.close(); session.close(); } finally { server.stop(); } } catch (ParseException e) { MessageUtil.showError(e.toString()); MessageUtil.showError("Current arguments: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar <this-file.jar>", options, true); } catch (Throwable e) { MessageUtil.showError(e.toString()); } }
From source file:com.genentech.chemistry.tool.sdf2DAlign.java
public static void main(String[] args) throws IOException { final String OPT_INFILE = "in"; final String OPT_OUTFILE = "out"; final String OPT_TEMPLATEFILE = "templates"; final String OPT_RESETCOORDS = "reset"; final String OPT_DEBUG = "debug"; Options options = new Options(); Option opt = new Option(OPT_INFILE, true, "Input file (oe-supported). Use .sdf to specify the file type."); opt.setRequired(true); options.addOption(opt);/*w w w . j a v a2 s.co m*/ opt = new Option(OPT_OUTFILE, true, "Output file (oe-supported). Use .sdf to specify the file type."); opt.setRequired(true); options.addOption(opt); opt = new Option(OPT_TEMPLATEFILE, true, "Template file (oe-supported). Use .sdf to specify the file type."); opt.setRequired(true); options.addOption(opt); opt = new Option(OPT_RESETCOORDS, false, "Reset coordinates in input file when aligning. This will delete original 2D coords and create new ones."); opt.setRequired(false); options.addOption(opt); opt = new Option(OPT_DEBUG, false, "Print debug statements."); opt.setRequired(false); options.addOption(opt); opt = new Option("h", false, "print usage statement"); opt.setRequired(false); options.addOption(opt); PosixParser parser = new PosixParser(); CommandLine cl = null; try { cl = parser.parse(options, args); } catch (Exception exp) { System.err.println(exp.getMessage()); exitWithHelp(options); } //get command line parameters String inFile = cl.getOptionValue(OPT_INFILE); String outFile = cl.getOptionValue(OPT_OUTFILE); String templateFile = cl.getOptionValue(OPT_TEMPLATEFILE); boolean resetCoords = cl.hasOption(OPT_RESETCOORDS); boolean debug = cl.hasOption(OPT_DEBUG); sdf2DAlign myAlign = new sdf2DAlign(inFile, outFile, templateFile, resetCoords); myAlign.setDebug(debug); //get templates as subsearches List<OESubSearch> templates = myAlign.getTemplates(); //apply template to input molecules myAlign.applyTemplates(templates); for (OESubSearch ss : templates) ss.delete(); }
From source file:com.opengamma.integration.marketdata.WatchListRecorder.java
/** * Main entry point./*from w ww . jav a 2 s . co m*/ * * @param args the arguments * @throws Exception if an error occurs */ public static void main(final String[] args) throws Exception { // CSIGNORE final CommandLineParser parser = new PosixParser(); final Options options = new Options(); final Option outputFileOpt = new Option("o", "output", true, "output file"); outputFileOpt.setRequired(true); options.addOption(outputFileOpt); final Option urlOpt = new Option("u", "url", true, "server url"); options.addOption(urlOpt); String outputFile = "watchList.txt"; String url = "http://localhost:8080/jax"; try { final CommandLine cmd = parser.parse(options, args); outputFile = cmd.getOptionValue("output"); url = cmd.getOptionValue("url"); } catch (final ParseException exp) { s_logger.error("Option parsing failed: {}", exp.getMessage()); System.exit(0); } final WatchListRecorder recorder = create(URI.create(url), "main", "combined"); recorder.addWatchScheme(ExternalSchemes.BLOOMBERG_TICKER); recorder.addWatchScheme(ExternalSchemes.BLOOMBERG_BUID); final PrintWriter pw = new PrintWriter(outputFile); recorder.setPrintWriter(pw); recorder.run(); pw.close(); System.exit(0); }
From source file:com.genentech.chemistry.openEye.apps.SDFTopologicalIndexer.java
/** * @param args// ww w . j av a 2 s .c o m */ public static void main(String... args) throws IOException { // create command line Options object Options options = new Options(); Option opt = new Option(OPT_INFILE, true, "input file oe-supported Use .sdf|.smi to specify the file type."); opt.setRequired(true); opt.setArgName("fn"); options.addOption(opt); opt = new Option(OPT_OUTFILE, true, "output file oe-supported. Use .sdf|.smi to specify the file type."); opt.setRequired(true); opt.setArgName("fn"); options.addOption(opt); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (Exception e) { System.err.println(e.getMessage()); exitWithHelp(options); } args = cmd.getArgs(); if (cmd.hasOption("d")) { System.err.println("Start debugger and press return:"); new BufferedReader(new InputStreamReader(System.in)).readLine(); } if (args.length == 0) { System.err.println("Specify at least one index type"); exitWithHelp(options); } String inFile = cmd.getOptionValue(OPT_INFILE); String outFile = cmd.getOptionValue(OPT_OUTFILE); Set<String> selectedIndexes = new HashSet<String>(args.length); if (args.length == 1 && "all".equalsIgnoreCase(args[0])) selectedIndexes = AVAILIndexes; else selectedIndexes.addAll(Arrays.asList(args)); if (!AVAILIndexes.containsAll(selectedIndexes)) { selectedIndexes.removeAll(AVAILIndexes); StringBuilder err = new StringBuilder("Unknown Index types: "); for (String it : selectedIndexes) err.append(it).append(" "); System.err.println(err); exitWithHelp(options); } SDFTopologicalIndexer sdfIndexer = new SDFTopologicalIndexer(outFile, selectedIndexes); sdfIndexer.run(inFile); sdfIndexer.close(); }
From source file:edu.wisc.doit.tcrypt.cli.TokenCrypt.java
public static void main(String[] args) throws IOException { // create Options object final Options options = new Options(); // operation opt group final OptionGroup cryptTypeGroup = new OptionGroup(); cryptTypeGroup.addOption(new Option("e", "encrypt", false, "Encrypt a token")); cryptTypeGroup.addOption(new Option("d", "decrypt", false, "Decrypt a token")); cryptTypeGroup/*from www. j a va 2 s . c o m*/ .addOption(new Option("c", "check", false, "Check if the string looks like an encrypted token")); cryptTypeGroup.setRequired(true); options.addOptionGroup(cryptTypeGroup); // token source opt group final OptionGroup tokenGroup = new OptionGroup(); final Option tokenOpt = new Option("t", "token", true, "The token(s) to operate on"); tokenOpt.setArgs(Option.UNLIMITED_VALUES); tokenGroup.addOption(tokenOpt); final Option tokenFileOpt = new Option("f", "file", true, "A file with one token per line to operate on, if - is specified stdin is used"); tokenGroup.addOption(tokenFileOpt); tokenGroup.setRequired(true); options.addOptionGroup(tokenGroup); final Option keyOpt = new Option("k", "keyFile", true, "Key file to use. Must be a private key for decryption and a public key for encryption"); keyOpt.setRequired(true); options.addOption(keyOpt); // create the parser final CommandLineParser parser = new GnuParser(); CommandLine line = null; try { // parse the command line arguments line = parser.parse(options, args); } catch (ParseException exp) { // automatically generate the help statement System.err.println(exp.getMessage()); final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java " + TokenCrypt.class.getName(), options, true); System.exit(1); } final Reader keyReader = createKeyReader(line); final TokenHandler tokenHandler = createTokenHandler(line, keyReader); if (line.hasOption("t")) { //tokens on cli final String[] tokens = line.getOptionValues("t"); for (final String token : tokens) { handleToken(tokenHandler, token); } } else { //tokens from a file final String tokenFile = line.getOptionValue("f"); final BufferedReader fileReader; if ("-".equals(tokenFile)) { fileReader = new BufferedReader(new InputStreamReader(System.in)); } else { fileReader = new BufferedReader(new FileReader(tokenFile)); } while (true) { final String token = fileReader.readLine(); if (token == null) { break; } handleToken(tokenHandler, token); } } }
From source file:edu.cmu.lti.oaqa.apps.Client.java
public static void main(String args[]) { BufferedReader inp = new BufferedReader(new InputStreamReader(System.in)); Options opt = new Options(); Option o = new Option(PORT_SHORT_PARAM, PORT_LONG_PARAM, true, PORT_DESC); o.setRequired(true); opt.addOption(o);/*from w ww.ja va2s . c o m*/ o = new Option(HOST_SHORT_PARAM, HOST_LONG_PARAM, true, HOST_DESC); o.setRequired(true); opt.addOption(o); opt.addOption(K_SHORT_PARAM, K_LONG_PARAM, true, K_DESC); opt.addOption(R_SHORT_PARAM, R_LONG_PARAM, true, R_DESC); opt.addOption(QUERY_TIME_SHORT_PARAM, QUERY_TIME_LONG_PARAM, true, QUERY_TIME_DESC); opt.addOption(RET_OBJ_SHORT_PARAM, RET_OBJ_LONG_PARAM, false, RET_OBJ_DESC); opt.addOption(RET_EXTERN_ID_SHORT_PARAM, RET_EXTERN_ID_LONG_PARAM, false, RET_EXTERN_ID_DESC); CommandLineParser parser = new org.apache.commons.cli.GnuParser(); try { CommandLine cmd = parser.parse(opt, args); String host = cmd.getOptionValue(HOST_SHORT_PARAM); String tmp = null; tmp = cmd.getOptionValue(PORT_SHORT_PARAM); int port = -1; try { port = Integer.parseInt(tmp); } catch (NumberFormatException e) { Usage("Port should be integer!"); } boolean retObj = cmd.hasOption(RET_OBJ_SHORT_PARAM); boolean retExternId = cmd.hasOption(RET_EXTERN_ID_SHORT_PARAM); String queryTimeParams = cmd.getOptionValue(QUERY_TIME_SHORT_PARAM); if (null == queryTimeParams) queryTimeParams = ""; SearchType searchType = SearchType.kKNNSearch; int k = 0; double r = 0; if (cmd.hasOption(K_SHORT_PARAM)) { if (cmd.hasOption(R_SHORT_PARAM)) { Usage("Range search is not allowed if the KNN search is specified!"); } tmp = cmd.getOptionValue(K_SHORT_PARAM); try { k = Integer.parseInt(tmp); } catch (NumberFormatException e) { Usage("K should be integer!"); } searchType = SearchType.kKNNSearch; } else if (cmd.hasOption(R_SHORT_PARAM)) { if (cmd.hasOption(K_SHORT_PARAM)) { Usage("KNN search is not allowed if the range search is specified!"); } searchType = SearchType.kRangeSearch; tmp = cmd.getOptionValue(R_SHORT_PARAM); try { r = Double.parseDouble(tmp); } catch (NumberFormatException e) { Usage("The range value should be numeric!"); } } else { Usage("One has to specify either range or KNN-search parameter"); } String separator = System.getProperty("line.separator"); StringBuffer sb = new StringBuffer(); String s; while ((s = inp.readLine()) != null) { sb.append(s); sb.append(separator); } String queryObj = sb.toString(); try { TTransport transport = new TSocket(host, port); transport.open(); TProtocol protocol = new TBinaryProtocol(transport); QueryService.Client client = new QueryService.Client(protocol); if (!queryTimeParams.isEmpty()) client.setQueryTimeParams(queryTimeParams); List<ReplyEntry> res = null; long t1 = System.nanoTime(); if (searchType == SearchType.kKNNSearch) { System.out.println(String.format("Running a %d-NN search", k)); res = client.knnQuery(k, queryObj, retExternId, retObj); } else { System.out.println(String.format("Running a range search (r=%g)", r)); res = client.rangeQuery(r, queryObj, retExternId, retObj); } long t2 = System.nanoTime(); System.out.println(String.format("Finished in %g ms", (t2 - t1) / 1e6)); for (ReplyEntry e : res) { System.out.println(String.format("id=%d dist=%g %s", e.getId(), e.getDist(), retExternId ? "externId=" + e.getExternId() : "")); if (retObj) System.out.println(e.getObj()); } transport.close(); // Close transport/socket ! } catch (TException te) { System.err.println("Apache Thrift exception: " + te); te.printStackTrace(); } } catch (ParseException e) { Usage("Cannot parse arguments"); } catch (Exception e) { e.printStackTrace(); System.exit(1); } }