KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > webapp > view > JPublishWrapper


1 /*
2  * $Id: JPublishWrapper.java 5462 2005-08-05 18:35:48Z jonesde $
3  *
4  * Copyright (c) 2003 The Open For Business Project - www.ofbiz.org
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included
14  * in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
21  * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  *
24  */

25 package org.ofbiz.webapp.view;
26
27 import java.io.File JavaDoc;
28 import java.io.FileNotFoundException JavaDoc;
29 import java.io.IOException JavaDoc;
30 import java.io.OutputStream JavaDoc;
31 import java.io.StringWriter JavaDoc;
32 import java.io.Writer JavaDoc;
33 import java.security.AccessController JavaDoc;
34 import java.security.PrivilegedAction JavaDoc;
35 import java.util.Iterator JavaDoc;
36 import javax.servlet.ServletContext JavaDoc;
37 import javax.servlet.http.HttpServletRequest JavaDoc;
38 import javax.servlet.http.HttpServletResponse JavaDoc;
39 import javax.servlet.http.HttpSession JavaDoc;
40
41 import org.ofbiz.base.util.Debug;
42 import org.ofbiz.base.util.GeneralException;
43
44 import org.jpublish.JPublishContext;
45 import org.jpublish.Page;
46 import org.jpublish.Repository;
47 import org.jpublish.RepositoryWrapper;
48 import org.jpublish.SiteContext;
49 import org.jpublish.StaticResourceManager;
50 import org.jpublish.Template;
51 import org.jpublish.action.ActionManager;
52 import org.jpublish.component.ComponentMap;
53 import org.jpublish.page.PageInstance;
54 import org.jpublish.util.CharacterEncodingMap;
55 import org.jpublish.util.DateUtilities;
56 import org.jpublish.util.NumberUtilities;
57 import org.jpublish.util.URLUtilities;
58
59 /**
60  * JPublishWrapper - Used for calling pages through JPublish
61  *
62  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
63  * @version $Rev: 5462 $
64  * @since 2.2
65  */

66 public class JPublishWrapper {
67     
68     public static final String JavaDoc module = JPublishWrapper.class.getName();
69     
70     protected ServletContext JavaDoc servletContext = null;
71     protected SiteContext siteContext = null;
72     
73     public JPublishWrapper(ServletContext JavaDoc context) {
74         this.servletContext = context;
75         // find the WEB-INF root
76
String JavaDoc rootDir = servletContext.getRealPath("/");
77         File JavaDoc contextRoot = new File JavaDoc(rootDir);
78         File JavaDoc webInfPath = new File JavaDoc(contextRoot, "WEB-INF");
79
80         // configure the classpath for scripting support
81
configureClasspath(webInfPath);
82
83         // create the site context
84
try {
85             //siteContext = new SiteContext(contextRoot, servletConfig.getInitParameter("config"));
86
siteContext = new SiteContext(contextRoot, "WEB-INF/jpublish.xml");
87             siteContext.setWebInfPath(webInfPath);
88         } catch (Exception JavaDoc e) {
89             Debug.logError(e, "Cannot load SiteContext", module);
90         }
91
92         // execute startup actions
93
try {
94             ActionManager actionManager = siteContext.getActionManager();
95             actionManager.executeStartupActions();
96         } catch (Exception JavaDoc e) {
97             Debug.logError(e, "Problems executing JPublish startup actions", module);
98         }
99         
100         // set this wrapper in the ServletContext for use by the ViewHandler
101
servletContext.setAttribute("jpublishWrapper", this);
102     }
103     
104     protected void configureClasspath(File JavaDoc webInfPath) {
105         File JavaDoc webLibPath = new File JavaDoc(webInfPath, "lib");
106         File JavaDoc webClassPath = new File JavaDoc(webInfPath, "classes");
107
108         // add WEB-INF/classes to the classpath
109
StringBuffer JavaDoc classPath = new StringBuffer JavaDoc();
110         classPath.append(System.getProperty("java.class.path"));
111
112         if (webClassPath.exists()) {
113             classPath.append(System.getProperty("path.separator"));
114             classPath.append(webClassPath);
115         }
116
117         // add WEB-INF/lib files to the classpath
118
if (webLibPath.exists()) {
119             File JavaDoc[] files = webLibPath.listFiles();
120             for (int i = 0; i < files.length; i++) {
121                 if (files[i].getName().toLowerCase().endsWith(".jar")
122                     || files[i].getName().toLowerCase().endsWith(".zip")) {
123                     classPath.append(System.getProperty("path.separator"));
124                     classPath.append(files[i]);
125                 }
126             }
127         }
128
129         AccessController.doPrivileged(new SetClassPathAction(classPath.toString()));
130     }
131
132     protected boolean executeGlobalActions(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, JPublishContext context, String JavaDoc path, boolean allowRedirect) throws Exception JavaDoc {
133         ActionManager actionManager = siteContext.getActionManager();
134         return optionalRedirect(actionManager.executeGlobalActions(context), path, response, allowRedirect);
135     }
136
137     protected boolean executePathActions(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, JPublishContext context, String JavaDoc path, boolean allowRedirect) throws Exception JavaDoc {
138         ActionManager actionManager = siteContext.getActionManager();
139         return optionalRedirect(actionManager.executePathActions(path, context), path, response, allowRedirect);
140     }
141
142     protected boolean executeParameterActions(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, JPublishContext context, String JavaDoc path, boolean allowRedirect) throws Exception JavaDoc {
143         if (!siteContext.isParameterActionsEnabled()) {
144             return false;
145         }
146
147         ActionManager actionManager = siteContext.getActionManager();
148         String JavaDoc[] actionNames = request.getParameterValues(siteContext.getActionIdentifier());
149         if (actionNames != null) {
150             for (int i = 0; i < actionNames.length; i++) {
151                 return optionalRedirect(actionManager.execute(actionNames[i], context), path, response, allowRedirect);
152             }
153         }
154         return false;
155     }
156
157     protected boolean executePreEvaluationActions(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, JPublishContext context, String JavaDoc path) throws Exception JavaDoc {
158         ActionManager actionManager = siteContext.getActionManager();
159         return actionManager.executePreEvaluationActions(path, context);
160     }
161
162     protected boolean executePostEvaluationActions(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, JPublishContext context, String JavaDoc path) throws Exception JavaDoc {
163         ActionManager actionManager = siteContext.getActionManager();
164         actionManager.executePostEvaluationActions(path, context);
165         return false;
166     }
167
168     private boolean optionalRedirect(String JavaDoc redirect, String JavaDoc path, HttpServletResponse JavaDoc response, boolean allowRedirect) throws IOException JavaDoc {
169         if (redirect != null && allowRedirect) {
170             response.sendRedirect(redirect);
171             return true;
172         }
173         return false;
174     }
175     
176     /**
177      * Renders a page and returns the string containing the content of the rendered page
178      * @param path Path to the page
179      * @param request HttpServletRequest object for page prep
180      * @param response HttpServletResponse object (not used for writing).
181      * @return a String containing the rendered page
182      * @throws GeneralException
183      */

184     public String JavaDoc render(String JavaDoc path, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws GeneralException {
185         Writer JavaDoc writer = new StringWriter JavaDoc();
186         String JavaDoc content = null;
187         render(path, request, response, writer);
188         try {
189             content = writer.toString();
190             writer.close();
191         } catch (IOException JavaDoc e) {
192             throw new GeneralException("Problems closing the Writer", e);
193         }
194         return content;
195     }
196     
197     public void render(String JavaDoc path, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, Writer JavaDoc writer) throws GeneralException {
198         render(path, request, response, writer, null, false);
199     }
200     
201     public void render(String JavaDoc path, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, Writer JavaDoc writer, OutputStream JavaDoc outputStream) throws GeneralException {
202         render(path, request, response, writer, outputStream, false);
203     }
204
205     public void render(String JavaDoc path, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, Writer JavaDoc writer, OutputStream JavaDoc outputStream, boolean allowRedirect) throws GeneralException {
206         HttpSession JavaDoc session = request.getSession();
207         ActionManager actionManager = siteContext.getActionManager();
208         //String path = servletContext.getRealPath(pagePath);
209
//Debug.logError("Path:" + path, module);
210

211         // get the character encoding map
212
CharacterEncodingMap characterEncodingMap = siteContext.getCharacterEncodingManager().getMap(path);
213
214         // put standard servlet stuff into the context
215
JPublishContext context = new JPublishContext(this);
216         context.put("request", request);
217         context.put("response", response);
218         context.put("session", session);
219         context.put("application", servletContext);
220
221         // add the character encoding map to the context
222
context.put("characterEncodingMap", characterEncodingMap);
223
224         // add the URLUtilities to the context
225
URLUtilities urlUtilities = new URLUtilities(request, response);
226         context.put("urlUtilities", urlUtilities);
227
228         // add the DateUtilities to the context
229
context.put("dateUtilities", DateUtilities.getInstance());
230
231         // add the NumberUtilities to the context
232
context.put("numberUtilities", NumberUtilities.getInstance());
233
234         // add the messages log to the context
235
context.put("syslog", SiteContext.syslog);
236
237         // expose the SiteContext
238
context.put("site", siteContext);
239
240         if (siteContext.isProtectReservedNames()) {
241             context.enableCheckReservedNames(this);
242         }
243
244         // add the repositories to the context
245
Iterator JavaDoc repositories = siteContext.getRepositories().iterator();
246         while (repositories.hasNext()) {
247             Repository repository = (Repository) repositories.next();
248             context.put(repository.getName(), new RepositoryWrapper(repository, context));
249             // add the fs_repository also as the name 'pages' so we can use existing logic in pages
250
// note this is a hack and we should look at doing this a different way; but first need
251
// to investigate how to get content from different repositories
252
if (repository.getName().equals("fs_repository")) {
253                 context.put("pages", new RepositoryWrapper(repository, context));
254             }
255         }
256
257         try {
258             if (executePreEvaluationActions(request, response, context, path))
259                 return;
260
261             // if the page is static
262
StaticResourceManager staticResourceManager = siteContext.getStaticResourceManager();
263             if (staticResourceManager.resourceExists(path)) {
264                 if (outputStream != null) {
265                     // execute the global actions
266
if (executeGlobalActions(request, response, context, path, allowRedirect))
267                         return;
268
269                     // execute path actions
270
if (executePathActions(request, response, context, path, allowRedirect))
271                         return;
272     
273                     // execute parameter actions
274
if (executeParameterActions(request, response, context, path, allowRedirect))
275                         return;
276
277                     // load and return the static resource
278
staticResourceManager.load(path, outputStream);
279                     outputStream.flush();
280                     return;
281                 } else {
282                     throw new GeneralException("Cannot load static resource with a null OutputStream");
283                 }
284             }
285             
286             // check and make sure we have a writer
287
if (writer == null)
288                 throw new GeneralException("Cannot load dynamic content with a null Writer");
289
290             // load the page
291
PageInstance pageInstance = siteContext.getPageManager().getPage(path);
292             Page page = new Page(pageInstance);
293
294             context.disableCheckReservedNames(this);
295
296             // expose the page in the context
297
context.put("page", page);
298
299             // expose components in the context
300
context.put("components", new ComponentMap(context));
301
302             if (siteContext.isProtectReservedNames()) {
303                 context.enableCheckReservedNames(this);
304             }
305
306             // execute the global actions
307
if (executeGlobalActions(request, response, context, path, allowRedirect))
308                 return;
309
310             // execute path actions
311
if (executePathActions(request, response, context, path, allowRedirect))
312                 return;
313
314             // execute parameter actions
315
if (executeParameterActions(request, response, context, path, allowRedirect))
316                 return;
317
318             // execute the page actions
319
if (optionalRedirect(page.executeActions(context), path, response, allowRedirect))
320                 return;
321
322             // get the template
323
Template template = siteContext.getTemplateManager().getTemplate(page.getFullTemplateName());
324            
325             // merge the template
326
template.merge(context, page, writer);
327             writer.flush();
328         } catch (FileNotFoundException JavaDoc e) {
329             throw new GeneralException("File not found", e);
330         } catch (Exception JavaDoc e) {
331             throw new GeneralException("JPublish execution error", e);
332         } finally {
333             try {
334                 executePostEvaluationActions(request, response, context, path);
335             } catch (Exception JavaDoc e) {
336                 throw new GeneralException("Error executing JPublish post evaluation actions", e);
337             }
338         }
339     }
340
341     /**
342      * Privleged action for setting the class path. This is used to get around
343      * the Java security system to set the class path so scripts have full
344      * access to all loaded Java classes.
345      *
346      * <p>Note: This functionality is untested.</p>
347      *
348      * @author Anthony Eden
349      */

350     class SetClassPathAction implements PrivilegedAction JavaDoc {
351         private String JavaDoc classPath;
352
353         /**
354          * Construct the action to set the class path.
355          * @param classPath The new class path
356          */

357         public SetClassPathAction(String JavaDoc classPath) {
358             this.classPath = classPath;
359         }
360
361         /**
362          * Set the "java.class.path" property.
363          * @return Returns null
364          */

365         public Object JavaDoc run() {
366             System.setProperty("java.class.path", classPath);
367             return null; // nothing to return
368
}
369     }
370 }
371
Popular Tags