@Test public void testGetOptionParser() throws Exception { OptionParser optionParser = Main.getOptionParser(); String tmpDir = systemTempDir().toString(); OptionSet optionSet = optionParser.parse( "-f", "/tmp/dummy", "-s", "9908:976098897", "-r", "9908:810017902", "-u", "https://ap.unit4.com", "-m", "as2", "-e", tmpDir); assertTrue(optionSet.has("u")); assertTrue(optionSet.has("f")); assertTrue(optionSet.has("e")); Object e = optionSet.valueOf("e"); assertNotNull(e); assertTrue(e instanceof File); File f = (File) e; assertEquals(f, new File(tmpDir)); }
protected void main(OptionParser parser, OptionSet options) { int flags = 0; if (options.has("o2")) flags |= QBImporter.TEXTUREPLANES; if (options.has("s")) flags |= QBImporter.SQUARETEXTURE; if (options.has("t")) flags |= QBImporter.MERGETEXTURES; if (options.has("r")) flags |= QBImporter.SCALEMC; File[] input = options.valuesOf("input").toArray(new File[0]); File[] outDir = new File[input.length]; if (options.has("out")) { File output = (File) options.valueOf("out"); if (output.isFile()) throw new RuntimeException("Output Path is not a directory"); if (!output.exists()) output.mkdirs(); for (int i = 0; i < input.length; i++) outDir[i] = output; } else { for (int i = 0; i < input.length; i++) outDir[i] = input[i].isDirectory() ? input[i] : input[i].getParentFile(); } for (int i = 0; i < input.length; i++) { File file = input[i]; if (file.isDirectory()) { for (File file2 : file.listFiles()) if (file2.getName().endsWith(".qb")) convert(file2, outDir[i], flags); } else convert(file, outDir[i], flags); } }
@Test public void supportsPosixlyCorrectBehavior() { OptionParser parser = new OptionParser("i:j::k"); String[] arguments = { "-ibar", "-i", "junk", "xyz", "-jixnay", "foo", "-k", "blah", "--", "bah" }; OptionSet options = parser.parse(arguments); assertTrue(options.has("i")); assertTrue(options.has("j")); assertTrue(options.has("k")); assertEquals(asList("bar", "junk"), options.valuesOf("i")); assertEquals(singletonList("ixnay"), options.valuesOf("j")); assertEquals(asList("xyz", "foo", "blah", "bah"), options.nonOptionArguments()); parser.posixlyCorrect(true); options = parser.parse(arguments); assertTrue(options.has("i")); assertFalse(options.has("j")); assertFalse(options.has("k")); assertEquals(asList("bar", "junk"), options.valuesOf("i")); assertEquals(emptyList(), options.valuesOf("j")); assertEquals( asList("xyz", "-jixnay", "foo", "-k", "blah", "--", "bah"), options.nonOptionArguments()); }
private static long getCreationTimeSeconds() { long creationTimeSeconds = 0; if (options.has(unixtimeFlag)) { creationTimeSeconds = unixtimeFlag.value(options); } else if (options.has(dateFlag)) { creationTimeSeconds = dateFlag.value(options).getTime() / 1000; } return creationTimeSeconds; }
private static void addKey() { ECKey key; long creationTimeSeconds = getCreationTimeSeconds(); if (options.has("privkey")) { String data = (String) options.valueOf("privkey"); if (data.startsWith("5J") || data.startsWith("5H") || data.startsWith("5K")) { DumpedPrivateKey dpk; try { dpk = new DumpedPrivateKey(params, data); } catch (AddressFormatException e) { System.err.println("Could not parse dumped private key " + data); return; } key = dpk.getKey(); } else { byte[] decode = Utils.parseAsHexOrBase58(data); if (decode == null) { System.err.println("Could not understand --privkey as either hex or base58: " + data); return; } key = new ECKey(new BigInteger(1, decode)); } if (options.has("pubkey")) { // Give the user a hint. System.out.println("You don't have to specify --pubkey when a private key is supplied."); } key.setCreationTimeSeconds(creationTimeSeconds); } else if (options.has("pubkey")) { byte[] pubkey = Utils.parseAsHexOrBase58((String) options.valueOf("pubkey")); key = new ECKey(null, pubkey); key.setCreationTimeSeconds(creationTimeSeconds); } else { // Freshly generated key. key = new ECKey(); if (creationTimeSeconds > 0) key.setCreationTimeSeconds(creationTimeSeconds); } if (wallet.findKeyFromPubKey(key.getPubKey()) != null) { System.err.println("That key already exists in this wallet."); return; } try { if (wallet.isEncrypted()) { if (password == null || !wallet.checkPassword(password)) { System.err.println("The password is incorrect."); return; } key = key.encrypt(wallet.getKeyCrypter(), wallet.getKeyCrypter().deriveKey(password)); } wallet.addKey(key); } catch (KeyCrypterException kce) { System.err.println( "There was an encryption related error when adding the key. The error was '" + kce.getMessage() + "'."); } System.out.println(key.toAddress(params) + " " + key); }
private void unschedule(String[] args) throws Exception { String[] ONE_REQUIRED = {OPT_RESOURCEID, OPT_GROUPID}; OptionParser p = getOptionParser(); p.accepts(OPT_RESOURCEID, "The id of the resource to unschedule from maintenance") .withRequiredArg() .ofType(Integer.class); p.accepts(OPT_GROUPID, "The id of the group to unschedule from maintenance") .withRequiredArg() .ofType(Integer.class); OptionSet options = getOptions(p, args); int criteria = 0; for (String opt : ONE_REQUIRED) { if (options.has(opt)) { criteria++; } } if (criteria == 0) { System.err.println("One of " + Arrays.toString(ONE_REQUIRED) + " is required."); System.exit(-1); } else if (criteria > 1) { System.err.println("Only one of " + Arrays.toString(ONE_REQUIRED) + " may be specified"); System.exit(-1); } HQApi api = getApi(options); MaintenanceApi maintenanceApi = api.getMaintenanceApi(); StatusResponse response = null; Integer id = null; if (options.has(OPT_GROUPID)) { id = (Integer) getRequired(options, OPT_GROUPID); response = maintenanceApi.unschedule(id); } else if (options.has(OPT_RESOURCEID)) { id = (Integer) getRequired(options, OPT_RESOURCEID); ResourceResponse resourceResponse = api.getResourceApi().getResource(id, false, false); checkSuccess(resourceResponse); response = maintenanceApi.unschedule(resourceResponse.getResource()); } checkSuccess(response); if (options.has(OPT_GROUPID)) { System.out.println("Maintenance for group " + id + " unscheduled."); } else { System.out.println("Maintenance for resource " + id + " unscheduled."); } }
@SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { OptionParser parser = new OptionParser(); parser.accepts("native", "use native admin client"); parser.accepts("f", "execute fetch operation"); parser.accepts("fu", "fetch and update").withRequiredArg().ofType(Integer.class); parser .accepts("n", "node id") .withRequiredArg() .ofType(Integer.class) .withValuesSeparatedBy(','); parser .accepts("p", "partition id") .withRequiredArg() .ofType(Integer.class) .withValuesSeparatedBy(','); OptionSet options = parser.parse(args); List<String> nonOptions = (List<String>) options.nonOptionArguments(); if (args.length < 2) { System.out.println(usageStr); return; } String bootstrapUrl = nonOptions.get(0); String storeName = nonOptions.get(1); if (!options.has("p") && !options.has("n")) { printUsage( System.err, parser, "One or more node and/or one or more partition has" + " to be specified"); } AdminTest adminTest; adminTest = new AdminTest(bootstrapUrl, storeName); SetMultimap<Integer, Integer> nodePartitions = adminTest.getNodePartitions( options.has("n") ? options.valuesOf("n") : null, options.has("p") ? options.valuesOf("p") : null); if (options.has("f")) adminTest.testFetch(nodePartitions); if (options.has("fu")) adminTest.testFetchAndUpdate(nodePartitions, (Integer) options.valueOf("fu")); }
private String managePermissions(IMessage message, OptionSet optionSet) { List<String> nonOptions = optionSet.valuesOf(permNonOptionSpec); if (optionSet.has("?") || nonOptions.size() < 2) { return null; } String permName = nonOptions.get(0).toLowerCase(); String action = nonOptions.get(1).toLowerCase(); Optional<Permission> permission = permissionService.findPermissionByName(permName); List<String> args = nonOptions.subList(2, nonOptions.size()); if (action.equals("list")) { return listPermissions(message, permName, args); } else if (action.equals("evict")) { permissionService.evict(); return "OK"; } else if (!permission.isPresent()) { return "Not a valid permission name"; } else if (action.equals("allow")) { return editPermission(Operation.ALLOW, message, permission.get(), args); } else if (action.equals("deny")) { return editPermission(Operation.DENY, message, permission.get(), args); } else if (action.equals("reset")) { return editPermission(Operation.RESET, message, permission.get(), args); } return "Invalid operation! Check details with `.perm -?`"; }
public static void main(String[] args) throws Exception { OptionParser parser = new OptionParser(); parser .accepts("client-zone-id", "client zone id for zone routing") .withRequiredArg() .describedAs("zone-id") .ofType(Integer.class); OptionSet options = parser.parse(args); List<String> nonOptions = options.nonOptionArguments(); if (nonOptions.size() < 2 || nonOptions.size() > 3) { System.err.println( "Usage: java VoldemortClientShell store_name bootstrap_url [command_file] [options]"); parser.printHelpOn(System.err); System.exit(-1); } String storeName = nonOptions.get(0); String bootstrapUrl = nonOptions.get(1); String commandsFileName = ""; BufferedReader fileReader = null; BufferedReader inputReader = null; try { if (nonOptions.size() == 3) { commandsFileName = nonOptions.get(2); fileReader = new BufferedReader(new FileReader(commandsFileName)); } inputReader = new BufferedReader(new InputStreamReader(System.in)); } catch (IOException e) { Utils.croak("Failure to open input stream: " + e.getMessage()); } ClientConfig clientConfig = new ClientConfig() .setBootstrapUrls(bootstrapUrl) .setRequestFormatType(RequestFormatType.VOLDEMORT_V3); if (options.has("client-zone-id")) { clientConfig.setClientZoneId((Integer) options.valueOf("client-zone-id")); } StoreClientFactory factory = new SocketStoreClientFactory(clientConfig); try { client = (DefaultStoreClient<Object, Object>) factory.getStoreClient(storeName); } catch (Exception e) { Utils.croak("Could not connect to server: " + e.getMessage()); } System.out.println("Established connection to " + storeName + " via " + bootstrapUrl); System.out.print(PROMPT); if (fileReader != null) { processCommands(factory, fileReader, true); fileReader.close(); } processCommands(factory, inputReader, false); }
@Test public void allowsDifferentFormsOfPairingArgumentWithOption() { OptionParser parser = new OptionParser(); parser.accepts("count").withRequiredArg(); parser.accepts("level").withOptionalArg(); OptionSet options = parser.parse("--count", "4", "--level=3"); assertTrue(options.has("count")); assertTrue(options.hasArgument("count")); assertEquals("4", options.valueOf("count")); assertTrue(options.has("level")); assertTrue(options.hasArgument("level")); assertEquals("3", options.valueOf("level")); }
private static void send(PaymentSession session) { try { System.out.println("Payment Request"); System.out.println("Amount: " + session.getValue().doubleValue() / 100000 + "mDOGE"); System.out.println("Date: " + session.getDate()); System.out.println("Memo: " + session.getMemo()); if (session.pkiVerificationData != null) { System.out.println("Pki-Verified Name: " + session.pkiVerificationData.name); if (session.pkiVerificationData.orgName != null) System.out.println("Pki-Verified Org: " + session.pkiVerificationData.orgName); System.out.println( "PKI data verified by: " + session.pkiVerificationData.rootAuthorityName); } final Wallet.SendRequest req = session.getSendRequest(); if (password != null) { if (!wallet.checkPassword(password)) { System.err.println("Password is incorrect."); return; } req.aesKey = wallet.getKeyCrypter().deriveKey(password); } wallet.completeTx(req); // may throw InsufficientMoneyException. if (options.has("offline")) { wallet.commitTx(req.tx); return; } setup(); // No refund address specified, no user-specified memo field. ListenableFuture<PaymentSession.Ack> future = session.sendPayment(ImmutableList.of(req.tx), null, null); if (future == null) { // No payment_url for submission so, broadcast and wait. peers.startAndWait(); peers.broadcastTransaction(req.tx).get(); } else { PaymentSession.Ack ack = future.get(); wallet.commitTx(req.tx); System.out.println("Memo from server: " + ack.getMemo()); } } catch (PaymentRequestException e) { System.err.println("Failed to send payment " + e.getMessage()); System.exit(1); } catch (VerificationException e) { System.err.println("Failed to send payment " + e.getMessage()); System.exit(1); } catch (ExecutionException e) { System.err.println("Failed to send payment " + e.getMessage()); System.exit(1); } catch (IOException e) { System.err.println("Invalid payment " + e.getMessage()); System.exit(1); } catch (InterruptedException e1) { // Ignore. } catch (InsufficientMoneyException e) { System.err.println( "Insufficient funds: have " + Utils.bitcoinValueToFriendlyString(wallet.getBalance())); } catch (BlockStoreException e) { throw new RuntimeException(e); } }
private File getPropertiesFile() { if (options.has(propertiesFileSpec)) { // a file was explicitly configured return new File(options.valueOf(propertiesFileSpec)); } else { return null; } }
private OptionSet parseOptions(OptionParser p, String[] args) throws IOException { OptionSet options = null; try { options = p.parse(args); if (options.has("?") || !options.has(maxwiOptName) || options.nonOptionArguments().size() < 2) { System.err.println("Usage:\nSimilarity <input_paths> <output_path> [options]"); System.err.println("Please specify " + maxwiOptName + " option\n"); p.printHelpOn(System.err); System.exit(0); } } catch (OptionException e) { System.err.println(e.getMessage()); System.exit(1); } return options; }
private static Properties asProperties(OptionSet options, String prefix) { Properties properties = new Properties(); for (Entry<OptionSpec<?>, List<?>> entry : options.asMap().entrySet()) { OptionSpec<?> spec = entry.getKey(); properties.setProperty( asPropertyKey(prefix, spec), asPropertyValue(entry.getValue(), options.has(spec))); } return properties; }
@Test public void testInitOptionsWithHelp_optionalArgument() { parser.accepts("argName", "Funky description"); OptionSet options = initOptionsWithHelp(parser, new String[] {"--argName"}); assertNotNull(options); assertEquals(1, options.specs().size()); assertTrue(options.has("argName")); }
@Test public void senderAndReceiverIsOptional() throws Exception { OptionParser optionParser = Main.getOptionParser(); OptionSet optionSet = optionParser.parse("-f", "/tmp/dummy", "-u", "https://ap.unit4.com", "-m", "as2"); assertFalse(optionSet.has("-r")); assertFalse(optionSet.has("-s")); }
public final void parseAndExecute(final String[] cmds) throws IOException { opts = parser.parse(cmds); if (opts.has(HELP)) { parser.printHelpOn(System.out); return; } Indexing.STORE = opts.has(STORE); Indexing.COMMIT = (Integer) opts.valueOf(COMMIT); // FORMAT if (opts.has(FORMAT)) { format = (Format) opts.valueOf(FORMAT); } else printError(FORMAT); // DUMPS_DIR if (opts.has(DUMPS_DIR)) { dumpsDir = (File) opts.valueOf(DUMPS_DIR); } else printError(DUMPS_DIR); // INDEX_DIR if (opts.has(INDEX_DIR)) { indexDir = (File) opts.valueOf(INDEX_DIR); } else printError(INDEX_DIR); logger.info( "Creating index at {} from the files at {}", indexDir.getAbsolutePath(), dumpsDir.getAbsolutePath()); final Indexing indexing; switch (format) { case SINDICE_DE: indexing = new SindiceDEIndexing(dumpsDir, FSDirectory.open(indexDir)); break; case SINDICE_ED: indexing = new SindiceEDIndexing(dumpsDir, FSDirectory.open(indexDir)); break; default: throw new IllegalArgumentException("No such dataset format: " + format); } indexing.indexIt(); indexing.close(); logger.info("Finished indexing"); }
public static void main(String[] args) throws IOException, TException { OptionParser parser = new OptionParser(); parser.accepts("c", "configuration file").withRequiredArg().ofType(String.class); parser.accepts("help", "print help statement"); OptionSet options = parser.parse(args); if (options.has("help")) { parser.printHelpOn(System.out); System.exit(-1); } // Logger configuration: log to the console BasicConfigurator.configure(); LOG.setLevel(Level.DEBUG); LOG.debug("debug logging on"); Configuration conf = new PropertiesConfiguration(); if (options.has("c")) { String configFile = (String) options.valueOf("c"); try { conf = new PropertiesConfiguration(configFile); } catch (ConfigurationException e) { } } // Start backend server BackendService.Processor<BackendService.Iface> processor = new BackendService.Processor<BackendService.Iface>(new ProtoBackend()); int listenPort = conf.getInt("listen_port", DEFAULT_LISTEN_PORT); NM_PORT = conf.getInt("node_monitor_port", NodeMonitorThrift.DEFAULT_NM_THRIFT_PORT); TServers.launchThreadedThriftServer(listenPort, THRIFT_WORKER_THREADS, processor); // Register server client = TClients.createBlockingNmClient(NM_HOST, NM_PORT); try { client.registerBackend(APP_ID, "localhost:" + listenPort); LOG.debug("Client successfullly registered"); } catch (TTransportException e) { LOG.debug("Error while registering backend: " + e.getMessage()); } }
private static void checkRequiredArgs( OptionParser parser, OptionSet options, OptionSpec[] required) throws IOException { for (OptionSpec arg : required) { if (!options.has(arg)) { System.err.println("Missing required argument \"" + arg + "\""); parser.printHelpOn(System.err); System.exit(1); } } }
public static void main(String[] args) throws Exception { SaraTouchClient client = new SaraTouchClient(); OptionParser parser = new OptionParser("ch:p:t"); OptionSet options = null; try { options = parser.parse(args); } catch (Exception e) { System.out.println("Could not parse command-line options:\n" + e); System.out.println(); System.out.println("-h <host> Server host"); System.out.println("-p <port> Server port"); System.out.println("-t Send TUIO events instead of mouse events"); System.out.println("-c Connect after starting up"); System.out.println(); System.exit(-1); } if (options.has("h")) { Object o = options.valueOf("h"); if (o != null) { String s = (String) o; client.setHost(s); } } if (options.has("p")) { Object o = options.valueOf("p"); if (o != null) { int i = Integer.parseInt((String) o); client.setPort(i); } } if (options.has("t")) client.setModeToTUIO(); if (options.has("c")) client.connect(); client.setSize(600, 500); client.setVisible(true); }
static void checkRequiredArgs( OptionParser parser, OptionSet options, OptionSpec<?>... optionSepcs) throws IOException { for (OptionSpec<?> arg : optionSepcs) { if (!options.has(arg)) { System.err.println("Missing required argument " + arg); // parser.formatHelpWith(new MyFormatter()); parser.printHelpOn(System.err); System.exit(1); } } }
public static void parseArgs(String args[]) throws java.io.IOException { parser.acceptsAll(asList("h", "?"), "show help then exit"); OptionSpec<String> CMD = parser.accepts("c", "command").withRequiredArg().ofType(String.class); OptionSpec<String> LOGIN = parser.accepts("u", "LoginId").withRequiredArg().ofType(String.class); OptionSpec<String> PASSWORD = parser.accepts("p", "password").withRequiredArg().ofType(String.class); OptionSpec<String> ISSUER = parser.accepts("i", "IssuerDN").withRequiredArg().ofType(String.class); OptionSpec<String> SUBJECT = parser.accepts("s", "SubjectDN").withRequiredArg().ofType(String.class); OptionSpec<String> CONTEXT = parser .accepts("C", "context:UNITTEST,DEVELOPMENT,SDK,PRODUCTION") .withRequiredArg() .ofType(String.class); OptionSet options = parser.parse(args); // check for help if (options.has("?")) { parser.printHelpOn(System.out); System.exit(0); } if (options.has(CMD)) { cmd = options.valueOf(CMD); } else { System.out.println("a -c cmd argument is required"); parser.printHelpOn(System.out); System.exit(0); } if (options.has(LOGIN)) { loginName = options.valueOf(LOGIN); } if (options.has(PASSWORD)) { password = options.valueOf(PASSWORD); } if (options.has(ISSUER)) { issuer = options.valueOf(ISSUER); } if (options.has(SUBJECT)) { subject = options.valueOf(SUBJECT); } if (options.has(CONTEXT)) { context = options.valueOf(CONTEXT); if (!context.equals("UNITTEST") && !context.equals("SDK") && !context.equals("DEVELOPMENT") && !context.equals("PRODUCTION")) { System.out.println("unrecognized CONTEXT value: " + context); System.exit(-1); } } }
public void run() { Reflections.log = null; printVersion(); OptionParser parser = buildOptionParser(); OptionSet options = parser.parse(arguments); if (options.has(ARGUMENT_EXPERIMENT)) { runExperiment(options.valueOf(ARGUMENT_EXPERIMENT).toString()); System.exit(0); } if (options.has(ARGUMENT_EXPERIMENT_LIST)) { printExperimentList(); System.exit(0); } if (options.has(ARGUMENT_HELP)) { printHelp(parser); System.exit(0); } printHelp(parser); }
private static OptionSet parseOptions(String[] argv) throws IOException { OptionSet args = null; OptionParser parser = new OptionParser(); parser.acceptsAll(Arrays.asList("l", CMD_LIST), "list readers"); parser.acceptsAll(Arrays.asList("p", OPT_PROVIDER), "specify provider").withRequiredArg(); parser.acceptsAll(Arrays.asList("v", OPT_VERBOSE), "be verbose"); parser.acceptsAll(Arrays.asList("e", OPT_ERROR), "fail if not 0x9000"); parser.acceptsAll(Arrays.asList("h", OPT_HELP), "show help"); parser.acceptsAll(Arrays.asList("r", OPT_READER), "use reader").withRequiredArg(); parser.acceptsAll(Arrays.asList("a", CMD_APDU), "send APDU").withRequiredArg(); parser.acceptsAll(Arrays.asList("w", OPT_WEB), "open ATR in web"); parser.acceptsAll(Arrays.asList("V", OPT_VERSION), "show version information"); parser.accepts(OPT_DUMP, "save dump to file").withRequiredArg().ofType(File.class); parser.accepts(OPT_REPLAY, "replay command from dump").withRequiredArg().ofType(File.class); parser.accepts(OPT_SUN, "load SunPCSC"); parser.accepts(OPT_JNA, "load jnasmartcardio"); parser.accepts(OPT_CONNECT, "connect to host:port or URL").withRequiredArg(); parser.accepts(OPT_PINNED, "require certificate").withRequiredArg().ofType(File.class); parser.accepts(OPT_PROVIDERS, "list providers"); parser.accepts(OPT_ALL, "process all readers"); parser.accepts(OPT_WAIT, "wait for card insertion"); parser.accepts(OPT_T0, "use T=0"); parser.accepts(OPT_T1, "use T=1"); parser.accepts(OPT_TEST_SERVER, "run a test server on port 10000").withRequiredArg(); parser.accepts(OPT_NO_GET_RESPONSE, "don't use GET RESPONSE with SunPCSC"); parser.accepts(OPT_LIB, "use specific PC/SC lib with SunPCSC").withRequiredArg(); parser.accepts(OPT_PROVIDER_TYPE, "provider type if not PC/SC").withRequiredArg(); // Parse arguments try { args = parser.parse(argv); // Try to fetch all values so that format is checked before usage for (String s : parser.recognizedOptions().keySet()) { args.valuesOf(s); } } catch (OptionException e) { if (e.getCause() != null) { System.err.println(e.getMessage() + ": " + e.getCause().getMessage()); } else { System.err.println(e.getMessage()); } System.err.println(); help_and_exit(parser, System.err); } if (args.has(OPT_HELP)) { help_and_exit(parser, System.out); } return args; }
private static void createWallet(OptionSet options, NetworkParameters params, File walletFile) throws IOException { if (walletFile.exists() && !options.has("force")) { System.err.println( "Wallet creation requested but " + walletFile + " already exists, use --force"); return; } wallet = new Wallet(params); if (password != null) { wallet.encrypt(password); wallet.addNewEncryptedKey(password); } wallet.saveToFile(walletFile); }
void run() { try { cloudInfo.props.init(getPropertiesFile()); cloudInfo.locationId = options.valueOf(locationSpec); cloudInfo.verbose = options.has(verboseSpec); if (options.has(showLocationsSpec)) { cloudInfo.init(); cloudInfo.showLocations(); } else if (options.has(showHardwareSpec)) { cloudInfo.init(); cloudInfo.showHardware(); } else if (options.has(showImagesSpec)) { cloudInfo.init(); cloudInfo.showImages(); } else { CliUtils.printHelpAndExit(parser); } } finally { cloudInfo.shutdown(); } }
public static void main(String[] args) { OptionParser p = new OptionParser("fc:q::"); p.accepts("ftp"); p.accepts("user").requiredIf("ftp").withRequiredArg(); p.accepts("pass").requiredIf("ftp").withRequiredArg(); OptionSet opt = p.parse(args); if (opt.has("f")) { System.out.println("-f exist"); System.out.println("-f with : " + opt.valueOf("f")); } if (opt.has("c")) { System.out.println("-c exist with:" + opt.valueOf("c")); } if (opt.has("ftp")) { // we know username and password // existe if -ftp is set String user = (String) opt.valueOf("user"); String pwd = (String) opt.valueOf("pass"); System.out.println("user:"******" pass:" + pwd); } }
/** * Process the options found in the commandline arguments and checks that all required options are * present. * * @param opts * @param cfg * @throws Exception */ private static void processOptions(OptionSet opts, ConfigurationOptions cfg) throws Exception { if (opts.has("N")) { cfg.numNodes = Integer.parseInt(opts.valueOf("N").toString()); } else throw new Exception("Argument --num-nodes is required"); if (opts.has("C")) { cfg.numVehicles = Integer.parseInt(opts.valueOf("C").toString()); } else throw new Exception("Argument --num-vehicles is required"); if (opts.has("D")) { cfg.degreeProb = Integer.parseInt(opts.valueOf("D").toString()) / (double) cfg.numNodes; } else throw new Exception("Argument --node-degree is required"); if (opts.has("node-capacity")) { cfg.capacity = Integer.parseInt(opts.valueOf("node-capacity").toString()); } // this argument is optional if (opts.has("o")) { cfg.outputFile = new File(opts.valueOf("o").toString()); } else throw new Exception("Argument --output-file is required"); if (opts.has("d")) { String s = opts.valueOf("d").toString(); String[] ss = s.split(":"); if (ss.length != 2) throw new Exception("Argument to node-delay must have the form min:max"); cfg.nodeDelay[0] = Integer.parseInt(ss[0]); cfg.nodeDelay[1] = Integer.parseInt(ss[1]); } else throw new Exception("Argument --node-delay is required"); if (opts.has("S")) { String[] ss = opts.valueOf("S").toString().split(","); for (String s : ss) { cfg.strategies.add(s); } } else throw new Exception("Argument --vehicle-strategies is required"); if (opts.has("one-way-prob")) { cfg.oneWay = Double.parseDouble(opts.valueOf("one-way-prob").toString()); } cfg.bottleneck = opts.has("congested"); if (opts.has("graph")) { cfg.graphFile = new File(opts.valueOf("graph").toString()); } }
@Override public int call(BurlapShell shell, String argString, Scanner is, PrintStream os) { OptionSet oset = this.parser.parse(argString.split(" ")); List<String> args = (List<String>) oset.nonOptionArguments(); if (oset.has("h")) { os.println( "[-v] objectClass objectName\nAdds an OO-MDP object instance of class objectClass and with name " + "objectName to the current state of the world." + "The Java ObjectInstance implementation used will be MutableObjectInstance.\n\n" + "-v print the new world state after completion."); return 0; } World w = ((SGWorldShell) shell).getWorld(); if (w.gameIsRunning()) { os.println("Cannot manually change state while a game is running."); return 0; } if (args.size() != 2) { return -1; } ObjectInstance o = new MutableObjectInstance(domain.getObjectClass(args.get(0)), args.get(1)); State s = w.getCurrentWorldState().copy(); s.addObject(o); w.setCurrentState(s); if (oset.has("v")) { os.println(s.getCompleteStateDescriptionWithUnsetAttributesAsNull()); } return 1; }
@Test public void supportsOptionSynonyms() { OptionParser parser = new OptionParser(); List<String> synonyms = asList("message", "blurb", "greeting"); parser.acceptsAll(synonyms).withRequiredArg(); String expectedMessage = "Hello"; OptionSet options = parser.parse("--message", expectedMessage); for (String each : synonyms) { assertTrue(each, options.has(each)); assertTrue(each, options.hasArgument(each)); assertEquals(each, expectedMessage, options.valueOf(each)); assertEquals(each, asList(expectedMessage), options.valuesOf(each)); } }