package example.common.interceptor;

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

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import example.common.util.ExampleUtils;

public class JndiLookupInterceptor implements MethodInterceptor {

    String name;

    public void setName(String name) {
        this.name = name;
    }

    public Object invoke(MethodInvocation invocation) throws Throwable {
        Object service = ExampleUtils.doJndiLookup(name);
        Method method = invocation.getMethod();
        Method serviceMethod = service.getClass()
                .getMethod(method.getName(), method.getParameterTypes());
        try {
            return serviceMethod.invoke(service, invocation.getArguments());
        } catch (InvocationTargetException e) {
            Throwable cause = e.getCause();
            throw (cause == null ? e : cause);
        }
    }

}
