views:

163

answers:

2

I recently implemented a Jersey JAX-RS Rest service. I created a JIBX provider that allows one to unmarshal and marshall between XML and Java types. I would like to also version my service by specifying the version in the URL path. Versioning would include the version of message binding used to marshal and unmarshall the Java types.

Therefore, it is necessary that the version is passed to the custom JIBX provider, and therefore the URL path that contains the version. However, the Provider interfaces (MessageBodyWriter and MessageBodyReader) do not provide the URI path in their interface methods.

The following is the method signature of the writeTo() method of the MessageBodyWriter interface:

writeTo(Object, Type, Annotation[], MediaType, MultivaluedMap, OutputStream)

This method parameters does not contain the path uri, therefore, the custom jibx provider cannot know which message binding version it should use to marshall the Java type. Is there a way around this?

A: 

You can access the URI path from the Provider by defining the @Context annotation on a field on the Provider.

For example,

public class CustomProvider implements MessageBodyWriter
{

    @Context HttpServletRequest request;

    ....
}

This field will automatically be set for each request. Even though the request is set as a field, the value is thread-safe as the actual request is using a proxy and most likely thread local to determine the request that belongs to thread.

jigjig
+1  A: 

If you want something a bit more JAX-RS specific than HttpServletRequest, you can inject a javax.ws.rs.core.UriInfo.

public class MyProvider implements MessageBodyWriter {
    @javax.ws.rs.core.Context
    javax.ws.rs.core.UriInfo uriInfo;
}

I'm assuming that you're using a @javax.ws.rs.PathParam to capture the path parameter. You can then potentially use UriInfo.getPathParameters(). You can also fall back to UriInfo.getPathSegments() to get the information you're looking for. This saves you the trouble of parsing the request URI yourself. Any JAX-RS implementation should be able to do this.

Bryant Luk