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 public abstract class AbstractScriptExpressionEvaluator implements ExpressionEvaluator, Disposable
33 {
34 protected Map cache = new WeakHashMap(8);
35
36
37
38
39
40
41
42
43 public Object evaluate(String expression, Object message)
44 {
45 Scriptable script = getScript(expression);
46 Bindings bindings = script.getScriptEngine().createBindings();
47 if (message instanceof MuleMessage)
48 {
49 script.populateBindings(bindings, (MuleMessage) message);
50 }
51 else
52 {
53 script.populateBindings(bindings, message);
54 }
55
56 try
57 {
58 return script.runScript(bindings);
59 }
60 catch (ScriptException e)
61 {
62 return null;
63 }
64 }
65
66
67
68
69
70
71 public void setName(String name)
72 {
73 throw new UnsupportedOperationException("setName");
74 }
75
76 protected Scriptable getScript(String expression)
77 {
78 Scriptable script = (Scriptable)cache.get(expression);
79 if(script==null)
80 {
81 script = new Scriptable();
82 script.setScriptEngineName(getName());
83 script.setScriptText(expression);
84 try
85 {
86 script.initialise();
87 }
88 catch (InitialisationException e)
89 {
90 throw new MuleRuntimeException(
91 CoreMessages.initialisationFailure("An error occurred initialising script."), e);
92 }
93 cache.put(expression, script);
94 }
95 return script;
96 }
97
98
99
100
101
102
103 public void dispose()
104 {
105 cache.clear();
106 }
107 }