users@jersey.java.net

[Jersey] Re: How to find resources by path?

From: Martin Matula <martin.matula_at_oracle.com>
Date: Thu, 8 Sep 2011 09:34:13 +0200

On Sep 6, 2011, at 3:57 PM, Rafael Nunes Verger wrote:

> Hey guys,
>
> So, I need build a service JSONPService, that must receive all requests that ends with "/jsonp". This is my first problem.. when I set a path, like "/users" for some service, I can't receive requests like "/users/some/thing/jsonp" in JSONPService, is there some priority annotation to do this ?

You should be able to achieve this using ContainerRequest/ReponseFilter - you can implement both interfaces by a single class, have an instance ThreadLocal variable to remember if the incoming path contained /jsonp suffix - in the method processing incoming request you would check that, if it has the suffix you would remove it from the request and switch the flag. In the response filtering method you would check the flag and if on, you would set the content type of the response to application/json instead of application/xml. That should cause the right messagebodywritter will be picked by Jersey.

Here is a sample code - you may need to tweak it to fit your needs:

public class Filter implements ContainerRequestFilter, ContainerResponseFilter {
    private ThreadLocal<Boolean> json = new ThreadLocal<Boolean>();

    @Override
    public ContainerRequest filter(ContainerRequest cr) {
        if (cr.getPath().endsWith("/jsonp")) {
            json.set(Boolean.TRUE);
            String requestPath = cr.getRequestUri().toString();
            requestPath = requestPath.substring(0, requestPath.length() - 6);
            cr.setUris(cr.getBaseUri(), UriBuilder.fromUri(requestPath).build());
            cr.getRequestHeaders().putSingle(HttpHeaders.ACCEPT, "application/xml");
        } else {
            json.set(Boolean.FALSE);
        }
        return cr;
    }

    @Override
    public ContainerResponse filter(ContainerRequest cr, ContainerResponse response) {
        if (json.get()) {
            response.getHttpHeaders().putSingle(HttpHeaders.CONTENT_TYPE, "application/json");
        }
        return response;
    }
}


Regards,
Martin


>
> The other problem is: if I set JSONPService to receive requests like "/jsonp/path/to/service", then if "/users/99" results in XML of user with ID 99, "/jsonp/users/99" must result in the same user but with jsonp; So, with this path I can receive those requests, but I need to get the result for "/path/to/service" and then set it with JSONP, is there any way to do it ?
>
> --
> Rafael Nunes Verger -- Software Developer
>