KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > roller > presentation > velocity > BasePageServlet


1 package org.roller.presentation.velocity;
2
3 import java.io.IOException JavaDoc;
4 import java.io.StringWriter JavaDoc;
5 import java.util.Map JavaDoc;
6
7 import javax.servlet.ServletConfig JavaDoc;
8 import javax.servlet.ServletException JavaDoc;
9 import javax.servlet.http.HttpServletRequest JavaDoc;
10 import javax.servlet.http.HttpServletResponse JavaDoc;
11 import javax.servlet.jsp.JspFactory JavaDoc;
12 import javax.servlet.jsp.PageContext JavaDoc;
13
14 import org.apache.commons.logging.Log;
15 import org.apache.commons.logging.LogFactory;
16 import org.apache.velocity.Template;
17 import org.apache.velocity.VelocityContext;
18 import org.apache.velocity.context.Context;
19 import org.apache.velocity.exception.ParseErrorException;
20 import org.apache.velocity.exception.ResourceNotFoundException;
21 import org.apache.velocity.servlet.VelocityServlet;
22 import org.roller.RollerException;
23 import org.roller.model.UserManager;
24 import org.roller.pojos.PageData;
25 import org.roller.pojos.UserData;
26 import org.roller.pojos.WebsiteData;
27 import org.roller.presentation.RollerRequest;
28
29 /**
30  * Base Servlet for Servlets that render user page templates. Loads the
31  * Velocity context using the ContextLoader and runs the page template
32  * selected by the request.
33  *
34  * @author llavandowska
35  * @author David M Johnson
36  */

37 public abstract class BasePageServlet extends VelocityServlet
38 {
39     private static Log mLogger =
40         LogFactory.getFactory().getInstance(BasePageServlet.class);
41     /**
42      * <p>Sets servletContext for WebappResourceLoader.</p>
43      *
44      * @param config servlet configuation
45      */

46     public void init( ServletConfig JavaDoc config )
47         throws ServletException JavaDoc
48     {
49         super.init( config );
50         WebappResourceLoader.setServletContext( getServletContext() );
51     }
52     public Template handleRequest( HttpServletRequest JavaDoc request,
53                                    HttpServletResponse JavaDoc response,
54                                    Context JavaDoc ctx ) throws Exception JavaDoc
55     {
56         String JavaDoc pid = null;
57         Template outty = null;
58         Exception JavaDoc pageException = null;
59         
60         try
61         {
62             PageContext JavaDoc pageContext =
63                 JspFactory.getDefaultFactory().getPageContext(
64                     this, request, response,"", true, 8192, true);
65             // Needed to init request attributes, etc.
66
RollerRequest rreq = RollerRequest.getRollerRequest(pageContext);
67             UserManager userMgr = rreq.getRoller().getUserManager();
68             
69             WebsiteData wd = null;
70             if (request.getAttribute(RollerRequest.OWNING_USER) != null) {
71                 UserData user = (UserData)
72                     request.getAttribute(RollerRequest.OWNING_USER);
73                 wd = userMgr.getWebsite(user.getUserName());
74             }
75             else
76             {
77                 wd = rreq.getWebsite();
78             }
79             
80             // If request specified the page, then go with that
81
PageData pd = null;
82             if (rreq.getPage() != null // RollerRequest does too much guess work
83
&& request.getAttribute(RollerRequest.OWNING_USER) == null)
84             {
85                 pd = rreq.getPage();
86                 pid = pd.getId();
87             }
88             // If page not available from request, then use website's default
89
else if (wd != null)
90             {
91                 pd = userMgr.retrievePage(wd.getDefaultPageId());
92                 pid = pd.getId();
93                 rreq.setPage(pd);
94             }
95             // Still no page ID, then we have a problem
96
if ( pid == null )
97             {
98                 throw new ResourceNotFoundException("Page not found");
99             }
100             
101             outty = prepareForPageExecution(ctx, rreq, response, pd);
102         }
103         catch( Exception JavaDoc e )
104         {
105             pageException = e;
106             response.setStatus( HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
107         }
108         if (pageException != null)
109         {
110             mLogger.error("EXCEPTION: in RollerServlet", pageException);
111             request.setAttribute("DisplayException", pageException);
112         }
113         return outty;
114     }
115
116     //------------------------------------------------------------------------
117
/**
118      * Try to load user-specified Decorator (if specified). Failing that
119      * see if user has a _decorator Page, if not check for a _decorator
120      * in the Preview resource loader. Finally, if none of those can
121      * be found fall back to the no-op decorator.
122      * @param object
123      * @return
124      */

125     private Template findDecorator(String JavaDoc decoratorName, UserManager userMgr, WebsiteData wd)
126         throws ResourceNotFoundException, ParseErrorException, RollerException, Exception JavaDoc
127     {
128         Template decorator = null;
129         PageData decoratorPage = null;
130         String JavaDoc decoratorId = null;
131         
132         // check for user-specified decorator
133
if (decoratorName != null)
134         {
135             decoratorPage = userMgr.getPageByName(wd, decoratorName);
136             if (decoratorPage != null)
137             {
138                 decoratorId = decoratorPage.getId();
139             }
140         }
141         
142         // if no user-specified decorator try default page-name
143
if (decoratorPage == null)
144         {
145             decoratorPage = userMgr.getPageByName(wd, "_decorator");
146             if (decoratorPage != null)
147             {
148                 decoratorId = decoratorPage.getId();
149             }
150             else
151             {
152                 // could be in PreviewResourceLoader
153
decoratorId = "_decorator";
154             }
155         }
156
157         // try loading Template
158
if (decoratorId != null)
159         {
160             try
161             {
162                 decorator = getTemplate(decoratorId, "UTF-8");
163             }
164             catch (Exception JavaDoc e)
165             {
166                 // it may not exist, so this is okay
167
}
168         }
169         
170         // couldn't find Template, load default "no-op" decorator
171
if (decorator == null)
172         {
173             decorator = getTemplate("/themes/noop_decorator.vm", "UTF-8");
174         }
175         return decorator;
176     }
177
178     /**
179      * Prepare for page execution be setting content type, populating context,
180      * and processing the page decorator if needed.
181      */

182     protected Template prepareForPageExecution(Context JavaDoc ctx, RollerRequest rreq,
183         HttpServletResponse JavaDoc response, PageData pd) throws Exception JavaDoc
184     {
185         Template outty = null;
186         UserManager userMgr = rreq.getRoller().getUserManager();
187         WebsiteData wd = pd.getWebsite();
188         
189         // if page has an extension - use that to set the contentType
190
String JavaDoc pageLink = pd.getLink();
191         String JavaDoc mimeType = getServletConfig().getServletContext().getMimeType(pageLink);
192         if(mimeType != null) {
193             // we found a match ... set the content type
194
response.setContentType(mimeType);
195         }
196         
197         /* old way ... not as flexible -- Allen G
198         int period = pd.getLink().indexOf('.');
199         if (period > -1)
200         {
201             String extension = pd.getLink().substring(period+1);
202             if ("js".equals(extension))
203             {
204                 extension = "javascript";
205             }
206             response.setContentType("text/" + extension);
207         }
208         */

209     
210         // Made it this far, populate the Context
211
ContextLoader.setupContext( ctx, rreq, response );
212
213         // Get the page
214
outty = getTemplate( pd.getId(), "UTF-8" );
215
216         /**
217          * User can define a Decorator Template.
218          */

219         if (wd != null)
220         {
221             // parse/merge Page template
222
StringWriter JavaDoc sw = new StringWriter JavaDoc();
223             outty.merge(ctx, sw);
224             ctx.put("decorator_body", sw.toString());
225
226             // replace outty with decorator Template
227
outty = findDecorator((String JavaDoc)ctx.get("decorator"), userMgr, wd);
228         }
229         return outty;
230     }
231     
232     //------------------------------------------------------------------------
233
/**
234      * Handle error in Velocity processing.
235      */

236     protected void error( HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res,
237         Exception JavaDoc e) throws ServletException JavaDoc, IOException JavaDoc
238     {
239         mLogger.warn("ERROR in VelocityServlet",e);
240     }
241    
242     /**
243      * Override to prevent Velocity from putting "req" and "res" into the context.
244      * Allowing users access to the underlying Servlet objects is a security risk.
245      * If need access to request parameters, use $requestParameters.
246      */

247     protected Context JavaDoc createContext(
248             HttpServletRequest JavaDoc req,
249             HttpServletResponse JavaDoc res) {
250         
251         VelocityContext context = new VelocityContext();
252         context.put(REQUEST, new RequestWrapper(req.getParameterMap()));
253         return context;
254         
255     }
256     
257     /** Provide access to request params only, not actual request */
258     public static class RequestWrapper
259     {
260         Map JavaDoc params = null;
261         public RequestWrapper(Map JavaDoc params)
262         {
263             this.params = params;
264         }
265         public String JavaDoc getParameter(String JavaDoc key)
266         {
267             String JavaDoc ret = null;
268             String JavaDoc[] array = (String JavaDoc[])params.get(key);
269             if (array != null && array.length > 0)
270             {
271                 ret = array[0];
272             }
273             return ret;
274         }
275     }
276 }
277
Popular Tags