package example.common.interceptor;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.seasar.framework.ejb.impl.InvocationContextImpl;

import example.common.exception.SystemException;

public class Ejb3ToAopallianceInterceptor implements MethodInterceptor {

    Object ejb3Interceptor;
    Method method;

    public Ejb3ToAopallianceInterceptor(Object ejb3Interceptor) {
        this.ejb3Interceptor = ejb3Interceptor;
        Class<?> clazz = ejb3Interceptor.getClass();
        for (Method method : clazz.getDeclaredMethods()) {
            if (method.getAnnotation(AroundInvoke.class) != null) {
                method.setAccessible(true);
                this.method = method;
                return;
            }
        }
        throw new SystemException("invoke method not found");
    }

    public Object invoke(MethodInvocation invocation) throws Throwable {
        InvocationContext context = new InvocationContextImpl(invocation);
        try {
            return method.invoke(ejb3Interceptor, context);
        } catch (InvocationTargetException e) {
            Throwable cause = e.getCause();
            throw (cause == null ? e : cause);
        }
    }

}
