package org.nthx.pat;
import org.apache.log4j.Logger;
import org.prevayler.Command;
import org.prevayler.PrevalentSystem;
import java.io.Serializable;
import java.lang.reflect.Method;
public class GenericCommand
implements Command
{
private String command;
private ObjectForStream[] targetAndArgsForStream;
private Class[] parameterTypes; private Class targetClass;
public GenericCommand(Object target, Method method, Object[] params)
{
String command = method.getName();
this.command = command;
this.targetAndArgsForStream = CommandGenerationHelper.targetAndBos2FakeOIDs(target, params);
this.parameterTypes = method.getParameterTypes();
this.targetClass = method.getDeclaringClass();
}
public Serializable execute(PrevalentSystem system)
throws Throwable
{
Object[] recoveredParams =
CommandGenerationHelper.fakeBOs2targetAndBos((IdentityMap)system,
targetAndArgsForStream,
targetClass+"."+command,
parameterTypes);
Object recoveredTarget = recoveredParams[0];
Method commandMethod = targetClass.getMethod(command, parameterTypes);
try
{
Object[] recoveredParamsOnly =
new Object[recoveredParams.length - 1];
System.arraycopy(recoveredParams, 1,
recoveredParamsOnly, 0,
recoveredParamsOnly.length);
commandMethod.setAccessible(true);
return (java.io.Serializable) commandMethod.invoke(
recoveredTarget,
recoveredParamsOnly);
} catch (IllegalAccessException e)
{
throw e.getCause();
} catch (java.lang.reflect.InvocationTargetException e)
{
throw e.getCause();
}
}
private void logCommand()
{
StringBuffer params = new StringBuffer();
for (int i=1; i<targetAndArgsForStream.length; i++)
{
if (targetAndArgsForStream[i] instanceof Identifiable)
params.append(targetAndArgsForStream[i].objectOrOID);
else
params.append(".., ");
}
log.debug("Recovering: " + command + "("+params+")");
}
public String toString()
{
String result = "<" + command + "\n";
if (null != targetAndArgsForStream)
{
for (int i = 0; i < targetAndArgsForStream.length; i++)
result = result + "\t<arg" + i + " " + targetAndArgsForStream[i].getClass().getName()
+ "\n\t " + targetAndArgsForStream[i] + "/>\n";
}
result = result + "\n</" + command + ">";
return result;
}
private static Logger log = Logger.getLogger("pat");
}