KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > openedit > modules > scriptrunner > ScriptModule


1 /*
2 Copyright (c) 2003 eInnovation Inc. All rights reserved
3
4 This library is free software; you can redistribute it and/or modify it under the terms
5 of the GNU Lesser General Public License as published by the Free Software Foundation;
6 either version 2.1 of the License, or (at your option) any later version.
7
8 This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
9 without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10 See the GNU Lesser General Public License for more details.
11 */

12
13 /*--
14
15  Copyright (C) 2001-2002 Anthony Eden.
16  All rights reserved.
17
18  */

19 package com.openedit.modules.scriptrunner;
20
21 import java.io.FileNotFoundException JavaDoc;
22 import java.io.IOException JavaDoc;
23 import java.io.Reader JavaDoc;
24 import java.io.StringWriter JavaDoc;
25 import java.util.Iterator JavaDoc;
26 import java.util.Map JavaDoc;
27
28 import javax.servlet.ServletContext JavaDoc;
29 import javax.servlet.http.HttpServletRequest JavaDoc;
30 import javax.servlet.http.HttpServletResponse JavaDoc;
31 import javax.servlet.http.HttpSession JavaDoc;
32
33 import org.apache.bsf.BSFException;
34 import org.apache.bsf.BSFManager;
35 import org.apache.commons.logging.Log;
36 import org.apache.commons.logging.LogFactory;
37 import org.openedit.repository.ContentItem;
38 import org.openedit.repository.filesystem.StringItem;
39 import org.springframework.beans.factory.BeanFactory;
40
41 import com.openedit.OpenEditException;
42 import com.openedit.WebPageRequest;
43 import com.openedit.modules.BaseModule;
44 import com.openedit.page.Page;
45 import com.openedit.page.PageAction;
46 import com.openedit.page.PageRequestKeys;
47 import com.openedit.page.PageStreamer;
48 import com.openedit.util.OutputFiller;
49 import com.openedit.util.PathUtilities;
50 import com.openedit.util.URLUtilities;
51
52 /**
53  * An action which is implemented in a BSF supported scripting language. Script actions have
54  * access to several varibles:
55  *
56  * <p>
57  * These are always available:
58  * </p>
59  *
60  * <p>
61  * <b>site</b> - The SiteContext<br><b>syslog</b> - Standard logging stream (Log4J Category)<br>
62  * </p>
63  *
64  * <p>
65  * If there is a context defined when the action is executed (all actions excluding startup
66  * actions):
67  * </p>
68  *
69  * <p>
70  * <b>context</b> - The current context<br>
71  * <b>application</b> - The ServletContext<br>
72  * <b>request</b> - The HTTP request<br>
73  * <b>response</b> - The HTTP response<br>
74  * <b>session</b> - The HTTP session<br>
75  * <b>page</b> - The Page object<br>
76  * </p>
77  *
78  * @author Anthony Eden
79  * @author Matt Avery, mavery@einnovation.com (converted to Spring framework)
80  */

81 public class ScriptModule extends BaseModule implements PageRequestKeys
82 {
83
84     public static final String JavaDoc SCRIPT_TAG = "script";
85     private static Log log = LogFactory.getLog(ScriptModule.class);
86
87     public ScriptModule()
88     {
89         super();
90     }
91     
92     /**
93      * Execute the action script represented by this ScriptAction.
94      *
95      * @param context The current context
96      *
97      * @throws OpenEditException
98      */

99     public synchronized void run( WebPageRequest context) throws OpenEditException
100     {
101         PageAction inAction = context.getCurrentAction();
102         String JavaDoc code = inAction.getConfig().getChildValue(SCRIPT_TAG);
103         //this could be passed in via the config
104

105         ScriptLogger logger = new ScriptLogger();
106         context.putPageValue("log", logger);
107
108         Map JavaDoc variableMap = context.getPageMap();
109         //TODO: Replace these with an OpenEdit object so they can call OpenEdit.getUserManager()
110

111         String JavaDoc filepath = context.getPath();
112         code = PathUtilities.resolveRelativePath(code, filepath);
113         
114         execScript(variableMap, code);
115     }
116
117     public void execScript(Map JavaDoc variableMap, String JavaDoc code) throws OpenEditException
118     {
119         variableMap.put("userManager", getUserManager() );
120         variableMap.put("moduleManager", getModuleManager() );
121         variableMap.put("pageManager", getPageManager() );
122         variableMap.put("root", getRoot() );
123
124         Script script = loadScript(code);
125         log.info("Executing script: " + script.getDescription());
126         
127         try
128         {
129             if (script.getDescription().endsWith(".js"))
130             {
131                 execWithRhino(script, variableMap);
132
133                 //execWithBsf(context, configuration);
134
}
135             else
136             {
137                 execWithBsf(script, variableMap);
138             }
139         }
140         catch (Exception JavaDoc e)
141         {
142             if ( e instanceof OpenEditException )
143             {
144                 throw (OpenEditException)e;
145             }
146             throw new OpenEditException(e);
147         }
148     }
149     
150     public Script loadScript(String JavaDoc code) throws OpenEditException
151     {
152         try
153         {
154
155             Page scriptPage = getPageManager().getPage( code );
156
157             Reader JavaDoc in = scriptPage.getReader();
158             StringWriter JavaDoc out = new StringWriter JavaDoc();
159             new OutputFiller().fill(in,out);
160             in.close();
161             out.close();
162             String JavaDoc text = out.toString();
163             Script script = new Script(text, code);
164             return script;
165         }
166         catch (Exception JavaDoc ex)
167         {
168             throw new OpenEditException(ex);
169         }
170     }
171     
172     public void saveScript(String JavaDoc code, String JavaDoc filepath, String JavaDoc inScript) throws OpenEditException
173     {
174         try
175         {
176             String JavaDoc relativecode = PathUtilities.buildRelative(code, filepath);
177             Page scriptPage = getPageManager().getPage( relativecode );
178             ContentItem scriptItem = new StringItem( relativecode, inScript,scriptPage.getCharacterEncoding() );
179             scriptPage.setContentItem( scriptItem );
180             getPageManager().putPage( scriptPage );
181         }
182         catch (Exception JavaDoc ex)
183         {
184             throw new OpenEditException(ex);
185         }
186     }
187
188     /**
189      * DOCUMENT ME!
190      *
191      * @param runner
192      * @param context
193      *
194      * @throws ScriptException DOCME
195      */

196     protected void declareAll(ScriptRunner runner, Map JavaDoc context) throws OpenEditException
197     {
198         if (context != null)
199         {
200             for (Iterator JavaDoc iter = context.keySet().iterator(); iter.hasNext();)
201             {
202                 String JavaDoc element = (String JavaDoc) iter.next();
203                 runner.declareBean((String JavaDoc) element, context.get(element));
204             }
205         }
206         runner.declareBean( "beanFactory", getBeanFactory());
207     }
208
209     protected void execWithBsf(Script script, Map JavaDoc context)
210         throws BSFException, IOException JavaDoc, FileNotFoundException JavaDoc
211     {
212         BSFManager bsfManager = new BSFManager();
213
214         // expose standard items in the context
215
if (context != null)
216         {
217             //TODO: Why not add all the items in there? Performance?
218
ServletContext JavaDoc application = (ServletContext JavaDoc) context.get(SERVLET_CONTEXT);
219             HttpServletRequest JavaDoc request = (HttpServletRequest JavaDoc) context.get(REQUEST);
220             HttpServletResponse JavaDoc response = (HttpServletResponse JavaDoc) context.get(RESPONSE);
221             HttpSession JavaDoc session = (HttpSession JavaDoc) context.get(SESSION);
222             Page page = (Page) context.get(PAGE);
223             PageStreamer pages = (PageStreamer) context.get(PAGES);
224
225             // expose the context
226
bsfManager.declareBean("context", context.get("context"), WebPageRequest.class);
227             bsfManager.declareBean(URL_UTILITIES, context.get(URL_UTILITIES), URLUtilities.class);
228
229             // expose the page object.
230
if (page == null)
231             {
232                 log.debug("Page request is null");
233             }
234             else
235             {
236                 bsfManager.declareBean(PAGE, page, Page.class);
237             }
238
239             // expose the pages object.
240
if (pages == null)
241             {
242                 log.debug("Pages request is null");
243             }
244             else
245             {
246                 bsfManager.declareBean(PAGES, pages, PageStreamer.class);
247             }
248
249             // expose standard HttpServlet objects
250
if (request == null)
251             {
252                 log.debug("HTTP request is null");
253             }
254             else
255             {
256                 bsfManager.declareBean(REQUEST, request, HttpServletRequest JavaDoc.class);
257             }
258
259             if (response == null)
260             {
261                 log.debug("HTTP response is null");
262             }
263             else
264             {
265                 bsfManager.declareBean(RESPONSE, response, HttpServletResponse JavaDoc.class);
266             }
267
268             if (session == null)
269             {
270                 log.debug("HTTP session is null");
271             }
272             else
273             {
274                 bsfManager.declareBean(SESSION, session, HttpSession JavaDoc.class);
275             }
276
277             if (application == null)
278             {
279                 log.debug("ServletContext is null");
280             }
281             else
282             {
283                 bsfManager.declareBean(SERVLET_CONTEXT, application, ServletContext JavaDoc.class);
284             }
285             
286             //bsfManager.declareBean( PAGEMANAGER, getPageManager(), PageManager.class );
287
//bsfManager.declareBean( USERMANAGER, getUserManager(), UserManager.class );
288
bsfManager.declareBean( "beanFactory", getBeanFactory(), BeanFactory.class );
289         }
290
291         // these objects are exposed regardless if there is a context
292
// object or not. In other words they are accesible to startup
293
// actions
294
//bsfManager.declareBean("syslog", LogSystem.syslog, Logger.class);
295
//bsfManager.declareBean("site", getSiteContext(), SiteContext.class);
296

297         // if(configuration == null){
298
// log.debug("Configuration is null");
299
// } else {
300
// bsfManager.declareBean("configuration", configuration, Configuration.class);
301
// }
302
bsfManager.exec(
303             BSFManager.getLangFromFilename(script.getDescription()),
304             script.getDescription(),
305             0,
306             0,
307             script.getScriptText());
308     }
309
310     protected void execWithRhino(Script inScript, Map JavaDoc inState) throws Exception JavaDoc
311     {
312
313         ScriptRunner runner = new RhinoScriptRunner(inScript);
314
315         //runner.declareBean("context", context);
316
declareAll(runner, inState);
317         runner.init();
318         runner.terminate();
319
320         //CB One day we should be able to call functions within a single cached JavaScript file
321
//that would be really cool! the syntax could be ./myfile.js#somefunction
322
}
323
324
325 }
326
Popular Tags