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,','));
Emmanuel Bourg
  • 9,601
  • 3
  • 48
  • 76
jayunit100
  • 17,388
  • 22
  • 92
  • 167
  • Just noticed : In order to get an option by its short name, you call getOpt() , rather than getArgName() or any other method. – jayunit100 Dec 21 '11 at 22:19

1 Answers1

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)

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
  • 1
    hmmm... thats to bad. looks like this api needs resurrection. – jayunit100 Dec 21 '11 at 23:17
  • 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. – Emmanuel Bourg May 29 '12 at 20:43
  • 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. – bcoughlan Oct 21 '13 at 22:49
  • 2
    `OptionBuilder` is deprecated now. Use `Option.builder("file")` instead – cahen Feb 02 '17 at 11:47