0

If I am given a relative path (say path = "/foo/1/bar"), how can I find out which resource's method will be used to treat the request (this would be FooResource.bar method in the current example)?

I have tried to use Reflections, by looking at all the @Path annotated classes and methods, and build a map to point back to those methods. However, that would not be ideal, since I'll have to test the given relative path against all existing @Paths.

Here is an example Resource:

@Path("/foo")  
public class FooResource {
    @GET
    @Path("{id}/bar")
    public String bar(@PathParam("id") int barId)
    {
        return "Hello Bar " + Integer(barId).toString();
    }


    @POST
    @Path("/biz")
    public String biz(BisRequest biz)
    {
        return "Hello Biz";
    }
}

Instead of my current solution, which is:

mapper = new HashMap<String, Method>();
/** content of mapper
String "/foo/{id}/bar" -> java.lang.reflect.Method FooResource.bar
String "/foo/biz"      -> java.lang.reflect.Method FooResource.biz
*/

public Method findResourceMethodForPath(String path, HashMap<String, Method> mapper) {
     String correctKey = findCorrectKeyForPath(path, mapper.keySet());
     return mapper.get(correctKey);
}

Would there be a cleaner way to implement findResourceMethodForPath without having to use the mapper, as defined in the snippet above?

adamaMG
  • 3
  • 2

1 Answers1

0

Found an answer, by using filters provided by Dropwizard.

public void filter(ContainerRequestContext requestContext) {
    UriRoutingContext routingContext = (UriRoutingContext) requestContext.getUriInfo();
    ResourceMethodInvoker invoker = (ResourceMethodInvoker) routingContext.getInflector();
    Class<?> className = invoker.getResourceClass();
    Method methodName = invoker.getResourceMethod(); 
}

Answer found from this post: How to retrieve matched resources of a request in a ContainerRequestFilter

adamaMG
  • 3
  • 2
  • Just inject ResourceInfo into the filter. It's easier. – Paul Samsotha Jan 12 '19 at 17:42
  • Just an FYI, looking at your answer, it seems your original question is sort of an "XY problem". Google the term and see what it means if you don't know. Try to avoid asking these type of questions. You will get better results. – Paul Samsotha Jan 12 '19 at 17:45