Tie

Java Method Interception

Cook Book

Marking which methods to intercept

Problem:

You want to intercept some methods, and not others, but there is no obvious way to for the code to determine which methods need interception.

Solution 1

Mark the methods to be intercepted with an annotation of your choosing, then use the InterceptionBuilder to apply an AnnotationPresentRule to your stack.

For example:

@Retention(RetentionPolicy.RUNTIME)
public @interface Secure { }
public interface HttpHandler 
{
    public void service(HttpServletRequest request, HttpServletResponse response);
}
public class MySecureService implements HttpHandler 
{
    @Secure
    public void service(HttpServletRequest request, HttpServletResponse response) { /* ... */ }
}
public class SecureHandlerInterceptor implements MethodInterceptor 
{
    public Object invoke(MethodInvocation invocation) throws Throwable
    {
        HttpServletRequest request = (HttpServletRequest) invocation.getArguments()[0] ;
        if(!request.isSecure())
        {
            throw new SecurityException();
        }
        return invocation.proceed();
    }
}
public InterceptionInjector createInjector()
{
    InterceptionBuilder builder = new InterceptionBuilder();
    builder.whenPresent(Secure.class, new SecureHandlerInterceptor());
    MethodInterceptorStack stack = builder.done();
    return new ProxyInjector(stack);
}

Solution 2

Use the MethodNameRule or the MethodPatternRule to match based on the names of the methods. The InterceptionBuilder can be used to apply these inteceptors to your stack.