Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache Commons CLI : Getting list of values for an option

For a CLI, I have a requirement to pass in an array of ints as input for a particular option.

Example - The below command would take in an array of customerIds and perform some operations.

myCommand -c 123 124 125

I have implemented the CLI using Apache commons CLI, and I am using getOptionValues("c") to retrieve this array.

The problem is that, this is returning only the first element in the array, i.e. [123], while I am expecting it to return [123, 124, 125].

A condensed version of my code,

CommandLine cmd;
CommandLineParser parser = new BasicParser();
cmd = parser.parse(options, args);
if (cmd.hasOption("c")){
String[] customerIdArray = cmd.getOptionValues("c");
// Code to parse data into int
}

Can someone help me identify the issue here?

like image 512
Gautham Reddy Avatar asked Jun 18 '13 23:06

Gautham Reddy


4 Answers

I'd like to add this here as an answer to @Zangdak and to add my findings on the same problem.

If you do not call #setArgs(int) then a RuntimeException will occur. When you know the exact maximum amount of arguments to this option, then set this specific value. When this value is not known, the class Option has a constant for it: Option.UNLIMITED_VALUES

This would change gerrytans answer to the following:

Options options = new Options();
Option option = new Option("c", "c desc");
// Set option c to take 1 to oo arguments
option.setArgs(Option.UNLIMITED_VALUES);
options.addOption(option);
like image 106
VeikkoW Avatar answered Oct 04 '22 09:10

VeikkoW


You have to set maximum the number of argument values the option can take, otherwise it assumes the option only has 1 argument value

Options options = new Options();
Option option = new Option("c", "c desc");
// Set option c to take maximum of 10 arguments
option.setArgs(10);
options.addOption(option);
like image 29
gerrytan Avatar answered Oct 04 '22 08:10

gerrytan


It looks like i am a bit late for the party but apache commons cli evolved and now (at least in 1.3.1) we have a new way to set that there can be unlimited number of arguments

Option c = Option.builder("c")
        .hasArgs() // sets that number of arguments is unlimited
        .build();
        Options options = new Options();
        options.addOption(c);
like image 35
David Michael Gang Avatar answered Oct 04 '22 08:10

David Michael Gang


You have to specify two parameters setArgs and setValueSeparator. Then you can pass a list of arguments like -k=key1,key2,key3.

Option option = new Option("k", "keys", true, "Description");
// Maximum of 10 arguments that can pass into option
option.setArgs(10);
// Comma as separator
option.setValueSeparator(',');
like image 45
ReaktorDTR Avatar answered Oct 04 '22 09:10

ReaktorDTR