View Javadoc

1   /*
2    * $Id: ScriptComponent.java 7976 2007-08-21 14:26:13Z dirk.olmes $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSource, Inc.  All rights reserved.  http://www.mulesource.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.components.script.jsr223;
12  
13  import org.mule.MuleManager;
14  import org.mule.umo.UMOEventContext;
15  import org.mule.umo.lifecycle.Callable;
16  import org.mule.umo.lifecycle.InitialisationException;
17  import org.mule.util.MuleLogger;
18  
19  import javax.script.Bindings;
20  
21  /**
22   * A JSR 223 Script component. 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  {
27      private Bindings bindings;
28  
29      public void initialise() throws InitialisationException
30      {
31          super.initialise();
32          bindings = getScriptEngine().createBindings();
33      }
34  
35      public Object onCall(UMOEventContext eventContext) throws Exception
36      {
37          populateBindings(bindings, eventContext);
38          Object result = runScript(bindings);
39          if (result == null)
40          {
41              result = bindings.get("result");
42          }
43          return result;
44      }
45  
46      protected void populateBindings(Bindings namespace, UMOEventContext context)
47      {
48          namespace.put("eventContext", context);
49          namespace.put("managementContext", MuleManager.getInstance());
50          namespace.put("message", context.getMessage());
51          namespace.put("descriptor", context.getComponentDescriptor());
52          namespace.put("componentNamespace", this.bindings);
53          namespace.put("log", new MuleLogger(logger));
54          namespace.put("result", new Object());
55      }
56  
57      public Bindings getBindings()
58      {
59          return bindings;
60      }
61  
62  }