1 | |
|
2 | |
|
3 | |
|
4 | |
|
5 | |
|
6 | |
|
7 | |
|
8 | |
|
9 | |
|
10 | |
package org.mule.module.scripting.expression; |
11 | |
|
12 | |
import org.mule.api.MuleContext; |
13 | |
import org.mule.api.MuleMessage; |
14 | |
import org.mule.api.MuleRuntimeException; |
15 | |
import org.mule.api.context.MuleContextAware; |
16 | |
import org.mule.api.expression.ExpressionEvaluator; |
17 | |
import org.mule.api.lifecycle.Disposable; |
18 | |
import org.mule.api.lifecycle.InitialisationException; |
19 | |
import org.mule.config.i18n.CoreMessages; |
20 | |
import org.mule.module.scripting.component.Scriptable; |
21 | |
|
22 | |
import java.util.Map; |
23 | |
import java.util.WeakHashMap; |
24 | |
|
25 | |
import javax.script.Bindings; |
26 | |
import javax.script.ScriptException; |
27 | |
|
28 | |
|
29 | |
|
30 | |
|
31 | |
|
32 | |
|
33 | |
|
34 | 0 | public abstract class AbstractScriptExpressionEvaluator implements ExpressionEvaluator, Disposable, MuleContextAware |
35 | |
{ |
36 | 0 | protected Map cache = new WeakHashMap(8); |
37 | |
|
38 | |
protected MuleContext muleContext; |
39 | |
|
40 | |
public void setMuleContext(MuleContext context) |
41 | |
{ |
42 | 0 | this.muleContext = context; |
43 | 0 | } |
44 | |
|
45 | |
|
46 | |
|
47 | |
|
48 | |
|
49 | |
|
50 | |
|
51 | |
|
52 | |
public Object evaluate(String expression, MuleMessage message) |
53 | |
{ |
54 | 0 | Scriptable script = getScript(expression); |
55 | 0 | script.setMuleContext(muleContext); |
56 | 0 | Bindings bindings = script.getScriptEngine().createBindings(); |
57 | 0 | script.populateBindings(bindings, message); |
58 | |
|
59 | |
try |
60 | |
{ |
61 | 0 | return script.runScript(bindings); |
62 | |
} |
63 | 0 | catch (ScriptException e) |
64 | |
{ |
65 | 0 | return null; |
66 | |
} |
67 | |
} |
68 | |
|
69 | |
|
70 | |
|
71 | |
|
72 | |
|
73 | |
|
74 | |
public void setName(String name) |
75 | |
{ |
76 | 0 | throw new UnsupportedOperationException("setName"); |
77 | |
} |
78 | |
|
79 | |
protected Scriptable getScript(String expression) |
80 | |
{ |
81 | 0 | Scriptable script = (Scriptable)cache.get(expression); |
82 | 0 | if (script==null) |
83 | |
{ |
84 | 0 | script = new Scriptable(muleContext); |
85 | 0 | script.setScriptEngineName(getName()); |
86 | 0 | script.setScriptText(expression); |
87 | |
try |
88 | |
{ |
89 | 0 | script.initialise(); |
90 | |
} |
91 | 0 | catch (InitialisationException e) |
92 | |
{ |
93 | 0 | throw new MuleRuntimeException( |
94 | |
CoreMessages.initialisationFailure("An error occurred initialising script."), e); |
95 | 0 | } |
96 | 0 | cache.put(expression, script); |
97 | |
} |
98 | 0 | return script; |
99 | |
} |
100 | |
|
101 | |
|
102 | |
|
103 | |
|
104 | |
|
105 | |
|
106 | |
public void dispose() |
107 | |
{ |
108 | 0 | cache.clear(); |
109 | 0 | } |
110 | |
} |