Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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,','));
like image 570
jayunit100 Avatar asked Dec 21 '11 22:12

jayunit100


1 Answers

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)

like image 108
Sean Patrick Floyd Avatar answered Sep 30 '22 18:09

Sean Patrick Floyd