List of usage examples for org.apache.commons.cli Options hasOption
public boolean hasOption(String opt)
From source file:ape_test.CLITest.java
public void testVersionOption() { Main.createOptions(); Options opts = Main.getOptions(); assertEquals(opts.hasOption("-v"), true); }
From source file:de.vandermeer.skb.commons.utils.Test_CLIApache.java
@Test public void testDeclareOptions() { CLIApache aca = new CLIApache(); aca.declareOptions(this.prepareComProperties()); assertEquals(6, aca.optionList.size()); for (String s : this.rows()) { assertTrue(aca.optionList.containsKey(Table.defaulSeparator + s)); }//from w w w . j ava 2 s. c o m Options op = aca.options; assertEquals(6, op.getOptions().size()); assertTrue(op.hasOption("-b")); assertTrue(op.hasOption("-d")); assertTrue(op.hasOption("-i")); assertTrue(op.hasOption("-l")); assertTrue(op.hasOption("-s")); assertTrue(op.hasOption("--test-boolean")); assertTrue(op.hasOption("--test-double")); assertTrue(op.hasOption("--test-integer")); assertTrue(op.hasOption("--test-long")); assertTrue(op.hasOption("--test-string")); assertTrue(op.hasOption("--test-string-w-arg")); assertTrue(op.getOption("--test-string-w-arg").hasArg()); assertTrue(op.getOption("--test-string-w-arg").hasArgName()); }
From source file:com.emc.vipr.sync.ViPRSync.java
/** * Loads and configures plugins based on command line options. *///from w w w .ja va 2s .co m protected static ViPRSync cliBootstrap(String[] args) throws ParseException { ViPRSync sync = new ViPRSync(); List<SyncPlugin> plugins = new ArrayList<>(); CommandLine line = gnuParser.parse(mainOptions(), args, true); // find a plugin that can read from the source String sourceUri = line.getOptionValue(SOURCE_OPTION); if (sourceUri != null) { for (SyncSource source : sourceLoader) { if (source.canHandleSource(sourceUri)) { source.setSourceUri(sourceUri); sync.setSource(source); plugins.add(source); LogMF.info(l4j, "source: {0} ({1})", source.getName(), source.getClass()); break; } } } String targetUri = line.getOptionValue(TARGET_OPTION); // find a plugin that can write to the target if (targetUri != null) { for (SyncTarget target : targetLoader) { if (target.canHandleTarget(targetUri)) { target.setTargetUri(targetUri); sync.setTarget(target); plugins.add(target); LogMF.info(l4j, "target: {0} ({1})", target.getName(), target.getClass()); break; } } } // load filters List<SyncFilter> filters = new ArrayList<>(); String filtersParameter = line.getOptionValue(FILTERS_OPTION); if (filtersParameter != null) { for (String filterName : filtersParameter.split(",")) { for (SyncFilter filter : filterLoader) { if (filter.getActivationName().equals(filterName)) { filters.add(filter); plugins.add(filter); LogMF.info(l4j, "filter: {0} ({1})", filter.getName(), filter.getClass()); break; } } } sync.setFilters(filters); } // configure thread counts if (line.hasOption(QUERY_THREADS_OPTION)) sync.setQueryThreadCount(Integer.parseInt(line.getOptionValue(QUERY_THREADS_OPTION))); if (line.hasOption(SYNC_THREADS_OPTION)) sync.setSyncThreadCount(Integer.parseInt(line.getOptionValue(SYNC_THREADS_OPTION))); // configure timings display if (line.hasOption(TIMINGS_OPTION)) sync.setTimingsEnabled(true); if (line.hasOption(TIMING_WINDOW_OPTION)) { sync.setTimingWindow(Integer.parseInt(line.getOptionValue(TIMING_WINDOW_OPTION))); } // configure recursive behavior if (line.hasOption(NON_RECURSIVE_OPTION)) sync.setRecursive(false); // configure failed object tracking if (line.hasOption(FORGET_FAILED_OPTION)) sync.setRememberFailed(false); // configure whether to delete source objects after they are successfully synced if (line.hasOption(DELETE_SOURCE_OPTION)) sync.setDeleteSource(true); // logging options if (line.hasOption(DEBUG_OPTION)) { sync.setLogLevel(DEBUG_OPTION); } if (line.hasOption(VERBOSE_OPTION)) { sync.setLogLevel(VERBOSE_OPTION); } if (line.hasOption(QUIET_OPTION)) { sync.setLogLevel(QUIET_OPTION); } if (line.hasOption(SILENT_OPTION)) { sync.setLogLevel(SILENT_OPTION); } // Quick check for no-args if (sync.getSource() == null) { throw new ConfigurationException("source must be specified"); } if (sync.getTarget() == null) { throw new ConfigurationException("target must be specified"); } // Let the plugins parse their own options // 1. add common options and all the options from the plugins Options options = mainOptions(); for (Object o : CommonOptions.getOptions().getOptions()) { options.addOption((Option) o); } for (SyncPlugin plugin : plugins) { for (Object o : plugin.getCustomOptions().getOptions()) { Option option = (Option) o; if (options.hasOption(option.getOpt())) { System.err.println( "WARNING: The option " + option.getOpt() + " is being used by more than one plugin"); } options.addOption(option); } } // 2. re-parse the command line based on these options line = gnuParser.parse(options, args); if (l4j.isDebugEnabled()) { for (Option option : line.getOptions()) { if (option.hasArg()) LogMF.debug(l4j, "parsed option {0}: {1}", option.getLongOpt(), line.getOptionValue(option.getLongOpt())); else LogMF.debug(l4j, "parsed option {0}", option.getLongOpt()); } } // 3. pass the result to each plugin separately for (SyncPlugin plugin : plugins) { plugin.parseOptions(line); } return sync; }
From source file:com.conversantmedia.mapreduce.tool.PosixParserRequiredProps.java
/** * Verifies that the properties don't contain undefined options which will * cause the base parser to blowup./*ww w .jav a 2s . com*/ * * @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); } } } }
From source file:com.ottogroup.bi.streaming.runtime.StreamingAppRuntimeTest.java
/** * Test case for {@link StreamingAppRuntime#getOptions()} *///from ww w . j av a2 s.c o m @Test public void testGetOptions() { final Options options = new DummyLogProcessingRuntime(new CountDownLatch(1)).getOptions(); Assert.assertNotNull(options); Assert.assertFalse(options.getOptions().isEmpty()); Assert.assertEquals(1, options.getOptions().size()); Assert.assertTrue(options.hasOption(StreamingAppRuntime.CLI_CONFIG_FILE)); Assert.assertTrue(options.hasOption(StreamingAppRuntime.CLI_CONFIG_FILE_SHORT)); }
From source file:ca.phon.app.modules.EntryPointArgParser.java
/** * ** COPIED FROM APACHE CLI CODE for GnuParser ** * ** Modified to split non-options with '=' into separate tokens ** * //w w w.j av a 2s .c om * This flatten method does so using the following rules: * <ol> * <li>If an {@link Option} exists for the first character of * the <code>arguments</code> entry <b>AND</b> an {@link Option} * does not exist for the whole <code>argument</code> then * add the first character as an option to the processed tokens * list e.g. "-D" and add the rest of the entry to the also.</li> * <li>Otherwise just add the token to the processed tokens list.</li> * </ol> * * @param options The Options to parse the arguments by. * @param arguments The arguments that have to be flattened. * @param stopAtNonOption specifies whether to stop flattening when * a non option has been encountered * @return a String array of the flattened arguments */ @SuppressWarnings({ "rawtypes", "unchecked" }) protected String[] flatten(Options options, String[] arguments, boolean stopAtNonOption) { List tokens = new ArrayList(); boolean eatTheRest = false; for (int i = 0; i < arguments.length; i++) { String arg = arguments[i]; if ("--".equals(arg)) { eatTheRest = true; tokens.add("--"); } else if ("-".equals(arg)) { tokens.add("-"); } else if (arg.startsWith("-")) { String opt = stripLeadingHyphens(arg); if (options.hasOption(opt)) { tokens.add(arg); } else { // if (opt.indexOf('=') != -1 && options.hasOption(opt.substring(0, opt.indexOf('=')))) if (opt.indexOf('=') != -1) { // the format is --foo=value or -foo=value tokens.add(arg.substring(0, arg.indexOf('='))); // --foo tokens.add(arg.substring(arg.indexOf('=') + 1)); // value } else if (options.hasOption(arg.substring(0, 2))) { // the format is a special properties option (-Dproperty=value) tokens.add(arg.substring(0, 2)); // -D tokens.add(arg.substring(2)); // property=value } } } else { tokens.add(arg); } if (eatTheRest) { for (i++; i < arguments.length; i++) { tokens.add(arguments[i]); } } } return (String[]) tokens.toArray(new String[tokens.size()]); }
From source file:com.conversantmedia.mapreduce.tool.AnnotatedToolContext.java
@Override protected void initExtraOptions(Options options) { // Find all the fields with @Option annotations... fieldsMap = new HashMap<>(); addedOptionsMap = new HashMap<>(); defaultValuesMap = new HashMap<>(); Class<?> clazz = this.bean.getClass(); while (clazz != Object.class) { for (Field field : clazz.getDeclaredFields()) { if (field.isAnnotationPresent(Option.class)) { Option option = field.getAnnotation(Option.class); // Ensure we don't add the same option more than 1x // For example, if our annotated bean includes an 'input', // we don't want to add a second version String optName = getValue(option.name(), field.getName()); org.apache.commons.cli.Option opt; if (options.hasOption(optName)) { opt = options.getOption(optName); updateOption(option, opt); } else { opt = initOption(options, option, optName); options.addOption(opt); addedOptionsMap.put(opt.getLongOpt(), field); }// w ww . java 2 s . c o m fieldsMap.put(opt.getLongOpt(), field); defaultValuesMap.put(opt.getLongOpt(), option.defaultValue()); } } clazz = clazz.getSuperclass(); } }
From source file:com.zimbra.cs.account.ProvUtil.java
/** * To remove a particular instance of an attribute, the prefix indicator '-' is used before the attribute name. When * the attribute name is started with one of the valid command arguments, such as -z or -a, the parser mistakenly * divides it into two parts instead of treating as one parameter of the '-' and attribute name. * <p>//from ww w .ja v a2s . c o m * This method detects such decapitated attribute, and recombines those two into one attribute name with '-'. * * @param parsedArgs * [cmd-args] which are parsed by PosixParser * @param options * set of valid [args] * @param args * @throws ServiceException */ static private String[] recombineDecapitatedAttrs(String[] parsedArgs, Options options, String[] orgArgs) throws ServiceException { List<String> newArgs = new ArrayList<String>(parsedArgs.length); String headStr = null; for (int i = 0; i < parsedArgs.length; i++) { String arg = parsedArgs[i]; if (arg.startsWith("-") && arg.length() == 2 && options.hasOption(arg)) { // Detect legitimate POSIX style parameters even after operation command; // such as "zmprov describe -a <attr>" if (i < parsedArgs.length - 1) { boolean missParsed = false; String tmpParam = arg + parsedArgs[i + 1]; for (String orgArg : orgArgs) { if (orgArg.equals(tmpParam)) { missParsed = true; break; } } if (missParsed) { headStr = arg; } else { newArgs.add(arg); } } else { newArgs.add(arg); } } else if (headStr != null) { newArgs.add(headStr + arg); headStr = null; } else { newArgs.add(arg); } } return (String[]) newArgs.toArray(new String[newArgs.size()]); }
From source file:net.thackbarth.sparrow.SparrowTest.java
@Test public void testConfiguration() throws ParseException { Options options = Sparrow.createOptions(); Assert.assertEquals("The size of option does not match!", 4, options.getOptions().size()); Assert.assertTrue("The options did not have option 'c'", options.hasOption("c")); Assert.assertTrue("The options did not have option 'clean'", options.hasOption("clean")); Assert.assertTrue("The options did not have option 'f'", options.hasOption("f")); Assert.assertTrue("The options did not have option 'folder'", options.hasOption("folder")); Assert.assertTrue("The options did not have option 'h'", options.hasOption("h")); Assert.assertTrue("The options did not have option 'help'", options.hasOption("help")); Assert.assertTrue("The options did not have option 'l'", options.hasOption("l")); Assert.assertTrue("The options did not have option 'limit'", options.hasOption("limit")); PosixParser parser = new PosixParser(); // Set new data to the configuration String[] args = { "-f", "newdata", "-l", "2000" }; CommandLine commandLine = parser.parse(options, args); Sparrow.processConfiguration(configuration, commandLine); Assert.assertEquals("The folder is not correct!", "newdata", configuration.getDataFolder()); Assert.assertEquals("The scanlimit is not corrent", Integer.valueOf(2000), configuration.getScanLimit()); // Set null configuration Sparrow.processConfiguration(null, null); // no change in the config Assert.assertEquals("The folder is not correct!", "newdata", configuration.getDataFolder()); Assert.assertEquals("The scanlimit is not corrent", Integer.valueOf(2000), configuration.getScanLimit()); // Create new configuration String[] newArgs = {};//from ww w . j a v a 2 s . c om commandLine = parser.parse(options, newArgs); Sparrow.processConfiguration(configuration, commandLine); // no change in the config Assert.assertEquals("The folder is not correct!", "newdata", configuration.getDataFolder()); Assert.assertEquals("The scanlimit is not corrent", Integer.valueOf(2000), configuration.getScanLimit()); }
From source file:org.apache.flink.table.client.config.Deployment.java
/** * Parses the given command line options from the deployment properties. Ignores properties * that are not defined by options./* w w w . ja v a2 s . c om*/ */ public CommandLine getCommandLine(Options commandLineOptions) throws Exception { final List<String> args = new ArrayList<>(); properties.forEach((k, v) -> { // only add supported options if (commandLineOptions.hasOption(k)) { final Option o = commandLineOptions.getOption(k); final String argument = "--" + o.getLongOpt(); // options without args if (!o.hasArg()) { final Boolean flag = Boolean.parseBoolean(v); // add key only if (flag) { args.add(argument); } } // add key and value else if (!o.hasArgs()) { args.add(argument); args.add(v); } // options with multiple args are not supported yet else { throw new IllegalArgumentException("Option '" + o + "' is not supported yet."); } } }); return CliFrontendParser.parse(commandLineOptions, args.toArray(new String[args.size()]), true); }