KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > webapp > ftl > FreeMarkerViewHandler


1 /*
2  * $Id: FreeMarkerViewHandler.java 5462 2005-08-05 18:35:48Z jonesde $
3  *
4  * Copyright (c) 2001-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.ftl;
26
27 import java.io.File JavaDoc;
28 import java.io.IOException JavaDoc;
29 import java.util.HashMap JavaDoc;
30 import java.util.Map JavaDoc;
31
32 import javax.servlet.ServletContext JavaDoc;
33 import javax.servlet.http.HttpServletRequest JavaDoc;
34 import javax.servlet.http.HttpServletResponse JavaDoc;
35 import javax.servlet.http.HttpSession JavaDoc;
36
37 import org.jpublish.view.freemarker.JPublishTemplateLoader;
38 import org.ofbiz.base.util.UtilHttp;
39 import org.ofbiz.base.util.template.FreeMarkerWorker;
40 import org.ofbiz.webapp.view.ViewHandler;
41 import org.ofbiz.webapp.view.ViewHandlerException;
42
43 import freemarker.ext.beans.BeansWrapper;
44 import freemarker.ext.jsp.TaglibFactory;
45 import freemarker.ext.servlet.HttpRequestHashModel;
46 import freemarker.ext.servlet.HttpSessionHashModel;
47 import freemarker.template.Configuration;
48 import freemarker.template.SimpleHash;
49 import freemarker.template.Template;
50 import freemarker.template.TemplateException;
51 import freemarker.template.WrappingTemplateModel;
52
53
54 /**
55  * FreemarkerViewHandler - Freemarker Template Engine View Handler
56  *
57  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
58  * @version $Rev: 5462 $
59  * @since 2.1
60  */

61 public class FreeMarkerViewHandler implements ViewHandler {
62     
63     public static final String JavaDoc module = FreeMarkerViewHandler.class.getName();
64     
65     protected ServletContext JavaDoc servletContext = null;
66     protected Configuration config = null;
67
68     public void init(ServletContext JavaDoc context) throws ViewHandlerException {
69         this.servletContext = context;
70
71         config = new freemarker.template.Configuration();
72
73         JPublishTemplateLoader templateLoader = new JPublishTemplateLoader();
74         //templateLoader.setSiteContext(siteContext);
75
config.setTemplateLoader(templateLoader);
76         config.setLocalizedLookup(false);
77         
78         //nice thought, but doesn't do auto reloading with this: config.setServletContextForTemplateLoading(context, "/");
79
try {
80             config.setDirectoryForTemplateLoading(new File JavaDoc(context.getRealPath("/")));
81         } catch (java.io.IOException JavaDoc e) {
82             throw new ViewHandlerException("Could not create file for webapp root path", e);
83         }
84         WrappingTemplateModel.setDefaultObjectWrapper(BeansWrapper.getDefaultInstance());
85         try {
86             config.setObjectWrapper(BeansWrapper.getDefaultInstance());
87             config.setCacheStorage(new OfbizCacheStorage("unknown"));
88             config.setSetting("datetime_format", "yyyy-MM-dd HH:mm:ss.SSS");
89         } catch (TemplateException e) {
90             throw new ViewHandlerException("Freemarker TemplateException", e.getCause());
91         }
92     }
93     
94     public void render(String JavaDoc name, String JavaDoc page, String JavaDoc info, String JavaDoc contentType, String JavaDoc encoding,
95             HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws ViewHandlerException {
96         if (page == null || page.length() == 0)
97             throw new ViewHandlerException("Invalid template source");
98         
99         // make the root context (data model) for freemarker
100
SimpleHash root = new SimpleHash(BeansWrapper.getDefaultInstance());
101         prepOfbizRoot(root, request, response);
102                        
103         // get the template
104
Template template = null;
105         try {
106             template = config.getTemplate(page, UtilHttp.getLocale(request));
107         } catch (IOException JavaDoc e) {
108             throw new ViewHandlerException("Cannot open template file: " + page, e);
109         }
110         template.setObjectWrapper(BeansWrapper.getDefaultInstance());
111         
112         // process the template & flush the output
113
try {
114             template.process(root, response.getWriter(), BeansWrapper.getDefaultInstance());
115             response.flushBuffer();
116         } catch (TemplateException te) {
117             throw new ViewHandlerException("Problems processing Freemarker template", te);
118         } catch (IOException JavaDoc ie) {
119             throw new ViewHandlerException("Problems writing to output stream", ie);
120         }
121     }
122     
123     public static void prepOfbizRoot(SimpleHash root, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
124         Map JavaDoc rootPrep = new HashMap JavaDoc();
125         prepOfbizRoot(rootPrep, request, response);
126         root.putAll(rootPrep);
127     }
128     
129     public static void prepOfbizRoot(Map JavaDoc root, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
130         ServletContext JavaDoc servletContext = (ServletContext JavaDoc) request.getAttribute("servletContext");
131         HttpSession JavaDoc session = request.getSession();
132         
133         BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
134         
135         // add in the OFBiz objects
136
root.put("delegator", request.getAttribute("delegator"));
137         root.put("dispatcher", request.getAttribute("dispatcher"));
138         root.put("security", request.getAttribute("security"));
139         root.put("userLogin", session.getAttribute("userLogin"));
140
141         // add the response object (for transforms) to the context as a BeanModel
142
root.put("response", response);
143             
144         // add the application object (for transforms) to the context as a BeanModel
145
root.put("application", servletContext);
146             
147         // add the servlet context -- this has been deprecated, and now requires servlet, do we really need it?
148
//root.put("applicationAttributes", new ServletContextHashModel(servletContext, BeansWrapper.getDefaultInstance()));
149

150         // add the session object (for transforms) to the context as a BeanModel
151
root.put("session", session);
152
153         // add the session
154
root.put("sessionAttributes", new HttpSessionHashModel(session, wrapper));
155
156         // add the request object (for transforms) to the context as a BeanModel
157
root.put("request", request);
158
159         // add the request
160
root.put("requestAttributes", new HttpRequestHashModel(request, wrapper));
161
162         // add the request parameters -- this now uses a Map from UtilHttp
163
Map JavaDoc requestParameters = UtilHttp.getParameterMap(request);
164         root.put("requestParameters", requestParameters);
165            
166         // add the TabLibFactory
167
TaglibFactory JspTaglibs = new TaglibFactory(servletContext);
168         root.put("JspTaglibs", JspTaglibs);
169
170         FreeMarkerWorker.addAllOfbizTransforms(root);
171     }
172 }
173
Popular Tags