View Javadoc

1   /*
2    * $Id: ScriptTransformer.java 11879 2008-06-01 22:45:57Z rossmason $
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.module.scripting.transformer;
12  
13  import org.mule.api.MuleMessage;
14  import org.mule.api.transformer.TransformerException;
15  import org.mule.module.scripting.component.Scriptable;
16  import org.mule.transformer.AbstractMessageAwareTransformer;
17  
18  import javax.script.ScriptException;
19  import javax.script.Bindings;
20  
21  /**
22   * Runs a script to perform transformation on an object.
23   */
24  public class ScriptTransformer extends AbstractMessageAwareTransformer
25  {
26      private Scriptable script;
27  
28      public Object transform(MuleMessage message, String outputEncoding) throws TransformerException
29      {
30          Bindings bindings = script.getScriptEngine().createBindings();
31          script.populateBindings(bindings, message);
32          try
33          {
34              return script.runScript(bindings);
35          }
36          catch (ScriptException e)
37          {
38              throw new TransformerException(this, e);
39          }
40      }
41  
42      public Scriptable getScript()
43      {
44          return script;
45      }
46  
47      public void setScript(Scriptable script)
48      {
49          this.script = script;
50      }
51  }