users@jersey.java.net

[Jersey] Re: Providing a DispatchingListener with UriRuleContext

From: Marshall Pierce <marshall_at_mpierce.org>
Date: Sun, 05 Aug 2012 10:10:32 -0700

On 07/31/2012 11:45 PM, noam_at_10ne.org wrote:
> Hi All,
>
> I'm looking for a way to inspect the details of a request and the
> requested resource method just before invocation (with an option to
> abort the request if my inspection detects an invalidity).
>
> For example, I've got a group of different resources on different paths
> that all receive a parameter of type "foo" in one way or another (query
> param, path param, etc); I would like to receive an event right before
> each resource is invoked so that I can check whether it expects a "foo"
> parameter, and if it does, to perform certain assertions in regard to
> the value of "foo".
>
> I've created an implementation of
> com.sun.jersey.spi.monitoring.DispatchingListener because the
> onResourceMethod seems to be a perfect fit for this situation.
>
> My only problem is that the listener is not provided with the context
> of the request; that is, onResourceMethod is provided with an
> AbstractResourceMethod which gives me all the details I need about the
> method to be invoked, but I've got no idea what has been sent by the
> user.
>
> I might be mistaken in this assumption, but since the listener must
> exist as a singleton, it looks like I can't inject the request context
> as I normally would with a resource.
>
> Reviewing the code, I see that onResourceMethod is eventually called
> from com.sun.jersey.server.impl.uri.rules.HttpMethodRule#accept, and
> that the request context does in fact exist at this stage, but it isn't
> being passed to the listener.
>
> Is there any way to provide the listener with the request context?
> Am I taking the right approach to this?
>
> Thanks
>

Have you considered using a ResourceMethodDispatchAdapter [1] and
ResourceMethodDispatchProvider [2]? That will give you access to the
HttpRequestContext and ExtendedUriInfo right before the resource method
is invoked, which sounds like everything you need. I wrote an article
[3] about how to use those classes.


[1]
jersey.java.net/nonav/apidocs/latest/jersey/com/sun/jersey/spi/container/ResourceMethodDispatchAdapter.html
[2]
http://jersey.java.net/nonav/apidocs/latest/jersey/com/sun/jersey/spi/container/ResourceMethodDispatchProvider.html
[3]
http://blog.palominolabs.com/2012/03/31/extending-the-simple-javajettyguicejerseyjackson-web-stack-with-automatic-jersey-resource-method-metrics/