/*
* JBoss, the OpenSource J2EE webOS
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.jboss.mx.server;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import javax.management.MBeanException;
import javax.management.RuntimeMBeanException;
import javax.management.RuntimeErrorException;
import javax.management.ReflectionException;
import org.jboss.mx.logging.Logger;
import org.jboss.mx.logging.SystemLogger;
/**
*
* @author <a href="mailto:juha@jboss.org">Juha Lindfors</a>.
* @version $Revision: 1.2 $
*
*/
public class ReflectedDispatcher
implements Dispatcher
{
// Static --------------------------------------------------------
private static Logger log = SystemLogger.getLogger(ReflectedDispatcher.class);
// Attributes ----------------------------------------------------
private Method method = null;
private Object target = null;
private Object[] args = null;
// Constructors --------------------------------------------------
public ReflectedDispatcher() {}
public ReflectedDispatcher(Object target, Method m)
{
this.method = m;
this.target = target;
}
// Dispatcher implementation -------------------------------------
public void setArgs(Object[] args)
{
this.args = args;
}
public Object[] getArgs()
{
return args;
}
public Object dispatch() throws InvocationException
{
if (method == null)
return Void.TYPE;
try
{
return method.invoke(target, args);
}
catch (Throwable t)
{
handleInvocationExceptions(t);
return null;
}
}
// Protected -----------------------------------------------------
protected void handleInvocationExceptions(Throwable t) throws InvocationException
{
// the invoked method threw an exception
if (t instanceof InvocationTargetException)
{
Throwable target = ((InvocationTargetException)t).getTargetException();
// Invoked method threw a runtime exception. We wrap it into a JMX
// runtime mbean exception
if (target instanceof RuntimeException)
{
throw new InvocationException(
new RuntimeMBeanException((RuntimeException)target, target.toString())
);
}
// Invoked method threw a checked exception. Wrapped as a JMX mbean
// exception.
else if (target instanceof Exception)
{
throw new InvocationException(
new MBeanException((Exception)target, target.toString())
);
}
// Invoked method threw an error. Wrapped as a JMX runtime error exception.
else if (target instanceof Error)
{
throw new InvocationException(
new RuntimeErrorException((Error)target, target.toString())
);
}
else throw new InvocationException(new Error("Unhandled exception: " + t.toString()));
}
// assume all other exceptions are reflection related
else if (t instanceof Exception)
{
throw new InvocationException(
new ReflectionException((Exception)t, t.toString())
);
}
else if (t instanceof Error)
{
throw new InvocationException(
new RuntimeErrorException((Error)t, t.toString())
);
}
throw new InvocationException(new Error("Unhandled exception: " + t.toString()));
}
}