Saturday, August 29, 2015

using bean validation with args4j

Full maven project is in github.

references


args4j

public class Opts {

    public static void main(final String[] args) throws CmdLineException {

        System.out.println("args: " + args);

        // parse arguments
        final Opts opts = new Opts();
        new CmdLineParser(opts).parseArgument(args);

        System.out.println("opts: " + opts);
    }

    @Option(name = "-buffer-capacity",
            usage = "each buffer's capacity in bytes")
    private int bufferCapacity = 65536;

    @Option(name = "-buffer-count", required = true,
            usage = "number of buffers to allocate")
    private int bufferCount;
}
예상과 같이 잘 동작한다.
$ mvn --quiet \
> -Dexec.args="-buffer-capacity 65536" \
> -Dexec.mainClass=com.github.jinahya.example.Opts \
> compile exec:java
args: [-buffer-capacity, 65536, -buffer-count, 1]
opts: com.github.jinahya.example.Opts@26d71e30?bufferCapacity=65536&bufferCount=1
$ mvn --quiet -Dexec.args="-buffer-capacity 65536" \
> -Dexec.mainClass=com.github.jinahya.example.Opts \
> compile exec:java
args: [-buffer-capacity, 65536]
[ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.4.0:java (default-cli) on project args4j-with-bean-validation-example: An exception occured while executing the Java class. null: InvocationTargetException: Option "-buffer-count" is required -> [Help 1]
...

validation

Bean Validation을 이용하여 추가적인 검증작업을 수행할 수 있다. 우선 다음과 같이 제약사항들을 추가하자.
@Option(name = "-buffer-capacity",
        usage = "each buffer's capacity in bytes")
@Min(1024)
private int bufferCapacity = 65536;

@Option(name = "-buffer-count", required = true,
        usage = "number of buffers to allocate")
@Min(1)
@Max(1024)
private int bufferCount;
이제 추가적인 검증작업을 수행한다.
// validate parameters
final ValidatorFactory factory
    = Validation.buildDefaultValidatorFactory();
final Validator validator = factory.getValidator();
final Set<ConstraintViolation<Opts>> violations
    = validator.validate(opts);
if (violations.stream().map(v -> {
    System.err.println("violation: " + v);
    return v;
}).count() > 0L) {
    return;
}
다음과 같이 추가적인 검증결과를 볼 수 있다.
$ mvn --quiet -Dexec.args="-buffer-capacity 1024 -buffer-count 0" \
> -Dexec.mainClass=com.github.jinahya.example.Opts \
> compile exec:java
args: [-buffer-capacity, 1024, -buffer-count, 0]
violation: ConstraintViolationImpl{interpolatedMessage='must be greater than or equal to 1', propertyPath=bufferCount, rootBeanClass=class com.github.jinahya.example.Opts, messageTemplate='{javax.validation.constraints.Min.message}'}

No comments:

Post a Comment