public HandlerContext executeHandler(final HandlerDefinition handlerDef, final String eventType,
final TokenContext context, NodeSocket currentSocket, NodeSocket nextSocket)
{
if (handlerDef != null && handlerDef.canHandle(eventType))
{
HandlerContext hc = new HandlerContext(this, eventType, context);
if (currentSocket == null)
currentSocket = context.getCurrentSocket();
if (currentSocket == null)
{
String msg = LogUtil.error(getClass(), "Cannot call handler w/o a current socket. [{0}]", context);
throw new OpenBPException("HandlerExecutionFailed", msg);
}
hc.setCurrentSocket(currentSocket);
if (nextSocket == null && currentSocket != null)
nextSocket = currentSocket.getNode().getDefaultExitSocket();
hc.setNextSocket(nextSocket);
// Execute the handler
if (handlerDef.getHandlerClassName() != null)
{
Object handlerInstanceObject = handlerDef.obtainHandlerInstance();
if (! (handlerInstanceObject instanceof Handler))
{
String msg = LogUtil.error(getClass(),
"Handler object class $0 does not implement the handler interface $1. [{2}]", handlerInstanceObject
.getClass().getName(), Handler.class.getName(), context);
throw new OpenBPException("HandlerExecutionFailed", msg);
}
Handler handlerInstance = (Handler) handlerInstanceObject;
LogUtil.trace(getClass(), "Executing handler on node $0 (class $1) as {2} handler. [{3}]",
currentSocket.getNode().getQualifier().toString(), handlerInstance.getClass().getName(), eventType, context);
// Execute the Java implementation of this handler
try
{
handlerInstance.execute(hc);
}
catch (OpenBPException ee)
{
// Engine exceptions can be rethrown.
throw ee;
}
catch (Throwable t)
{
// Catch any exceptions, so the server won't be confused by errors in handlers
String msg = LogUtil.error(getClass(), "Error executing handler of $0. [{1}]", currentSocket.getNode()
.getQualifier().toString(), t);
throw new OpenBPException("HandlerExecutionFailed", msg, t);
}
}
else if (handlerDef.getScript() != null)
{
LogUtil.trace(getClass(), "Executing script on node $0 as {1} handler. [{2}]",
currentSocket.getNode().getQualifier().toString(), eventType, context);
// Execute the script associated with this handler
ScriptEngine scriptEngine = getScriptEngineFactory().obtainScriptEngine(hc.getTokenContext());
try
{
scriptEngine.prepareHandlerExecution(hc);
String script = handlerDef.getScript();
scriptEngine.executeScript(script, "handler script", currentSocket.getNode().getQualifier().toString());