Search code examples
javadesign-patternsjava-ee-6interceptor

JEE: how to pass parameter to an interceptor


In my JEE application, running on glassfish 3, I have the following situation:

MyFacade class

@Interceptors(SomeInterceptor.class)
public void delete(Flag somethingForTheInterceptor, String idToDelete) {
    .......
}

@Interceptors(SomeInterceptor.class)
public void update(Flag somethingForTheInterceptor, MyStuff newStuff) {
    .......
}

The variable somethingForTheInterceptor is not used in these methods, it is only used in the interceptor:

SomeInterceptor class

@AroundInvoke
public Object userMayAccessOutlet(InvocationContext ctx) throws Exception {
   Flag flag = extractParameterOfType(Arrays.asList(ctx.getParameters()), Flag.class);
   // some checks on the flag
}

Somehow it doesn't feel good to have a parameter that is not used in the method. Is there another way to "send" somethingForTheInterceptor to the interceptor?

UPDATE: The callers of delete() and update() have different ways of calculating the somethingForTheInterceptor variable. And this is not a constant. The information needed to calculate it is in the REST call. But the 2 REST methods have different input objects so it is not enough to inject the http request.

These are the callers:

MyResource class

@DELETE
@Path("/delete/{" + ID + "}")
public Response delete(@PathParam(ID) final String id) {
   Flag flag = calculateFlagForInterceptor(id);
   facade.delete(flag, id);
}

@POST
@Path("/update")
@Consumes(MediaType.APPLICATION_JSON + RestResourceConstants.CHARSET_UTF_8)
public Response update(final WebInputDTO updateDetails) throws ILeanException {
   Flag flag = calculateFlagForInterceptor(updateDetails);
   facade.update(flag, convertToMyStuff(updateDetails));
}

I was thinking - is it possible for the methods in the Resource to set the flag in some kind of Context, that can be later injected in the Interceptor?


Solution

  • In Java EE, Interceptors allow to add pre and post processings to a method. So, the context of the Interceptor execution is the context of the method.

    I was thinking - is it possible for the methods in the Resource to set the flag in some kind of Context, that can be later injected in the Interceptor?

    Staless Service should be privileged when you may. So, you should avoid storing data on the server (ThreadLocal, Session, etc..).

    The information needed to calculate it is in the REST call.

    Why ? A Rest controller has no vocation to do computations and logic.

    To solve your problem, are you sure you could not move the flag computation in your interceptor ? By enhancing the interceptor responsibilities, you would have not need anly longer to transit the flag :

    @AroundInvoke
    public Object userMayAccessOutlet(InvocationContext ctx) throws Exception {
       Flag flag = calculFlag(Arrays.asList(ctx.getParameters()));
       // some checks on the flag
    }