List of usage examples for org.apache.commons.cli Options hasOption
public boolean hasOption(String opt)
From source file:org.apache.stratos.cli.commands.UpdateKubernetesHostCommand.java
@Override public int execute(StratosCommandContext context, String[] args, Option[] alreadyParsedOpts) throws CommandException { if (log.isDebugEnabled()) { log.debug("Executing command: ", getName()); }/* ww w . j a va2s . c o m*/ if ((args == null) || (args.length <= 0)) { context.getStratosApplication().printUsage(getName()); return CliConstants.COMMAND_FAILED; } try { CommandLineParser parser = new GnuParser(); CommandLine commandLine = parser.parse(options, args); //merge newly discovered options with previously discovered ones. Options opts = mergeOptionArrays(alreadyParsedOpts, commandLine.getOptions()); if (opts.hasOption(CliConstants.RESOURCE_PATH)) { // get resource path arg value String resourcePath = opts.getOption(CliConstants.RESOURCE_PATH).getValue(); if (resourcePath == null) { context.getStratosApplication().printUsage(getName()); return CliConstants.COMMAND_FAILED; } String resourceFileContent = CliUtils.readResource(resourcePath); RestCommandLineService.getInstance().updateKubernetesHost(resourceFileContent); return CliConstants.COMMAND_SUCCESSFULL; } else { context.getStratosApplication().printUsage(getName()); return CliConstants.COMMAND_FAILED; } } catch (ParseException e) { log.error("Error parsing arguments", e); System.out.println(e.getMessage()); return CliConstants.COMMAND_FAILED; } catch (IOException e) { System.out.println("Invalid resource path"); return CliConstants.COMMAND_FAILED; } catch (Exception e) { String message = "Unknown error occurred: " + e.getMessage(); System.out.println(message); log.error(message, e); return CliConstants.COMMAND_FAILED; } }
From source file:org.apache.stratos.cli.commands.UpdateKubernetesMasterCommand.java
@Override public int execute(StratosCommandContext context, String[] args, Option[] alreadyParsedOpts) throws CommandException { if (log.isDebugEnabled()) { log.debug("Executing command: ", getName()); }// w w w. ja v a2 s.c o m if ((args == null) || (args.length <= 0)) { context.getStratosApplication().printUsage(getName()); return CliConstants.COMMAND_FAILED; } try { CommandLineParser parser = new GnuParser(); CommandLine commandLine = parser.parse(options, args); //merge newly discovered options with previously discovered ones. Options opts = mergeOptionArrays(alreadyParsedOpts, commandLine.getOptions()); if ((opts.hasOption(CliConstants.RESOURCE_PATH)) && (opts.hasOption(CliConstants.CLUSTER_ID_OPTION))) { // get cluster id arg value String clusterId = opts.getOption(CliConstants.CLUSTER_ID_OPTION).getValue(); if (clusterId == null) { context.getStratosApplication().printUsage(getName()); return CliConstants.COMMAND_FAILED; } // get resource path arg value String resourcePath = opts.getOption(CliConstants.RESOURCE_PATH).getValue(); if (resourcePath == null) { context.getStratosApplication().printUsage(getName()); return CliConstants.COMMAND_FAILED; } String resourceFileContent = CliUtils.readResource(resourcePath); RestCommandLineService.getInstance().updateKubernetesMaster(resourceFileContent, clusterId); return CliConstants.COMMAND_SUCCESSFULL; } else { context.getStratosApplication().printUsage(getName()); return CliConstants.COMMAND_FAILED; } } catch (ParseException e) { log.error("Error parsing arguments", e); System.out.println(e.getMessage()); return CliConstants.COMMAND_FAILED; } catch (IOException e) { System.out.println("Invalid resource path"); return CliConstants.COMMAND_FAILED; } catch (Exception e) { String message = "Unknown error occurred: " + e.getMessage(); System.out.println(message); log.error(message, e); return CliConstants.COMMAND_FAILED; } }
From source file:org.apache.stratos.cli.commands.UpdateNetworkPartitionCommand.java
public int execute(StratosCommandContext context, String[] args, Option[] alreadyParsedOpts) throws CommandException { if (log.isDebugEnabled()) { log.debug("Executing {} command...", getName()); }/*from www . ja v a2 s . co m*/ if (args != null && args.length > 0) { String resourcePath = null; String resourceFileContent = null; final CommandLineParser parser = new GnuParser(); CommandLine commandLine; try { commandLine = parser.parse(options, args); //merge newly discovered options with previously discovered ones. Options opts = mergeOptionArrays(alreadyParsedOpts, commandLine.getOptions()); if (log.isDebugEnabled()) { log.debug("Network partition deployment"); } if (opts.hasOption(CliConstants.RESOURCE_PATH)) { if (log.isTraceEnabled()) { log.trace("Resource path option is passed"); } resourcePath = opts.getOption(CliConstants.RESOURCE_PATH).getValue(); resourceFileContent = CliUtils.readResource(resourcePath); } if (resourcePath == null) { context.getStratosApplication().printUsage(getName()); return CliConstants.COMMAND_FAILED; } RestCommandLineService.getInstance().updateNetworkPartition(resourceFileContent); return CliConstants.COMMAND_SUCCESSFULL; } catch (ParseException e) { log.error("Error parsing arguments", e); System.out.println(e.getMessage()); return CliConstants.COMMAND_FAILED; } catch (IOException e) { System.out.println("Invalid resource path"); return CliConstants.COMMAND_FAILED; } } else { context.getStratosApplication().printUsage(getName()); return CliConstants.COMMAND_FAILED; } }
From source file:org.apache.stratos.cli.commands.UpdateTenantCommand.java
public int execute(StratosCommandContext context, String[] args, Option[] alreadyParsedOpts) throws CommandException { if (log.isDebugEnabled()) { log.debug("Executing {} command...", getName()); }// w ww.j av a 2 s . c o m if (args != null && args.length > 0) { String admin = null; String firstName = null; String lastName = null; String password = null; String domain = null; String email = null; int id = 0; final CommandLineParser parser = new GnuParser(); CommandLine commandLine; try { commandLine = parser.parse(options, args); //merge newly discovered options with previously discovered ones. Options opts = mergeOptionArrays(alreadyParsedOpts, commandLine.getOptions()); if (log.isDebugEnabled()) { log.debug("Update tenant"); } if (opts.hasOption(CliConstants.USERNAME_OPTION)) { if (log.isTraceEnabled()) { log.trace("Username option is passed"); } admin = opts.getOption(CliConstants.USERNAME_OPTION).getValue(); } if (opts.hasOption(CliConstants.FIRST_NAME_OPTION)) { if (log.isTraceEnabled()) { log.trace("First name option is passed"); } firstName = opts.getOption(CliConstants.FIRST_NAME_OPTION).getValue(); } if (opts.hasOption(CliConstants.LAST_NAME_OPTION)) { if (log.isTraceEnabled()) { log.trace("Last name option is passed"); } lastName = opts.getOption(CliConstants.LAST_NAME_OPTION).getValue(); } if (opts.hasOption(CliConstants.PASSWORD_OPTION)) { if (log.isTraceEnabled()) { log.trace("Password option is passed"); } password = opts.getOption(CliConstants.PASSWORD_OPTION).getValue(); } if (opts.hasOption(CliConstants.DOMAIN_NAME_OPTION)) { if (log.isTraceEnabled()) { log.trace("Domain name option is passed"); } domain = opts.getOption(CliConstants.DOMAIN_NAME_OPTION).getValue(); } if (opts.hasOption(CliConstants.EMAIL_OPTION)) { if (log.isTraceEnabled()) { log.trace("Email option is passed"); } email = opts.getOption(CliConstants.EMAIL_OPTION).getValue(); } if (opts.hasOption(CliConstants.ID_OPTION)) { if (log.isTraceEnabled()) { log.trace("Id option is passed"); } id = Integer.parseInt(opts.getOption(CliConstants.ID_OPTION).getValue()); } if (id == 0 || admin == null || firstName == null || lastName == null || password == null || domain == null || email == null) { context.getStratosApplication().printUsage(getName()); return CliConstants.COMMAND_FAILED; } RestCommandLineService.getInstance().updateTenant(id, admin, firstName, lastName, password, domain, email); return CliConstants.COMMAND_SUCCESSFULL; } catch (ParseException e) { log.error("Error parsing arguments", e); System.out.println(e.getMessage()); return CliConstants.COMMAND_FAILED; } } else { context.getStratosApplication().printUsage(getName()); return CliConstants.COMMAND_FAILED; } }
From source file:org.apache.stratos.cli.commands.UpdateUserCommand.java
public int execute(StratosCommandContext context, String[] args, Option[] alreadyParsedOpts) throws CommandException { if (log.isDebugEnabled()) { log.debug("Executing {} command...", getName()); }//from www . j a v a2 s . co m if (args != null && args.length > 0) { String userName = null; String credential = null; String role = null; String firstName = null; String lastName = null; String email = null; String profileName = null; final CommandLineParser parser = new GnuParser(); CommandLine commandLine; try { commandLine = parser.parse(options, args); //merge newly discovered options with previously discovered ones. Options opts = mergeOptionArrays(alreadyParsedOpts, commandLine.getOptions()); if (log.isDebugEnabled()) { log.debug("Update user"); } if (opts.hasOption(CliConstants.USERNAME_OPTION)) { if (log.isTraceEnabled()) { log.trace("Username option is passed"); } userName = opts.getOption(CliConstants.USERNAME_OPTION).getValue(); } if (opts.hasOption(CliConstants.PASSWORD_OPTION)) { if (log.isTraceEnabled()) { log.trace("Credential option is passed"); } credential = opts.getOption(CliConstants.PASSWORD_OPTION).getValue(); } if (opts.hasOption(CliConstants.ROLE_NAME_OPTION)) { if (log.isTraceEnabled()) { log.trace("Role option is passed"); } role = opts.getOption(CliConstants.ROLE_NAME_OPTION).getValue(); } if (opts.hasOption(CliConstants.FIRST_NAME_OPTION)) { if (log.isTraceEnabled()) { log.trace("First name option is passed"); } firstName = opts.getOption(CliConstants.FIRST_NAME_OPTION).getValue(); } if (opts.hasOption(CliConstants.LAST_NAME_OPTION)) { if (log.isTraceEnabled()) { log.trace("Last name option is passed"); } lastName = opts.getOption(CliConstants.LAST_NAME_OPTION).getValue(); } if (opts.hasOption(CliConstants.EMAIL_OPTION)) { if (log.isTraceEnabled()) { log.trace("Email option is passed"); } email = opts.getOption(CliConstants.EMAIL_OPTION).getValue(); } if (opts.hasOption(CliConstants.PROFILE_NAME_OPTION)) { if (log.isTraceEnabled()) { log.trace("Profile name option is passed"); } profileName = opts.getOption(CliConstants.PROFILE_NAME_OPTION).getValue(); } if (userName == null || credential == null || role == null || firstName == null || lastName == null || email == null) { context.getStratosApplication().printUsage(getName()); return CliConstants.COMMAND_FAILED; } RestCommandLineService.getInstance().updateUser(userName, credential, role, firstName, lastName, email, profileName); return CliConstants.COMMAND_SUCCESSFULL; } catch (ParseException e) { log.error("Error parsing arguments", e); System.out.println(e.getMessage()); return CliConstants.COMMAND_FAILED; } } else { context.getStratosApplication().printUsage(getName()); return CliConstants.COMMAND_FAILED; } }
From source file:org.apache.tajo.yarn.Client.java
/** * @param args the command line arguments * @throws Exception//from ww w. jav a 2 s . co m */ @SuppressWarnings("rawtypes") public void run(String[] args) throws Exception { HashMap<String, Command> commands = new HashMap<String, Command>(); HelpCommand help = new HelpCommand(commands); commands.put("help", help); commands.put("launch", new LaunchCommand(conf)); commands.put("worker", new WorkerOpCommand(conf)); String commandName = null; String[] commandArgs = null; if (args.length < 1) { commandName = "help"; commandArgs = new String[0]; } else { commandName = args[0]; commandArgs = Arrays.copyOfRange(args, 1, args.length); } Command command = commands.get(commandName); if (command == null) { LOG.error("ERROR: " + commandName + " is not a supported command."); help.printHelpFor(null); System.exit(1); } Options opts = command.getOpts(); if (!opts.hasOption("h")) { opts.addOption("h", "help", false, "print out a help message"); } CommandLine cl = new GnuParser().parse(command.getOpts(), commandArgs); if (cl.hasOption("help")) { help.printHelpFor(Arrays.asList(commandName)); } else { command.process(cl); } }
From source file:org.codehaus.groovy.cli.GroovyPosixParser.java
/** * An implementation of {@link Parser}'s abstract * {@link Parser#flatten(Options,String[],boolean) flatten} method. * <p>/*from w ww. j a v a2 s . c o m*/ * The following are the rules used by this flatten method. * <ol> * <li>if <code>stopAtNonOption</code> is <b>true</b> then do not * burst anymore of <code>arguments</code> entries, just add each * successive entry without further processing. Otherwise, ignore * <code>stopAtNonOption</code>.</li> * <li>if the current <code>arguments</code> entry is "<b>--</b>" * just add the entry to the list of processed tokens</li> * <li>if the current <code>arguments</code> entry is "<b>-</b>" * just add the entry to the list of processed tokens</li> * <li>if the current <code>arguments</code> entry is two characters * in length and the first character is "<b>-</b>" then check if this * is a valid {@link Option} id. If it is a valid id, then add the * entry to the list of processed tokens and set the current {@link Option} * member. If it is not a valid id and <code>stopAtNonOption</code> * is true, then the remaining entries are copied to the list of * processed tokens. Otherwise, the current entry is ignored.</li> * <li>if the current <code>arguments</code> entry is more than two * characters in length and the first character is "<b>-</b>" then * we need to burst the entry to determine its constituents. For more * information on the bursting algorithm see * {@link GroovyPosixParser#burstToken(String, boolean) burstToken}.</li> * <li>if the current <code>arguments</code> entry is not handled * by any of the previous rules, then the entry is added to the list * of processed tokens.</li> * </ol> * * @param options The command line {@link Options} * @param arguments The command line arguments to be parsed * @param stopAtNonOption Specifies whether to stop flattening when an non option is found. * @return The flattened <code>arguments</code> String array. */ protected String[] flatten(Options options, String[] arguments, boolean stopAtNonOption) { init(); this.options = options; // an iterator for the command line tokens Iterator iter = Arrays.asList(arguments).iterator(); // process each command line token while (iter.hasNext()) { // get the next command line token String token = (String) iter.next(); // handle long option --foo or --foo=bar if (token.startsWith("--")) { int pos = token.indexOf('='); String opt = pos == -1 ? token : token.substring(0, pos); // --foo if (!options.hasOption(opt)) { processNonOptionToken(token, stopAtNonOption); } else { tokens.add(opt); if (pos != -1) { tokens.add(token.substring(pos + 1)); } else { currentOption = options.getOption(opt); } } } // single hyphen else if ("-".equals(token)) { tokens.add(token); } else if (token.startsWith("-")) { if (token.length() == 2 || options.hasOption(token)) { processOptionToken(token, stopAtNonOption); } // requires bursting else { burstToken(token, stopAtNonOption); } } else { processNonOptionToken(token, stopAtNonOption); } gobble(iter); } return (String[]) tokens.toArray(new String[tokens.size()]); }
From source file:org.codeseed.common.config.ext.CommandLineOptionsBuilder.java
/** * Potentially adds an option to the supplied collection. Used by the * {@link #build()} method to populate an options collection. * * @param options// ww w . j ava 2 s .com * the current collection of options * @param groups * mappings of argument group identifiers to groups * @param method * the configuration method to look up */ protected void addOption(Options options, Map<String, OptionGroup> groups, Method method) { final CommandLine commandLine = method.getAnnotation(CommandLine.class); // Iterate over the triggers; take the first values String opt = null; String longOpt = null; for (String trigger : commandLine.value()) { if (!options.hasOption(trigger)) { if (opt == null && trigger.length() == 1) { opt = trigger; } else if (longOpt == null) { longOpt = trigger; } } } // Either we can use the method name or there is no option being added if (opt == null && longOpt == null) { String methodOpt = LOWER_CAMEL.to(LOWER_HYPHEN, method.getName()); if (!options.hasOption(methodOpt)) { longOpt = methodOpt; } else { // TODO Warn? return; } } // Create a new option Option option = new Option(opt, null); option.setLongOpt(longOpt); // Set the number of arguments based on the return type final Class<?> returnType = Primitives.wrap(method.getReturnType()); if (returnType.equals(Boolean.class)) { option.setArgs(0); } else if (Iterable.class.isAssignableFrom(returnType)) { option.setArgs(commandLine.maximum()); } else if (Map.class.isAssignableFrom(returnType)) { option.setArgs(2); option.setValueSeparator('='); } else { option.setArgs(1); } // Add some descriptive text if (bundle != null) { try { // TODO Does this make sense? String key = option.hasLongOpt() ? option.getLongOpt() : method.getName(); option.setDescription(bundle.getString(key + ".description")); } catch (MissingResourceException e) { option.setDescription(null); } } // Set argument names if (bundle != null && option.getArgs() > 0) { try { option.setArgName(bundle.getString(method.getName() + ".argName")); } catch (MissingResourceException e) { option.setArgName(null); } } // Add to either the collection or to the option groups String groupKey = commandLine.groupId(); if (groupKey.isEmpty()) { options.addOption(option); } else { OptionGroup group = groups.get(groupKey); if (group == null) { group = new OptionGroup(); groups.put(groupKey, group); } group.addOption(option); } }
From source file:org.g_node.converter.ConvCliToolControllerTest.java
/** * Tests for the {@link CommandLine} {@link Options} of the RDF to RDF converter tool. */// w w w.j a va2s. c o m @Test public void optionsTest() { Options checkOpt = this.convCont.options(); assertThat(checkOpt.getOptions().size()).isEqualTo(4); assertThat(checkOpt.hasOption("-i")).isTrue(); assertThat(checkOpt.hasLongOption("in-file")).isTrue(); assertThat(checkOpt.getOption("-i").isRequired()).isTrue(); assertThat(checkOpt.hasOption("-o")).isTrue(); assertThat(checkOpt.hasLongOption("out-file")).isTrue(); assertThat(checkOpt.getOption("-o").isRequired()).isFalse(); assertThat(checkOpt.hasOption("-f")).isTrue(); assertThat(checkOpt.hasLongOption("out-format")).isTrue(); assertThat(checkOpt.getOption("-f").isRequired()).isFalse(); assertThat(checkOpt.hasOption("-h")).isTrue(); }
From source file:org.g_node.crawler.LKTLogbook.LKTLogCliToolControllerTest.java
/** * Tests for the {@link CommandLine} {@link Options} of the RDF to RDF converter tool. * @throws Exception//from ww w.ja v a2 s . c o m */ @Test public void testOptions() throws Exception { Options checkOpt = this.logCtrl.options(); assertThat(checkOpt.getOptions().size()).isEqualTo(4); assertThat(checkOpt.hasOption("-i")).isTrue(); assertThat(checkOpt.hasLongOption("in-file")).isTrue(); assertThat(checkOpt.getOption("-i").isRequired()).isTrue(); assertThat(checkOpt.hasOption("-o")).isTrue(); assertThat(checkOpt.hasLongOption("out-file")).isTrue(); assertThat(checkOpt.getOption("-o").isRequired()).isFalse(); assertThat(checkOpt.hasOption("-f")).isTrue(); assertThat(checkOpt.hasLongOption("out-format")).isTrue(); assertThat(checkOpt.getOption("-f").isRequired()).isFalse(); assertThat(checkOpt.hasOption("-h")).isTrue(); }