package org.mockejb.interceptor;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import net.sf.cglib.reflect.FastClass;
import net.sf.cglib.reflect.FastMethod;
public class InterceptorInvoker implements Serializable {
private transient AspectSystem aspectSystem = AspectSystemFactory.getAspectSystem();
private Map context = new HashMap();
public Object invoke( Object proxyObj, Method proxyMethod,
Object targetObj, Method targetMethod, Object[] paramVals ) throws Exception {
List interceptorList =
aspectSystem.findInterceptors( proxyMethod, targetMethod );
interceptorList.add( new CglibMethodInvoker( ) );
InvocationContext invocationContext = new InvocationContext( interceptorList, proxyObj,
proxyMethod, targetObj, targetMethod, paramVals, context );
invocationContext.proceed();
return invocationContext.getReturnObject();
}
public void setContext( String key, Object data ){
context.put( key, data );
}
public Object getContext( String key ) {
return context.get( key );
}
static public class CglibMethodInvoker implements Interceptor {
public void intercept( InvocationContext invocationContext ) throws Exception {
try { Method targetMethod = invocationContext.getTargetMethod();
FastClass fastClass = FastClass.create( targetMethod.getDeclaringClass() );
FastMethod fastMethod = fastClass.getMethod( targetMethod );
Object returnObj;
try {
returnObj = fastMethod.invoke( invocationContext.getTargetObject(),
invocationContext.getParamVals());
}
catch( InvocationTargetException ite ){
throw ite.getTargetException();
}
invocationContext.setReturnObject( returnObj );
}
catch( Throwable throwable) {
if ( throwable instanceof Error ) {
throw (Error)throwable;
}
else if ( throwable instanceof Exception ){
throw (Exception)throwable;
}
}
}
}
}