users@jersey.java.net

[Jersey] Re: Custom Context Variables

From: Jakub Podlesak <jakub.podlesak_at_oracle.com>
Date: Fri, 28 Jun 2013 15:23:53 +0200

Hi,

The only thing required should be to implement a custom binder,
and even that is not needed. Detailed instructions on how to create
your own injectables is available at [1].

On Jun 27, 2013, at 2:50 AM, buko <buko_at_chiubarobot.com> wrote:

>
> I'm trying to inject a custom variable into a method. Very simply, I'd like to have a method like:
>
> @GET
> @Produces(MediaType.TEXT_HTML)
> public Response doGet(RemoteUser remoteUser) throws ServiceException;

I believe you are simplifying here a bit, right? The unannotated parameter is usually taken from
request entity body.

Anyway, please check out the doc linked in [1] and i believe things would be clearer.

~Jakub

[1]https://jersey.java.net/documentation/latest/migration.html#mig-server-inject-custom-objects


>
> Where RemoteUser is a custom type that wraps the HttpSession and some other stuff. We do this *a lot* in a Jersey1 application and I thought it'd be easier to do in Jersey2 with all the new injection stuff. Been at this for a few *days* now and finally have something that seems to work. Namely:
>
> (1) Application extends ResourceConfig and registerInstance's a custom Binder. (why??)
>
> (2) custom Binder extends AbstractBinder and must be annotated with @Provider (why??).
>
> (3) Create a provider. This provider must implement ContextResolver and org.glassfish.hk2.api.Factory. (why???). The factory must be request-scoped so it can get the HttpServletRequest @Inject'd but you can't actually put @RequestScoped on the factory. Instead you've got to
>
> bindFactory(RemoteUserProvider.class).to(RemoteUser.class).in(RequestScoped.class);
>
> in your Binder.
>
> (4) Annotate the above the method with @Context
>
> So this seems to work. RemoteUser is getting injected with a non-null session. But I have to ask: (1) is there an easier way to do this? (2) is there a more portable way to accomplish this without implementing strange hk2 apis? and (3) Is there a way to do this with less code (creating a *Provider that implements ContextResolver and Factory for every Form seems fantastically tedious!).
>
>
> (Got to say, I'm having very mixed feelings about Jersey2. It really seems like things that were trivial to do in Jersey1 require some real *strange*, black magic in Jersey2. If there was some documentation about this it might be tolerable but we're flying completely blind. This experience makes me very, very wary of continuing with this upgrade!)