Problem
I'm trying to parse some command line arguments in any order. Two of them are single-value and mandatory and the other one is an optional comma-separated list:
usage:
-mo <value1,value2,...,valueN>
-sm1 <value>
-sm2 <value>
Using any of the old parsers (BasicParser
, PosixParser
and GnuParser
) the code works fine but if I use DefaultParser
instead, a MissingOptionException
is thrown.
Code
import java.util.Arrays;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
public class Foo {
public static void main(String[] args) throws Exception {
Option singleMandatory1 = Option.builder("sm1")
.argName("value")
.hasArg()
.required()
.build();
Option singleMandatory2 = Option.builder("sm2")
.argName("value")
.hasArg()
.required()
.build();
Option multipleOptional = Option.builder("mo")
.argName("value1,value2,...,valueN")
.hasArgs()
.valueSeparator(',')
.build();
Options options = new Options();
options.addOption(singleMandatory1);
options.addOption(singleMandatory2);
options.addOption(multipleOptional);
CommandLineParser parser = new DefaultParser();
CommandLine line = parser.parse(options, args);
for (Option o : line.getOptions()) {
System.out.println(o.getOpt() + '\t'
+ Arrays.toString(o.getValues()));
}
}
}
Command line arguments
-sm1 Alice -sm2 Bob -mo Charles,David
works
-sm1 Alice -mo Charles,David -sm2 Bob
works only using the old (and now deprecated) parsers
Am I missing something? I'm using commons-cli-1.4-SNAPSHOT
.
Thanks for any help.