Wow, that actually worked. Thanks.

So for anyone else wanting to use the @Valid on their method params simply
add the following property to your system properties.

org.apache.openejb.default.system.interceptors =
org.apache.openejb.bval.BeanValidationAppendixInterceptor

And then your jax-rs methods can be of the following (note that you don’t
need the @ValidateRequest):

@POST
@Path("/bounce")
public Coffee bounce(@Valid Coffee coffee) {
        return coffee;
}

If the Coffee bean sent has any violations (such as a field within being
null when a @NotNull annotation is brandished) then a
javax.validation.ConstraintViolationException will be thrown.

Simply pick that up by your exception mapper and do what you want with it,
so something along the lines of:

@Provider
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class MyExceptionMapper implements ExceptionMapper<Exception> {
        if (ex instanceof ConstraintViolationException) { 
                // return back nice json
                return ExceptionResponse.build(new
IllegalArgumentException(ExceptionResponse.MALFORMED_BODY),
Response.Status.BAD_REQUEST); 
        }
}

(here ExceptionResponse is my own custom class for representing exceptions
in a nice format back to the caller).

Remember to add your MyExceptionMapper to your system properties also:

"cxf.jaxrs.providers": “my.package.MyExceptionMapper”


If you use openejb.json (in conf/openejb.json) or resources.json (in
project’s resources/META-INF/resources.json) then you can add the two
properties like so:

resources.json/open.json :

{
        "system-properties": {
                "cxf.jaxrs.providers": “my.package.MyExceptionMapper",
                "org.apache.openejb.default.system.interceptors":
"org.apache.openejb.bval.BeanValidationAppendixInterceptor”,
                "org.apache.openejb.cxf.bus.features":
"org.apache.cxf.feature.LoggingFeature"
        }
        // other stuff….
}

(The LoggingFeature is to log the requests and responses in a pretty format,
thank me later :P)



Hope this helps someone in the future.

Thanks again Romain,

Chris



--
View this message in context: 
http://openejb.979440.n4.nabble.com/JAX-RS-Bean-Validation-tp4667501p4667504.html
Sent from the OpenEJB User mailing list archive at Nabble.com.

Reply via email to