'Parsing Options using Apache Commons Library
This might be sort of a noob question, but I am using the import org.apache.commons.cli.*; to set up my command line parser application.
This is how I am setting up my option.
Option n = Option.builder().hasArg(true).option("n").build();
options.addOption(n);
In one of our scenarios, we have a particular case where the input looks something like this "-n", "2", "3". Now this is not a valid scenario, because n should fail if you provide more than one value, without the "-n" flag.
Invalid: "-n", "2", "3"
Valid: "-n", "2", "-n", "3"
I was able to get the valid scenario working, but I am unable to get the invalid scenario working. because when I use getOptionValues(), I only get back 2 and not 3. Does anyone know how I can grab 3 too, and fail the invalid scenario.
Thanks.
Solution 1:[1]
You can use CommandLine.getArgList() to check for such "trailing" arguments,
CommandLine cmd = parser.parse(options, new String[] {"-n", "2", "3"});
assertTrue(cmd.hasOption(n));
assertEquals("[3]", cmd.getArgList().toString());
So you can fail parsing if cmd.getArgList() is not empty to catch such cases.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | centic |
