users@jersey.java.net

[Jersey] Re: UriInfo injection at resource initialization time

From: Markus Karg <karg_at_quipsy.de>
Date: Wed, 9 Mar 2011 08:21:28 +0100

Try this one:

@GET
@Path("individuals")
public Individual getIndividual(@Context UriInfo uriInfo) {
        return new Individual(uriInfo);
}

Regards
Markus

-----Original Message-----
From: Martynas Jusevicius [mailto:martynas.jusevicius_at_gmail.com]
Sent: Mittwoch, 9. März 2011 02:40
To: users_at_jersey.java.net
Subject: [Jersey] UriInfo injection at resource initialization time

Hey list,

I'm new here and would like to start with a question :)

I have Resource classes implementing JAX-RS, however I also want to
combine it with RDF using Jena API.
Each Resource should have a reference to Individual (RDF resource) -
and they share the same absolute URI.
This is a root Resource class:

@Path("")
@Singleton
public class TestResource
{
  private Individual individual = null;

  ...
}

This means Individual has to be initiated at some point, and at that
point the Resource needs to know its URI to be able to look up
Individual in the RDF model.

What I've tried (the code goes inside the TestResource defined above):

1. Injected class field

    @Context UriInfo uriInfo;

    public TestResource()
    {
        System.out.println("TestResource.uriInfo: " + uriInfo);
    }

Doesn't work - returns null

2. Injected constructor parameter

    public TestResource(@Context UriInfo uriInfo)
    {
        System.out.println("TestResource(uriInfo): " + uriInfo);
    }

Doesn't work - I get
java.lang.IllegalStateException
        com.sun.jersey.server.impl.ThreadLocalHttpContext.getUriInfo
as described in
http://jersey.576304.n2.nabble.com/injecting-UriInfo-in-constructor-td4510740.html
Same message suggests "access the reference when a request is in
scope" -- but this is not good enough.

However constructor param is used in JAX-RS tutorial:
http://wikis.sun.com/display/Jersey/Overview+of+JAX-RS+1.0+Features#OverviewofJAX-RS1.0Features-ConditionalGETsandReturning304%28NotModified%29Responses

3. @PostConstruct method

    @PostConstruct
    public void init()
    {
        System.out.println("@PostConstruct UriInfo: " + uriInfo);
    }

Doesn't work - never gets executed

Am I missing something? It seems as such a common use case - why isn't
there a simple solution?
I see no reason why root Resources with static @Path could not have
access to their UriInfo at any time - their URI is known right from
the start?
And why does @PostConstruct not work? I'm running Tomcat 6.0.26.

Thanks,

Martynas
semantic-web.dk