title: Jersey/Jax-RS: how to filter resource and sub-resources
body: <p>In Jersey 2, how can I bind a filter to all the method of a Resource as well as to all the methods of its sub-resources?</p>
  
  <p>For example, if I have the following 2 resources:</p>
  
  <pre><code>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();
      }
  }
  </code></pre>
  
  <p>I would like to filter <code>RootResource.get(Long)</code> and <code>SubResource.get(Long, Long)</code>. But if I have other resources, those should not be filtered.</p>
  
  <p>Using the <code>DynamicFeature</code>, we only have info on the Class and Method. </p>
  
  <pre><code>import javax.ws.rs.container.DynamicFeature;
  import javax.ws.rs.container.ResourceInfo;
  import javax.ws.rs.core.FeatureContext;
  
  public class MyFeature implements DynamicFeature {
  
      @Override
      public void configure(ResourceInfo resourceInfo, FeatureContext context) {
          // Here how can I find out that SubResource is actually a sub-resource of RootResource
      }
  
  }
  </code></pre>
  
  <p>The idea is that I want to be able to filter out all calls for a certain set of id's (the set of id's is dynamic), with something more or less like this:</p>
  
  <pre><code>import java.io.IOException;
  
  import javax.ws.rs.container.ContainerRequestContext;
  import javax.ws.rs.container.ContainerRequestFilter;
  
  
  public class MyFilter implements ContainerRequestFilter {
  
      @Override
      public void filter(ContainerRequestContext requestContext) throws IOException {
          for(Object resource:requestContext.getUriInfo().getMatchedResources()) {
              if(resource instanceof RootResource) {
                  Long id = Long.valueOf(requestContext.getUriInfo().getPathParameters().getFirst("id"));
                  // ...
              }
          }
      }
  
  }
  </code></pre>
  
  <p>but I would like to avoid having to search for the matched resources. Is this possible?</p>