KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > opensymphony > webwork > views > freemarker > FreemarkerResult


1 /*
2  * Copyright (c) 2002-2003 by OpenSymphony
3  * All rights reserved.
4  */

5 /*
6  * Created on 15/04/2004
7  */

8 package com.opensymphony.webwork.views.freemarker;
9
10 import com.opensymphony.webwork.ServletActionContext;
11 import com.opensymphony.webwork.views.util.ResourceUtil;
12 import com.opensymphony.webwork.dispatcher.WebWorkResultSupport;
13 import com.opensymphony.xwork.ActionInvocation;
14 import com.opensymphony.xwork.ActionContext;
15 import com.opensymphony.xwork.util.OgnlValueStack;
16
17 import freemarker.template.*;
18
19 import javax.servlet.ServletContext JavaDoc;
20 import javax.servlet.http.HttpServletRequest JavaDoc;
21 import javax.servlet.http.HttpServletResponse JavaDoc;
22 import java.io.IOException JavaDoc;
23 import java.io.Writer JavaDoc;
24 import java.util.Locale JavaDoc;
25
26
27 /**
28  * @author CameronBraid
29  */

30 public class FreemarkerResult extends WebWorkResultSupport {
31     //~ Instance fields ////////////////////////////////////////////////////////
32

33     protected ActionInvocation invocation;
34     protected Configuration configuration;
35     protected ObjectWrapper wrapper;
36
37     /*
38      * webwork results are constructed for each result execeution
39      *
40      * the current context is availible to subclasses via these protected fields
41      */

42     protected String JavaDoc location;
43     private String JavaDoc pContentType = "text/html";
44
45     //~ Methods ////////////////////////////////////////////////////////////////
46

47     public void setContentType(String JavaDoc aContentType) {
48         pContentType = aContentType;
49     }
50
51     /**
52      * allow parameterization of the contentType
53      * the default being text/html
54      */

55     public String JavaDoc getContentType() {
56         return pContentType;
57     }
58
59     /**
60      * Execute this result, using the specified template location.
61      * <p/>
62      * The template location has already been interoplated for any variable substitutions
63      * <p/>
64      * this method obtains the freemarker configuration and the object wrapper from the provided hooks.
65      * It them implements the template processing workflow by calling the hooks for
66      * preTemplateProcess and postTemplateProcess
67      */

68     public void doExecute(String JavaDoc location, ActionInvocation invocation) throws IOException JavaDoc, TemplateException {
69         this.location = location;
70         this.invocation = invocation;
71         this.configuration = getConfiguration();
72         this.wrapper = getObjectWrapper();
73
74         if (!location.startsWith("/")) {
75             ActionContext ctx = invocation.getInvocationContext();
76             HttpServletRequest JavaDoc req = (HttpServletRequest JavaDoc) ctx.get(ServletActionContext.HTTP_REQUEST);
77             String JavaDoc base = ResourceUtil.getResourceBase(req);
78             location = base + "/" + location;
79         }
80
81         Template template = configuration.getTemplate(location, deduceLocale());
82         TemplateModel model = createModel();
83
84         // Give subclasses a chance to hook into preprocessing
85
if (preTemplateProcess(template, model)) {
86             try {
87                 // Process the template
88
template.process(model, getWriter());
89             } finally {
90                 // Give subclasses a chance to hook into postprocessing
91
postTemplateProcess(template, model);
92             }
93         }
94     }
95
96     /**
97      * This method is called from {@link #doExecute(String, ActionInvocation)} to obtain the
98      * FreeMarker configuration object that this result will use for template loading. This is a
99      * hook that allows you to custom-configure the configuration object in a subclass, or to fetch
100      * it from an IoC container.
101      * <p/>
102      * <b>
103      * The default implementation obtains the configuration from the ConfigurationManager instance.
104      * </b>
105      */

106     protected Configuration getConfiguration() throws TemplateException {
107         return FreemarkerManager.getInstance().getConfigruation(ServletActionContext.getServletContext());
108     }
109
110     /**
111      * This method is called from {@link #doExecute(String, ActionInvocation)} to obtain the
112      * FreeMarker object wrapper object that this result will use for adapting objects into template
113      * models. This is a hook that allows you to custom-configure the wrapper object in a subclass.
114      * <p/>
115      * <b>
116      * The default implementation returns {@link Configuration#getObjectWrapper()}
117      * </b>
118      */

119     protected ObjectWrapper getObjectWrapper() {
120         return configuration.getObjectWrapper();
121     }
122
123     /**
124      * The default writer writes directly to the response writer.
125      */

126     protected Writer JavaDoc getWriter() throws IOException JavaDoc {
127         return ServletActionContext.getResponse().getWriter();
128     }
129
130     /**
131      * Build the instance of the ScopesHashModel, including JspTagLib support
132      * <p/>
133      * Objects added to the model are
134      * <p/>
135      * <ul>
136      * <li>Application - servlet context attributes hash model
137      * <li>JspTaglibs - jsp tag lib factory model
138      * <li>Request - request attributes hash model
139      * <li>Session - session attributes hash model
140      * <li>req - the HttpServletRequst object for direct access
141      * <li>res - the HttpServletResponse object for direct access
142      * <li>stack - the OgnLValueStack instance for direct access
143      * <li>ognl - the instance of the OgnlTool
144      * <li>action - the action itself
145      * <li>exception - optional : the JSP or Servlet exception as per the servlet spec (for JSP Exception pages)
146      * <li>webwork - instance of the WebWorkUtil class
147      * </ul>
148      */

149     protected TemplateModel createModel() throws TemplateModelException {
150         ServletContext JavaDoc servletContext = ServletActionContext.getServletContext();
151         HttpServletRequest JavaDoc request = ServletActionContext.getRequest();
152         HttpServletResponse JavaDoc response = ServletActionContext.getResponse();
153         OgnlValueStack stack = ServletActionContext.getContext().getValueStack();
154         return FreemarkerManager.getInstance().buildTemplateModel(stack, invocation.getAction(), servletContext, request, response, wrapper);
155     }
156
157     /**
158      * Returns the locale used for the
159      * {@link Configuration#getTemplate(String, Locale)} call.
160      * The base implementation simply returns the locale setting of the
161      * configuration. Override this method to provide different behaviour,
162      */

163     protected Locale JavaDoc deduceLocale() {
164         return configuration.getLocale();
165     }
166
167     /**
168      * the default implementation of postTemplateProcess applies the contentType parameter
169      */

170     protected void postTemplateProcess(Template template, TemplateModel data) throws IOException JavaDoc {
171     }
172
173     /**
174      * Called before the execution is passed to template.process().
175      * This is a generic hook you might use in subclasses to perform a specific
176      * action before the template is processed. By default does nothing.
177      * A typical action to perform here is to inject application-specific
178      * objects into the model root
179      *
180      * @return true to process the template, false to suppress template processing.
181      */

182     protected boolean preTemplateProcess(Template template, TemplateModel model) throws IOException JavaDoc {
183         Object JavaDoc attrContentType = template.getCustomAttribute("content_type");
184
185         if (attrContentType != null) {
186             ServletActionContext.getResponse().setContentType(attrContentType.toString());
187         } else {
188             String JavaDoc contentType = getContentType();
189
190             if (contentType == null) {
191                 contentType = "text/html";
192             }
193
194             String JavaDoc encoding = template.getEncoding();
195
196             if (encoding != null) {
197                 contentType = contentType + "; charset=" + encoding;
198             }
199
200             ServletActionContext.getResponse().setContentType(contentType);
201         }
202
203         return true;
204     }
205 }
206
Popular Tags