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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With