Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Jersey 2 replacement for ResourceContext.matchResource(URI)?

How do I find out what Resource an arbitrary URI maps to under Jersey 2.0? Under Jersey 1.x I'd use ResourceContext.matchResource(URI).

What I'm trying to do: I'm trying to process an incoming request that references another resource by URI. For example, here is an operation that links a user to a department.

POST /departments/5
{
  "user": "http://example.com/users/10"
}

POST /departments/5 resolves to:

class DepartmentResource
{
  @POST
  void linkUser() { ... }
}

In order to honor this request, I need to resolve the URI back to a UserResource and from there to its database id. Adding @Context UriInfo to linkUser() won't help because this UriInfo corresponds to the URI of the department instead of the user.

UPDATE: I filed a bug report at https://github.com/eclipse-ee4j/jersey/issues/2444

UPDATE2: Posted a follow-up question: Jersey2: Navigating from a Resource to an instance

like image 436
Gili Avatar asked Jun 24 '13 20:06

Gili


1 Answers

If you are running in a container, you can do the following:

// Classes that may be of interest
import org.glassfish.jersey.server.ExtendedResourceContext;
import org.glassfish.jersey.server.model.Invocable;
import org.glassfish.jersey.server.model.Parameter;
import org.glassfish.jersey.server.model.Resource;
import org.glassfish.jersey.server.model.ResourceMethod;

@Context private ExtendedResourceContext rconfig;    

public Resource dumpResources(String relUrl){
    List<Resource> parents = rconfig.getResourceModel().getRootResources();
    for(Resource res: parents){
        if(relUrl.startsWith(res.getPath()){
            return res;
        }
    }
}

If you have a more complex hierarchy with children resources, you can either recursively descend into their children with the following method, or you can create a ResourceModelVisitor and use the visitor pattern via:

rconfig.getResourceModel().accept( (ResourceModelVisitor) visitor);

There may be another solution, but I can verify this works. I use this pattern to dynamically document my resources (instead of wadl)

like image 148
Brian Avatar answered Sep 25 '22 19:09

Brian