// Parse the given argument vector
public Command parse(String[] argv) {
CommandLineParser parser = new PosixParser();
CommandLine cmdline = null;
try {
cmdline = parser.parse(this.rules, argv);
}
catch (ParseException e) {
error(e.getMessage());
}
// Unpack the cmdline into a simple Map of options and optionally
// assign values to any corresponding fields found in the Command class.
for (Option option : cmdline.getOptions()) {
String name = option.getLongOpt();
Object value = option.getValue();
// Figure out the type of the option and convert the value.
if (!option.hasArg()) {
// If it has no arg, then its implicitly boolean and presence
// of the argument indicates truth.
value = true;
}
else {
Class type = (Class)option.getType();
if (type == null) {
// Null implies String, no conversion necessary
}
else if (type == Integer.class) {
value = Integer.parseInt((String)value);
}
else {
assert false; // Unsupported type
}
}
this.opts.put(name, value);
// Look for a field of the Command class (or subclass) that
// matches the long name of the option and, if found, assign the
// corresponding option value in order to provide simplified
// access to command options.
try {
java.lang.reflect.Field field = this.getClass().getField(name);
field.set(this, value);
}
catch (NoSuchFieldException e) { continue; }
catch (IllegalAccessException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
String[] orig = this.args;
String[] more = cmdline.getArgs();
this.args = new String[orig.length + more.length];
System.arraycopy(orig, 0, this.args, 0, orig.length);
System.arraycopy(more, 0, this.args, orig.length, more.length);
if (this.help) {