1
2
3
4
5
6
7 package org.mule.module.scripting.component;
8
9 import org.mule.api.MuleEvent;
10 import org.mule.api.MuleException;
11 import org.mule.api.component.InterfaceBinding;
12 import org.mule.api.lifecycle.InitialisationException;
13 import org.mule.component.AbstractComponent;
14 import org.mule.component.BindingInvocationHandler;
15 import org.mule.util.ClassUtils;
16
17 import java.lang.reflect.Proxy;
18 import java.util.ArrayList;
19 import java.util.HashMap;
20 import java.util.Iterator;
21 import java.util.List;
22 import java.util.Map;
23
24 import javax.script.Bindings;
25
26
27
28
29
30 public class ScriptComponent extends AbstractComponent
31 {
32 protected List<InterfaceBinding> bindings = new ArrayList<InterfaceBinding>();
33
34 private Scriptable script;
35
36 private Map<String, Object> proxies;
37
38 @Override
39 protected void doInitialise() throws InitialisationException
40 {
41 script.setMuleContext(muleContext);
42 super.doInitialise();
43 try
44 {
45 configureComponentBindings();
46 }
47 catch (MuleException e)
48 {
49 throw new InitialisationException(e, this);
50 }
51 }
52
53 @Override
54 protected Object doInvoke(MuleEvent event) throws Exception
55 {
56
57 Bindings bindings = script.getScriptEngine().createBindings();
58 if (proxies.size() > 0)
59 {
60 bindings.putAll(proxies);
61 }
62 script.populateBindings(bindings, event);
63 try
64 {
65 return script.runScript(bindings);
66 }
67 catch (Exception e)
68 {
69
70 throw e;
71 } finally {
72 bindings.clear();
73 }
74 }
75
76 public Scriptable getScript()
77 {
78 return script;
79 }
80
81 public void setScript(Scriptable script)
82 {
83 this.script = script;
84 }
85
86 public List<InterfaceBinding> getInterfaceBindings()
87 {
88 return bindings;
89 }
90
91 public void setInterfaceBindings(List<InterfaceBinding> bindingCollection)
92 {
93 this.bindings = bindingCollection;
94 }
95
96 protected void configureComponentBindings() throws MuleException
97 {
98 proxies = new HashMap<String, Object>();
99
100
101 if (bindings != null && bindings.size() > 0)
102 {
103 for (Iterator<?> it = bindings.iterator(); it.hasNext();)
104 {
105 InterfaceBinding interfaceBinding = (InterfaceBinding) it.next();
106 String bindingName = ClassUtils.getSimpleName(interfaceBinding.getInterface());
107 if (proxies.containsKey(bindingName))
108 {
109 Object proxy = proxies.get(bindingName);
110 BindingInvocationHandler handler = (BindingInvocationHandler) Proxy.getInvocationHandler(proxy);
111 handler.addRouterForInterface(interfaceBinding);
112 }
113 else
114 {
115 Object proxy = Proxy.newProxyInstance(muleContext.getExecutionClassLoader(),
116 new Class[]{interfaceBinding.getInterface()},
117 new BindingInvocationHandler(interfaceBinding));
118 proxies.put(bindingName, proxy);
119 }
120 }
121 }
122 }
123 }