After Advice Example : Spring Aspect « Spring « Java






After Advice Example

/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/


////////////////////////////////////////////////////////

import java.util.Random;

public class KeyGenerator {

    public static final long WEAK_KEY = 0xFFFFFFF0000000L;
    public static final long STRONG_KEY = 0xACDF03F590AE56L;
    
    public long getKey() {
        Random rand = new Random();
        int x = rand.nextInt(3);
        
        if(x == 1) {
            return WEAK_KEY;
        } else {
            return STRONG_KEY;
        }
    }
}


////////////////////////////////////////////////////////

import java.lang.reflect.Method;

import org.springframework.aop.AfterReturningAdvice;

public class WeakKeyCheckAdvice implements AfterReturningAdvice {

    public void afterReturning(Object returnValue, Method method,
            Object[] args, Object target) throws Throwable {

        if ((target instanceof KeyGenerator)
                && ("getKey".equals(method.getName()))) {
            long key = ((Long) returnValue).longValue();

            if (key == KeyGenerator.WEAK_KEY) {
                throw new SecurityException(
                        "Key Generator generated a weak key. Try again");
            }
        }
    }

}

////////////////////////////////////////////////////////
import org.springframework.aop.framework.ProxyFactory;

public class AfterAdviceExample {

    public static void main(String[] args) {
        KeyGenerator keyGen = getKeyGenerator();
        
        for(int x = 0; x < 10; x++) {
            try {
                long key = keyGen.getKey();
                System.out.println("Key: " + key);
            } catch(SecurityException ex) {
                System.out.println("Weak Key Generated!");
            }
        }
        
    }
    
    private static KeyGenerator getKeyGenerator() {
        
        KeyGenerator target = new KeyGenerator();
        
        ProxyFactory factory = new ProxyFactory();
        factory.setTarget(target);
        factory.addAdvice(new WeakKeyCheckAdvice());
        
        return (KeyGenerator)factory.getProxy();
    }
}

           
       








AfterAdviceExample.zip( 1,479 k)

Related examples in the same category

1.Profiling Example
2.Introduction Config Example
3.Security Example
4.Simple After Returning Advice
5.Simple Before Advice
6.Simple Throws Advice
7.Composable Pointcut Example
8.Control Flow Example
9.Dynamic Pointcut Example
10.Hello World With Pointcut
11.Spring Aspect Introduction Example
12.Static Pointcut Example
13.Name Pointcut Example
14.Name Pointcut Using Advisor
15.Proxy Factory Bean Example
16.Proxy Perf Test
17.Regexp Pointcut Example
18.AspectJ Example from Pro Spring
19.Aspect Hello World Example