List of usage examples for org.apache.commons.cli Option getValue
public String getValue()
null
if there is no value. From source file:lcmc.ArgumentParser.java
public void parseClusterOptionsAndCreateClusterButton(final CommandLine cmd) throws ParseException { String clusterName = null;/*from w w w .j a va2s .c o m*/ List<HostOptions> hostsOptions = null; final Map<String, List<HostOptions>> clusters = new LinkedHashMap<String, List<HostOptions>>(); for (final Option option : cmd.getOptions()) { final String op = option.getLongOpt(); if (CLUSTER_OP.equals(op)) { clusterName = option.getValue(); if (clusterName == null) { throw new ParseException("could not parse " + CLUSTER_OP + " option"); } clusters.put(clusterName, new ArrayList<HostOptions>()); } else if (HOST_OP.equals(op)) { final String[] hostNames = option.getValues(); if (clusterName == null) { clusterName = "default"; clusters.put(clusterName, new ArrayList<HostOptions>()); } if (hostNames == null) { throw new ParseException("could not parse " + HOST_OP + " option"); } hostsOptions = new ArrayList<HostOptions>(); for (final String hostNameEntered : hostNames) { final String hostName; String port = null; if (hostNameEntered.indexOf(':') > 0) { final String[] he = hostNameEntered.split(":"); hostName = he[0]; port = he[1]; if (port != null && port.isEmpty() || !lcmc.common.domain.util.Tools.isNumber(port)) { throw new ParseException("could not parse " + HOST_OP + " option"); } } else { hostName = hostNameEntered; } final HostOptions ho = new HostOptions(hostName); if (port != null) { ho.setPort(port); } hostsOptions.add(ho); clusters.get(clusterName).add(ho); } } else if (SUDO_OP.equals(op)) { if (hostsOptions == null) { throw new ParseException(SUDO_OP + " must be defined after " + HOST_OP); } for (final HostOptions ho : hostsOptions) { ho.setUseSudo(true); } } else if (USER_OP.equals(op)) { if (hostsOptions == null) { throw new ParseException(USER_OP + " must be defined after " + HOST_OP); } final String userName = option.getValue(); if (userName == null) { throw new ParseException("could not parse " + USER_OP + " option"); } for (final HostOptions ho : hostsOptions) { ho.setLoginUser(userName); } } else if (PORT_OP.equals(op)) { if (hostsOptions == null) { throw new ParseException(PORT_OP + " must be defined after " + HOST_OP); } final String port = option.getValue(); if (port == null) { throw new ParseException("could not parse " + PORT_OP + " option"); } for (final HostOptions ho : hostsOptions) { ho.setPort(port); } } else if (PCMKTEST_OP.equals(op)) { final String index = option.getValue(); if (index != null && !index.isEmpty()) { application.setAutoTest(new Test(StartTests.Type.PCMK, index.charAt(0))); } } else if (DRBDTEST_OP.equals(op)) { final String index = option.getValue(); if (index != null && !index.isEmpty()) { application.setAutoTest(new Test(StartTests.Type.DRBD, index.charAt(0))); } } else if (VMTEST_OP.equals(op)) { final String index = option.getValue(); if (index != null && !index.isEmpty()) { application.setAutoTest(new Test(StartTests.Type.VM, index.charAt(0))); } } else if (GUITEST_OP.equals(op)) { final String index = option.getValue(); if (index != null && !index.isEmpty()) { application.setAutoTest(new Test(StartTests.Type.GUI, index.charAt(0))); } } } for (final Map.Entry<String, List<HostOptions>> clusterEntry : clusters.entrySet()) { final List<HostOptions> hostOptions = clusterEntry.getValue(); if (hostOptions.size() < 1 || (hostOptions.size() == 1 && !application.isOneHostCluster())) { throw new ParseException("not enough hosts for cluster: " + clusterEntry.getKey()); } } final String failedHost = setUserConfigFromOptions(clusters); if (failedHost != null) { LOG.appWarning("parseClusterOptions: could not resolve host \"" + failedHost + "\" skipping"); } }
From source file:com.inetpsa.seed.plugin.CmdMojoDelegate.java
protected Command createCommand(CommandRegistry commandRegistry, String qualifiedName, String[] args) { if (Strings.isNullOrEmpty(qualifiedName)) { throw new IllegalArgumentException("No command named " + qualifiedName); }//from w w w. j a va 2 s . co m String commandScope; String commandName; if (qualifiedName.contains(":")) { String[] splitName = qualifiedName.split(":"); commandScope = splitName[0].trim(); commandName = splitName[1].trim(); } else { commandScope = null; commandName = qualifiedName.trim(); } // Build CLI options Options options = new Options(); for (org.seedstack.seed.core.spi.command.Option option : commandRegistry.getOptionsInfo(commandScope, commandName)) { options.addOption(option.name(), option.longName(), option.hasArgument(), option.description()); } // Parse the command options CommandLine cmd; try { cmd = commandLineParser.parse(options, args); } catch (ParseException e) { throw new IllegalArgumentException("Syntax error in arguments", e); } Map<String, String> optionValues = new HashMap<String, String>(); for (Option option : cmd.getOptions()) { optionValues.put(option.getOpt(), option.getValue()); } return commandRegistry.createCommand(commandScope, commandName, cmd.getArgList(), optionValues); }
From source file:de.nrw.hbz.regal.sync.MyConfiguration.java
/** * /* w w w. j ava 2s . co m*/ * generates the configuration in terms of arguments and options * * @param args * Command line arguments * @param options * Command line options * @throws ParseException * When the configuration cannot be parsed */ MyConfiguration(String[] args, Options options) { try { CommandLineParser parser = new BasicParser(); CommandLine commandLine = parser.parse(options, args); for (Option option : commandLine.getOptions()) { String key = option.getLongOpt(); // System.out.println(key); if (key.compareTo("set") == 0) { String[] vals = option.getValues(); if (vals == null || vals.length == 0) { this.addProperty(key, "N/A"); } else { StringBuffer val = new StringBuffer(); for (int i = 0; i < vals.length; i++) { val.append(vals[i]); val.append(","); } val.delete(val.length(), val.length()); this.addProperty(key, val.toString()); } } else { String val = option.getValue(); if (val == null) { this.addProperty(key, "N/A"); } else { this.addProperty(key, val); } } } } catch (ParseException e) { throw new ConfigurationParseException(e); } }
From source file:com.imgur.backup.SnapshotS3Util.java
/** * Get args /*from ww w . j a v a 2 s .c o m*/ * @param args * @throws Exception */ private void getAndCheckArgs(String[] args) throws Exception { CommandLineParser parser = new PosixParser(); CommandLine cmd = null; cmd = parser.parse(getOptions(), args); for (Option option : cmd.getOptions()) { switch (option.getId()) { case 'c': createSnapshot = true; break; case 'x': createSnapshot = true; exportSnapshot = true; break; case 'e': exportSnapshot = true; break; case 'i': importSnapshot = true; break; case 't': tableName = option.getValue(); break; case 'n': snapshotName = option.getValue(); break; case 'k': accessKey = option.getValue(); break; case 's': accessSecret = option.getValue(); break; case 'b': bucketName = option.getValue(); break; case 'p': s3Path = option.getValue(); break; case 'd': hdfsPath = option.getValue(); break; case 'm': mappers = Long.parseLong(option.getValue()); break; case 'a': s3protocol = S3N_PROTOCOL; break; case 'l': snapshotTtl = Long.parseLong(option.getValue()); break; default: throw new IllegalArgumentException("unexpected option " + option); } } if (createSnapshot && StringUtils.isEmpty(tableName)) { throw new IllegalArgumentException("Need a table name"); } if ((importSnapshot || (exportSnapshot && !createSnapshot)) && StringUtils.isEmpty(snapshotName)) { throw new IllegalArgumentException("Need a snapshot name"); } }
From source file:com.cloudbees.sdk.commands.Command.java
protected boolean parseCommandLine() throws Exception { boolean ok = true; // parse the command line arguments line = getParser().parse(getOptions(true), getArgs()); for (Option option : line.getOptions()) { // System.out.println("Option: " + option); String str = option.getLongOpt(); if (str == null) str = option.getOpt();//ww w . jav a 2s. c o m str = str.replace("-", ""); if (option.hasArg()) { Class[] types = { String.class }; Method method = getMethod(str, "", types); if (method == null) { method = getMethod(str, "Option", types); } method.invoke(this, option.getValue()); } else { Class[] types = { Boolean.class }; Method method = getMethod(str, "", types); if (method == null) { method = getMethod(str, "Option", types); } method.invoke(this, Boolean.TRUE); } } return ok; }
From source file:com.aliyun.odps.mapred.bridge.streaming.StreamJob.java
void parseArgv() { CommandLine cmdLine = null;/*from w w w . ja v a 2 s . c o m*/ try { cmdLine = parser.parse(allOptions, argv_); } catch (Exception oe) { LOG.error(oe.getMessage()); exitUsage(argv_.length > 0 && "-info".equals(argv_[0])); } if (cmdLine == null) { exitUsage(argv_.length > 0 && "-info".equals(argv_[0])); return; } @SuppressWarnings("unchecked") List<String> args = cmdLine.getArgList(); if (args != null && args.size() > 0) { fail("Found " + args.size() + " unexpected arguments on the " + "command line " + args); } detailedUsage_ = cmdLine.hasOption("info"); if (cmdLine.hasOption("help") || detailedUsage_) { printUsage = true; return; } verbose_ = cmdLine.hasOption("verbose"); background_ = cmdLine.hasOption("background"); debug_ = cmdLine.hasOption("debug") ? debug_ + 1 : debug_; output_ = cmdLine.getOptionValue("output"); comCmd_ = cmdLine.getOptionValue("combiner"); redCmd_ = cmdLine.getOptionValue("reducer"); lazyOutput_ = cmdLine.hasOption("lazyOutput"); String[] values = cmdLine.getOptionValues("file"); SessionState ss = SessionState.get(); MetaExplorer metaExplorer = new MetaExplorerImpl(ss.getOdps()); Map<String, String> aliasToTempResource = new HashMap<String, String>(); String padding = "_" + UUID.randomUUID().toString(); if (values != null && values.length > 0) { for (int i = 0; i < values.length; i++) { String file = values[i]; packageFiles_.add(file); try { aliasToTempResource.put(FilenameUtils.getName(file), metaExplorer.addFileResourceWithRetry(file, Resource.Type.FILE, padding, true)); } catch (OdpsException e) { throw new RuntimeException(e); } } config_.set("stream.temp.resource.alias", JSON.toJSONString(aliasToTempResource)); String[] res = config_.getResources(); Set<String> resources = aliasToTempResource.keySet(); if (res != null) { config_.setResources(StringUtils.join(res, ",") + "," + StringUtils.join(resources, ",")); } else { config_.setResources(StringUtils.join(resources, ",")); } } additionalConfSpec_ = cmdLine.getOptionValue("additionalconfspec"); numReduceTasksSpec_ = cmdLine.getOptionValue("numReduceTasks"); partitionerSpec_ = cmdLine.getOptionValue("partitioner"); mapDebugSpec_ = cmdLine.getOptionValue("mapdebug"); reduceDebugSpec_ = cmdLine.getOptionValue("reducedebug"); ioSpec_ = cmdLine.getOptionValue("io"); String[] car = cmdLine.getOptionValues("cacheArchive"); if (null != car) { fail("no -cacheArchive option any more, please use -resources instead."); } String[] caf = cmdLine.getOptionValues("cacheFile"); if (null != caf) { fail("no -cacheFile option any more, please use -resources instead."); } mapCmd_ = cmdLine.getOptionValue("mapper"); String[] cmd = cmdLine.getOptionValues("cmdenv"); if (null != cmd && cmd.length > 0) { for (String s : cmd) { if (addTaskEnvironment_.length() > 0) { addTaskEnvironment_ += " "; } addTaskEnvironment_ += s; } } // per table input config Map<String, Map<String, String>> inputConfigs = new HashMap<String, Map<String, String>>(); String[] columns = null; for (Option opt : cmdLine.getOptions()) { if ("jobconf".equals(opt.getOpt())) { String[] jobconf = opt.getValues(); if (null != jobconf && jobconf.length > 0) { for (String s : jobconf) { String[] parts = s.split("=", 2); config_.set(parts[0], parts[1]); } } } else if ("columns".equals(opt.getOpt())) { String columnsValue = opt.getValue(); if (columnsValue.equals("ALL")) { columns = null; } else { columns = columnsValue.split(","); } } else if ("input".equals(opt.getOpt())) { values = opt.getValues(); if (values != null && values.length > 0) { for (String input : values) { TableInfo ti = parseTableInfo(input); if (columns != null) { ti.setCols(columns); } inputSpecs_.add(ti); String inputKey = (ti.getProjectName() + "." + ti.getTableName()).toLowerCase(); // XXX only apply once per table if (inputConfigs.get(inputKey) != null) { continue; } Map<String, String> inputConfig = new HashMap<String, String>(); inputConfig.put("stream.map.input.field.separator", config_.get("stream.map.input.field.separator", "\t")); // TODO other per table input config: cols, etc. inputConfigs.put(inputKey, inputConfig); } } } } try { config_.set("stream.map.input.configs", JSON.toJSONString(inputConfigs)); } catch (Exception e) { throw new RuntimeException("fail to set input configs"); } }
From source file:com.google.api.ads.adwords.keywordoptimizer.KeywordOptimizer.java
/** * Creates the seed generator based on the command line options. * * @param cmdLine the parsed command line parameters * @param context holding shared objects during the optimization process * @return a {@link SeedGenerator} object * @throws KeywordOptimizerException in case of an error constructing the seed generator *//*from w w w. ja v a 2 s . co m*/ private static SeedGenerator getSeedGenerator(CommandLine cmdLine, OptimizationContext context) throws KeywordOptimizerException { Option seedOption = getOnlySeedOption(cmdLine); if ("sk".equals(seedOption.getOpt())) { String[] keywords = cmdLine.getOptionValues("sk"); SimpleSeedGenerator seedGenerator = new SimpleSeedGenerator(); for (String keyword : keywords) { log("Using seed keyword: " + keyword); seedGenerator.addKeyword(keyword); } return seedGenerator; } else if ("skf".equals(seedOption.getOpt())) { List<String> keywords = loadFromFile(cmdLine.getOptionValue("skf")); SimpleSeedGenerator seedGenerator = new SimpleSeedGenerator(); for (String keyword : keywords) { log("Using seed keyword: " + keyword); seedGenerator.addKeyword(keyword); } return seedGenerator; } else if ("st".equals(seedOption.getOpt())) { String[] keywords = cmdLine.getOptionValues("st"); TisSearchTermsSeedGenerator seedGenerator = new TisSearchTermsSeedGenerator(context, null); for (String keyword : keywords) { log("Using seed search term: " + keyword); seedGenerator.addSearchTerm(keyword); } return seedGenerator; } else if ("stf".equals(seedOption.getOpt())) { List<String> terms = loadFromFile(cmdLine.getOptionValue("skf")); TisSearchTermsSeedGenerator seedGenerator = new TisSearchTermsSeedGenerator(context, null); for (String term : terms) { log("Using seed serach term: " + term); seedGenerator.addSearchTerm(term); } return seedGenerator; } else if ("su".equals(seedOption.getOpt())) { String[] urls = cmdLine.getOptionValues("su"); TisUrlSeedGenerator seedGenerator = new TisUrlSeedGenerator(context, null); for (String url : urls) { log("Using seed url: " + url); seedGenerator.addUrl(url); } return seedGenerator; } else if ("suf".equals(seedOption.getOpt())) { List<String> urls = loadFromFile(cmdLine.getOptionValue("suf")); TisUrlSeedGenerator seedGenerator = new TisUrlSeedGenerator(context, null); for (String url : urls) { log("Using seed url: " + url); seedGenerator.addUrl(url); } return seedGenerator; } else if ("sc".equals(seedOption.getOpt())) { int category = Integer.parseInt(seedOption.getValue()); log("Using seed category: " + category); TisCategorySeedGenerator seedGenerator = new TisCategorySeedGenerator(context, category, null); return seedGenerator; } throw new KeywordOptimizerException("Seed option " + seedOption.getOpt() + " is not supported yet"); }
From source file:org.apache.activemq.apollo.util.cli.CommonsCLISupport.java
/** *//* w ww . j a va 2s . co m*/ static public String[] setOptions(Object target, CommandLine cli) { Option[] options = cli.getOptions(); for (Option option : options) { String name = option.getLongOpt(); if (name == null) continue; String propName = convertOptionToPropertyName(name); String value = option.getValue(); if (value != null) { Class<?> type = IntrospectionSupport.getPropertyType(target, propName); if (type.isArray()) { IntrospectionSupport.setProperty(target, propName, option.getValues()); } else if (type.isAssignableFrom(ArrayList.class)) { IntrospectionSupport.setProperty(target, propName, new ArrayList(option.getValuesList())); } else if (type.isAssignableFrom(HashSet.class)) { IntrospectionSupport.setProperty(target, propName, new HashSet(option.getValuesList())); } else { IntrospectionSupport.setProperty(target, propName, value); } } else { IntrospectionSupport.setProperty(target, propName, true); } } return cli.getArgs(); }
From source file:org.apache.blur.shell.DiscoverFileBufferSizeUtil.java
@Override public void doit(PrintWriter out, Iface client, String[] args) throws CommandException, TException, BlurException { CommandLine cmd = parse(args, out);// ww w .j a va 2 s .c om if (cmd == null) { throw new CommandException(name() + " missing required arguments"); } Option[] options = cmd.getOptions(); for (Option option : options) { out.println(option); String opt = option.getOpt(); String value = option.getValue(); System.out.println(opt + " " + value); } Path path = new Path(cmd.getOptionValue("p")); long size = Long.parseLong(cmd.getOptionValue("s", "1000000000"));// 1GB int sampleSize = Integer.parseInt(cmd.getOptionValue("S", "10"));// 10 int warmupSize = Integer.parseInt(cmd.getOptionValue("W", "3"));// 3 int min = Integer.parseInt(cmd.getOptionValue("n", "12"));// 12 int max = Integer.parseInt(cmd.getOptionValue("x", "19"));// 19 int readSamplesPerPass = Integer.parseInt(cmd.getOptionValue("r", "1000"));// 1000 Configuration configuration = new Configuration(); FileSystem fileSystem; try { fileSystem = path.getFileSystem(configuration); } catch (IOException e) { if (Main.debug) { e.printStackTrace(); } throw new CommandException(e.getMessage()); } Random random = new Random(); Map<Integer, Long> writingResults; try { writingResults = runWritingTest(out, path, fileSystem, random, sampleSize, warmupSize, size, min, max); } catch (IOException e) { if (Main.debug) { e.printStackTrace(); } throw new CommandException(e.getMessage()); } Map<Integer, Long> readingResults; try { readingResults = runReadingTest(out, path, fileSystem, random, sampleSize, warmupSize, size, min, max, readSamplesPerPass); } catch (IOException e) { if (Main.debug) { e.printStackTrace(); } throw new CommandException(e.getMessage()); } out.println("Printing Results for Writing"); printResults(out, writingResults); out.println("Printing Results for Reading"); printResults(out, readingResults); }
From source file:org.apache.blur.shell.ExecutePlatformCommandCommand.java
private BlurObject createBlurObject(CommandLine commandLine, CommandDescriptor descriptor) throws CommandException { Map<String, ArgumentDescriptor> arguments = new TreeMap<String, ArgumentDescriptor>( descriptor.getOptionalArguments()); arguments.putAll(descriptor.getRequiredArguments()); BlurObject blurObject = new BlurObject(); if (commandLine == null) { return null; }//from w ww .j av a 2 s .co m Option[] options = commandLine.getOptions(); for (Option option : options) { String name = option.getOpt(); String value = option.getValue(); ArgumentDescriptor argumentDescriptor = arguments.get(name); String type = argumentDescriptor.getType(); blurObject.put(name, convertIfNeeded(value, type)); } return blurObject; }