001: /*
002: * Licensed to the Apache Software Foundation (ASF) under one or more
003: * contributor license agreements. The ASF licenses this file to You
004: * under the Apache License, Version 2.0 (the "License"); you may not
005: * use this file except in compliance with the License.
006: * You may obtain a copy of the License at
007: *
008: * http://www.apache.org/licenses/LICENSE-2.0
009: *
010: * Unless required by applicable law or agreed to in writing, software
011: * distributed under the License is distributed on an "AS IS" BASIS,
012: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013: * See the License for the specific language governing permissions and
014: * limitations under the License. For additional information regarding
015: * copyright in this work, please see the NOTICE file in the top level
016: * directory of this distribution.
017: */
018:
019: package org.apache.roller.ui.rendering.velocity.deprecated;
020:
021: import java.net.MalformedURLException;
022: import java.net.URL;
023: import java.text.SimpleDateFormat;
024: import java.util.ArrayList;
025: import java.util.Date;
026: import java.util.Locale;
027: import java.util.Map;
028: import javax.servlet.ServletContext;
029: import javax.servlet.http.HttpServletRequest;
030: import javax.servlet.http.HttpServletResponse;
031: import javax.servlet.http.HttpSession;
032: import javax.servlet.jsp.PageContext;
033: import org.apache.commons.logging.Log;
034: import org.apache.commons.logging.LogFactory;
035: import org.apache.roller.RollerException;
036: import org.apache.roller.config.RollerConfig;
037: import org.apache.roller.config.RollerRuntimeConfig;
038: import org.apache.roller.business.Roller;
039: import org.apache.roller.business.RollerFactory;
040: import org.apache.roller.pojos.CommentData;
041: import org.apache.roller.pojos.FolderData;
042: import org.apache.roller.pojos.RollerPropertyData;
043: import org.apache.roller.pojos.Template;
044: import org.apache.roller.pojos.WeblogCategoryData;
045: import org.apache.roller.pojos.WeblogEntryData;
046: import org.apache.roller.pojos.WebsiteData;
047: import org.apache.roller.pojos.wrapper.CommentDataWrapper;
048: import org.apache.roller.pojos.wrapper.TemplateWrapper;
049: import org.apache.roller.pojos.wrapper.WeblogEntryDataWrapper;
050: import org.apache.roller.pojos.wrapper.WebsiteDataWrapper;
051: import org.apache.roller.ui.core.RollerContext;
052: import org.apache.roller.ui.core.RollerSession;
053: import org.apache.roller.ui.rendering.velocity.deprecated.NewsfeedCache;
054: import org.apache.roller.ui.rendering.util.WeblogEntryCommentForm;
055: import org.apache.roller.ui.rendering.util.WeblogPageRequest;
056: import org.apache.roller.util.DateUtil;
057: import org.apache.roller.util.RegexUtil;
058: import org.apache.roller.util.URLUtilities;
059: import org.apache.struts.util.RequestUtils;
060: import org.apache.velocity.VelocityContext;
061:
062: /**
063: * Load Velocity Context with Roller objects, values, and custom plugins.
064: *
065: * NOTE: This class has been deprecated and should no longer be used. It is
066: * left here so that old weblogs which rely on it will continue to
067: * function properly. This should only be used by weblog pages.
068: */
069: public class ContextLoader {
070:
071: public static final String WEBLOG_KEY = "weblog";
072: public static final String ANCHOR_KEY = "entry";
073: public static final String ANCHOR_KEY_OLD = "anchor";
074: public static final String USERNAME_KEY = "username";
075:
076: public static final String PAGELINK_KEY = "pagelink";
077: public static final String EXCERPTS_KEY = "excerpts";
078: public static final String WEBLOGENTRY_COUNT = "count";
079: public static final String WEBLOGCATEGORYNAME_KEY = "cat";
080: public static final String WEBLOGENTRIES_KEY = "entries";
081: public static final String WEBLOGDAY_KEY = "day";
082:
083: public static final String WEBLOGENTRYID_KEY = "entryid";
084:
085: public static final String WEBLOGCATEGORYID_KEY = "categoryId";
086: public static final String PINGTARGETID_KEY = "pingtargetId";
087: public static final String REFERERID_KEY = "refId";
088: public static final String WEBLOGCOMMENTID_KEY = "commentId";
089: public static final String WEBSITEID_KEY = "websiteId";
090: public static final String BOOKMARKID_KEY = "bookmarkId";
091: public static final String FOLDERID_KEY = "folderId";
092: public static final String PARENTID_KEY = "parentId";
093: public static final String NEWSFEEDID_KEY = "feedId";
094: public static final String PAGEID_KEY = "pageId";
095: public static final String LOGIN_COOKIE = "sessionId";
096: public static final String OWNING_WEBSITE = "OWNING_WEBSITE";
097:
098: private static Log mLogger = LogFactory.getLog(ContextLoader.class);
099:
100: /**
101: * Setup the a Velocity context by loading it with objects, values, and
102: * RollerPagePlugins needed for Roller page execution.
103: */
104: public static void setupContext(Map ctx,
105: HttpServletRequest request, HttpServletResponse response,
106: PageContext pageContext, WeblogPageRequest pageRequest)
107: throws RollerException {
108:
109: mLogger.debug("setupContext( ctx = " + ctx + ")");
110:
111: RollerContext rollerCtx = RollerContext.getRollerContext();
112:
113: WebsiteData weblog = null;
114: WeblogEntryData entry = null;
115: WeblogCategoryData category = null;
116: Template page = null;
117: FolderData folder = null; // don't even know how this is involved :/
118: Date date = null;
119: boolean isDay = false;
120: boolean isMonth = false;
121: String locale = null;
122:
123: // get data from page request
124: locale = pageRequest.getLocale();
125: weblog = pageRequest.getWeblog();
126: entry = pageRequest.getWeblogEntry();
127: category = pageRequest.getWeblogCategory();
128: page = pageRequest.getWeblogPage();
129: if (page == null) {
130: page = weblog.getDefaultPage();
131: }
132:
133: // setup date, isDay, and isMonth
134: if (pageRequest.getWeblogDate() != null) {
135:
136: Date now = new Date();
137: if (pageRequest.getWeblogDate().length() == 8) {
138: isDay = true;
139: try {
140: date = DateUtil.get8charDateFormat().parse(
141: pageRequest.getWeblogDate());
142: if (date.after(now)) {
143: date = now;
144: }
145: } catch (Exception e) {
146: // bleh
147: }
148: } else if (pageRequest.getWeblogDate().length() == 6) {
149: isMonth = true;
150: try {
151: date = DateUtil.get6charDateFormat().parse(
152: pageRequest.getWeblogDate());
153: if (date.after(now)) {
154: date = now;
155: }
156: } catch (Exception e) {
157: // bleh
158: }
159: } else {
160: isMonth = true;
161: }
162: }
163:
164: try {
165: // Add old page model object to context
166: OldWeblogPageModel pageModel = new OldWeblogPageModel();
167: pageModel.init(request, weblog, entry, category, date,
168: isDay, isMonth, locale);
169: ctx.put("pageModel", pageModel);
170:
171: // along with old pages list :/
172: ctx.put("pages", pageModel.getPages());
173:
174: } catch (Exception e) {
175: throw new RollerException("ERROR creating Page Model", e);
176: }
177:
178: // Add page helper to context
179: OldPageHelper pageHelper = new OldPageHelper(request, response,
180: ctx, weblog, (date == null) ? new Date() : date,
181: folder, page.getName(), pageContext, pageRequest);
182: ctx.put("pageHelper", pageHelper);
183:
184: // Load standard Roller objects and values into the context
185: loadWeblogValues(ctx, weblog, pageRequest.getLocaleInstance(),
186: request);
187: loadPathValues(ctx, request, rollerCtx, weblog, locale);
188: loadRssValues(ctx, request, weblog, category);
189: loadUtilityObjects(ctx, request, rollerCtx, weblog, page);
190: loadRequestParamKeys(ctx);
191: loadStatusMessage(ctx, request);
192:
193: // If single entry is specified, load comments too
194: if (entry != null) {
195: loadCommentValues(ctx, request, entry);
196: }
197: }
198:
199: /**
200: * Load website object and related objects.
201: */
202: private static void loadWeblogValues(Map ctx, WebsiteData weblog,
203: Locale locale, HttpServletRequest request)
204: throws RollerException {
205:
206: // weblog cannot be null
207: if (weblog == null)
208: return;
209:
210: Roller mRoller = RollerFactory.getRoller();
211: Map props = mRoller.getPropertiesManager().getProperties();
212:
213: ctx.put("userName", weblog.getHandle());
214: ctx.put("fullName", weblog.getName());
215: ctx.put("emailAddress", weblog.getEmailAddress());
216: ctx.put("encodedEmail", RegexUtil.encode(weblog
217: .getEmailAddress()));
218: ctx.put("obfuscatedEmail", RegexUtil.obfuscateEmail(weblog
219: .getEmailAddress()));
220:
221: // setup Locale for future rendering
222: ctx.put("locale", weblog.getLocaleInstance());
223:
224: // setup Timezone for future rendering
225: ctx.put("timezone", weblog.getTimeZoneInstance());
226: ctx.put("timeZone", weblog.getTimeZoneInstance());
227: ctx.put("website", WebsiteDataWrapper.wrap(weblog));
228:
229: String siteName = ((RollerPropertyData) props.get("site.name"))
230: .getValue();
231: if ("Roller-based Site".equals(siteName))
232: siteName = "Main";
233: ctx.put("siteName", siteName);
234:
235: String siteShortName = ((RollerPropertyData) props
236: .get("site.shortName")).getValue();
237: ctx.put("siteShortName", siteShortName);
238:
239: // add language of the session (using locale specified by request)
240: ctx.put("viewLocale", locale);
241: mLogger.debug("context viewLocale = " + ctx.get("viewLocale"));
242:
243: // alternative display pages - customization
244: Template entryPage = weblog.getPageByName("_entry");
245: if (entryPage != null) {
246: ctx.put("entryPage", TemplateWrapper.wrap(entryPage));
247: }
248: // TODO: ATLAS: no templates use this, should be safe to remove
249: // Template descPage = weblog.getPageByName("_desc");
250: //if (descPage != null) {
251: //ctx.put("descPage", TemplateWrapper.wrap(descPage));
252: //}
253:
254: boolean commentsEnabled = RollerRuntimeConfig
255: .getBooleanProperty("users.comments.enabled");
256: boolean trackbacksEnabled = RollerRuntimeConfig
257: .getBooleanProperty("users.trackbacks.enabled");
258: boolean linkbacksEnabled = RollerRuntimeConfig
259: .getBooleanProperty("site.linkbacks.enabled");
260:
261: ctx.put("commentsEnabled", new Boolean(commentsEnabled));
262: ctx.put("trackbacksEnabled", new Boolean(trackbacksEnabled));
263: ctx.put("linkbacksEnabled", new Boolean(linkbacksEnabled));
264: }
265:
266: /**
267: * Load comments for one weblog entry and related objects.
268: */
269: private static void loadCommentValues(Map ctx,
270: HttpServletRequest request, WeblogEntryData entry)
271: throws RollerException {
272:
273: mLogger.debug("Loading comment values");
274:
275: String escapeHtml = RollerRuntimeConfig
276: .getProperty("users.comments.escapehtml");
277: String autoFormat = RollerRuntimeConfig
278: .getProperty("users.comments.autoformat");
279: ctx.put("isCommentPage", Boolean.TRUE);
280: ctx.put("escapeHtml", new Boolean(escapeHtml));
281: ctx.put("autoformat", new Boolean(autoFormat));
282:
283: // Make sure comment form object is available in context
284: WeblogEntryCommentForm commentForm = (WeblogEntryCommentForm) request
285: .getAttribute("commentForm");
286: if (commentForm == null) {
287: commentForm = new WeblogEntryCommentForm();
288:
289: // Set fields to spaces to please Velocity
290: commentForm.setName("");
291: commentForm.setEmail("");
292: commentForm.setUrl("");
293: commentForm.setContent("");
294: }
295: ctx.put("commentForm", commentForm);
296:
297: // Either put a preview comment in to context
298: if (commentForm.isPreview()) {
299: ArrayList list = new ArrayList();
300: list.add(commentForm.getPreviewComment());
301: ctx.put("previewComments", list);
302: }
303:
304: if (entry.getStatus().equals(WeblogEntryData.PUBLISHED)) {
305: ctx.put("entry", WeblogEntryDataWrapper.wrap(entry));
306: }
307: }
308:
309: /**
310: * Load objects needed for RSS and Atom newsfeed generation.
311: */
312: private static void loadRssValues(Map ctx,
313: HttpServletRequest request, WebsiteData website,
314: WeblogCategoryData category) throws RollerException {
315:
316: mLogger.debug("Loading rss values");
317:
318: int entryLength = -1;
319: String sExcerpts = request.getParameter("excerpts");
320: if (sExcerpts != null && sExcerpts.equalsIgnoreCase("true")) {
321: entryLength = 150;
322: }
323: ctx.put("entryLength", new Integer(entryLength));
324:
325: // Display same number of entries in feed as displayed on page
326: int entryCount = website.getEntryDisplayCount();
327:
328: // But don't exceed installation-wide maxEntries settings
329: int defaultEntries = RollerRuntimeConfig
330: .getIntProperty("site.newsfeeds.defaultEntries");
331: if (entryCount < 1)
332: entryCount = defaultEntries;
333: if (entryCount > defaultEntries)
334: entryCount = defaultEntries;
335: ctx.put("entryCount", new Integer(entryCount));
336:
337: String catname = null;
338: String catPath = null;
339: if (category != null) {
340: catname = category.getName();
341: catPath = category.getPath();
342: }
343: ctx.put("catname", (catname != null) ? catname : "");
344: ctx.put("catPath", (catPath != null) ? catPath : "");
345: ctx.put("updateTime", website.getLastModified());
346: ctx.put("now", new Date());
347: }
348:
349: /**
350: * Load useful utility objects for string and date formatting.
351: */
352: private static void loadUtilityObjects(Map ctx,
353: HttpServletRequest request, RollerContext rollerCtx,
354: WebsiteData website, Template page) throws RollerException {
355:
356: mLogger.debug("Loading utility objects");
357:
358: // date formatter for macro's set this up with the Locale to make
359: // sure we can reuse it with other patterns in the macro's
360: Locale viewLocale = (Locale) ctx.get("viewLocale");
361: SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd",
362: viewLocale);
363: if (website != null) {
364: sdf.setTimeZone(website.getTimeZoneInstance());
365: }
366: // add formatter to context
367: ctx.put("dateFormatter", sdf);
368:
369: // Note: in the macro's, the formats are taken from the ResourceBundles.
370: // Only the plainFormat is specified here, because it is used to render
371: // the Entry Day link.
372: ctx.put("plainFormat", "yyyyMMdd");
373:
374: ctx.put("page", TemplateWrapper.wrap(page));
375: ctx.put("utilities", new OldUtilities());
376: ctx.put("stringUtils", new OldStringUtils());
377: ctx.put("rollerVersion", rollerCtx.getRollerVersion());
378: ctx.put("rollerBuildTime", rollerCtx.getRollerBuildTime());
379: ctx.put("rollerBuildUser", rollerCtx.getRollerBuildUser());
380: ctx.put("newsfeedCache", NewsfeedCache.getInstance());
381:
382: ctx.put("requestParameters", request.getParameterMap());
383: }
384:
385: /**
386: * Load URL paths useful in page templates.
387: */
388: private static void loadPathValues(Map ctx,
389: HttpServletRequest request, RollerContext rollerCtx,
390: WebsiteData website, String locale) throws RollerException {
391:
392: mLogger.debug("Loading path values");
393:
394: String url = null;
395: if (website != null
396: && !"zzz_none_zzz".equals(website.getHandle())) {
397: url = URLUtilities.getWeblogURL(website, locale, true);
398: } else {
399: url = RollerRuntimeConfig.getAbsoluteContextURL();
400: }
401: ctx.put("websiteURL", url);
402: ctx.put("baseURL", RollerRuntimeConfig.getRelativeContextURL());
403: ctx.put("absBaseURL", RollerRuntimeConfig
404: .getAbsoluteContextURL());
405: ctx.put("ctxPath", RollerRuntimeConfig.getRelativeContextURL());
406: ctx.put("uploadPath", ContextLoader.figureResourcePath());
407:
408: try {
409: URL absUrl = RequestUtils.absoluteURL(request, "/");
410: ctx.put("host", absUrl.getHost());
411: } catch (MalformedURLException e) {
412: throw new RollerException(e);
413: }
414: }
415:
416: /**
417: * Determine URL path to Roller upload directory.
418: */
419: private static String figureResourcePath() {
420:
421: // legacy junk. this no longer makes any sense as of 3.0, but oh well
422: return "/resources";
423: }
424:
425: /**
426: * If there is an ERROR or STATUS message in the session,
427: * place it into the Context for rendering later.
428: */
429: private static void loadStatusMessage(Map ctx,
430: HttpServletRequest req) {
431:
432: mLogger.debug("Loading status message");
433:
434: HttpSession session = req.getSession(false);
435: String msg = null;
436: if (session != null)
437: msg = (String) session
438: .getAttribute(RollerSession.ERROR_MESSAGE);
439: if (msg != null) {
440: ctx.put("errorMessage", msg);
441: session.removeAttribute(RollerSession.ERROR_MESSAGE);
442: }
443:
444: if (session != null)
445: msg = (String) session
446: .getAttribute(RollerSession.STATUS_MESSAGE);
447: if (msg != null) {
448: ctx.put("statusMessage", msg);
449: session.removeAttribute(RollerSession.STATUS_MESSAGE);
450: }
451: }
452:
453: private static void loadRequestParamKeys(Map ctx) {
454:
455: mLogger.debug("Loading request param keys");
456:
457: // Since Velocity *requires* accessor methods, these values from
458: // RollerRequest are not available to it, put them into the context
459: ctx.put("USERNAME_KEY", USERNAME_KEY);
460: ctx.put("WEBSITEID_KEY", WEBSITEID_KEY);
461: ctx.put("FOLDERID_KEY", FOLDERID_KEY);
462: ctx.put("NEWSFEEDID_KEY", NEWSFEEDID_KEY);
463: ctx.put("PAGEID_KEY", PAGEID_KEY);
464: ctx.put("PAGELINK_KEY", PAGELINK_KEY);
465: ctx.put("ANCHOR_KEY", ANCHOR_KEY);
466: ctx.put("EXCERPTS_KEY", EXCERPTS_KEY);
467: ctx.put("BOOKMARKID_KEY", BOOKMARKID_KEY);
468: ctx.put("REFERERID_KEY", REFERERID_KEY);
469: ctx.put("WEBLOGENTRYID_KEY", WEBLOGENTRYID_KEY);
470: ctx.put("WEBLOGCATEGORYNAME_KEY", WEBLOGCATEGORYNAME_KEY);
471: ctx.put("WEBLOGCATEGORYID_KEY", WEBLOGENTRIES_KEY);
472: ctx.put("WEBLOGENTRIES_KEY", WEBLOGENTRIES_KEY);
473: ctx.put("WEBLOGDAY_KEY", WEBLOGDAY_KEY);
474: ctx.put("WEBLOGCOMMENTID_KEY", WEBLOGCOMMENTID_KEY);
475: }
476:
477: }
|