0
votes

I have a RESTful service implemented in Jersey that consists of a top-level resource and many sub-resources. To illustrate:

Parent resource:

@Path("parent")
public class ParentResource {
   private SubResourceA subResourceA;
   private SubResourceB subResourceB;
   private SubResourceC subResourceC;

   public ParentResource() {
      subResourceA = new SubResourceA();
      subResourceB = new SubResourceB();
      subResourceC = new SubResourceC();
   }

   @Path("a")
   public SubResourceA getA() {
      return subResourceA;
   }

   @Path("b")
   public SubResourceB getB() {
      return subResourceB;
   }

   @Path("c")
   public SubResourceC getC() {
      return subResourceC;
   }

What I am looking for is to define a GET method on the ParentResource class that returns a link to all sub resources available in this class (similar to how on a file system if you select a folder which has folders inside of it, then you see the child folders).

Without such an implementation, if I hit GET /parent then I will get a 404 from my web service. Ideally GET /parent should give me a link to SubResourceA, SubResourceB and SubResourceC.

Is anyone aware of a standard convention for implementing such a feature? Specifically in JAX-RS/Jersey if possible.

Thanks

1

1 Answers

0
votes

You don't need to return an instance. You can just return the class, and let Jersey create it for you. You could simply do something like

@Path("parent")
public class ParentResource {

    @Path("{x}")
    public Class getX(@PathParam("x") String x) {
        switch (x) {
            case "a": return SubResourceA.class;
            case "b": return SubResourceB.class;
            case "c": return SubResourceC.class;
            default: throw new WebApplicationException(404);
        }
    }

    public static class SubResourceA {
        @GET               // @PathParam is forwarded parent
        public String getA(@PathParam("x") String x) {
            return "A";
        }
    }
}

"What I am looking for is to define a GET method on the ParentResource class that returns a link to all sub resources"

That breaks what defines a Sub resource locator method. It should not be annotated with any HTTP method annotations. Those annotation should only be in the sub resource class` methods.