/** * Parses the command line arguments and returns a Configuration according to the given * switches. * @param args the command line arguments given to main * @return the configuration * @throws ParseException */ public Configuration parseArgs(String[] args) throws ParseException { CommandLine cl = null; try { cl = parser.parse(options, args); } catch (UnrecognizedOptionException uoe){ logger.error("unrecognized option: {}",uoe.getOption()); printHelp(); System.exit(1); } Configuration config = new Configuration(); if(!cl.hasOption('c')){ config.setTargetCount(1); } else { config.setTargetCount(Long.parseLong(cl.getOptionValue('c'))); } if(!cl.hasOption('p')){ config.setUserNamePrefix("user"); } else { config.setUserNamePrefix(cl.getOptionValue('p')); } return config; }
@SuppressWarnings("unchecked") public static String process(ParseException e) { if (e instanceof MissingOptionException) { StringBuilder sb = new StringBuilder(); Iterator<String> options = ((MissingOptionException) e).getMissingOptions().iterator(); while (options.hasNext()) { sb.append(options.next()); if (options.hasNext()) { sb.append(", "); } } return String.format("Missing required option(s) %s.", sb.toString()); } else if (e instanceof MissingArgumentException) { return String.format("%s is missing a required argument.", ((MissingArgumentException) e).getOption()); } else if (e instanceof UnrecognizedOptionException) { return String.format("%s is not a valid option.", ((UnrecognizedOptionException) e).getOption()); } else { return String.format("%s.", e.getMessage()); } }
/** * Parse the command line arguments. */ protected static CommandLine parseArgs(String[] args) { CommandLine cl = null; try { cl = argParser.parse(cmdOptions, args); } catch (AlreadySelectedException dupex) { displayHelp(); display("\nDuplicate option: " + dupex.getMessage()); } catch (MissingOptionException opex) { displayHelp(); display("\nMissing command line option: " + opex.getMessage()); } catch (UnrecognizedOptionException uex) { displayHelp(); display(uex.getMessage()); } catch (ParseException pe) { display("Unable to parse the command line arguments: " + pe); } catch (Exception ex) { ex.printStackTrace(); } return cl; }
public static CommandLine parseCli(ModeType mode, String[] args) { CommandLine cli = null; Options opt = ConfigModes.getMode(mode); try { cli = new IgnorePosixParser(true).parse(opt, args); } catch (MissingArgumentException me) { Formatter.usageError(me.getLocalizedMessage(), mode); System.exit(-1); } catch (MissingOptionException mo) { Formatter.usageError(mo.getLocalizedMessage(), mode); System.exit(-1); } catch (AlreadySelectedException ase) { Formatter.usageError(ase.getLocalizedMessage(), mode); } catch (UnrecognizedOptionException uoe) { Formatter.usageError(uoe.getLocalizedMessage(), mode); } catch (ParseException e) { Formatter.printStackTrace(e); System.exit(-1); } return cli; }
/** * Parses the command line arguments and returns a Configuration according to the given * switches. * @param args the command line arguments given to main * @return the configuration * @throws ParseException */ public Configuration parseArgs(String[] args) throws ParseException { CommandLine cl = null; try { cl = parser.parse(options, args); } catch (UnrecognizedOptionException uoe){ logger.error("unrecognized option: {}",uoe.getOption()); printHelp(); System.exit(1); } Configuration config = new Configuration(); config.setLoginUrl(cl.getOptionValue('t')); if(!cl.hasOption('l')){ config.setLoops(1); } else { config.setLoops(Long.parseLong(cl.getOptionValue('l'))); } if(!cl.hasOption('r')){ config.setRequestsPerMinute(-1); } else { config.setRequestsPerMinute(Long.parseLong(cl.getOptionValue('r'))); } if(!cl.hasOption('i')){ config.setOriginIpAddress(null); } else { config.setOriginIpAddress(cl.getOptionValue('i')); } config.setCredentials(getCredentials(cl.getOptionValue('f'), cl.getOptionValues('c'))); if (!ConfigurationValidator.isValid(config)){ printHelp(); } return config; }
/** * Checks if the specifying some random argument work throws an exception. */ @Test public void checkRandomArgDoesNotWork() throws KeywordOptimizerException { thrown.expect(KeywordOptimizerException.class); thrown.expectCause(isA(UnrecognizedOptionException.class)); KeywordOptimizer.run("-x"); }
@Test(expected = UnrecognizedOptionException.class) public void testParseArgumentsUnrecognizedOptionException() throws ParseException { ArgumentParser argParser = new ArgumentParser(""); argParser.addArgument("a", "configured_option", false, "Some flag parameter", false); argParser.parseArguments(new String[] {"-b", "unrecognized_option"}); }
/** * Verifies that the properties don't contain undefined options which will * cause the base parser to blowup. * * @param options the options config * @param properties overriding properties * @throws UnrecognizedOptionException if a property exists that isn't * configured in the options. */ protected void validateProperties(Options options, Properties properties) throws UnrecognizedOptionException { if (properties != null) { for (Entry<Object, Object> e : properties.entrySet()) { String arg = (String) e.getKey(); boolean hasOption = options.hasOption(arg); if (!hasOption) { throw new UnrecognizedOptionException( "Unrecognized option: " + arg, arg); } } } }
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(OPT_CONFIGFILE, true, "The XML Configuration file describing what to anonymize."); options.addOption(OPT_SYNONYMFILE, true, "The XML file to read/write synonyms to. " + "If the file does not exist it will be created."); options.addOption("configexample", false, "Prints out a demo/template configuration file."); options.addOption(OPT_DRYRUN, false, "Do not make changes to the database."); BasicParser parser = new BasicParser(); try { CommandLine commandline = parser.parse(options, args); String configfileName = commandline.getOptionValue(OPT_CONFIGFILE); String synonymfileName = commandline.getOptionValue(OPT_SYNONYMFILE); boolean dryrun = commandline.hasOption(OPT_DRYRUN); if (configfileName != null) { anonymize(configfileName, synonymfileName, dryrun); } else if (commandline.hasOption("configexample")) { printDemoConfiguration(); } else { printHelp(options); } } catch (UnrecognizedOptionException e) { System.err.println(e.getMessage()); printHelp(options); } }
private ReservationACL getReservationACLFromAuditConstant( String auditConstant) throws YarnException{ if (auditConstant.equals(AuditConstants.SUBMIT_RESERVATION_REQUEST)) { return ReservationACL.SUBMIT_RESERVATIONS; } else if (auditConstant.equals(AuditConstants.LIST_RESERVATION_REQUEST)) { return ReservationACL.LIST_RESERVATIONS; } else if (auditConstant.equals(AuditConstants.DELETE_RESERVATION_REQUEST) || auditConstant.equals(AuditConstants.UPDATE_RESERVATION_REQUEST)) { return ReservationACL.ADMINISTER_RESERVATIONS; } else { String error = "Audit Constant " + auditConstant + " is not recognized."; LOG.error(error); throw RPCUtil.getRemoteException(new UnrecognizedOptionException(error)); } }
@Override public void execute(CommandLine options) throws Exception { String[] args = options.getArgs(); if (args.length < min) { throw new MissingArgumentException("missing required arguments"); } if (args.length > max) { throw new UnrecognizedOptionException("unknown extra argument \"" + args[max] + "\""); } }
/** * Invalid arguments on the command line result in an exception. * * @throws Exception */ @Test public void testParseCommandLine_InvalidArguments_ThrowsException() throws Exception { // Setup final StartApplication main = new StartApplication(); thrown.expect(UnrecognizedOptionException.class); thrown.expectMessage("Unrecognized option: -foo"); // Run main.parseCommandLine(new String[] { "-foo" }); }
@Test(expected = UnrecognizedOptionException.class) public void mainPrintUsage5Test() throws Exception { Main.main(new String[]{"-nifi","http://localhost:8080/nifi-api", "-branch","\"root>N2\"","-conf","adr","-m","undeploy", "-userErr","user"}); }
/** * Test case for {@link StreamingAppRuntime#parseCommandLine(String[])} being * provided an array showing unknown settings */ @Test(expected=UnrecognizedOptionException.class) public void testParseCommandLine_withUnknownSettings() throws Exception { new DummyLogProcessingRuntime(new CountDownLatch(1)).parseCommandLine(new String[]{"-a","123"}); }
/** * Test case for {@link StreamingAppRuntime#parseCommandLine(String[])} being * provided an array showing known and unknown settings */ @Test(expected=UnrecognizedOptionException.class) public void testParseCommandLine_withKnownAndUnknownSettings() throws Exception { new DummyLogProcessingRuntime(new CountDownLatch(1)).parseCommandLine(new String[]{"-a","123", "-f", "/tmp/file.txt"}); }
/** * <p>Parses options from the given string array. </p> * * The algorithm for handling options is as follows: * <ol> * <li>if <code>HELP</code> options is found - prints usage and exists</li> * <li>if the given options are cmd line options (not from config file) and * if the <code>CONFIG_FILE</code> option is found, then first loads options from the * file specified through the <code>CONFIG_FILE</code> option.</li> * <li>loads options from cmd line</li> * <li>stores options to <code>ConfigManger</code> instance</li> * <li>checks for required options</li> * <li>initializes stuff according to the previously parsed options</li> * </ol> * * @param args * options to parse * @param fromFile * whether the given options are from file or from cmd line. * @see #loadFromFile(String) * @see #processConfigFile(InputStream) * @see #storeOptions() * @see #checkRequiredOptions() * @see #initStuffFromOptions() */ private void parseArgs(String[] args, boolean fromFile) { try { CommandLine cl = new PosixParser().parse(koratOptions, args); if (fromFile) { fromFileCmdLine = cl; } else { cmdLine = cl; } if (cl.hasOption(HELP.getOpt())) { printUsage(koratOptions); System.exit(0); } if (!fromFile) { if (cl.hasOption(CONFIG_FILE.getOpt())) { String confFileName = cl.getOptionValue(CONFIG_FILE.getOpt()); try { args = loadFromFile(confFileName); parseArgs(args, true); } catch (IOException e) { System.err.println("Cannot load file: " + confFileName); } } } storeOptions(); checkRequiredOptions(); initStuffFromOptions(); } catch (ParseException pe) { String msg = ""; if (pe instanceof MissingOptionException) msg = "The following required options are missing: "; else if (pe instanceof UnrecognizedOptionException) msg = "The following options were not recognized: "; System.err.println(msg + pe.getMessage()); System.err.println(); System.exit(5); } }
/** * Constructor. * * @param args Command-line arguments to process. * @param out PrintStream to write on. * * @throws ParseException Failed parse of command line. */ public CommandLineParser(String [] args, PrintWriter out) throws ParseException { super(); this.out = out; this.options = new Options(); this.options.addOption(new Option("h","help", false, "Prints this message and exits.")); Option opt = new Option("o","mode", true, "Index by URL, HASH or BOTH. Default: BOTH."); opt.setArgName("type"); this.options.addOption(opt); this.options.addOption(new Option("s","equivalent", false, "Include a stripped URL in the index for equivalent URL " + "matches.")); this.options.addOption(new Option("t","timestamp", false, "Include the time of fetch in the index.")); this.options.addOption(new Option("e","etag", false, "Include etags in the index (if available in the source).")); opt = new Option("m","mime", true, "A filter on what mime types are added into the index " + "(blacklist). Default: ^text/.*"); opt.setArgName("reg.expr."); this.options.addOption(opt); this.options.addOption(new Option("w","whitelist", false, "Make the --mime filter a whitelist instead of blacklist.")); opt = new Option("i","iterator", true, "An iterator suitable for the source data (default iterator " + "works on Heritrix's crawl.log)."); opt.setArgName("classname"); this.options.addOption(opt); this.options.addOption(new Option("a","add", false, "Add source data to existing index.")); opt = new Option("r","origin", true, "If set, the 'origin' of each URI will be added to the index." + " If no origin is provided by the source data then the " + "argument provided here will be used."); opt.setArgName("origin"); this.options.addOption(opt); this.options.addOption(new Option("d","skip-duplicates", false, "If set, URIs marked as duplicates will not be added to the " + "index.")); PosixParser parser = new PosixParser(); try { this.commandLine = parser.parse(this.options, args, false); } catch (UnrecognizedOptionException e) { usage(e.getMessage(), 1); } }