users@jersey.java.net

[Jersey] How to filter resource and its sub-resources

From: Guillaume Polet <guillaume.polet_at_bluepimento.eu>
Date: Sat, 25 Apr 2015 10:15:59 +0200

Hi,

How can I bind a filter to all the method of a Resource as well as to
all the methods of its sub-resources?

For example, if I have the following 2 resources:

import javax.inject.Singleton;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.server.model.Resource;

@Path("/myresource/{id: \\d+}")
@Produces(MediaType.APPLICATION_JSON)
@Singleton
class RootResource {

     @GET
     @Produces(MediaType.APPLICATION_JSON)
     public Response get(@PathParam("id") Long id) {
         return Response.ok().build();
     }

     @Path("/sub")
     public Resource getSubResource() {
         return Resource.from(SubResource.class);
     }
}

@Produces(MediaType.APPLICATION_JSON)
@Singleton
class SubResource {
     @GET
     @Path("/{subid: \\d+}")
     public Response get(@PathParam("id") Long id, @PathParam("subid")
Long subid) {
         return Response.ok().build();
     }
}

I would like to filter |RootResource.get(Long)| and
|SubResource.get(Long, Long)|. But if I have other resources, those
should not be filtered.

Using the |DynamicFeature|, we only have info on the Class and Method.
Is there an easy way to find if that method is actually a sub-resource
of a given resource (I would like this to work also on
sub-sub-resources, sub-sub-sub-resources, etc...)

The alternative is to write a global filter and check if the
RootResource is amongst the set of matched resources, but it's a bit
less efficient I guess.

Cheers,
Guillaume