KickJava   Java API By Example, From Geeks To Geeks.

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


1 package org.roller.presentation.velocity;
2
3 import java.net.MalformedURLException JavaDoc;
4 import java.net.URL JavaDoc;
5 import java.text.SimpleDateFormat JavaDoc;
6 import java.util.ArrayList JavaDoc;
7 import java.util.Date JavaDoc;
8 import java.util.List JavaDoc;
9 import java.util.Locale JavaDoc;
10 import java.util.Map JavaDoc;
11 import java.util.TimeZone JavaDoc;
12
13 import javax.servlet.ServletContext JavaDoc;
14 import javax.servlet.http.HttpServletRequest JavaDoc;
15 import javax.servlet.http.HttpServletResponse JavaDoc;
16 import javax.servlet.http.HttpSession JavaDoc;
17
18 import org.apache.commons.logging.Log;
19 import org.apache.commons.logging.LogFactory;
20 import org.apache.struts.util.RequestUtils;
21 import org.apache.velocity.context.Context;
22 import org.apache.velocity.tools.view.context.ChainedContext;
23 import org.apache.velocity.tools.view.context.ToolboxContext;
24 import org.apache.velocity.tools.view.servlet.ServletToolboxManager;
25 import org.roller.RollerException;
26 import org.roller.config.RollerConfig;
27 import org.roller.config.RollerRuntimeConfig;
28 import org.roller.model.Roller;
29 import org.roller.model.RollerFactory;
30 import org.roller.pojos.CommentData;
31 import org.roller.pojos.PageData;
32 import org.roller.pojos.RollerPropertyData;
33 import org.roller.pojos.UserData;
34 import org.roller.pojos.WeblogEntryData;
35 import org.roller.pojos.WebsiteData;
36 import org.roller.presentation.LanguageUtil;
37 import org.roller.presentation.RollerContext;
38 import org.roller.presentation.RollerRequest;
39 import org.roller.presentation.RollerSession;
40 import org.roller.presentation.newsfeeds.NewsfeedCache;
41 import org.roller.presentation.weblog.formbeans.CommentFormEx;
42 import org.roller.util.RegexUtil;
43 import org.roller.util.StringUtils;
44 import org.roller.util.Utilities;
45
46 /**
47  * Load Velocity Context with Roller objects, values, and custom plugins.
48  *
49  * @author llavandowska
50  * @author David M Johnson
51  */

52 public class ContextLoader
53 {
54     private RollerRequest mRollerReq = null;
55     
56     // List of PagePlugins for "transforming" WeblogEntries
57
static List JavaDoc mPagePlugins = new ArrayList JavaDoc();
58     
59     private static Log mLogger =
60        LogFactory.getFactory().getInstance(ContextLoader.class);
61
62     //------------------------------------------------------------------------
63

64     /**
65      * Setup the a Velocity context by loading it with objects, values, and
66      * RollerPagePlugins needed for Roller page execution.
67      */

68     public static void setupContext( Context JavaDoc ctx,
69         RollerRequest rreq, HttpServletResponse JavaDoc response )
70         throws RollerException
71     {
72         mLogger.debug("setupContext( ctx = "+ctx+")");
73         
74         HttpServletRequest JavaDoc request = rreq.getRequest();
75         RollerContext rollerCtx = RollerContext.getRollerContext( request );
76         
77         try
78         {
79             // Add page model object to context
80
String JavaDoc pageModelClassName =
81                 RollerConfig.getProperty("velocity.pagemodel.classname");
82             Class JavaDoc pageModelClass = Class.forName(pageModelClassName);
83             PageModel pageModel = (PageModel)pageModelClass.newInstance();
84             pageModel.init(rreq);
85             ctx.put("pageModel", pageModel );
86             ctx.put("pages", pageModel.getPages());
87         }
88         catch (Exception JavaDoc e)
89         {
90             throw new RollerException("ERROR creating Page Model",e);
91         }
92         
93         // Add Velocity page helper to context
94
PageHelper pageHelper = new PageHelper(rreq, response, ctx);
95         pageHelper.initializePlugins(mPagePlugins);
96         ctx.put("pageHelper", pageHelper );
97
98         // Add legacy macros too, so that old-school pages still work
99
Macros macros= new Macros(rreq.getPageContext(), pageHelper);
100         ctx.put("macros", macros);
101
102         // Load standard Roller objects and values into the context
103
String JavaDoc userName = loadWebsiteValues(ctx, rreq, rollerCtx );
104         loadWeblogValues( ctx, rreq, rollerCtx, userName );
105         loadPathValues( ctx, rreq, rollerCtx, userName );
106         loadRssValues( ctx, rreq, userName );
107         loadUtilityObjects( ctx, rreq, rollerCtx, userName );
108         loadRequestParamKeys(ctx);
109         loadStatusMessage( ctx, rreq );
110         
111         // If single entry is specified, load comments too
112
if ( rreq.getWeblogEntry() != null )
113         {
114             loadCommentValues( ctx, rreq, rollerCtx );
115         }
116         
117         // add Velocity Toolbox tools to context
118
loadToolboxContext(request, response, ctx);
119     }
120     
121     //------------------------------------------------------------------------
122

123     /**
124      * If there is an ERROR or STATUS message in the session,
125      * place it into the Context for rendering later.
126      *
127      * @param rreq
128      */

129     private static void loadStatusMessage(Context JavaDoc ctx, RollerRequest rreq)
130     {
131         HttpSession JavaDoc session = rreq.getRequest().getSession(false);
132         String JavaDoc msg = null;
133         if (session != null)
134             msg = (String JavaDoc)session.getAttribute(RollerSession.ERROR_MESSAGE);
135         if (msg != null)
136         {
137             ctx.put("errorMessage", msg);
138             session.removeAttribute(RollerSession.ERROR_MESSAGE);
139         }
140
141         if (session != null)
142             msg = (String JavaDoc)session.getAttribute(RollerSession.STATUS_MESSAGE);
143         if (msg != null)
144         {
145             ctx.put("statusMessage", msg);
146             session.removeAttribute(RollerSession.STATUS_MESSAGE);
147         }
148     }
149     
150     //------------------------------------------------------------------------
151

152     /**
153      * @param ctx
154      * @param rreq
155      * @param rollerCtx
156      * @param userName
157      */

158     private static void loadWeblogValues(
159        Context JavaDoc ctx, RollerRequest rreq, RollerContext rollerCtx, String JavaDoc userName)
160        throws RollerException
161     {
162         // if there is an "_entry" page, only load it once
163
WebsiteData website = rreq.getRoller().getUserManager().getWebsite(userName);
164         PageModel pageModel = (PageModel)ctx.get("pageModel");
165         if (website != null && pageModel != null)
166         {
167             /* alternative display pages - customization */
168             PageData entryPage = pageModel.getUsersPageByName(website, "_entry");
169             if (entryPage != null)
170             {
171                 ctx.put("entryPage", entryPage);
172             }
173             PageData descPage = pageModel.getUsersPageByName(website, "_desc");
174             if (descPage != null)
175             {
176                 ctx.put("descPage", descPage);
177             }
178         }
179     }
180
181     private static String JavaDoc figureResourcePath( RollerRequest rreq )
182     {
183         /* old way -- Allen G
184         HttpServletRequest request = rreq.getRequest();
185         RollerContext rCtx = RollerContext.getRollerContext( request );
186         RollerConfigData rollerConfig = rCtx.getRollerConfig();
187     
188         StringBuffer sb = new StringBuffer();
189         String uploadPath = rollerConfig.getUploadPath();
190         if ( uploadPath != null && uploadPath.trim().length() > 0 )
191         {
192             sb.append( uploadPath );
193         }
194         else
195         {
196             sb.append( request.getContextPath() );
197             sb.append( RollerContext.USER_RESOURCES );
198         }
199         return sb.toString();
200         */

201         
202         String JavaDoc uploadurl = null;
203         try {
204             uploadurl = RollerFactory.getRoller().getFileManager().getUploadUrl();
205         } catch(Exception JavaDoc e) {}
206         
207         return uploadurl;
208     }
209
210     //------------------------------------------------------------------------
211

212     public boolean isUserAuthorizedToEdit()
213     {
214         try
215         {
216             return mRollerReq.isUserAuthorizedToEdit();
217         }
218         catch (Exception JavaDoc e)
219         {
220             mLogger.warn("PageHelper.isUserAuthorizedToEdit)", e);
221         }
222         return false;
223     }
224     
225     //------------------------------------------------------------------------
226

227     protected static void loadCommentValues(
228        Context JavaDoc ctx, RollerRequest rreq, RollerContext rollerCtx )
229        throws RollerException
230     {
231         HttpServletRequest JavaDoc request = rreq.getRequest();
232         
233         String JavaDoc escapeHtml = RollerRuntimeConfig.getProperty("users.comments.escapehtml");
234         String JavaDoc autoFormat = RollerRuntimeConfig.getProperty("users.comments.autoformat");
235         
236         // Add comments related values to context
237
ctx.put("isCommentPage", Boolean.TRUE);
238         ctx.put("escapeHtml", new Boolean JavaDoc(escapeHtml) );
239         ctx.put("autoformat", new Boolean JavaDoc(autoFormat) );
240         
241         // Make sure comment form object is available in context
242
CommentFormEx commentForm =
243             (CommentFormEx)request.getAttribute("commentForm");
244         if ( commentForm == null )
245         {
246             commentForm = new CommentFormEx();
247         
248             // Set fields to spaces to please Velocity
249
commentForm.setName("");
250             commentForm.setEmail("");
251             commentForm.setUrl("");
252             commentForm.setContent("");
253         }
254         ctx.put("commentForm",commentForm);
255             
256         // Either put a preview comment in to context
257
if ( request.getAttribute("previewComments")!=null )
258         {
259             ArrayList JavaDoc list = new ArrayList JavaDoc();
260             CommentData cd = new CommentData();
261             commentForm.copyTo(cd, request.getLocale());
262             list.add(cd);
263             ctx.put("previewComments",list);
264         }
265         WeblogEntryData entry = rreq.getWeblogEntry();
266         ctx.put("entry",entry);
267     }
268
269     //------------------------------------------------------------------------
270

271     protected static void loadPathValues(
272         Context JavaDoc ctx, RollerRequest rreq, RollerContext rollerCtx, String JavaDoc userName)
273         throws RollerException
274     {
275         HttpServletRequest JavaDoc request = rreq.getRequest();
276         String JavaDoc url = null;
277         if ( userName != null && !userName.equals("zzz_none_zzz"))
278         {
279             url = Utilities.escapeHTML(
280                 rollerCtx.getAbsoluteContextUrl(request)+"/page/"+userName);
281         }
282         else
283         {
284             url= Utilities.escapeHTML(rollerCtx.getAbsoluteContextUrl(request));
285         }
286         ctx.put("websiteURL", url);
287         ctx.put("baseURL", rollerCtx.getContextUrl( request ) );
288         ctx.put("absBaseURL", rollerCtx.getAbsoluteContextUrl( request ) );
289         ctx.put("ctxPath", request.getContextPath() );
290         ctx.put("uploadPath", ContextLoader.figureResourcePath( rreq ) );
291         
292         try
293         {
294             URL JavaDoc absUrl = RequestUtils.absoluteURL(request, "/");
295             ctx.put("host", absUrl.getHost());
296         }
297         catch (MalformedURLException JavaDoc e)
298         {
299             throw new RollerException(e);
300         }
301     }
302
303     //------------------------------------------------------------------------
304

305     protected static void loadRequestParamKeys(Context JavaDoc ctx)
306     {
307         // Since Velocity *requires* accessor methods, these values from
308
// RollerRequest are not available to it, put them into the context
309
ctx.put("USERNAME_KEY", RollerRequest.USERNAME_KEY);
310         ctx.put("WEBSITEID_KEY", RollerRequest.WEBSITEID_KEY);
311         ctx.put("FOLDERID_KEY", RollerRequest.FOLDERID_KEY);
312         ctx.put("NEWSFEEDID_KEY", RollerRequest.NEWSFEEDID_KEY);
313         ctx.put("PAGEID_KEY", RollerRequest.PAGEID_KEY);
314         ctx.put("PAGELINK_KEY", RollerRequest.PAGELINK_KEY);
315         ctx.put("ANCHOR_KEY", RollerRequest.ANCHOR_KEY);
316         ctx.put("EXCERPTS_KEY", RollerRequest.EXCERPTS_KEY);
317         ctx.put("BOOKMARKID_KEY", RollerRequest.BOOKMARKID_KEY);
318         ctx.put("REFERERID_KEY", RollerRequest.REFERERID_KEY);
319         ctx.put("WEBLOGENTRYID_KEY", RollerRequest.WEBLOGENTRYID_KEY);
320         ctx.put("WEBLOGCATEGORYNAME_KEY", RollerRequest.WEBLOGCATEGORYNAME_KEY);
321         ctx.put("WEBLOGCATEGORYID_KEY", RollerRequest.WEBLOGENTRIES_KEY);
322         ctx.put("WEBLOGENTRIES_KEY", RollerRequest.WEBLOGENTRIES_KEY);
323         ctx.put("WEBLOGDAY_KEY", RollerRequest.WEBLOGDAY_KEY);
324         ctx.put("WEBLOGCOMMENTID_KEY", RollerRequest.WEBLOGCOMMENTID_KEY);
325     }
326
327     //------------------------------------------------------------------------
328

329     protected static void loadRssValues(
330        Context JavaDoc ctx, RollerRequest rreq, String JavaDoc userName) throws RollerException
331     {
332         HttpServletRequest JavaDoc request = rreq.getRequest();
333         
334         int entryLength = -1;
335         String JavaDoc sExcerpts = request.getParameter("excerpts");
336         if ( sExcerpts!=null && sExcerpts.equalsIgnoreCase("true"))
337         {
338             entryLength = 150;
339         }
340         ctx.put("entryLength", new Integer JavaDoc(entryLength));
341         
342         int entryCount = 15;
343         String JavaDoc sCount = request.getParameter("count");
344         if ( sCount!=null && sExcerpts.trim().equals(""))
345         {
346             try
347             {
348                 entryCount = Integer.parseInt(sCount);
349             }
350             catch (NumberFormatException JavaDoc e)
351             {
352                 mLogger.warn("Improperly formatted count parameter");
353             }
354             if ( entryCount > 50 ) entryCount = 50;
355             if ( entryCount < 0 ) entryCount = 15;
356         }
357         ctx.put("entryCount", new Integer JavaDoc(entryCount));
358             
359         String JavaDoc catname = null;
360         String JavaDoc catPath = null;
361         if ( rreq.getWeblogCategory() != null )
362         {
363             catname = rreq.getWeblogCategory().getName();
364             catPath = rreq.getWeblogCategory().getPath();
365         }
366         ctx.put("catname", (catname!=null) ? catname : "");
367         ctx.put("catPath", (catPath != null) ? catPath : "");
368         ctx.put("updateTime", request.getAttribute("updateTime"));
369         ctx.put("now", new Date JavaDoc());
370     }
371
372     //------------------------------------------------------------------------
373

374     protected static void loadUtilityObjects(
375         Context JavaDoc ctx, RollerRequest rreq, RollerContext rollerCtx, String JavaDoc username)
376         throws RollerException
377     {
378
379         // date formatter for macro's
380
// set this up with the Locale to make sure we can reuse it with other patterns
381
// in the macro's
382
Locale JavaDoc viewLocale = (Locale JavaDoc) ctx.get("viewLocale");
383         SimpleDateFormat JavaDoc sdf = new SimpleDateFormat JavaDoc("yyyyMMdd", viewLocale);
384         WebsiteData website = rreq.getRoller().getUserManager().getWebsite(username);
385         if (website != null)
386         {
387             sdf.setTimeZone(website.getTimeZoneInstance());
388         }
389         // add formatter to context
390
ctx.put("dateFormatter", sdf );
391
392         // Note: in the macro's, the formats are taken from the ResourceBundles.
393
// Only the plainFormat is specified here, because it is used to render
394
// the Entry Day link.
395
ctx.put("plainFormat", "yyyyMMdd");
396
397         ctx.put("page", rreq.getPage() );
398         ctx.put("utilities", new Utilities() );
399         ctx.put("stringUtils", new StringUtils() );
400         ctx.put("rollerVersion", rollerCtx.getRollerVersion() );
401         ctx.put("rollerBuildTime", rollerCtx.getRollerBuildTime() );
402         ctx.put("rollerBuildUser", rollerCtx.getRollerBuildUser() );
403         ctx.put("newsfeedCache", NewsfeedCache.getInstance() );
404         
405         ctx.put("requestParameters", rreq.getRequest().getParameterMap());
406     }
407     
408     //------------------------------------------------------------------------
409

410     protected static String JavaDoc loadWebsiteValues(
411         Context JavaDoc ctx, RollerRequest rreq, RollerContext rollerCtx )
412         throws RollerException
413     {
414         String JavaDoc userName = null;
415         UserData user = null;
416         WebsiteData website = null;
417         
418         Roller mRoller = RollerFactory.getRoller();
419         Map JavaDoc props = mRoller.getPropertiesManager().getProperties();
420         
421         if ( rreq.getRequest().getAttribute(RollerRequest.OWNING_USER) != null)
422         {
423             user = (UserData)
424                 rreq.getRequest().getAttribute(RollerRequest.OWNING_USER);
425         }
426         else if ( rreq.getUser() != null )
427         {
428             user = rreq.getUser();
429         }
430         
431         if ( user != null )
432         {
433             userName = user.getUserName();
434             website = rreq.getRoller().getUserManager().getWebsite(userName);
435             ctx.put("userName", user.getUserName() );
436             ctx.put("fullName", user.getFullName() );
437             ctx.put("emailAddress", user.getEmailAddress() );
438
439             ctx.put("encodedEmail", RegexUtil.encode(user.getEmailAddress()));
440             ctx.put("obfuscatedEmail", RegexUtil.obfuscateEmail(user.getEmailAddress()));
441             
442             // setup Locale for future rendering
443
ctx.put("locale", website.getLocaleInstance());
444            
445             // setup Timezone for future rendering
446
ctx.put("timezone", website.getTimeZoneInstance());
447         }
448         else
449         {
450             website = new WebsiteData();
451             website.setName(((RollerPropertyData)props.get("site.name")).getValue());
452             website.setAllowComments(Boolean.FALSE);
453             website.setDescription(((RollerPropertyData)props.get("site.description")).getValue());
454             userName = "zzz_none_zzz";
455             ctx.put("userName",userName );
456             ctx.put("fullName","zzz_none_zzz");
457             ctx.put("emailAddress",
458                 ((RollerPropertyData)props.get("site.adminemail")).getValue());
459             ctx.put("locale", Locale.getDefault());
460             ctx.put("timezone", TimeZone.getDefault());
461         }
462         ctx.put("website", website );
463
464         String JavaDoc siteName = ((RollerPropertyData)props.get("site.name")).getValue();
465         if ("Roller-based Site".equals(siteName)) siteName = "Main";
466         ctx.put("siteName", siteName);
467
468         // add language of the session (using locale of viewer set by Struts)
469
ctx.put(
470             "viewLocale",
471             LanguageUtil.getViewLocale(rreq.getRequest()));
472         mLogger.debug("context viewLocale = "+ctx.get( "viewLocale"));
473
474         return userName;
475     }
476     
477     //------------------------------------------------------------------------
478

479     /**
480      * Initialize PagePlugins declared in web.xml. By using the full class
481      * name we also allow for the implementation of "external" Plugins
482      * (maybe even packaged seperately). These classes are then later
483      * instantiated by PageHelper.
484      *
485      * @param mContext
486      */

487     public static void initializePagePlugins(ServletContext JavaDoc mContext)
488     {
489         String JavaDoc pluginStr = RollerConfig.getProperty("plugins.page");
490         if (mLogger.isDebugEnabled()) mLogger.debug(pluginStr);
491         if (pluginStr != null)
492         {
493             String JavaDoc[] plugins = StringUtils.stripAll(
494                                    StringUtils.split(pluginStr, ",") );
495             for (int i=0; i<plugins.length; i++)
496             {
497                 if (mLogger.isDebugEnabled()) mLogger.debug("try " + plugins[i]);
498                 try
499                 {
500                     Class JavaDoc pluginClass = Class.forName(plugins[i]);
501                     if (isPagePlugin(pluginClass))
502                     {
503                         mPagePlugins.add(pluginClass.newInstance());
504                     }
505                     else
506                     {
507                         mLogger.warn(pluginClass + " is not a PagePlugin");
508                     }
509                 }
510                 catch (ClassNotFoundException JavaDoc e)
511                 {
512                     mLogger.error("ClassNotFoundException for " + plugins[i]);
513                 }
514                 catch (InstantiationException JavaDoc e)
515                 {
516                     mLogger.error("InstantiationException for " + plugins[i]);
517                 }
518                 catch (IllegalAccessException JavaDoc e)
519                 {
520                     mLogger.error("IllegalAccessException for " + plugins[i]);
521                 }
522             }
523         }
524     }
525     
526     /**
527      * @param pluginClass
528      * @return
529      */

530     private static boolean isPagePlugin(Class JavaDoc pluginClass)
531     {
532         Class JavaDoc[] interfaces = pluginClass.getInterfaces();
533         for (int i=0; i<interfaces.length; i++)
534         {
535             if (interfaces[i].equals(PagePlugin.class)) return true;
536         }
537         return false;
538     }
539
540     public static boolean hasPlugins()
541     {
542         mLogger.debug("mPluginClasses.size(): " + mPagePlugins.size());
543         return (mPagePlugins != null && mPagePlugins.size() > 0);
544     }
545     
546     public static List JavaDoc getPagePlugins()
547     {
548         return mPagePlugins;
549     }
550
551
552     private static final String JavaDoc TOOLBOX_KEY =
553         "org.roller.presentation.velocity.toolbox";
554
555     private static final String JavaDoc TOOLBOX_MANAGER_KEY =
556         "org.roller.presentation.velocity.toolboxManager";
557
558     private static ToolboxContext loadToolboxContext(
559                     HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, Context JavaDoc ctx)
560     {
561         ServletContext JavaDoc servletContext = RollerContext.getServletContext();
562
563         // get the toolbox manager
564
ServletToolboxManager toolboxManager =
565             (ServletToolboxManager)servletContext.getAttribute(TOOLBOX_MANAGER_KEY);
566         if (toolboxManager==null)
567         {
568             String JavaDoc file = RollerConfig.getProperty("velocity.toolbox.file");
569             mLogger.debug("Creating new toolboxContext using config-file: "+file);
570             toolboxManager = ServletToolboxManager.getInstance(servletContext, file);
571             servletContext.setAttribute(TOOLBOX_MANAGER_KEY, toolboxManager);
572         }
573         
574         // load a toolbox context
575
ChainedContext chainedContext =
576             new ChainedContext(ctx, request, response, servletContext);
577         ToolboxContext toolboxContext =
578             toolboxManager.getToolboxContext(chainedContext);
579
580         if (toolboxContext != null)
581         {
582             // add MessageTool to VelocityContext
583
ctx.put("text", toolboxContext.internalGet("text"));
584             
585             /*
586             Object[] keys = toolboxContext.internalGetKeys();
587             for (int i=0;i<keys.length;i++) {
588                 String key = (String)keys[i];
589                 System.out.println("key = "+key);
590                 Object tool = toolboxContext.get(key);
591                 System.out.println("tool = "+tool);
592                 ctx.put(key, tool);
593             }
594             */

595         }
596         
597         return toolboxContext;
598     }
599 }
600
Popular Tags