Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating JAX-RS (Apache Wink) resources with JSR303?

Is it possible to make effective use of JSR303 (Bean Validation) annotations on JAX-RS resources?

So for example, if I have a resource member that I've annotated @NotEmpty, generate an error back to the client if this constraint is not met?

This seems like the obvious thing to do, but also happy to be told better ways (I don't want to move the validation down to the ORM/database level)

like image 466
brabster Avatar asked Oct 08 '22 13:10

brabster


2 Answers

Do you really mean validating the resource members? Usually the resource members are injected in this way or another (it's either contexts, or entity, or path/query/matrix params), as long as the JAX-RS framework works you'll get these members properly injected.

Personally I think it makes more sense to validate the entity since it has arrived by the wire, filled by a MessageBodyReader and basically you have no idea what's inside, right?

So if you decide to validate the entities, there are several approaches that you can take:

  1. AFAIK, Apache Wink does not support built-in validations. You can implement a handler. See DeploymentConfiguration.initRequestHandlersChain(). It supports adding user handlers. In your handler you can perform any validations. I even think that the Wink community will be glad if you contribute this code.
    The only problem with this approach - it's bound to the Apache Wink. It won't work if you decide to move to a different JAX-RS framework.

  2. Another approach is to make this validation in your own MessageBodyReader. All you need to do is registering a special reader for your entities and validate the entity inside. You can still take advantage of standard MessageBodyReaders (like JAXB or Jackson) by using @Context Providers.getMessageBodyReader(). The good part of this approach that it's standard JAX-RS. The bad that you use MessageBodyReaders for something they were not designed to.

  3. The simplest approach is to validate the entity in first line of each resource method. It will create some code duplication, but sometimes simplicity wins.

like image 68
Tarlog Avatar answered Oct 12 '22 11:10

Tarlog


One solution - as I'm using Spring 2.5.x, I can create a wrapper class that implements InitializingBean and delegates to Hibernate's validator. It works - is there a better solution?

like image 45
brabster Avatar answered Oct 12 '22 10:10

brabster