KickJava   Java API By Example, From Geeks To Geeks.

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


1 package org.roller.presentation.velocity;
2
3 import org.apache.commons.logging.Log;
4 import org.apache.commons.logging.LogFactory;
5 import org.apache.struts.Globals;
6 import org.apache.struts.util.RequestUtils;
7 import org.apache.velocity.VelocityContext;
8 import org.apache.velocity.app.Velocity;
9 import org.apache.velocity.context.Context;
10 import org.roller.RollerException;
11 import org.roller.pojos.RefererData;
12 import org.roller.pojos.UserData;
13 import org.roller.pojos.WeblogEntryData;
14 import org.roller.presentation.LanguageUtil;
15 import org.roller.presentation.RollerContext;
16 import org.roller.presentation.RollerRequest;
17 import org.roller.presentation.tags.calendar.CalendarModel;
18 import org.roller.presentation.tags.calendar.CalendarTag;
19 import org.roller.presentation.tags.menu.EditorNavigationBarTag;
20 import org.roller.presentation.tags.menu.MenuTag;
21 import org.roller.presentation.weblog.tags.BigWeblogCalendarModel;
22 import org.roller.presentation.weblog.tags.WeblogCalendarModel;
23 import org.roller.util.StringUtils;
24
25 import java.io.StringWriter JavaDoc;
26 import java.net.MalformedURLException JavaDoc;
27 import java.util.ArrayList JavaDoc;
28 import java.util.Collection JavaDoc;
29 import java.util.Hashtable JavaDoc;
30 import java.util.Iterator JavaDoc;
31 import java.util.List JavaDoc;
32 import java.util.Locale JavaDoc;
33 import java.util.Vector JavaDoc;
34
35 import javax.servlet.http.HttpServletRequest JavaDoc;
36 import javax.servlet.http.HttpServletResponse JavaDoc;
37 import javax.servlet.jsp.PageContext JavaDoc;
38
39 /**
40  * Provides assistance to VelociMacros, filling in where Velocity falls.
41  *
42  * @author llavandowska
43  * @author David M Johnson
44  *
45  */

46 public class PageHelper
47 {
48     private static Log mLogger =
49        LogFactory.getFactory().getInstance(PageHelper.class);
50     
51     private Context mVelocityContext = null;
52     private PageContext JavaDoc mPageContext = null;
53     private HttpServletResponse JavaDoc mResponse = null;
54     private RollerRequest mRollerReq = null;
55     private String JavaDoc mUsername = null;
56     private Collection JavaDoc mPagePlugins = new ArrayList JavaDoc();
57     private boolean mSkipFlag = false;
58     
59     //------------------------------------------------------------------------
60

61     /**
62      * Initialize VelocityHelper, setting the variables it will be hiding from
63      * the Velocimacros.
64      */

65     public PageHelper(
66             RollerRequest rreq, HttpServletResponse JavaDoc response, Context ctx)
67     {
68         mVelocityContext = ctx;
69         mRollerReq = rreq;
70         mResponse = response;
71         if (rreq != null)
72         {
73             mPageContext = rreq.getPageContext();
74             UserData user = null;
75             if ( rreq.getRequest().getAttribute(RollerRequest.OWNING_USER) != null)
76             {
77                 user = (UserData)
78                     rreq.getRequest().getAttribute(RollerRequest.OWNING_USER);
79             }
80             else if ( rreq.getUser() != null )
81             {
82                 user = rreq.getUser();
83             }
84             if ( user != null )
85             {
86                 mUsername = user.getUserName();
87             }
88         }
89         
90         if (mVelocityContext == null) mVelocityContext = new VelocityContext();
91     }
92     
93     //------------------------------------------------------------------------
94

95     /**
96      * Initialized VelocityHelper without a Velocity Context.
97      */

98     public PageHelper(RollerRequest rreq, HttpServletResponse JavaDoc response)
99     {
100         this(rreq, response, null);
101     }
102
103     //------------------------------------------------------------------------
104
/**
105      * Return a PageHelper with a new VelocityContext.
106      */

107     public static PageHelper createPageHelper(
108         HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
109     {
110         Context ctx = (Context)(new VelocityContext());
111         RollerRequest rreq = RollerRequest.getRollerRequest(request);
112         PageHelper pageHelper = new PageHelper(rreq, response, ctx);
113         pageHelper.initializePlugins(ContextLoader.getPagePlugins());
114
115         return pageHelper;
116     }
117
118     //------------------------------------------------------------------------
119
/**
120      * Create individual instances of the PagePlugins for use by this PageHelper.
121      */

122     protected void initializePlugins(Collection JavaDoc pluginClasses)
123     {
124         Iterator JavaDoc it = pluginClasses.iterator();
125         while (it.hasNext())
126         {
127             try
128             {
129                 PagePlugin plugin = (PagePlugin)it.next();
130                 plugin.init(mRollerReq, mVelocityContext);
131                 mPagePlugins.add(plugin);
132             }
133             catch (RollerException e)
134             {
135                 mLogger.warn("Unable to init() PagePlugin: ", e );
136             }
137         }
138     }
139
140     //------------------------------------------------------------------------
141
/**
142      * This is a quasi-hack: there are places we don't want to render the
143      * ReadMore Plugin in particular (I cannot think of other plugins
144      * which warrant this treatment). The "skip flag" will be made
145      * available to the Plugin if it wants to check to see if it should
146      * be skipped.
147      */

148     public void setSkipFlag(boolean skip)
149     {
150         mSkipFlag = skip;
151     }
152     
153     //------------------------------------------------------------------------
154

155     /**
156      * Another stupid helper method to make up for the shortcomings of Velocity.
157      * @return HashMap
158      */

159     public Hashtable JavaDoc addParam(String JavaDoc key, String JavaDoc value, Hashtable JavaDoc map)
160     {
161         if (map == null) map = new Hashtable JavaDoc();
162         if (key != null && value != null)
163             map.put(key, value);
164         return map;
165     }
166         
167     //------------------------------------------------------------------------
168

169     /**
170      * Evaluates the String as a Velocimacro, returning the results.
171      *
172      * @param str String
173      * @return String
174      */

175     public String JavaDoc evaluateString(String JavaDoc str)
176     {
177         if (mVelocityContext == null) return str;
178         
179         StringWriter JavaDoc sw = new StringWriter JavaDoc();
180         try
181         {
182             Velocity.evaluate( mVelocityContext, sw, "evalStr", str );
183             return sw.toString();
184         }
185         catch (Exception JavaDoc e)
186         {
187             mLogger.warn("VelocityHelper.evaluateString()", e);
188         }
189         return "";
190     }
191    
192     /** Build the URL for editing an WeblogEntry **/
193     public String JavaDoc getEntryEditUrl(WeblogEntryData entry)
194     {
195         Hashtable JavaDoc params = new Hashtable JavaDoc();
196         params.put( RollerRequest.WEBLOGENTRYID_KEY, entry.getId());
197         params.put( RollerRequest.ANCHOR_KEY, entry.getAnchor());
198         if (mUsername != null)
199         {
200             params.put( RollerRequest.USERNAME_KEY, mUsername);
201         }
202         try
203         {
204             return RequestUtils.computeURL( mPageContext,
205                 "weblogEdit", null, null, null, params, null, false);
206         }
207         catch (MalformedURLException JavaDoc mue)
208         {
209             mLogger.warn("RollerRequest.editEntryUrl exception: ", mue);
210         }
211         return
212            mRollerReq.getRequest().getContextPath() + "edtior/weblog.do?method=edit";
213     }
214     
215     //-------------------------------------------------------------------------
216
public String JavaDoc getToggleLinkbackDisplayHTML(RefererData referer)
217     {
218         String JavaDoc ret = "";
219         String JavaDoc link = null;
220         try
221         {
222             if ( mRollerReq.isUserAuthorizedToEdit() )
223             {
224                 Hashtable JavaDoc params = new Hashtable JavaDoc();
225                 params.put( RollerRequest.REFERERID_KEY, referer.getId());
226                 params.put( RollerRequest.USERNAME_KEY, mUsername);
227                 link = RequestUtils.computeURL( mPageContext,
228                     "toggleLinkback", null, null, null, params,null,false);
229                     
230                 StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
231                 sb.append("[<a HREF=\"");
232                 sb.append(link);
233                 if ( referer.getVisible().booleanValue() )
234                 {
235                     sb.append("\">Visible</a>] ");
236                 }
237                 else
238                 {
239                     sb.append("\">Hidden</a>] ");
240                 }
241                 ret = sb.toString();
242             }
243         }
244         catch (Exception JavaDoc e)
245         {
246            // should never happen, but if it does:
247
mLogger.error("ERROR creating toggle-linkback URL",e);
248         }
249         
250         return ret;
251     }
252     
253     //------------------------------------------------------------------------
254

255     public boolean isUserAuthorizedToEdit()
256     {
257         try
258         {
259             return mRollerReq.isUserAuthorizedToEdit();
260         }
261         catch (Exception JavaDoc e)
262         {
263             mLogger.warn("PageHelper.isUserAuthorizedToEdit)", e);
264         }
265         return false;
266     }
267     
268     //------------------------------------------------------------------------
269
public void setContentType( String JavaDoc type )
270     {
271         mResponse.setContentType(type);
272     }
273
274     //------------------------------------------------------------------------
275
/**
276      * Display big weblog calendar, well suited for an archive page.
277      * @return HTML for calendar.
278      */

279     public String JavaDoc showBigWeblogCalendar()
280     {
281         return showWeblogCalendar(true, null);
282     }
283         
284     //------------------------------------------------------------------------
285

286     /**
287      * Call hybrid EditorNavBarTag to render editor navbar.
288      * @param vertical True for vertical navbar.
289      * @return String HTML for navbar.
290      */

291     public String JavaDoc showEditorNavBar(boolean vertical)
292     {
293         EditorNavigationBarTag editorTag = new EditorNavigationBarTag();
294         editorTag.setPageContext(mPageContext);
295         if ( vertical )
296         {
297             editorTag.setView("/navbar-vertical.vm");
298         }
299         else
300         {
301             editorTag.setView("/navbar-horizontal.vm");
302         }
303         editorTag.setModel("editor-menu.xml");
304         return editorTag.emit();
305     }
306     
307     //------------------------------------------------------------------------
308

309     /**
310      * Call hybrid EditorNavBarTag to render editor navbar.
311      * @param model Name of XML file in WEB-INF that contains XML for menu.
312      * @param template Name of Velocity template in classpath to display menu.
313      * @return String HTML for menu.
314      */

315     public String JavaDoc showMenu(String JavaDoc model, String JavaDoc template)
316     {
317         MenuTag menuTag = new MenuTag();
318         menuTag.setPageContext(mPageContext);
319         menuTag.setModel(model);
320         menuTag.setView(template);
321         return menuTag.emit();
322     }
323     
324     //------------------------------------------------- WeblogCalendar methods
325

326     /**
327      * Display weblog calendar.
328      * @return HTML for calendar.
329      */

330     public String JavaDoc showWeblogCalendar()
331     {
332         return showWeblogCalendar(false, null);
333     }
334
335     //------------------------------------------------------------------------
336
/**
337      * Weblog calendar display implementation.
338      * @param big Show big archive style calendar.
339      * @return HTML for calendar.
340      */

341     public String JavaDoc showWeblogCalendar( boolean big, String JavaDoc cat )
342     {
343         if (PageModel.VELOCITY_NULL.equals(cat)) cat = null;
344         String JavaDoc ret = null;
345         try
346         {
347             HttpServletRequest JavaDoc request =
348                 (HttpServletRequest JavaDoc)mPageContext.getRequest();
349             HttpServletResponse JavaDoc response =
350                 (HttpServletResponse JavaDoc)mPageContext.getResponse();
351
352             String JavaDoc selfUrl = null;
353             String JavaDoc pageLink = mRollerReq.getPageLink();
354             if ( pageLink != null )
355             {
356                 selfUrl =
357                     request.getContextPath()+"/page/"+mUsername+"/"+pageLink;
358             }
359             else
360             {
361                 selfUrl = request.getContextPath()+"/page/"+mUsername;
362             }
363
364             // setup weblog calendar model
365
CalendarModel model = null;
366             if ( big )
367             {
368                 model = new BigWeblogCalendarModel(
369                            mRollerReq, response, selfUrl, cat);
370             }
371             else
372             {
373                 model = new WeblogCalendarModel(
374                             mRollerReq, response, selfUrl, cat);
375             }
376
377             // save model in JSP page context so CalendarTag can find it
378
mPageContext.setAttribute("calendarModel",model);
379
380             // Create and setup calendar tag
381
CalendarTag calTag = new CalendarTag();
382             calTag.setPageContext(mPageContext);
383             calTag.setName("calendar");
384             calTag.setModel("calendarModel");
385             //calTag.setLocale(mRollerReq.getWebsite().getLocaleInstance());
386
calTag.setLocale(LanguageUtil.getViewLocale(request));
387             //calTag.setTimeZone(mRollerReq.getWebsite().getTimeZoneInstance());
388
if ( big )
389             {
390                 calTag.setClassSuffix("Big");
391             }
392             ret = calTag.emit();
393         }
394         catch (Exception JavaDoc e)
395         {
396             mLogger.error("Unexpected exception",e);
397         }
398         return ret;
399     }
400     
401     //------------------------------------------------------------------------
402

403     /**
404      * Convenience method, contrived helper for Velocity.
405      * @param useIds
406      * @param isAction
407      * @param path
408      * @param val1
409      * @param val2
410      * @return String
411      */

412     public String JavaDoc strutsUrlHelper( boolean useIds, boolean isAction,
413         String JavaDoc path, String JavaDoc val1, String JavaDoc val2)
414     {
415         Hashtable JavaDoc params = new Hashtable JavaDoc();
416         return strutsUrlHelper( useIds, isAction, path, val1, val2, params);
417     }
418     
419     //------------------------------------------------------------------------
420

421     /**
422      * Very contrived helper method for Velocimacros generating Struts links.
423      * This is really only of use to the showNavBar macro.
424      * @param useIds
425      * @param isAction
426      * @param path
427      * @param val1
428      * @param val2
429      * @return String
430      */

431     public String JavaDoc strutsUrlHelper( boolean useIds, boolean isAction,
432         String JavaDoc path, String JavaDoc val1, String JavaDoc val2, Hashtable JavaDoc params)
433     {
434         if (useIds)
435         {
436             if (mRollerReq.getFolder() != null)
437             {
438                 params.put(RollerRequest.FOLDERID_KEY,
439                 mRollerReq.getFolder().getId());
440             }
441             if (mUsername != null)
442             {
443                 params.put(RollerRequest.USERNAME_KEY, mUsername);
444             }
445         }
446         
447         if (StringUtils.isNotEmpty(val1) && !val1.equals("null"))
448         {
449             params.clear();
450             params.put("rmk", val1);
451             params.put("rmik", val2);
452         }
453         
454         String JavaDoc returnUrl = "";
455         try
456         {
457             if (isAction)
458             {
459                 returnUrl = RequestUtils.computeURL( mPageContext,
460                                 path, null, null, null, params, null, false);
461             }
462             else
463             {
464                 returnUrl = RequestUtils.computeURL( mPageContext,
465                                 null, path, null, null, params, null, false);
466             }
467         }
468         catch (MalformedURLException JavaDoc mue)
469         {
470             mLogger.warn("RollerRequest.strutsUrlHelper exception: ", mue);
471             returnUrl = "<span class=\"error\">ERROR generating link</span>";
472         }
473         return returnUrl;
474     }
475     
476     /**
477      * Pass the String through any PagePlugins that have been
478      * assigned to the PageHelper.
479      *
480      * @param str
481      * @return
482      */

483     public String JavaDoc renderPlugins(String JavaDoc str)
484     {
485         if (mPagePlugins != null)
486         {
487             Iterator JavaDoc iter = mPagePlugins.iterator();
488             while (iter.hasNext())
489             {
490                 str = ((PagePlugin)iter.next()).render(str);
491             }
492         }
493         return str;
494     }
495     
496     /**
497      * Pass the String through any PagePlugins that have been
498      * assigned to the PageHelper, as selected by the Entry.
499      *
500      * @param str
501      * @return
502      */

503     public String JavaDoc renderPlugins(WeblogEntryData entry)
504     {
505         // we have to make a copy to temporarily store the
506
// changes wrought by Plugins (otherwise they might
507
// end up persisted!).
508
WeblogEntryData copy = new WeblogEntryData(entry);
509         
510         if (mPagePlugins != null)
511         {
512             List JavaDoc entryPlugins = copy.getPluginsList();
513             // if no Entry plugins, don't bother looping.
514
if (entryPlugins != null && !entryPlugins.isEmpty())
515             {
516                 // need to do this to tell ReadMore not to do its job
517
// if we are in the "view one Entry" page.
518
if (mRollerReq == null || mRollerReq.getWeblogEntry() != null)
519                 {
520                     mSkipFlag = true;
521                 }
522                 
523                 // now loop over mPagePlugins, matching
524
// against Entry plugins (by name):
525
// where a match is found render Plugin.
526
Iterator JavaDoc iter = mPagePlugins.iterator();
527                 PagePlugin pagePlugin = null;
528                 while (iter.hasNext())
529                 {
530                     pagePlugin = (PagePlugin)iter.next();
531                     if (entryPlugins.contains(pagePlugin.getName()))
532                     {
533                         copy.setText((pagePlugin).render(copy, mSkipFlag));
534                     }
535                 }
536             }
537         }
538         return copy.getText();
539     }
540     
541     /**
542      * This method returns an array of Locales for each supported
543      * language available, with the exeception of the language of the
544      * current locale, if that language is supported.
545      *
546      * So, if English and Dutch are supported, and the current Locale is Dutch,
547      * only English is returned. If the current Locale is Spanish, both English and Dutch are
548      * returned.
549      *
550      * @return
551      */

552     public Locale JavaDoc[] getSupportedLanguages()
553     {
554         Locale JavaDoc currentLocale =
555             (Locale JavaDoc) mPageContext.getSession().getAttribute(Globals.LOCALE_KEY);
556         if (currentLocale==null)
557         {
558             currentLocale = mPageContext.getRequest().getLocale();
559         }
560             
561         Locale JavaDoc[] supportedLanguages =
562             LanguageUtil.getSupportedLanguages(mPageContext.getServletContext());
563         if (supportedLanguages==null) {
564             return null;
565         }
566         
567         // filter out the current selected language
568
Vector JavaDoc result = new Vector JavaDoc();
569         for (int i = 0; i < supportedLanguages.length; i++)
570         {
571             if (currentLocale == null
572                 || (!supportedLanguages[i].equals(currentLocale)
573                 && !supportedLanguages[i].equals(
574                     new Locale JavaDoc(currentLocale.getLanguage())))
575                 )
576             {
577                 result.add(supportedLanguages[i]);
578             }
579         }
580         return (Locale JavaDoc[]) result.toArray(new Locale JavaDoc[result.size()]);
581     }
582
583     /**
584      * @return relative URL to page, starting with /username
585      */

586     public String JavaDoc getPathInfo()
587     {
588         return mRollerReq.getPathInfo();
589     }
590     
591     public String JavaDoc getCommentAuthenticatorHtml()
592     {
593         RollerContext rctx =
594             RollerContext.getRollerContext(mRollerReq.getRequest());
595         return rctx.getCommentAuthenticator().getHtml(
596             mVelocityContext, mRollerReq.getRequest(), mResponse);
597     }
598 }
599
Popular Tags