public static void checkRequiredOptions() throws MissingOptionException { OptionGroup[] groups = {contentGroup}; for(OptionGroup group : groups) { ArrayList<Option> groupOptions = new ArrayList<Option>(group.getOptions()); boolean groupIsGiven = false; for (Option option : groupOptions){ if (commandLine.hasOption(option.getOpt())) { groupIsGiven = true; break; } } if (!groupIsGiven){ throw new MissingOptionException(groupOptions); } } }
@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()); } }
public static void checkRequiredOptions() throws MissingOptionException { OptionGroup[] groups = {typeGroup, contentGroup}; for(OptionGroup group : groups) { ArrayList<Option> groupOptions = new ArrayList<Option>(group.getOptions()); boolean groupIsGiven = false; for (Option option : groupOptions){ if (commandLine.hasOption(option.getOpt())) { groupIsGiven = true; break; } } if (!groupIsGiven){ throw new MissingOptionException(groupOptions); } } }
/** * Checks for the presence of the required options. * * @throws MissingOptionException if a required options is not provided. */ private void checkRequiredOptions() throws MissingOptionException { String missingOptions = ""; ConfigManager config = ConfigManager.getInstance(); if (config.className == null) { missingOptions += CLZ.getSwitches(); } if (config.args == null) { if (missingOptions.length() > 0) missingOptions += ", "; missingOptions += ARGS.getSwitches(); } if (missingOptions.length() > 0) { throw new MissingOptionException(missingOptions); } }
/** * 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; }
@SuppressWarnings("rawtypes") protected void checkRequiredOptions() throws MissingOptionException { List requiredOptions = this.getRequiredOptions(); if (!requiredOptions.isEmpty()) { Iterator it = requiredOptions.iterator(); while (it.hasNext()) { Object opt = it.next(); if (opt.getClass().equals(String.class)) { if (Configuration.has(((String) opt))) { it.remove(); } } else if (opt.getClass().equals(Option.class)) { if (Configuration.has(((Option) opt).getLongOpt())) { it.remove(); } } } } if (!requiredOptions.isEmpty()) { throw new MissingOptionException(requiredOptions); } }
public static CommandLine tryParse(CommandLineParser parser, Options options, String[] args) { try { return parser.parse(options, args); } catch (MissingOptionException moe) { logger.error("Required options missing: " + Joiner.on(',').join(moe.getMissingOptions())); throw new CliParser.ParsingException(moe); } catch (ParseException e) { logger.error("Failed parsing options", e); throw new CliParser.ParsingException(e); } }
@Test public void testGetChangeStatusNoPassword() throws Exception { thrown.expect(MissingOptionException.class); thrown.expectMessage("Missing required option: p"); // // Comment line below in order to go against the real back-end as specified via -h setMock(setupMock()); GetChangeStatus.main(new String[] { "-u", SERVICE_USER, "-e", SERVICE_ENDPOINT, "8000038673"}); }
@Test(expected = MissingOptionException.class) public void testFailOnMissingMandatoryOption() throws Exception { // Test for a help dialog displayed upon failure String[] args = {"-s 0"}; ConfigurationBuilder.createBuilder() .loadCommandLineConfiguration(CLIConstants.setupOptions(), args) .getConfiguration(); }
@Test(expected = MissingOptionException.class) public void testHelpFromFail() throws Exception { // First test for a user requested help dialog String[] args = {"--help"}; ConfigurationBuilder.createBuilder() .loadCommandLineConfiguration(CLIConstants.setupOptions(), args) .getConfiguration(); }
/** * Checks if specifying no arg works. */ @Test public void checkNoArg() throws KeywordOptimizerException { thrown.expect(KeywordOptimizerException.class); thrown.expectCause(isA(MissingOptionException.class)); KeywordOptimizer.main(new String[]{}); }
public static void afterParseChecks() throws MissingOptionException { if (commandLine.hasOption("h")) { System.out.println("You passed help flag."); help(0); } else if (commandLine.hasOption("v")) { printVersions(); }else { checkRequiredOptions(); } }
public static void afterParseChecks() throws MissingOptionException{ if (commandLine.hasOption("h")) { System.out.println("You passed help flag."); help(0); } else if (commandLine.hasOption("v")) { printVersions(); } else { checkRequiredOptions(); } }
@Test(expected = MissingOptionException.class) public void testParseArgumentsFailOnMissingArgumentTrue() throws ParseException { // Create an argument parser with a required "a" option. ArgumentParser argParser = new ArgumentParser(""); argParser.addArgument("a", "some_optional_parameter", false, "Some argument", true); // Parse the arguments with a missing argument which should thrown an exception since we are passing the flag which WILL fail on missing arguments. argParser.parseArguments(new String[] {}, true); }
@Test(expected = MissingOptionException.class) public void testParseArguments() throws ParseException { // Create an argument parser with a required "a" option. ArgumentParser argParser = new ArgumentParser(""); argParser.addArgument("a", "some_required_parameter", true, "Some argument", true); // Parse the arguments with a missing argument which should thrown an exception since we are using the method that WILL fail on missing arguments. argParser.parseArguments(new String[] {}); }
@Test public void commandLineWithoutPDDParameterMustFail() throws Exception { try { runner.run( "" ); fail(); } catch (MissingOptionException ex) { // Expected } }
@Test(expected = MissingOptionException.class) public void testNoOptions() throws Exception { String cl = "systemml"; String[] args = cl.split(" "); Options options = DMLScript.createCLIOptions(); DMLScript.parseCLArguments(args, options); }
@Test public void test() throws Exception { MyFactory factory = new MyFactory(); MyObject object; try { // Try to build object with missing constructor argument, which is required object = factory.buildObject(new String[]{}, 0, false, "usage"); Assert.fail(); } catch (IOException exc) { // Expected Assert.assertEquals(exc.getCause().getClass(), MissingOptionException.class); } object = factory.buildObject(new String[]{"-myArg", "required"}, 0, false, "usage"); Assert.assertEquals(object.required, "required"); Assert.assertNull(object.string1); Assert.assertNull(object.string2); object = factory.buildObject(new String[]{"-setString1", "str1", "-myArg", "required"}, 0, false, "usage"); Assert.assertEquals(object.required, "required"); Assert.assertEquals(object.string1, "str1"); Assert.assertNull(object.string2); object = factory.buildObject(new String[]{"-foo", "bar", "-myArg", "required"}, 0, false, "usage"); Assert.assertEquals(object.required, "required"); Assert.assertEquals(object.string2, "bar"); Assert.assertNull(object.string1); object = factory.buildObject(new String[]{"-foo", "bar", "-setString1", "str1", "-myArg", "required"}, 0, false, "usage"); Assert.assertEquals(object.required, "required"); Assert.assertEquals(object.string2, "bar"); Assert.assertEquals(object.string1, "str1"); }
@Override protected void checkRequiredOptions() { try { super.checkRequiredOptions(); } catch (MissingOptionException e) { incomplete = true; } }
@SuppressWarnings("rawtypes") protected void checkRequiredOptions() throws MissingOptionException { List requiredOptions = this.getRequiredOptions(); if (!requiredOptions.isEmpty()) { Iterator it = requiredOptions.iterator(); while (it.hasNext()) { Object opt = it.next(); if (opt.getClass().equals(String.class)) { if (Configuration.has(((String) opt))) { it.remove(); } } else if (opt.getClass().equals(Option.class)) { if (Configuration.has(((Option) opt).getLongOpt())) { it.remove(); } } else if (opt.getClass().equals(OptionGroup.class)) { for (Object o : ((OptionGroup)opt).getOptions()) { if (Configuration.has(((Option)o).getLongOpt())) { it.remove(); break; } } } } } if (!requiredOptions.isEmpty()) { throw new MissingOptionException(requiredOptions); } }
public static int getExceptionCode(Exception e) { if (e instanceof MissingOptionException) { return CLI_MISSING_OPTION_EXCEPTION; } return CLI_EXCEPTION; }
public static int getExceptionCode(Exception e) { if (e instanceof MissingOptionException) { return CLI_MISSING_OPTION_EXCEPTION; } return 1; }
@Override public void run(CommandLine commandLine) throws Exception { PrintStream output = null; //parse required parameters parameterFile = new ParameterFile(new File( commandLine.getOptionValue("parameterFile"))); parameters = loadParameters(new File( commandLine.getOptionValue("parameters"))); metric = Integer.parseInt(commandLine.getOptionValue("metric")); //parse optional parameters if (commandLine.hasOption("band")) { bandWidth = Integer.parseInt(commandLine.getOptionValue("band")); } if (commandLine.hasOption("threshold")) { threshold = Double.parseDouble(commandLine.getOptionValue( "threshold")); } //if analyzing hypervolume, require the hypervolume option if (metric == 0) { if (commandLine.hasOption("hypervolume")) { threshold *= Double.parseDouble(commandLine.getOptionValue( "hypervolume")); } else { throw new MissingOptionException("requires hypervolume option"); } } try { //setup the output stream if (commandLine.hasOption("output")) { output = new PrintStream(new File( commandLine.getOptionValue("output"))); } else { output = System.out; } //process all the files listed on the command line String[] filenames = commandLine.getArgs(); for (int i=0; i<filenames.length; i++) { if (i > 0) { output.println(); } metrics = loadMetrics(new File(filenames[i])); output.print(filenames[i]); output.println(":"); output.print(" Best: "); output.println(calculateBest()); output.print(" Attainment: "); output.println(calculateAttainment()); if (commandLine.hasOption("controllability")) { output.print(" Controllability: "); output.println(calculateControllability()); } if (commandLine.hasOption("efficiency")) { output.print(" Efficiency: "); output.println(calculateEfficiency()); } } } finally { if ((output != null) && (output != System.out)) { output.close(); } } }
/** * <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); } }
/** * The main method that does the parsing of the commandline, and makes the * actual index request. * * @param args * the arguments */ public static void main(String[] args) { Options options = new Options(); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; Option indexType = new Option("t", "type", true, "Type of index"); Option jobList = new Option("l", "jobids", true, "list of jobids"); indexType.setRequired(true); jobList.setRequired(true); options.addOption(indexType); options.addOption(jobList); try { // parse the command line arguments cmd = parser.parse(options, args); } catch (MissingOptionException e) { System.err.println("Some of the required parameters are missing: " + e.getMessage()); dieWithUsage(); } catch (ParseException exp) { System.err.println("Parsing of parameters failed: " + exp.getMessage()); dieWithUsage(); } String typeValue = cmd.getOptionValue(INDEXTYPE_OPTION); String jobidsValue = cmd.getOptionValue(JOBIDS_OPTION); String[] jobidsAsStrings = jobidsValue.split(","); Set<Long> jobIDs = new HashSet<Long>(); for (String idAsString : jobidsAsStrings) { jobIDs.add(Long.valueOf(idAsString)); } JobIndexCache cache = null; String indexTypeAstring = ""; if (typeValue.equalsIgnoreCase("CDX")) { indexTypeAstring = "CDX"; cache = IndexClientFactory.getCDXInstance(); } else if (typeValue.equalsIgnoreCase("DEDUP")) { indexTypeAstring = "DEDUP"; cache = IndexClientFactory.getDedupCrawllogInstance(); } else if (typeValue.equalsIgnoreCase("CRAWLLOG")) { indexTypeAstring = "CRAWLLOG"; cache = IndexClientFactory.getFullCrawllogInstance(); } else { System.err.println("Unknown indextype '" + typeValue + "' requested."); dieWithUsage(); } System.out.println("Creating " + indexTypeAstring + " index for ids: " + jobIDs); Index<Set<Long>> index = cache.getIndex(jobIDs); JMSConnectionFactory.getInstance().cleanup(); }
public static void main(String[] args) throws Exception { Options options = new Options(); Option option = new Option("p", "port", true, "Port number"); option.setType(Integer.class); option.setRequired(true); options.addOption(option); option = new Option("d", "stateDir", true, "Directory in which lucene data is located"); option.setType(String.class); option.setRequired(true); options.addOption(option); PosixParser parser = new PosixParser(); CommandLine commandLine = null; try { commandLine = parser.parse(options, args); } catch (MissingOptionException e) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("start-suggestion-server" , options); System.exit(1); } Integer port = new Integer(commandLine.getOptionValue("p")); String stateDir = commandLine.getOptionValue("d"); if (Charset.defaultCharset() != Charset.forName("UTF-8")) { System.err.println("file.encoding must be UTF-8."); System.exit(1); } SuggestionIndex suggestionIndex = new SuggestionIndex(stateDir + "/suggestions", stateDir + "/ngram", MIN_SHINGLE_SIZE, MAX_SHINGLE_SIZE, COMMIT_COUNT); ExecutorThreadPool pool = new ExecutorThreadPool(50, 200, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1000)); Server server = new Server(pool); ServerConnector http = new ServerConnector(server, new HttpConnectionFactory()); http.setPort(port); server.addConnector(http); OutOfMemoryShutdown shutdown = new SuggestionShutdown(server, suggestionIndex); registerShutdownHandler(shutdown); server.setHandler(new SuggestionHandler(suggestionIndex, shutdown)); server.start(); server.join(); }