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