3

I have a problem with the JCommander. I want the program to throw an Exception, if the required parameter iam testing has no value. This Exception i want occurs when i forget to add a value to the last parameter.

Example(note: all Parameters are required and strings):

--user hugo --password boss --confirmPassword //no value

com.beust.jcommander.ParameterException: Expected a value after parameter --comfirmPassword

If i forget to add a value to the other parameters, the next parameter is considered as the value.

--user --password --confirmPassword hugo
//--password is considered as the value of user

In consequence of this behavior, --password can no longer be found and i get the wrong Exception.

com.beust.jcommander.ParameterException: the following options are required: --password

Is there a way to tell jCommander that he should not consider the next parameter as a value?

leif_good
  • 376
  • 6
  • 19
  • Sorry, i dont really get what you are trying to tell me. can you explain it to me? – leif_good Nov 26 '15 at 16:50
  • if you say `--user --password` what do you do in the case the username is `--password` ? fail even though the user is valid? – Alexander Oh Nov 26 '15 at 16:58
  • This is, indeed, a problem. But imo this is unlikely. The user forgetting to add a value to user may happen way more often. And in this scenario, the user cant even tell whats the problem, since the Exception is not telling the right mistake. But sure, you are absolutely right! – leif_good Nov 26 '15 at 17:08

1 Answers1

2

So I've checked up the documentation.

If you are certain your parameters are not going to be prefixed with -- you can add the Parameter validation separately.

public class IsUserName implements IParameterValidator {
  public void validate(String name, String value)
    throws ParameterException {
      if (value.startsWith("--")) {
        throw new ParameterException("probably missing user name"); 
      }
  }
}

@Parameter(names = "--user", validateWith = IsUserName.class)
private String user;

Another option might be to use the variableArity flag in combination with an Parameter Validation. try Checking the parameter against 0 length.

Looking at how parameter validation is done (String, String) pair, it is most likely not supporting variable arity arguments though.

Alexander Oh
  • 24,223
  • 14
  • 73
  • 76