01: /*
02: * $Id: ScriptComponent.java 11195 2008-03-06 04:13:01Z tcarlson $
03: * --------------------------------------------------------------------------------------
04: * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com
05: *
06: * The software in this package is published under the terms of the CPAL v1.0
07: * license, a copy of which has been included with this distribution in the
08: * LICENSE.txt file.
09: */
10:
11: package org.mule.module.scripting.component;
12:
13: import org.mule.api.MuleEventContext;
14: import org.mule.api.lifecycle.Callable;
15: import org.mule.api.lifecycle.InitialisationException;
16: import org.mule.api.lifecycle.LifecycleTransitionResult;
17: import org.mule.util.MuleLogger;
18:
19: import javax.script.Bindings;
20:
21: /**
22: * A JSR 223 Script service. Allows any JSR 223 compliant script engines such as
23: * JavaScript, Groovy or Rhino to be embedded as Mule components.
24: */
25: public class ScriptComponent extends Scriptable implements Callable {
26: private Bindings bindings;
27:
28: public LifecycleTransitionResult initialise()
29: throws InitialisationException {
30: return LifecycleTransitionResult.initialiseAll(super
31: .initialise(), new LifecycleTransitionResult.Closure() {
32: public LifecycleTransitionResult doContinue() {
33: bindings = getScriptEngine().createBindings();
34: return LifecycleTransitionResult.OK;
35: }
36: });
37: }
38:
39: public Object onCall(MuleEventContext eventContext)
40: throws Exception {
41: populateBindings(bindings, eventContext);
42: Object result = runScript(bindings);
43: if (result == null) {
44: result = bindings.get("result");
45: }
46: return result;
47: }
48:
49: protected void populateBindings(Bindings namespace,
50: MuleEventContext context) {
51: namespace.put("eventContext", context);
52: namespace.put("muleContext", context.getMuleContext());
53: namespace.put("message", context.getMessage());
54: namespace.put("descriptor", context.getService());
55: namespace.put("componentNamespace", this .bindings);
56: namespace.put("log", new MuleLogger(logger));
57: namespace.put("result", new Object());
58: }
59:
60: public Bindings getBindings() {
61: return bindings;
62: }
63:
64: }
|