@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()); }
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); } }
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 -?`"; }
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; }
@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")); }
@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)); } }
@Test public void parsesFilesWithWhitespaceSuccessfully() throws IOException { File tempFile = File.createTempFile("this is a test with whitespaces", ".txt"); tempFile.deleteOnExit(); System.out.println("Using temp file: " + tempFile.getAbsolutePath()); // use a dummy configuration final CompositeConfiguration dummyConfig = new CompositeConfiguration(); final GlacierUploaderOptionParser optionParser = new GlacierUploaderOptionParser(dummyConfig); final OptionSet options = optionParser.parse("-m", tempFile.getAbsolutePath()); final List<File> optionsFiles = options.valuesOf(optionParser.MULTIPARTUPLOAD); final List<String> nonOptions = options.nonOptionArguments(); assertEquals(1, optionsFiles.size()); assertEquals(0, nonOptions.size()); final ArrayList<File> files = optionParser.mergeNonOptionsFiles(optionsFiles, nonOptions); assertEquals(tempFile.getName(), files.get(0).getName()); }
private static void work(CardTerminal reader, OptionSet args) throws CardException { if (!reader.isCardPresent()) { System.out.println("No card in " + reader.getName()); return; } FileOutputStream o = null; if (args.has(OPT_DUMP)) { try { o = new FileOutputStream((File) args.valueOf(OPT_DUMP)); } catch (FileNotFoundException e) { System.err.println("Can not dump to " + args.valueOf(OPT_DUMP)); } } reader = LoggingCardTerminal.getInstance(reader, o); // This allows to override the protocol for RemoteTerminal as well. final String protocol; if (args.has(OPT_T0)) { protocol = "T=0"; } else if (args.has(OPT_T1)) { protocol = "T=1"; } else { protocol = "*"; } if (args.has(CMD_APDU)) { Card c = null; try { c = reader.connect(protocol); if (args.has(CMD_APDU)) { for (Object s : args.valuesOf(CMD_APDU)) { CommandAPDU a = new CommandAPDU(HexUtils.stringToBin((String) s)); ResponseAPDU r = c.getBasicChannel().transmit(a); if (args.has(OPT_ERROR) && r.getSW() != 0x9000) { System.out.println( "Card returned " + String.format("%04X", r.getSW()) + ", exiting!"); return; } } } } catch (CardException e) { if (TerminalManager.getExceptionMessage(e) != null) { System.out.println("PC/SC failure: " + TerminalManager.getExceptionMessage(e)); } else { throw e; } } finally { if (c != null) { c.disconnect(true); } } } else if (args.has(OPT_CONNECT)) { String remote = (String) args.valueOf(OPT_CONNECT); JSONMessagePipe transport = null; try { if (remote.startsWith("http://") || remote.startsWith("https://")) { if (args.has(OPT_PINNED)) { transport = HTTPTransport.open( new URL(remote), certFromPEM(((File) args.valueOf(OPT_PINNED)).getPath())); } else { transport = HTTPTransport.open(new URL(remote), null); } } else { transport = SocketTransport.connect(string2socket(remote), null); } // Connect the transport and the terminal CmdlineRemoteTerminal c = new CmdlineRemoteTerminal(transport, reader); c.forceProtocol(protocol); // Run c.run(); } catch (IOException e) { System.err.println("Communication error: " + e.getMessage()); } finally { if (transport != null) transport.close(); } } }
/** * Try to set the arguments from main method on the fields loaded by loadOpts(Class<?> c). * * @param args - Arguments passed from main method. * @return this */ public Flags parse(String[] args) { optionSet = optionParser.parse(args); // Store non option arguments nonOptionArguments = optionSet.nonOptionArguments(); if (nonOptionArguments == null) { nonOptionArguments = new ArrayList<String>(); } // do not parse options if "help" is a part of the arguments given if (helpFlagged()) { return this; } if (propertiesFlagged()) { List<String> files = optionSet.valuesOf(PROPERTIES_FILE); ArrayList<String> newArgs = new ArrayList<String>(); for (String filename : files) { final Properties props = new Properties(); try { final FileInputStream stream = new FileInputStream(filename); props.load(stream); for (Enumeration<?> keys = props.propertyNames(); keys.hasMoreElements(); ) { String flagName = (String) keys.nextElement(); if (!options.containsKey(flagName) || optionSet.hasArgument(flagName)) { // Properties contains something not in options or is already set by commandline // argument // Command line argument takes precedence over properties file continue; } newArgs.add("--" + flagName); newArgs.add(props.getProperty(flagName)); } stream.close(); } catch (IOException e) { throw new RuntimeException("Could not parse property-file", e); } } Collections.addAll(newArgs, args); optionSet = optionParser.parse(newArgs.toArray(new String[newArgs.size()])); } for (OptionHolder holder : options.values()) { try { OptionSpec<?> optionSpec = holder.getOptionSpec(); // Deal with the flags that were given on the command line. if (optionSet.has(optionSpec)) { switch (holder.getType()) { case INTEGER: if (holder.isInstanced()) { holder.getField().set(holder.getObjectSource(), optionSet.valueOf(optionSpec)); } else { holder.getField().set(holder.getField().getClass(), optionSet.valueOf(optionSpec)); } break; case LONG: if (holder.isInstanced()) { holder.getField().set(holder.getObjectSource(), optionSet.valueOf(optionSpec)); } else { holder.getField().set(holder.getField().getClass(), optionSet.valueOf(optionSpec)); } break; case STRING: if (holder.isInstanced()) { holder.getField().set(holder.getObjectSource(), optionSet.valueOf(optionSpec)); } else { holder.getField().set(holder.getField().getClass(), optionSet.valueOf(optionSpec)); } break; case BOOLEAN: Object value = optionSet.valueOf(optionSpec); if (holder.isInstanced()) { holder.getField().set(holder.getObjectSource(), (value == null) ? true : value); } else { holder.getField().set(holder.getField().getClass(), (value == null) ? true : value); } break; case ENUM: if (holder.isInstanced()) { try { holder.getField().set(holder.getObjectSource(), optionSet.valueOf(optionSpec)); } catch (Exception e) { throw new IllegalArgumentException( "Option given is not a valid option. Valid options are: " + enumOptions.get(holder.flag.options()).toString() + "."); } } else { try { holder .getField() .set(holder.getField().getClass(), optionSet.valueOf(optionSpec)); } catch (Exception e) { throw new IllegalArgumentException( "Option given is not a valid option. Valid options are: " + enumOptions.get(holder.flag.options()).toString() + "."); } } break; } // No further action needed for this field. continue; } // Check if flag that does not occur in command line was required. if (holder.getFlag().required()) { throw new IllegalArgumentException( "Required argument missing: " + holder.getFlag().name()); } } catch (IllegalAccessException e) { throw new RuntimeException( "Programming error, illegal access for " + holder.getField().toGenericString()); } } return this; }
@Override public void configure(Binder binder) { OptionParser parser = new OptionParser(); ArgumentAcceptingOptionSpec<Integer> portSpec = parser .accepts("port", "The port to listen on") .withOptionalArg() .ofType(Integer.class) .defaultsTo(8080); ArgumentAcceptingOptionSpec<String> addressSpec = parser .accepts("address", "The address to bind to") .withOptionalArg() .ofType(String.class) .defaultsTo("0.0.0.0"); ArgumentAcceptingOptionSpec<Integer> proxyPortRange = parser .accepts("proxyPortRange", "The range of ports to use for proxies") .withOptionalArg() .ofType(Integer.class) .defaultsTo(8081, 8581) .withValuesSeparatedBy('-'); ArgumentAcceptingOptionSpec<Integer> ttlSpec = parser .accepts("ttl", "Time in seconds until an unused proxy is deleted") .withOptionalArg() .ofType(Integer.class) .defaultsTo(0); parser.acceptsAll(asList("help", "?"), "This help text"); OptionSet options = parser.parse(args); if (options.has("?")) { try { parser.printHelpOn(System.out); System.exit(0); } catch (IOException e) { // should never happen, but... e.printStackTrace(); } return; } List<Integer> ports = options.valuesOf(proxyPortRange); if (ports.size() < 2) { throw new IllegalArgumentException(); } Integer minPort; Integer maxPort; if (ports.get(1) > ports.get(0)) { minPort = ports.get(0); maxPort = ports.get(1); } else { minPort = ports.get(1); maxPort = ports.get(0); } Integer port = portSpec.value(options); if (port >= minPort && port <= maxPort) { int num = maxPort - minPort; minPort = port + 1; maxPort = minPort + num; } binder.bind(Key.get(Integer.class, new NamedImpl("port"))).toInstance(port); binder .bind(Key.get(String.class, new NamedImpl("address"))) .toInstance(addressSpec.value(options)); binder.bind(Key.get(Integer.class, new NamedImpl("minPort"))).toInstance(minPort); binder.bind(Key.get(Integer.class, new NamedImpl("maxPort"))).toInstance(maxPort); binder.bind(Key.get(Integer.class, new NamedImpl("ttl"))).toInstance(ttlSpec.value(options)); /* * Init User Agent String Parser, update of the UAS datastore will run in background. */ // temporarily disabled because user-agent-string.info no longer exists // BrowserMobHttpClient.getUserAgentStringParser(); }
public static void main(String[] args) throws Exception { OptionParser parser = new OptionParser("p:f:c:r:H:s:t:h"); OptionSet options = null; try { options = parser.parse(args); } catch (OptionException ex) { System.err.println(ex.getMessage()); System.exit(1); } if (options.has("h")) { printHelp(System.out); System.exit(0); } final int port; if (options.has("p")) { String portStr = options.valueOf("p").toString(); try { port = Integer.parseInt(portStr); } catch (NumberFormatException ex) { throw new IllegalArgumentException("Invalid port number: " + portStr, ex); } } else { port = -1; System.err.println("Mandatory parameter port not given."); System.exit(1); } AnyUrlServlet servlet = new AnyUrlServlet(); if (options.has("f")) { String fileStr = options.valueOf("f").toString(); servlet.setFile(new File(fileStr)); } if (options.has("c")) { servlet.setContentType(options.valueOf("c").toString()); } if (options.has("r")) { servlet.setCharset(options.valueOf("r").toString()); } if (options.has("H")) { MultiValueMap headers = new MultiValueMapLinkedHashSet(); for (Object t : options.valuesOf("H")) { final String headerLine = t.toString().trim(); final int sepIdx = headerLine.indexOf(':'); if ((sepIdx > 0) && (sepIdx < headerLine.length())) { final String header = headerLine.substring(0, sepIdx).trim(); final String value = headerLine.substring(sepIdx + 1).trim(); // System.out.printf("\nHeader: Value => %s:%s\n", header, value); headers.put(header, value); } } servlet.setHeaders(headers); } if (options.has("s")) { try { int statusCode = Integer.parseInt(options.valueOf("s").toString()); servlet.setStatusCode(statusCode); } catch (NumberFormatException ex) { throw new IllegalArgumentException("Param -s must be a valid status code."); } } if (options.has("t")) { try { long throttleMillis = Long.parseLong(options.valueOf("t").toString()); if (throttleMillis > 1) { servlet.setThrottleMillis(throttleMillis); } else { throw new NumberFormatException(); } } catch (NumberFormatException ex) { throw new IllegalArgumentException("Param -t must be a valid number."); } } Server server = new Server(port); server.setStopAtShutdown(true); // Attach the servlet: ServletContextHandler ctx = new ServletContextHandler(); ctx.setContextPath("/"); server.setHandler(ctx); ctx.addServlet(new ServletHolder(servlet), "/*"); server.start(); }