View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.module.scripting.transformer;
8   
9   import org.mule.api.MuleMessage;
10  import org.mule.api.transformer.TransformerException;
11  import org.mule.module.scripting.component.Scriptable;
12  import org.mule.transformer.AbstractMessageTransformer;
13  
14  import javax.script.ScriptException;
15  import javax.script.Bindings;
16  
17  /**
18   * Runs a script to perform transformation on an object.
19   */
20  public class ScriptTransformer extends AbstractMessageTransformer
21  {
22      private Scriptable script;
23  
24      @Override
25      public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException
26      {
27          Bindings bindings = script.getScriptEngine().createBindings();
28          script.populateBindings(bindings, message);
29          try
30          {
31              return script.runScript(bindings);
32          }
33          catch (ScriptException e)
34          {
35              throw new TransformerException(this, e);
36          } finally {
37              bindings.clear();
38          }
39      }
40  
41      public Scriptable getScript()
42      {
43          return script;
44      }
45  
46      public void setScript(Scriptable script)
47      {
48          this.script = script;
49      }
50  }