Search code examples
javarestjerseyjax-rswebresource

Jersey REST extending methods


I was wondering if it is possible to do the following trick with jersey restful resources:

I have an example jersey resource:

@Path("/example")
public class ExampleRessource {


  @GET
  @Path("/test")
  @CustomPermissions({"foo","bar"})
  public Response doStuff() {
    //implicit call to checkPermissions(new String[] {"foo","bar"}) 

  }  

  private void checkPermissions(String[] permissions) {
    //stuff happens here
  }

}

What I want to achieve is: before executing each resource's method to implicitly check the rights from the annotation by calling the checkPermissions method without actually writing the call inside the method body. Kind of "decorating" each jersey method inside this resource.

Is there an elegant solution? For example with jersey Provider?

Thx!


Solution

  • With Jersey 2 can use ContainerRequestFilter.

    @Provider
    public class CheckPermissionsRequestFilter 
                                         implements ContainerRequestFilter {
        @Override
        public void filter(ContainerRequestContext crc) throws IOException {
    
        }  
    }
    

    We can get the annotation on the called method through the ResourceInfo class

    @Context
    private ResourceInfo info;
    
    @Override
    public void filter(ContainerRequestContext crc) throws IOException {
        Method method = info.getResourceMethod();
        CheckPermissions annotation = method.getAnnotation(CheckPermissions.class);
        if (annotation != null) {
            String[] permissions = annotation.value();
        }
    } 
    

    You can use this annotation

    @NameBinding
    @Target({ElementType.METHOD, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface CheckPermissions {
        String[] value();
    }
    

    And annotate the resource class or the resource method with @CheckPermissions({...})



    UPDATE

    The annotation above allows for annotating classes also. Just for completeness, you'll want to check the class also. Something like

    Class resourceClass = info.getResourceClass();
    CheckPermissions checkPermissions = resourceClass.getAnnotation(CheckPermissions.class);
    if (checkPermissions != null) {
       String[] persmission = checkPermissions.value();
    }