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