KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > servicemix > components > script > ScriptComponent


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17 package org.apache.servicemix.components.script;
18
19 import java.io.IOException JavaDoc;
20 import java.io.InputStreamReader JavaDoc;
21 import java.util.HashMap JavaDoc;
22 import java.util.Map JavaDoc;
23 import java.util.logging.Logger JavaDoc;
24
25 import javax.jbi.JBIException;
26 import javax.jbi.messaging.InOnly;
27 import javax.jbi.messaging.MessageExchange;
28 import javax.jbi.messaging.MessagingException;
29 import javax.jbi.messaging.NormalizedMessage;
30 import javax.script.Compilable;
31 import javax.script.CompiledScript;
32 import javax.script.Namespace;
33 import javax.script.ScriptEngine;
34 import javax.script.ScriptEngineManager;
35 import javax.script.ScriptException;
36 import javax.xml.namespace.QName JavaDoc;
37
38 import org.apache.servicemix.components.util.TransformComponentSupport;
39 import org.apache.servicemix.jbi.messaging.NormalizedMessageImpl;
40 import org.springframework.core.io.Resource;
41
42 /**
43  * A component which is capable of invoking a compiledScript using
44  * <a HREF="http://servicemix.org/JSR+223">JSR 223</a> to allow any scripting language to be integrated.
45  *
46  * @version $Revision: 426415 $
47  */

48 public class ScriptComponent extends TransformComponentSupport {
49
50     public static final QName JavaDoc SERVICE = new QName JavaDoc("http://servicemix.org/example/", "receiver");
51     public static final String JavaDoc ENDPOINT = "receiver";
52
53     private ScriptEngine engine;
54     private String JavaDoc scriptEngineName;
55     private CompiledScript compiledScript;
56     private String JavaDoc scriptText;
57     private Resource script;
58     private String JavaDoc logResourceBundle;
59
60     private boolean disableOutput;
61     private Logger JavaDoc scriptLogger;
62     private Map JavaDoc bindings = new HashMap JavaDoc();
63
64     public ScriptComponent() {
65         super(SERVICE, ENDPOINT);
66     }
67
68     public ScriptComponent(QName JavaDoc service, String JavaDoc endpoint) {
69         super(service, endpoint);
70     }
71
72     public void start() throws JBIException {
73
74         if (engine == null) {
75             if (compiledScript != null) {
76                 engine = compiledScript.getEngine();
77             }
78             else {
79                 if (scriptEngineName != null) {
80                     engine = createScriptEngine();
81                 }
82                 if (engine == null) {
83                     throw new JBIException("Must be configured with either the 'compiledScript' or 'engine' property");
84                 }
85             }
86         }
87         if (compiledScript == null) {
88             checkScriptTextAvailable();
89         }
90         if (compiledScript == null) {
91             if (engine instanceof Compilable) {
92                 Compilable compilable = (Compilable) engine;
93                 compileScript(compilable);
94             }
95         }
96     }
97
98     // Properties
99
//-------------------------------------------------------------------------
100
public ScriptEngine getEngine() {
101         return engine;
102     }
103
104     public void setEngine(ScriptEngine engine) {
105         this.engine = engine;
106     }
107
108     public CompiledScript getCompiledScript() {
109         return compiledScript;
110     }
111
112     public void setCompiledScript(CompiledScript compiledScript) {
113         this.compiledScript = compiledScript;
114     }
115
116     public String JavaDoc getScriptText() {
117         return scriptText;
118     }
119
120     /**
121      * Sets the script as a String
122      *
123      * @param scriptText
124      */

125     public void setScriptText(String JavaDoc scriptText) {
126         this.scriptText = scriptText;
127     }
128
129     /**
130      * Returns the script as a spring resource
131      *
132      * @return
133      */

134     public Resource getScript() {
135         return script;
136     }
137
138     /**
139      * Sets the script as a Spring resource
140      *
141      * @param script
142      */

143     public void setScript(Resource script) {
144         this.script = script;
145     }
146
147     public String JavaDoc getScriptEngineName() {
148         return scriptEngineName;
149     }
150
151     public void setScriptEngineName(String JavaDoc scriptEngineName) {
152         this.scriptEngineName = scriptEngineName;
153     }
154
155     public boolean isDisableOutput() {
156         return disableOutput;
157     }
158
159     public void setDisableOutput(boolean disableOutput) {
160         this.disableOutput = disableOutput;
161     }
162
163     public String JavaDoc getLogResourceBundle() {
164         return logResourceBundle;
165     }
166
167     public Map JavaDoc getBindings() {
168         return bindings;
169     }
170
171     /**
172      * Sets the component level bindings available to scripts as a variable called 'bindings'
173      *
174      * @param bindings
175      */

176     public void setBindings(Map JavaDoc bindings) {
177         this.bindings = bindings;
178     }
179
180     /**
181      * Sets the resource bundle to use when creating a logger, if one is not
182      * explicitly configured.
183      *
184      * @param logResourceBundle
185      */

186     public void setLogResourceBundle(String JavaDoc logResourceBundle) {
187         this.logResourceBundle = logResourceBundle;
188     }
189
190     public Logger JavaDoc getScriptLogger() throws MessagingException {
191         if (scriptLogger == null) {
192             scriptLogger = createScriptLogger();
193         }
194         return scriptLogger;
195     }
196
197     /**
198      * Sets the logger to use if the script decides to log
199      *
200      * @param scriptLogger
201      */

202     public void setScriptLogger(Logger JavaDoc scriptLogger) {
203         this.scriptLogger = scriptLogger;
204     }
205
206
207     // Implementation methods
208
//-------------------------------------------------------------------------
209
protected boolean transform(MessageExchange exchange, NormalizedMessage in, NormalizedMessage out) throws Exception JavaDoc {
210         Namespace namespace = engine.createNamespace();
211         
212         populateNamespace(namespace, exchange, in, out);
213         try {
214             runScript(namespace);
215             return !isDisableOutput();
216         }
217         catch (ScriptException e) {
218             System.out.println("Caught: " + e);
219             e.printStackTrace();
220             throw new MessagingException("Failed to run compiledScript. Reason: " + e, e);
221         }
222     }
223
224     protected void populateNamespace(Namespace namespace, MessageExchange exchange, NormalizedMessage in, NormalizedMessage out) throws MessagingException {
225         namespace.put("componentContext", getContext());
226         namespace.put("deliveryChannel", getDeliveryChannel());
227         namespace.put("exchange", exchange);
228         namespace.put("inMessage", in);
229         namespace.put("log", getScriptLogger());
230         namespace.put("componentNamespace", namespace);
231         namespace.put("bindings", bindings);
232
233         InOnly outExchange = null;
234         if (isInAndOut(exchange)) {
235             namespace.put("outMessage", out);
236         }
237         else if (!isDisableOutput()) {
238             outExchange = getExchangeFactory().createInOnlyExchange();
239             if (out instanceof NormalizedMessageImpl) {
240                 namespace.put("outExchange", ((NormalizedMessageImpl) out).getExchange());
241             }
242             namespace.put("outMessage", out);
243         }
244     }
245
246     protected Logger JavaDoc createScriptLogger() throws MessagingException {
247         if (logResourceBundle != null) {
248             try {
249                 return getContext().getLogger(getClass().getName(), logResourceBundle);
250             }
251             catch (JBIException e) {
252                 throw new MessagingException(e);
253             }
254         }
255         else {
256         return Logger.getLogger(getClass().getName());
257         } }
258
259     protected void runScript(Namespace namespace) throws ScriptException {
260         if (compiledScript != null) {
261             compiledScript.eval(namespace);
262         }
263         else {
264             evaluteScript(namespace);
265         }
266     }
267
268     protected void evaluteScript(Namespace namespace) throws ScriptException {
269         engine.eval(scriptText, namespace);
270     }
271
272     protected void compileScript(Compilable compilable) throws JBIException {
273         try {
274             if (scriptText != null) {
275                 compiledScript = compilable.compile(scriptText);
276             }
277             else if (script != null) {
278                 compiledScript = compilable.compile(new InputStreamReader JavaDoc(script.getInputStream()));
279
280             }
281         }
282         catch (ScriptException e) {
283             throw new JBIException("Failed to parse compiledScript. Reason: " + e, e);
284         }
285         catch (IOException JavaDoc e) {
286             throw new JBIException("Failed to parse compiledScript. Reason: " + e, e);
287         }
288     }
289
290     protected ScriptEngine createScriptEngine() {
291         ScriptEngineManager manager = new ScriptEngineManager();
292         return manager.getEngineByName(scriptEngineName);
293     }
294
295     protected void checkScriptTextAvailable() throws JBIException {
296         if (scriptText == null) {
297             throw new JBIException("If no 'compiledScript' is specified you must specify the 'scriptText'");
298         }
299     }
300 }
301
Popular Tags