// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package dynamic;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.aspectj.lang.annotation.Around;

//work with Spring DI
@Component("check2")
// aspect
@Aspect
public class Check2 {
    // pointcut:
    //   public visibility, any return type, any class, divide method, two arguments any type
    @Pointcut("execution(public * *.divide(*, *))")
    public void mathcheck() { };
    // advice:
    //    around
    @Around("mathcheck()")
    public Object trace(ProceedingJoinPoint pjp) {
        Object o = pjp.getArgs()[1];
        if(o instanceof Integer) {
            Integer oi = (Integer)o;
            if(oi.intValue() == 0) {
                System.out.println("AOP> About to divide by integer zero");
            }
        } else if(o instanceof Double) {
            Double od = (Double)o; 
            if(od.doubleValue() == 0.0) {
                System.out.println("AOP> About to divide by double zero");
            }
        } else {
            throw new RuntimeException("Unsupported data type in divide: " + o.getClass().getName());
        }
        Object res = null;
        try {
            res = pjp.proceed();
        } catch(Throwable e) {
             throw (RuntimeException)e;
        }
        return res;
    }
}
