KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > opensymphony > webwork > portlet > servlet > WebWorkAbstractServlet


1 /*
2  * Copyright (c) 2005 Opensymphony. All Rights Reserved.
3  */

4 package com.opensymphony.webwork.portlet.servlet;
5
6 import com.opensymphony.module.sitemesh.*;
7 import com.opensymphony.module.sitemesh.filter.PageResponseWrapper;
8 import com.opensymphony.module.sitemesh.util.Container;
9 import com.opensymphony.module.sitemesh.util.OutputConverter;
10 import com.opensymphony.util.TextUtils;
11 import com.opensymphony.webwork.ServletActionContext;
12 import com.opensymphony.webwork.portlet.util.FileUtils;
13 import com.opensymphony.webwork.portlet.util.GeneralUtil;
14 import com.opensymphony.webwork.portlet.velocity.VelocityManager;
15 import com.opensymphony.xwork.ActionContext;
16 import com.opensymphony.xwork.util.OgnlValueStack;
17 import org.apache.velocity.Template;
18 import org.apache.velocity.app.VelocityEngine;
19 import org.apache.velocity.context.Context;
20
21 import javax.servlet.RequestDispatcher JavaDoc;
22 import javax.servlet.ServletConfig JavaDoc;
23 import javax.servlet.ServletContext JavaDoc;
24 import javax.servlet.ServletException JavaDoc;
25 import javax.servlet.http.HttpServlet JavaDoc;
26 import javax.servlet.http.HttpServletRequest JavaDoc;
27 import javax.servlet.http.HttpServletResponse JavaDoc;
28 import java.io.IOException JavaDoc;
29 import java.io.PrintWriter JavaDoc;
30 import java.io.StringWriter JavaDoc;
31
32 /**
33  * @author <a HREF="mailto:hu_pengfei@yahoo.com.cn"> Henry Hu </a>
34  * @since 2005-7-6
35  */

36 public abstract class WebWorkAbstractServlet extends HttpServlet JavaDoc implements RequestConstants {
37     //~ Instance fields
38
// ////////////////////////////////////////////////////////
39

40     private VelocityManager velocityManager;
41
42     private Factory factory = null;
43
44     private ServletConfig JavaDoc servletConfig = null;
45
46     private static final TextUtils TEXT_UTILS = new TextUtils();
47
48     private static final FileUtils FILE_UTILS = new FileUtils();
49
50     private static final GeneralUtil GENERAL_UTIL = new GeneralUtil();
51
52     //~ Constructors
53
// ///////////////////////////////////////////////////////////
54

55     public WebWorkAbstractServlet() {
56         velocityManager = VelocityManager.getInstance();
57     }
58
59     //~ Methods
60
// ////////////////////////////////////////////////////////////////
61

62     protected abstract void doRequest(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws ServletException JavaDoc, IOException JavaDoc;
63
64     public void init(ServletConfig JavaDoc servletConfig) throws ServletException JavaDoc {
65         super.init(servletConfig);
66
67         this.servletConfig = servletConfig;
68         factory = Factory.getInstance(new Config JavaDoc(servletConfig));
69
70         servletConfig.getServletContext().setAttribute("webwork.servlet", this);
71
72         //Initialize VelocityEngine@VelocityManager
73
VelocityManager.getInstance().init(getServletContext());
74     }
75
76     public void doGet(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws ServletException JavaDoc, IOException JavaDoc {
77         doFilter(request, response);
78     }
79
80     public void doPost(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws ServletException JavaDoc, IOException JavaDoc {
81         doFilter(request, response);
82     }
83
84     protected void service(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws ServletException JavaDoc, IOException JavaDoc {
85         doFilter(request, response);
86     }
87
88     public void doFilter(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws IOException JavaDoc, ServletException JavaDoc {
89
90         //Prepare the SiteMesh factory for ApplyDecoratorDirective to use.
91
com.opensymphony.webwork.portlet.context.PortletContext.getContext().setSiteMeshFactory(factory);
92
93         OgnlValueStack stack = ActionContext.getContext().getValueStack();
94
95         request.setAttribute(ServletActionContext.WEBWORK_VALUESTACK_KEY, stack);
96         stack.getContext().put(ServletActionContext.HTTP_REQUEST, request);
97         stack.getContext().put(ServletActionContext.HTTP_RESPONSE, response);
98         stack.getContext().put(ServletActionContext.SERVLET_CONTEXT, getServletContext());
99
100         //if (request.getAttribute(FILTER_APPLIED) != null ||
101
// factory.isPathExcluded(extractRequestPath(request))) {
102
if (factory.isPathExcluded(extractRequestPath(request))) {
103             // ensure that filter is only applied once per request
104
doRequest(request, response);
105         } else {
106             ////////////////////Fix for Jetspeed/Tomcat ///////////////////////
107
//request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
108

109             // force creation of the session now because Tomcat 4 had problems
110
// with
111
// creating sessions after the response had been committed
112
if (Container.get() == Container.TOMCAT) {
113                 request.getSession(true);
114             }
115
116             // parse data into Page object (or continue as normal if Page not
117
// parseable)
118
Page page = parsePage(request, response);
119
120             if (page != null) {
121                 page.setRequest(request);
122
123                 Decorator decorator = factory.getDecoratorMapper().getDecorator(request, page);
124                 if (decorator != null && decorator.getPage() != null) {
125                     applyDecorator(page, decorator, request, response);
126                     page = null;
127                     return;
128                 }
129
130                 // if we got here, an exception occured or the decorator was
131
// null,
132
// what we don't want is an exception printed to the user, so
133
// we write the original page
134
writeOriginal(request, response, page);
135                 page = null;
136             }
137
138         }
139     }
140
141     protected void applyDecorator(Page page, Decorator decorator, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
142             throws ServletException JavaDoc, IOException JavaDoc {
143
144         String JavaDoc decoratorPageName = decorator.getPage();
145
146         if (decoratorPageName.lastIndexOf(".jsp") >= 0) {
147             applyDecoratorUsingJSP(page, decorator, request, response);
148         } else if (decoratorPageName.lastIndexOf(".vm") >= 0) {
149             applyDecoratorUsingVelocity(request, page, response, decorator);
150         }
151     }
152
153     private String JavaDoc extractRequestPath(HttpServletRequest JavaDoc request) {
154         String JavaDoc servletPath = request.getServletPath();
155         String JavaDoc pathInfo = request.getPathInfo();
156         String JavaDoc query = request.getQueryString();
157         return (servletPath == null ? "" : servletPath) + (pathInfo == null ? "" : pathInfo) + (query == null ? "" : ("?" + query));
158     }
159
160     /**
161      * Continue in filter-chain, writing all content to buffer and parsing into
162      * returned {@link com.opensymphony.module.sitemesh.Page}object. If
163      * {@link com.opensymphony.module.sitemesh.Page}is not parseable, null is
164      * returned.
165      */

166     protected Page parsePage(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws IOException JavaDoc, ServletException JavaDoc {
167         try {
168             PageResponseWrapper pageResponse = new PageResponseWrapper(response, factory);
169             doRequest(request, pageResponse);
170             // check if another servlet or filter put a page object to the
171
// request
172
Page result = (Page) request.getAttribute(PAGE);
173             if (result == null) {
174                 // parse the page
175
result = pageResponse.getPage();
176             }
177             request.setAttribute(USING_STREAM, new Boolean JavaDoc(pageResponse.isUsingStream()));
178             return result;
179         } catch (IllegalStateException JavaDoc e) {
180             // weblogic throws an IllegalStateException when an error page is
181
// served.
182
// it's ok to ignore this, however for all other containers it
183
// should be thrown
184
// properly.
185
if (Container.get() != Container.WEBLOGIC)
186                 throw e;
187             return null;
188         }
189     }
190
191     /**
192      * Write the original page data to the response.
193      */

194     private void writeOriginal(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, Page page) throws IOException JavaDoc {
195         response.setContentLength(page.getContentLength());
196         if (request.getAttribute(USING_STREAM).equals(Boolean.TRUE)) {
197             PrintWriter JavaDoc writer = new PrintWriter JavaDoc(response.getOutputStream());
198             page.writePage(writer);
199             //flush writer to underlying outputStream
200
writer.flush();
201             response.getOutputStream().flush();
202         } else {
203             page.writePage(response.getWriter());
204             response.getWriter().flush();
205         }
206     }
207
208     /**
209      * Apply {@link com.opensymphony.module.sitemesh.Decorator}to
210      * {@link com.opensymphony.module.sitemesh.Page}and write to the response.
211      */

212     protected void applyDecoratorUsingJSP(Page page, Decorator decorator, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
213             throws ServletException JavaDoc, IOException JavaDoc {
214         try {
215             request.setAttribute(PAGE, page);
216             ServletContext JavaDoc context = getServletContext();
217             // see if the URI path (webapp) is set
218
if (decorator.getURIPath() != null) {
219                 // in a security conscious environment, the servlet container
220
// may return null for a given URL
221
if (context.getContext(decorator.getURIPath()) != null) {
222                     context = context.getContext(decorator.getURIPath());
223                 }
224             }
225             // get the dispatcher for the decorator
226
RequestDispatcher JavaDoc dispatcher = context.getRequestDispatcher(decorator.getPage());
227             // create a wrapper around the response
228
dispatcher.include(request, response);
229
230             // set the headers specified as decorator init params
231
while (decorator.getInitParameterNames().hasNext()) {
232                 String JavaDoc initParam = (String JavaDoc) decorator.getInitParameterNames().next();
233                 if (initParam.startsWith("header.")) {
234                     response.setHeader(initParam.substring(initParam.indexOf('.')), decorator.getInitParameter(initParam));
235                 }
236             }
237
238             request.removeAttribute(PAGE);
239         } catch (RuntimeException JavaDoc e) {
240             // added a print message here because otherwise Tomcat swallows
241
// the error and you never see it = bad!
242
if (Container.get() == Container.TOMCAT)
243                 e.printStackTrace();
244
245             throw e;
246         }
247     }
248
249     protected void applyDecoratorUsingVelocity(HttpServletRequest JavaDoc request, Page page, HttpServletResponse JavaDoc response, Decorator decorator)
250             throws IOException JavaDoc {
251         try {
252             request.setAttribute(PAGE, page);
253             Context context = VelocityManager.getInstance().createContext(ActionContext.getContext().getValueStack(), request, response);
254
255             context.put("textUtils", TEXT_UTILS);
256             context.put("fileUtil", FILE_UTILS);
257             context.put("generalUtil", GENERAL_UTIL);
258
259             context.put("page", page);
260             context.put("title", page.getTitle());
261
262             StringWriter JavaDoc buffer = new StringWriter JavaDoc();
263             page.writeBody(OutputConverter.getWriter(buffer));
264             context.put("body", buffer.toString());
265
266             if (page instanceof HTMLPage) {
267                 HTMLPage htmlPage = (HTMLPage) page;
268                 buffer = new StringWriter JavaDoc();
269                 htmlPage.writeHead(OutputConverter.getWriter(buffer));
270                 context.put("head", buffer.toString());
271             }
272
273             //Rendering the content
274
VelocityEngine velocityEngine = VelocityManager.getInstance().getVelocityEngine();
275
276             Template template = velocityEngine.getTemplate(decorator.getPage());
277             StringWriter JavaDoc tempWriter = new StringWriter JavaDoc();
278             template.merge(context, tempWriter);
279             String JavaDoc renderResult = tempWriter.toString();
280
281             response.getWriter().print(renderResult);
282
283             while (decorator.getInitParameterNames().hasNext()) {
284                 String JavaDoc initParam = (String JavaDoc) decorator.getInitParameterNames().next();
285                 if (initParam.startsWith("header."))
286                     response.setHeader(initParam.substring(initParam.indexOf('.')), decorator.getInitParameter(initParam));
287             }
288
289             request.removeAttribute(PAGE);
290         } catch (RuntimeException JavaDoc e) {
291             if (Container.get() == 1)
292                 e.printStackTrace();
293             throw e;
294         } catch (Exception JavaDoc e) {
295             e.printStackTrace();
296         }
297
298     }
299 }
Popular Tags