Friday, September 24, 2010

Interceptor Advisor Pattern

Your standard CDI/EJB Interceptor example uses a logger as an around advice. Generally this gives you an interceptor that looks like so:

@Log
public class LoggingInterceptor {

    private java.util.logging.Logger logger =
            java.util.logging.Logger.getLogger("theLogger");

    @AroundInvoke
    public Object intercept(InvocationContext context) throws Exception {
        logger.info("" + context.getMethod().getName());
        return context.proceed();
    }
}

As of the Interceptors 1.1 spec, you can bind that to a bean via creating our own javax.interceptor.InterceptorBinding annotation. In our example, we've created one called @Log:

@InterceptorBinding
@Target(value = {ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
}

Now we just apply that to the bean as follows.

@Log
public class FooBean {

    public void somethingCommon(){
        //...
    }

    public void somethingImportant() {
        //...
    }

    public void somethingNoteworthy() {
        //...
    }
}

Great! Now we are done. Every time that bean is invoked, the LoggerInterceptor will issue a log message on info level. Aren't interceptors wonderful! End of story, right? Not quite.

Fundamentally, our example is still very contrived. Who wants to log everything on the same level?

Here is a little pattern that you can use to better advise your LoggerInterceptor around advice. First, we create a couple new annotations for log levels: @Fine and @Info

@Target(value = {ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Fine {
}

@Target(value = {ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Info {
}

Then we apply those to the bean...

@Log
public class FooBean {

    public void somethingCommon(){
        //...
    }

    @Info
    public void somethingImportant() {
        //...
    }

    @Fine
    public void somethingNoteworthy() {
        //...
    }
}

Now we alter our LoggerInterceptor to check for our new annotations and alter its behavior.

@Log
public class LoggingInterceptor {

    private java.util.logging.Logger logger =
            java.util.logging.Logger.getLogger("theLogger");

    @AroundInvoke
    public Object intercept(InvocationContext context) throws Exception {
        final Method method = context.getMethod();
        if (method.isAnnotationPresent(Info.class)) {
            return info(context);
        } else if (method.isAnnotationPresent(Fine.class)) {
            return fine(context);
        } else {
            return finest(context);
        }
    }

    public Object info(InvocationContext context) throws Exception {
        logger.info("" + context.getMethod().getName());
        return context.proceed();
    }

    public Object fine(InvocationContext context) throws Exception {
        logger.finest("" + context.getMethod().getName());
        return context.proceed();
    }

    public Object finest(InvocationContext context) throws Exception {
        logger.finest("" + context.getMethod().getName());
        return context.proceed();
    }
}

Done! Now we have a pattern to advise our interceptor!

This will totally work today. But this pattern is so simple and elegant what if we could support it right inside the container? Imagine how cool it would be if we could just do this in our interceptor and the container would just figure it out.

@Log
public class LoggingInterceptor {

    private java.util.logging.Logger logger =
            java.util.logging.Logger.getLogger("theLogger");

    @Info
    public Object info(InvocationContext context) throws Exception {
        logger.info("" + context.getMethod().getName());
        return context.proceed();
    }

    @Fine
    public Object fine(InvocationContext context) throws Exception {
        logger.finest("" + context.getMethod().getName());
        return context.proceed();
    }

    @AroundInvoke
    public Object finest(InvocationContext context) throws Exception {
        logger.finest("" + context.getMethod().getName());
        return context.proceed();
    }
}

Definitely something I plan to propose for the next round of specifications....

As always, comments welcome.

12 comments:

爸爸 x said...

20170619 junda
oakley sunglasses sale
cheap jerseys wholesale
burberry outlet sale
cheap ray ban sunglasses
adidas uk store
michael kors outlet clearance
cheap nba jerseys
true religion outlet
ray ban sunglasses
nike air max 90

爸爸 x said...

20170619 junda
rolex watches,rolex watches,swiss watches,watches for men,watches for women,omega watches,replica watches,rolex watches for sale,rolex replica,rolex watch,cartier watches,rolex submariner,fake rolex,rolex replica watches,replica rolex
ray ban sunglasses
ferragamo outlet
ray ban wayfarer
true religion jeans sale
fitflops
christian louboutin sale
ralph lauren outlet
jordan 4
cheap nfl jerseys

eric yao said...

Coach Outlet ED Hardy Outlet Coach Outlet Store Online Kate Spade Outlet Cheap Jordans Coach Purses Coach Outlet Kate Spade Outlet Toms Outlet Louis Vuitton

Habib Malik said...

Sarkari Naukri
OBC Bank Recruitment 2018

Danish Ahmed said...

Thanks for sharing this article, now you can check your cut off marks by following below given links

rajasthan post office gds result 2017

north eastern post office gds result 2017

karnataka post office gds result 2017

punjab post office gds result 2017

uttarakhand post office gds result 2017

Danish Ahmed said...

Thanks for sharing this article, now you can check your Time table & Date sheet 2017 by following below given links

ap ssc time table 2017

assam hslc date sheet 2017

bihar board 10th date sheet 2017

cbse board 10th date sheet 2017

ch board 10th date sheet 2017


luu quoc trung said...

Thank you both for sharing Holy Mass with us each day FNAF Sister Location Juegos Friv Friv 2018 to make yourselves available Friv Twizl Jeux De Twizl Juegos De FNAF Sister Location when we were called out late at night and any other time and for your support and encouragement in every respect. Juegos Friv 2021 Juegos Twizl Juegos Yepi 2017 Juegos De Twizl

Danish Ahmed said...

Thanks for sharing this article, now you can also check your Admit card & Recuritment 2017 by following below given links...

police si admit card 2017

gpsc medical officer admit card 2017

tamilnadu teacher recuritment 2017

bihar police constable recuritment 2017

gujarat high court recruitment 2017

ngoem199 said...

Danke, dafur dass Ihr jeden Tag mit uns die Hl. Messe gefeiert habt, fur all die Reparaturen im ganzen Haus Jeux De Friv Jogos Friv Jogos Friv fur Euere Bereitschaft Juegos Friv Juegos Friv Juegos De Friv immer zur Verfugung zu stehen Juegos Geometry Dash Juegos Twizl Twizy Twizl Danke, dass Sie Ihr Muhen um den Aufbau des Leibes Christi mit uns teilten.

ngoem199 said...

A todos que partilham e trabalham sob estas mesmas convicções e princípios Friv Friv 360 Friv4school 2020 Senhor Deputado Cashman, agradeço-lhe a informação. Jeux De Friv 2018 Juegos De Roblox Juegos De Zoxy Mais uma vez, obrigada ao Parlamento por comungar da visão que informa a nova política dos consumidores Juegos Kizi 2017 Juegos Yepi 2017 Twizl 3 Zoxy 2 assente no mercado - a visão de um mercado de consumidores informados e capacitados que procuram e usufruem, com confiança,

Monis Rajpoot said...


Delhi police Constable Physical Exam Date 2017
BRABU Part-i-ii-Exam Result
Tripura Court System Officer 13th August Exam result
Assam PSC BDO 2017
Gujarat high court Civil Judge Pre-Exam Result

Danish Ahmed said...

Thanks for sharing this article, now you can also check your Admit Card 2017 by following below given links...

gsssc food safety officer admit card 2017

hssc pgt admit card 2017