/** * Parse the command line, validate the arguments and make them available through the getValue() * and isExists() methods. * * @param args the command line arguments, usually from the main() method * @param caseSensitive if true then the argument names must match exactly, else a case * insensitive match is used. */ public void parse(String[] args, boolean caseSensitive) { args = concatenateDelimitedArgs(args); for (String arg : args) { String[] nameValue = arg.split("="); String name = null; String value = null; if (nameValue.length > 0) name = nameValue[0]; if (nameValue.length > 1) value = nameValue[1]; if (name != null) { CommandLineOption commandLineArg = null; if (caseSensitive) commandLineArg = commandLineDefinition.valueOf(name); else commandLineArg = commandLineDefinition.valueOfIgnoreCase(name); if (commandLineArg != null) { try { Object typedObject = createTypedObject(value, commandLineArg.getType()); nameValuePairs.put(commandLineArg, typedObject); } catch (NumberFormatException x) { parseErrorMessages.add( "Incorrect format for value of parameter '" + name + "', must be parsable to type '" + commandLineArg.getType().toString() + "'."); } } else parseErrorMessages.add("Unknown parameter '" + name + "'."); } } for (Iterator<? extends CommandLineOption> iter = commandLineDefinition.iterator(); iter.hasNext(); ) { CommandLineOption arg = iter.next(); if (arg.isRequired() && !nameValuePairs.containsKey(arg)) parseErrorMessages.add( "Required parameter '" + arg.toString() + "' is not provided on the command line, use " + arg.toString() + ((arg.getType() == null) ? "." : "=<value>.")); if (nameValuePairs.containsKey(arg) && (arg.getType() != null) && nameValuePairs.get(arg) == null) parseErrorMessages.add( "Parameter '" + arg.toString() + "' must have a value and it does not, use " + arg.toString() + "=<value>."); } if (parseErrorMessages.size() > 0) parseErrorMessages.add( "Valid parameters are: \n" + commandLineDefinition.getUselessMessage()); }
/** * Return the value of the named argument, or null if it does not exist. The return type is * guaranteed to be of the type defined in the command line definition. Note: flag type parameters * (those with no value) will also return null. * * @param parameterName * @return */ public Object getValue(String parameterName) { CommandLineOption option = commandLineDefinition.valueOf(parameterName); return option == null ? null : getValue(option); }
/** * Return true if the named arguments exists on the command line that was most recently parsed. * * @param parameterName * @return */ public boolean isExists(String parameterName) { CommandLineOption option = commandLineDefinition.valueOf(parameterName); return option == null ? null : isExists(option); }