How to ensure that all arguments are provided in Apache Commons CLI?
Asked Answered
L

1

7

I don't see a standard way of checking if all Options are provided in a String[] input to apache's CLI library . That is - my options are all REUIRED at the command line, otherwise, i want an exception to throw.

Im trying the following as a workaround, but getting a Nullpointer exception in the if statement...

PosixParser p = new PosixParser();
        CommandLine cli=p.parse(options,args);
        for(Object o : options.getOptions())
        {
            Option op = (Option)o;
            if(cli.getOptionValue(op.getName()))
            throw new ParseException("Missing argument ! " + op.getArgName() + ":"+op.getDescription());
    }

UPDATE ON THIS : the getOpt() method seems to provide the arguments short name.

However, if I replace op.getName() with opt.getLongName()... it works !

In any case.. I have 2 questions :

1) Why would an option have a null name, yet a non-null longName ?
2) Is there a way to simply ensure that all options are provided the String[] ? For example, I would like to call :

  if(! options.isAllProvided())
     throw new ParseException("You are missing some options ! " + StringUtils.join(userInputArray,','));
Lecialecithin answered 21/12, 2011 at 22:15 Comment(1)
Just noticed : In order to get an option by its short name, you call getOpt() , rather than getArgName() or any other method.Lecialecithin
T
10

Here's how you can set an Option to be required:

Option logfile = OptionBuilder.withArgName( "file" )
            .isRequired() // make it required
            .hasArg()
            .withDescription(  "use given file for log" )
            .create( "logfile" );

(I don't think there's an easy way to make all Options required in one step)

Talesman answered 21/12, 2011 at 22:27 Comment(4)
hmmm... thats to bad. looks like this api needs resurrection.Lecialecithin
You have indeed to mark the options as required. If some options are missing you'll then get an exception containing the list of the missing options.Subsidence
Indeed it is verbose and ugly, but I find that making a Factory class with methods like makeRequiredOption can greatly improve the readability of your main class.Intwine
OptionBuilder is deprecated now. Use Option.builder("file") insteadJackiejackinoffice

© 2022 - 2024 — McMap. All rights reserved.