View Javadoc

1   /*
2    * $Id: ScriptTransformer.java 19191 2010-08-25 21:05:23Z tcarlson $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.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.AbstractMessageTransformer;
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 AbstractMessageTransformer
25  {
26      private Scriptable script;
27  
28      @Override
29      public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException
30      {
31          Bindings bindings = script.getScriptEngine().createBindings();
32          script.populateBindings(bindings, message);
33          try
34          {
35              return script.runScript(bindings);
36          }
37          catch (ScriptException e)
38          {
39              throw new TransformerException(this, e);
40          }
41      }
42  
43      public Scriptable getScript()
44      {
45          return script;
46      }
47  
48      public void setScript(Scriptable script)
49      {
50          this.script = script;
51      }
52  }