KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > roller > ui > rendering > velocity > deprecated > ContextLoader


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. The ASF licenses this file to You
4  * under the Apache License, Version 2.0 (the "License"); you may not
5  * use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License. For additional information regarding
15  * copyright in this work, please see the NOTICE file in the top level
16  * directory of this distribution.
17  */

18
19 package org.apache.roller.ui.rendering.velocity.deprecated;
20
21 import java.net.MalformedURLException JavaDoc;
22 import java.net.URL JavaDoc;
23 import java.text.SimpleDateFormat JavaDoc;
24 import java.util.ArrayList JavaDoc;
25 import java.util.Date JavaDoc;
26 import java.util.Locale JavaDoc;
27 import java.util.Map JavaDoc;
28 import javax.servlet.ServletContext JavaDoc;
29 import javax.servlet.http.HttpServletRequest JavaDoc;
30 import javax.servlet.http.HttpServletResponse JavaDoc;
31 import javax.servlet.http.HttpSession JavaDoc;
32 import javax.servlet.jsp.PageContext JavaDoc;
33 import org.apache.commons.logging.Log;
34 import org.apache.commons.logging.LogFactory;
35 import org.apache.roller.RollerException;
36 import org.apache.roller.config.RollerConfig;
37 import org.apache.roller.config.RollerRuntimeConfig;
38 import org.apache.roller.model.Roller;
39 import org.apache.roller.model.RollerFactory;
40 import org.apache.roller.pojos.CommentData;
41 import org.apache.roller.pojos.FolderData;
42 import org.apache.roller.pojos.RollerPropertyData;
43 import org.apache.roller.pojos.Template;
44 import org.apache.roller.pojos.WeblogCategoryData;
45 import org.apache.roller.pojos.WeblogEntryData;
46 import org.apache.roller.pojos.WebsiteData;
47 import org.apache.roller.pojos.wrapper.CommentDataWrapper;
48 import org.apache.roller.pojos.wrapper.TemplateWrapper;
49 import org.apache.roller.pojos.wrapper.WeblogEntryDataWrapper;
50 import org.apache.roller.pojos.wrapper.WebsiteDataWrapper;
51 import org.apache.roller.ui.core.RollerContext;
52 import org.apache.roller.ui.core.RollerSession;
53 import org.apache.roller.ui.rendering.velocity.deprecated.NewsfeedCache;
54 import org.apache.roller.ui.rendering.util.WeblogEntryCommentForm;
55 import org.apache.roller.ui.rendering.util.WeblogPageRequest;
56 import org.apache.roller.util.DateUtil;
57 import org.apache.roller.util.RegexUtil;
58 import org.apache.roller.util.URLUtilities;
59 import org.apache.struts.util.RequestUtils;
60 import org.apache.velocity.VelocityContext;
61
62
63 /**
64  * Load Velocity Context with Roller objects, values, and custom plugins.
65  *
66  * NOTE: This class has been deprecated and should no longer be used. It is
67  * left here so that old weblogs which rely on it will continue to
68  * function properly. This should only be used by weblog pages.
69  */

70 public class ContextLoader {
71
72     public static final String JavaDoc WEBLOG_KEY = "weblog";
73     public static final String JavaDoc ANCHOR_KEY = "entry";
74     public static final String JavaDoc ANCHOR_KEY_OLD = "anchor";
75     public static final String JavaDoc USERNAME_KEY = "username";
76
77     public static final String JavaDoc PAGELINK_KEY = "pagelink";
78     public static final String JavaDoc EXCERPTS_KEY = "excerpts";
79     public static final String JavaDoc WEBLOGENTRY_COUNT = "count";
80     public static final String JavaDoc WEBLOGCATEGORYNAME_KEY = "cat";
81     public static final String JavaDoc WEBLOGENTRIES_KEY = "entries";
82     public static final String JavaDoc WEBLOGDAY_KEY = "day";
83     
84     public static final String JavaDoc WEBLOGENTRYID_KEY = "entryid";
85     
86     public static final String JavaDoc WEBLOGCATEGORYID_KEY = "categoryId";
87     public static final String JavaDoc PINGTARGETID_KEY = "pingtargetId";
88     public static final String JavaDoc REFERERID_KEY = "refId";
89     public static final String JavaDoc WEBLOGCOMMENTID_KEY = "commentId";
90     public static final String JavaDoc WEBSITEID_KEY = "websiteId";
91     public static final String JavaDoc BOOKMARKID_KEY = "bookmarkId";
92     public static final String JavaDoc FOLDERID_KEY = "folderId";
93     public static final String JavaDoc PARENTID_KEY = "parentId";
94     public static final String JavaDoc NEWSFEEDID_KEY = "feedId";
95     public static final String JavaDoc PAGEID_KEY = "pageId";
96     public static final String JavaDoc LOGIN_COOKIE = "sessionId";
97     public static final String JavaDoc OWNING_WEBSITE = "OWNING_WEBSITE";
98
99     private static Log mLogger = LogFactory.getLog(ContextLoader.class);
100     
101     
102     /**
103      * Setup the a Velocity context by loading it with objects, values, and
104      * RollerPagePlugins needed for Roller page execution.
105      */

106     public static void setupContext(
107             Map JavaDoc ctx,
108             HttpServletRequest JavaDoc request,
109             HttpServletResponse JavaDoc response,
110             PageContext JavaDoc pageContext,
111             WeblogPageRequest pageRequest) throws RollerException {
112         
113         mLogger.debug("setupContext( ctx = "+ctx+")");
114         
115         RollerContext rollerCtx = RollerContext.getRollerContext( );
116         
117         WebsiteData weblog = null;
118         WeblogEntryData entry = null;
119         WeblogCategoryData category = null;
120         Template page = null;
121         FolderData folder = null; // don't even know how this is involved :/
122
Date JavaDoc date = null;
123         boolean isDay = false;
124         boolean isMonth = false;
125         String JavaDoc locale = null;
126         
127         // get data from page request
128
locale = pageRequest.getLocale();
129         weblog = pageRequest.getWeblog();
130         entry = pageRequest.getWeblogEntry();
131         category = pageRequest.getWeblogCategory();
132         page = pageRequest.getWeblogPage();
133         if(page == null) {
134             page = weblog.getDefaultPage();
135         }
136         
137         // setup date, isDay, and isMonth
138
if(pageRequest.getWeblogDate() != null) {
139             
140             Date JavaDoc now = new Date JavaDoc();
141             if(pageRequest.getWeblogDate().length() == 8) {
142                 isDay = true;
143                 try {
144                     date = DateUtil.get8charDateFormat().parse(pageRequest.getWeblogDate());
145                     if(date.after(now)) {
146                         date = now;
147                     }
148                 } catch(Exception JavaDoc e) {
149                     // bleh
150
}
151             } else if(pageRequest.getWeblogDate().length() == 6) {
152                 isMonth = true;
153                 try {
154                     date = DateUtil.get6charDateFormat().parse(pageRequest.getWeblogDate());
155                     if(date.after(now)) {
156                         date = now;
157                     }
158                 } catch(Exception JavaDoc e) {
159                     // bleh
160
}
161             } else {
162                 isMonth = true;
163             }
164         }
165         
166         try {
167             // Add old page model object to context
168
OldWeblogPageModel pageModel = new OldWeblogPageModel();
169             pageModel.init(request,
170                     weblog,
171                     entry,
172                     category,
173                     date,
174                     isDay,
175                     isMonth,
176                     locale);
177             ctx.put("pageModel", pageModel);
178             
179             // along with old pages list :/
180
ctx.put("pages", pageModel.getPages());
181             
182         } catch (Exception JavaDoc e) {
183             throw new RollerException("ERROR creating Page Model",e);
184         }
185         
186         // Add page helper to context
187
OldPageHelper pageHelper = new OldPageHelper(request,
188                 response,
189                 ctx,
190                 weblog,
191                 (date == null) ? new Date JavaDoc() : date,
192                 folder,
193                 page.getName(),
194                 pageContext,
195                 pageRequest);
196         ctx.put("pageHelper", pageHelper);
197         
198         // Load standard Roller objects and values into the context
199
loadWeblogValues(ctx, weblog, pageRequest.getLocaleInstance(), request);
200         loadPathValues(ctx, request, rollerCtx, weblog, locale);
201         loadRssValues(ctx, request, weblog, category);
202         loadUtilityObjects(ctx, request, rollerCtx, weblog, page);
203         loadRequestParamKeys(ctx);
204         loadStatusMessage(ctx, request);
205         
206         // If single entry is specified, load comments too
207
if (entry != null) {
208             loadCommentValues(ctx, request, entry);
209         }
210     }
211     
212     
213     /**
214      * Load website object and related objects.
215      */

216     private static void loadWeblogValues(
217             Map JavaDoc ctx,
218             WebsiteData weblog,
219             Locale JavaDoc locale,
220             HttpServletRequest JavaDoc request) throws RollerException {
221         
222         // weblog cannot be null
223
if(weblog == null)
224             return;
225         
226         Roller mRoller = RollerFactory.getRoller();
227         Map JavaDoc props = mRoller.getPropertiesManager().getProperties();
228         
229         ctx.put("userName", weblog.getHandle());
230         ctx.put("fullName", weblog.getName() );
231         ctx.put("emailAddress", weblog.getEmailAddress() );
232         ctx.put("encodedEmail", RegexUtil.encode(weblog.getEmailAddress()));
233         ctx.put("obfuscatedEmail", RegexUtil.obfuscateEmail(weblog.getEmailAddress()));
234         
235         // setup Locale for future rendering
236
ctx.put("locale", weblog.getLocaleInstance());
237         
238         // setup Timezone for future rendering
239
ctx.put("timezone", weblog.getTimeZoneInstance());
240         ctx.put("timeZone", weblog.getTimeZoneInstance());
241         ctx.put("website", WebsiteDataWrapper.wrap(weblog) );
242         
243         String JavaDoc siteName = ((RollerPropertyData)props.get("site.name")).getValue();
244         if ("Roller-based Site".equals(siteName)) siteName = "Main";
245         ctx.put("siteName", siteName);
246         
247         String JavaDoc siteShortName = ((RollerPropertyData)props.get("site.shortName")).getValue();
248         ctx.put("siteShortName", siteShortName);
249         
250         // add language of the session (using locale specified by request)
251
ctx.put("viewLocale", locale);
252         mLogger.debug("context viewLocale = "+ctx.get( "viewLocale"));
253         
254         // alternative display pages - customization
255
Template entryPage = weblog.getPageByName("_entry");
256         if (entryPage != null) {
257             ctx.put("entryPage", TemplateWrapper.wrap(entryPage));
258         }
259         // TODO: ATLAS: no templates use this, should be safe to remove
260
// Template descPage = weblog.getPageByName("_desc");
261
//if (descPage != null) {
262
//ctx.put("descPage", TemplateWrapper.wrap(descPage));
263
//}
264

265         boolean commentsEnabled =
266                 RollerRuntimeConfig.getBooleanProperty("users.comments.enabled");
267         boolean trackbacksEnabled =
268                 RollerRuntimeConfig.getBooleanProperty("users.trackbacks.enabled");
269         boolean linkbacksEnabled =
270                 RollerRuntimeConfig.getBooleanProperty("site.linkbacks.enabled");
271         
272         ctx.put("commentsEnabled", new Boolean JavaDoc(commentsEnabled) );
273         ctx.put("trackbacksEnabled", new Boolean JavaDoc(trackbacksEnabled) );
274         ctx.put("linkbacksEnabled", new Boolean JavaDoc(linkbacksEnabled) );
275     }
276     
277     
278     /**
279      * Load comments for one weblog entry and related objects.
280      */

281     private static void loadCommentValues(
282             Map JavaDoc ctx,
283             HttpServletRequest JavaDoc request,
284             WeblogEntryData entry) throws RollerException {
285         
286         mLogger.debug("Loading comment values");
287         
288         String JavaDoc escapeHtml =
289                 RollerRuntimeConfig.getProperty("users.comments.escapehtml");
290         String JavaDoc autoFormat =
291                 RollerRuntimeConfig.getProperty("users.comments.autoformat");
292         ctx.put("isCommentPage", Boolean.TRUE);
293         ctx.put("escapeHtml", new Boolean JavaDoc(escapeHtml) );
294         ctx.put("autoformat", new Boolean JavaDoc(autoFormat) );
295         
296         // Make sure comment form object is available in context
297
WeblogEntryCommentForm commentForm =
298                 (WeblogEntryCommentForm) request.getAttribute("commentForm");
299         if ( commentForm == null ) {
300             commentForm = new WeblogEntryCommentForm();
301             
302             // Set fields to spaces to please Velocity
303
commentForm.setName("");
304             commentForm.setEmail("");
305             commentForm.setUrl("");
306             commentForm.setContent("");
307         }
308         ctx.put("commentForm",commentForm);
309         
310         // Either put a preview comment in to context
311
if(commentForm.isPreview()) {
312             ArrayList JavaDoc list = new ArrayList JavaDoc();
313             list.add(commentForm.getPreviewComment());
314             ctx.put("previewComments", list);
315         }
316         
317         if (entry.getStatus().equals(WeblogEntryData.PUBLISHED)) {
318             ctx.put("entry", WeblogEntryDataWrapper.wrap(entry));
319         }
320     }
321     
322     
323     /**
324      * Load objects needed for RSS and Atom newsfeed generation.
325      */

326     private static void loadRssValues(
327             Map JavaDoc ctx,
328             HttpServletRequest JavaDoc request,
329             WebsiteData website,
330             WeblogCategoryData category)
331             throws RollerException {
332         
333         mLogger.debug("Loading rss values");
334         
335         int entryLength = -1;
336         String JavaDoc sExcerpts = request.getParameter("excerpts");
337         if ( sExcerpts!=null && sExcerpts.equalsIgnoreCase("true")) {
338             entryLength = 150;
339         }
340         ctx.put("entryLength", new Integer JavaDoc(entryLength));
341         
342         // Display same number of entries in feed as displayed on page
343
int entryCount = website.getEntryDisplayCount();
344         
345         // But don't exceed installation-wide maxEntries settings
346
int maxEntries =
347                 RollerRuntimeConfig.getIntProperty("site.newsfeeds.maxEntries");
348         int defaultEntries =
349                 RollerRuntimeConfig.getIntProperty("site.newsfeeds.defaultEntries");
350         if (entryCount < 1) entryCount = defaultEntries;
351         if (entryCount > maxEntries) entryCount = maxEntries;
352         ctx.put("entryCount", new Integer JavaDoc(entryCount));
353         
354         String JavaDoc catname = null;
355         String JavaDoc catPath = null;
356         if (category != null ) {
357             catname = category.getName();
358             catPath = category.getPath();
359         }
360         ctx.put("catname", (catname!=null) ? catname : "");
361         ctx.put("catPath", (catPath != null) ? catPath : "");
362         ctx.put("updateTime", website.getLastModified());
363         ctx.put("now", new Date JavaDoc());
364     }
365     
366     
367     /**
368      * Load useful utility objects for string and date formatting.
369      */

370     private static void loadUtilityObjects(
371             Map JavaDoc ctx,
372             HttpServletRequest JavaDoc request,
373             RollerContext rollerCtx,
374             WebsiteData website,
375             Template page) throws RollerException {
376         
377         mLogger.debug("Loading utility objects");
378         
379         // date formatter for macro's set this up with the Locale to make
380
// sure we can reuse it with other patterns in the macro's
381
Locale JavaDoc viewLocale = (Locale JavaDoc) ctx.get("viewLocale");
382         SimpleDateFormat JavaDoc sdf = new SimpleDateFormat JavaDoc("yyyyMMdd", viewLocale);
383         if (website != null) {
384             sdf.setTimeZone(website.getTimeZoneInstance());
385         }
386         // add formatter to context
387
ctx.put("dateFormatter", sdf );
388         
389         // Note: in the macro's, the formats are taken from the ResourceBundles.
390
// Only the plainFormat is specified here, because it is used to render
391
// the Entry Day link.
392
ctx.put("plainFormat", "yyyyMMdd");
393         
394         ctx.put("page", TemplateWrapper.wrap(page));
395         ctx.put("utilities", new OldUtilities() );
396         ctx.put("stringUtils", new OldStringUtils() );
397         ctx.put("rollerVersion", rollerCtx.getRollerVersion() );
398         ctx.put("rollerBuildTime", rollerCtx.getRollerBuildTime() );
399         ctx.put("rollerBuildUser", rollerCtx.getRollerBuildUser() );
400         ctx.put("newsfeedCache", NewsfeedCache.getInstance() );
401         
402         ctx.put("requestParameters", request.getParameterMap());
403     }
404     
405     
406     /**
407      * Load URL paths useful in page templates.
408      */

409     private static void loadPathValues(
410             Map JavaDoc ctx,
411             HttpServletRequest JavaDoc request,
412             RollerContext rollerCtx,
413             WebsiteData website,
414             String JavaDoc locale) throws RollerException {
415         
416         mLogger.debug("Loading path values");
417         
418         String JavaDoc url = null;
419         if (website != null && !"zzz_none_zzz".equals(website.getHandle())) {
420             url = URLUtilities.getWeblogURL(website, locale, true);
421         } else {
422             url= RollerRuntimeConfig.getAbsoluteContextURL();
423         }
424         ctx.put("websiteURL", url);
425         ctx.put("baseURL", RollerRuntimeConfig.getRelativeContextURL() );
426         ctx.put("absBaseURL", RollerRuntimeConfig.getAbsoluteContextURL() );
427         ctx.put("ctxPath", RollerRuntimeConfig.getRelativeContextURL() );
428         ctx.put("uploadPath", ContextLoader.figureResourcePath());
429         
430         try {
431             URL JavaDoc absUrl = RequestUtils.absoluteURL(request, "/");
432             ctx.put("host", absUrl.getHost());
433         } catch (MalformedURLException JavaDoc e) {
434             throw new RollerException(e);
435         }
436     }
437     
438     
439     /**
440      * Determine URL path to Roller upload directory.
441      */

442     private static String JavaDoc figureResourcePath() {
443         
444         String JavaDoc uploadurl = null;
445         try {
446             uploadurl = RollerFactory.getRoller().getFileManager().getUploadUrl();
447         } catch(Exception JavaDoc e) {}
448         
449         return uploadurl;
450     }
451     
452     
453     /**
454      * If there is an ERROR or STATUS message in the session,
455      * place it into the Context for rendering later.
456      */

457     private static void loadStatusMessage(Map JavaDoc ctx, HttpServletRequest JavaDoc req) {
458         
459         mLogger.debug("Loading status message");
460         
461         HttpSession JavaDoc session = req.getSession(false);
462         String JavaDoc msg = null;
463         if (session != null)
464             msg = (String JavaDoc)session.getAttribute(RollerSession.ERROR_MESSAGE);
465         if (msg != null) {
466             ctx.put("errorMessage", msg);
467             session.removeAttribute(RollerSession.ERROR_MESSAGE);
468         }
469         
470         if (session != null)
471             msg = (String JavaDoc)session.getAttribute(RollerSession.STATUS_MESSAGE);
472         if (msg != null) {
473             ctx.put("statusMessage", msg);
474             session.removeAttribute(RollerSession.STATUS_MESSAGE);
475         }
476     }
477     
478     
479     private static void loadRequestParamKeys(Map JavaDoc ctx) {
480         
481         mLogger.debug("Loading request param keys");
482         
483         // Since Velocity *requires* accessor methods, these values from
484
// RollerRequest are not available to it, put them into the context
485
ctx.put("USERNAME_KEY", USERNAME_KEY);
486         ctx.put("WEBSITEID_KEY", WEBSITEID_KEY);
487         ctx.put("FOLDERID_KEY", FOLDERID_KEY);
488         ctx.put("NEWSFEEDID_KEY", NEWSFEEDID_KEY);
489         ctx.put("PAGEID_KEY", PAGEID_KEY);
490         ctx.put("PAGELINK_KEY", PAGELINK_KEY);
491         ctx.put("ANCHOR_KEY", ANCHOR_KEY);
492         ctx.put("EXCERPTS_KEY", EXCERPTS_KEY);
493         ctx.put("BOOKMARKID_KEY", BOOKMARKID_KEY);
494         ctx.put("REFERERID_KEY", REFERERID_KEY);
495         ctx.put("WEBLOGENTRYID_KEY", WEBLOGENTRYID_KEY);
496         ctx.put("WEBLOGCATEGORYNAME_KEY", WEBLOGCATEGORYNAME_KEY);
497         ctx.put("WEBLOGCATEGORYID_KEY", WEBLOGENTRIES_KEY);
498         ctx.put("WEBLOGENTRIES_KEY", WEBLOGENTRIES_KEY);
499         ctx.put("WEBLOGDAY_KEY", WEBLOGDAY_KEY);
500         ctx.put("WEBLOGCOMMENTID_KEY", WEBLOGCOMMENTID_KEY);
501     }
502        
503 }
504
Popular Tags