users@jersey.java.net

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

From: Marek Potociar <marek.potociar_at_oracle.com>
Date: Wed, 29 Apr 2015 13:34:46 +0200

I thought that you would bind your filters to all methods and then use UriInfo information from the filter code. That way you will use it from within a request scope.

Marek

> On 28 Apr 2015, at 10:28, guillaume.polet_at_bluepimento.eu wrote:
>
> Hi Marek,
>
>
> unfortunately we cannot use UriInfo outside the scope of a request. I tried and throws an IllegalStateException. This is also confirmed by the javadoc
>
>> All methods throw {_at_code java.lang.IllegalStateException} if called outside the scope of a request (e.g. from a provider constructor).
>>
> Any other ideas?
>
>
> Guillaume
>
> On 27.04.2015 16:43, Marek Potociar wrote:
>
>> You can try injecting javax.ws.rs.core.UriInfo in your dynamic feature and then check the result of UriInfo.getMatchedResources()...
>>
>> Marek
>>
>>> On 25 Apr 2015, at 10:15, Guillaume Polet <guillaume.polet_at_bluepimento.eu <mailto:guillaume.polet_at_bluepimento.eu>> wrote:
>>>
>>> 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+ <smb://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+ <smb://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
>>>
>
>