KickJava   Java API By Example, From Geeks To Geeks.

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


1
2 package org.roller.presentation.velocity;
3
4 import org.apache.commons.logging.Log;
5 import org.apache.commons.logging.LogFactory;
6 import org.apache.velocity.Template;
7 import org.apache.velocity.VelocityContext;
8 import org.apache.velocity.runtime.RuntimeSingleton;
9 import org.roller.model.RefererManager;
10 import org.roller.model.UserManager;
11 import org.roller.pojos.PageData;
12 import org.roller.pojos.RefererData;
13 import org.roller.pojos.UserData;
14 import org.roller.pojos.WeblogCategoryData;
15 import org.roller.pojos.WebsiteData;
16 import org.roller.presentation.RollerContext;
17 import org.roller.presentation.RollerRequest;
18 import org.roller.presentation.bookmarks.tags.ViewBookmarksTag;
19 import org.roller.presentation.tags.menu.EditorNavigationBarTag;
20 import org.roller.presentation.tags.menu.NavigationBarTag;
21 import org.roller.presentation.weblog.tags.RssBadgeTag;
22 import org.roller.presentation.weblog.tags.ViewWeblogEntriesTag;
23 import org.roller.presentation.weblog.tags.WeblogCategoryChooserTag;
24 import org.roller.util.Utilities;
25
26 import java.io.PrintWriter JavaDoc;
27 import java.io.StringWriter JavaDoc;
28 import java.text.SimpleDateFormat JavaDoc;
29 import java.util.ArrayList JavaDoc;
30 import java.util.Date JavaDoc;
31 import java.util.Iterator JavaDoc;
32 import java.util.List JavaDoc;
33
34 import javax.servlet.ServletContext JavaDoc;
35 import javax.servlet.http.HttpServletRequest JavaDoc;
36 import javax.servlet.http.HttpServletResponse JavaDoc;
37 import javax.servlet.jsp.PageContext JavaDoc;
38 import org.roller.config.RollerRuntimeConfig;
39 import org.roller.model.RollerFactory;
40
41 /**
42  * Provides the macros object that is available to Roller templates and
43  * weblog entries.
44  */

45 public class Macros
46 {
47     private static Log mLogger =
48         LogFactory.getFactory().getInstance(Macros.class);
49
50     protected PageContext JavaDoc mPageContext = null;
51     
52     protected PageHelper mPageHelper = null;
53
54     /** Maximum depth of recursion for includePage and showWeblogEntry calls */
55     public static final int MAX_RECURSION_DEPTH = 6;
56     
57     /** Keep track of each thread's recursive depth in includePage(). */
58     protected static final ThreadLocal JavaDoc mIncludePageTLS = new ThreadLocal JavaDoc();
59     
60     /** Keep track of each thread's recursive depth in showWeblogEntries(s */
61     protected static final ThreadLocal JavaDoc mEntriesTLS = new ThreadLocal JavaDoc();
62     
63     /** Keep track of each thread's recursive depth in showWeblogEntries(s */
64     protected static final ThreadLocal JavaDoc mEntriesDayTLS = new ThreadLocal JavaDoc();
65
66     //------------------------------------------------------------------------
67
/** Construts a macros object for a JSP page context. */
68     public Macros( PageContext JavaDoc ctx, PageHelper helper )
69     {
70         mPageContext = ctx;
71         mPageHelper = helper;
72     }
73
74     //------------------------------------------------------------------------
75
/** Get the Roller request object associated with this instance */
76     protected RollerRequest getRollerRequest()
77     {
78         return RollerRequest.getRollerRequest(mPageContext);
79     }
80
81     //------------------------------------------------------------------------
82
/**
83      * Returns the current date formatted according to the specified pattern.
84      * @param pattern Date pattern, @see java.text.SimpleDateFormat
85      * @return Current date formatted according to specified pattern.
86      */

87     public String JavaDoc formatCurrentDate( String JavaDoc pattern )
88     {
89         String JavaDoc date = null;
90         try
91         {
92             SimpleDateFormat JavaDoc format = new SimpleDateFormat JavaDoc( pattern );
93             date = format.format( new Date JavaDoc() );
94         }
95         catch (RuntimeException JavaDoc e)
96         {
97             date = "ERROR: formatting date";
98         }
99         return date;
100     }
101
102     //------------------------------------------------------------------------
103
/**
104      * Returns most recent update time of collection of weblog entries using
105      * the specified pattern.
106      * @param weblogEntries Collection of weblog entries.
107      * @param Date format pattern, @see java.text.SimpleDateFormat.
108      * @return Most recent update time formatted by pattern.
109      */

110     public String JavaDoc formatUpdateTime( ArrayList JavaDoc weblogEntries, String JavaDoc pattern )
111     {
112         String JavaDoc date = null;
113         Date JavaDoc updateTime = getUpdateTime(weblogEntries);
114         try
115         {
116             SimpleDateFormat JavaDoc format = new SimpleDateFormat JavaDoc( pattern );
117             date = format.format( updateTime );
118         }
119         catch (RuntimeException JavaDoc e)
120         {
121             date = "ERROR: formatting date";
122         }
123         return date;
124     }
125    
126     //------------------------------------------------------------------------
127
/**
128      * Returns most recent update time of collection of weblog entries.
129      * @param weblogEntries Collection of weblog entries.
130      * @return Most recent update time.
131      */

132     public Date JavaDoc getUpdateTime( ArrayList JavaDoc weblogEntries )
133     {
134         return PageModel.getUpdateTime( weblogEntries );
135     }
136    
137     //------------------------------------------------------------------------
138
/**
139      * Version number of Roller.
140      * @return Version number of Roller.
141      */

142     public String JavaDoc showVersion()
143     {
144         ServletContext JavaDoc ctx = mPageContext.getServletContext();
145         return ctx.getInitParameter( RollerContext.VERSION_KEY );
146     }
147     //------------------------------------------------------------------------
148
/**
149      * Title of your website.
150      * @return Title of your website.
151      */

152     public String JavaDoc showWebsiteTitle()
153     {
154         WebsiteData wd = null;
155         RollerRequest rreq = getRollerRequest();
156         try {
157             wd = rreq.getWebsite();
158         }
159         catch (Exception JavaDoc e) {
160             return "ERROR finding website in request: " + e.toString();
161         }
162         return wd.getName();
163     }
164     //------------------------------------------------------------------------
165
/**
166      * Website description.
167      * @return Website description.
168      */

169     public String JavaDoc showWebsiteDescription()
170     {
171         WebsiteData wd = null;
172         RollerRequest rreq = getRollerRequest();
173         try {
174             wd = rreq.getWebsite();
175         }
176         catch (Exception JavaDoc e) {
177             return "ERROR finding website in request: " + e.toString();
178         }
179         return wd.getDescription();
180     }
181     //------------------------------------------------------------------------
182
/**
183      * Show navigation links for pages that are not hidden.
184      * @param vertical Display links in a vertical column, separated by BR tags.
185      * @return HTML for navigation bar.
186      */

187     public String JavaDoc showNavBar( boolean vertical )
188     {
189         NavigationBarTag navTag = new NavigationBarTag();
190         navTag.setPageContext(mPageContext);
191         navTag.setVertical(vertical);
192         return navTag.emit();
193     }
194     //------------------------------------------------------------------------
195
/**
196      * Show navigation links for pages that are not hidden, separated by a
197      * specified delimeter.
198      * @param vertical Display links in a vertical column.
199      * @param delimeter Delimeter to separate links.
200      * @return HTML for navigation bar.
201      */

202     public String JavaDoc showNavBar( boolean vertical, String JavaDoc delimiter )
203     {
204         NavigationBarTag navTag = new NavigationBarTag();
205         navTag.setPageContext(mPageContext);
206         navTag.setVertical(vertical);
207         navTag.setDelimiter(delimiter);
208         return navTag.emit();
209     }
210     //------------------------------------------------------------------------
211
/**
212      * Show the Roller Editor menu as a navigation bar.
213      * specified delimeter.
214      * @param vertical Displaylinks in a vertical column.
215      * @return HTML for navigation bar.
216      * */

217     public String JavaDoc showEditorNavBar( boolean vertical )
218     {
219         EditorNavigationBarTag editorTag = new EditorNavigationBarTag();
220         editorTag.setPageContext(mPageContext);
221         if ( vertical )
222         {
223             editorTag.setView("/navbar-vertical.vm");
224         }
225         else
226         {
227             editorTag.setView("/navbar-horizontal.vm");
228         }
229         editorTag.setModel("editor-menu.xml");
230         return editorTag.emit();
231     }
232
233     //------------------------------------------------------------------------
234

235     /**
236      * Display bookmarks in specified folder using specified title.
237      * @param folderName Folder to be dislayed.
238      * @param title Title to be displayed.
239      * @return HTML for bookmarks display.
240      */

241     public String JavaDoc showBookmarks( String JavaDoc folderName, String JavaDoc title )
242     {
243         ViewBookmarksTag booksTag = new ViewBookmarksTag();
244         booksTag.setPageContext(mPageContext);
245         return booksTag.view( folderName, title );
246     }
247
248     /**
249      * Display bookmarks in specified folder using specified title.
250      * @param folderName Folder to be dislayed.
251      * @param showFolderName Display folder name as title.
252      * @return HTML for bookmarks display.
253      */

254     public String JavaDoc showBookmarks( String JavaDoc folderName, boolean showFolderName )
255     {
256         ViewBookmarksTag booksTag = new ViewBookmarksTag();
257         booksTag.setPageContext(mPageContext);
258         return booksTag.view( folderName, showFolderName );
259     }
260
261     /**
262      * Display bookmarks in specified folder as an expandable link.
263      * @param folderName Folder to be dislayed.
264      * @param showFolderName Display folder name as title.
265      * @param expandingFolder Show bookmarks in expanding folder.
266      * @return HTML and JavaScript for bookmarks display.
267      */

268     public String JavaDoc showBookmarks(
269         String JavaDoc folderName, boolean showFolderName, boolean expandingFolder )
270     {
271         ViewBookmarksTag booksTag = new ViewBookmarksTag();
272         booksTag.setPageContext(mPageContext);
273         return booksTag.view( folderName, showFolderName, expandingFolder );
274     }
275
276     //------------------------------------------------------------------------
277
/**
278      * Get {@link org.roller.pojos.UserData UserData} object.
279      * @see org.roller.pojos.UserData
280      * @return User object.
281      */

282     public UserData getUser()
283     {
284         try
285         {
286             return getRollerRequest().getUser();
287         }
288         catch (Exception JavaDoc e)
289         {
290             mLogger.error("Getting user",e);
291         }
292         return null;
293     }
294
295     //------------------------------------------------------------------------
296
/**
297      * Get
298      * {@link org.roller.presentation.users.WebsiteDataEx WebsiteDataEx}
299      * object.
300      * @see org.roller.pojos.WebsiteData
301      * @return Website object.
302      */

303     public WebsiteData getWebsite()
304     {
305         try
306         {
307             return getRollerRequest().getWebsite();
308         }
309         catch (Exception JavaDoc e)
310         {
311             mLogger.error("Getting website",e);
312         }
313         return null;
314     }
315
316     //------------------------------------------------------------------------
317
/**
318      * Show weblog enties using the day template specified in your site
319      * settings.
320      * @return HTML for weblog entries.
321      */

322     public String JavaDoc showWeblogEntries()
323     {
324         return showWeblogEntries(15);
325     }
326
327     //------------------------------------------------------------------------
328
/**
329      * Show up to 100 weblog enties using the day template specified in your site
330      * settings.
331      * @param maxEntries Maximum number of entries to display.
332      * @return HTML for weblog entries.
333      */

334     public String JavaDoc showWeblogEntries(int maxEntries)
335     {
336         String JavaDoc ret = null;
337         try
338         {
339             // protection from recursion
340
if ( mEntriesTLS.get() == null )
341             {
342                 mEntriesTLS.set( new Integer JavaDoc(0) );
343             }
344             else
345             {
346                 Integer JavaDoc countObj = (Integer JavaDoc)mEntriesTLS.get();
347                 int count = countObj.intValue();
348                 if ( count++ > MAX_RECURSION_DEPTH )
349                 {
350                     return "ERROR: recursion level too deep";
351                 }
352                 mEntriesTLS.set( new Integer JavaDoc(count) );
353             }
354
355             ViewWeblogEntriesTag entriesTag = new ViewWeblogEntriesTag();
356             entriesTag.setPageContext(mPageContext);
357             entriesTag.setMaxEntries(maxEntries);
358             ret = entriesTag.emit();
359         }
360         finally
361         {
362             mEntriesTLS.set( null );
363         }
364
365         return ret;
366     }
367
368     //------------------------------------------------------------------------
369
/**
370      * Show most recent 15 weblog enties using specified day template.
371      * @param dayTemplate Name of day template.
372      * @return HTML for weblog entries.
373      */

374     public String JavaDoc showWeblogEntries( String JavaDoc dayTemplate )
375     {
376         return showWeblogEntries(dayTemplate,15);
377     }
378
379     //------------------------------------------------------------------------
380
/**
381      * Show weblog enties using specified day template.
382      * @param dayTemplate Name of day template.
383      * @param maxEntries Maximum number of entries to display.
384      * @return HTML for weblog entries.
385      */

386     public String JavaDoc showWeblogEntries( String JavaDoc dayTemplate, int maxEntries )
387     {
388         String JavaDoc ret = null;
389         try
390         {
391             // protection from recursion
392
if ( mEntriesDayTLS.get() == null )
393             {
394                 mEntriesDayTLS.set( new Integer JavaDoc(0) );
395             }
396             else
397             {
398                 Integer JavaDoc countObj = (Integer JavaDoc)mEntriesDayTLS.get();
399                 int count = countObj.intValue();
400                 if ( count++ > MAX_RECURSION_DEPTH )
401                 {
402                     return "ERROR: recursion level too deep";
403                 }
404                 mEntriesDayTLS.set( new Integer JavaDoc(count) );
405             }
406
407             ViewWeblogEntriesTag entriesTag = new ViewWeblogEntriesTag();
408             entriesTag.setPageContext(mPageContext);
409             entriesTag.setMaxEntries(maxEntries);
410             entriesTag.setDayTemplate( dayTemplate );
411             ret = entriesTag.emit();
412         }
413         finally
414         {
415             mEntriesDayTLS.set( null );
416         }
417         return ret;
418     }
419
420     //------------------------------------------------------------------------
421
/**
422      * Display weblog calendar.
423      * @return HTML for calendar.
424      */

425     public String JavaDoc showWeblogCalendar()
426     {
427         return showWeblogCalendar(false);
428     }
429
430     //------------------------------------------------------------------------
431
/**
432      * Display big weblog calendar, well suited for an archive page.
433      * @return HTML for calendar.
434      */

435     public String JavaDoc showBigWeblogCalendar()
436     {
437         return showWeblogCalendar(true);
438     }
439
440     //------------------------------------------------------------------------
441
/**
442      * Weblog calendar display implementation.
443      * @param big Show big archive style calendar.
444      * @return HTML for calendar.
445      */

446     public String JavaDoc showWeblogCalendar( boolean big )
447     {
448         return mPageHelper.showWeblogCalendar(big, null);
449     }
450
451     //------------------------------------------------------------------------
452
/**
453      * Show a list of links to each of your weblog categores.
454      * @return HTML for category chooser.
455      */

456     public String JavaDoc showWeblogCategoryChooser()
457     {
458         WeblogCategoryChooserTag catTag = new WeblogCategoryChooserTag();
459         catTag.setPageContext(mPageContext);
460         return catTag.emit();
461     }
462
463     //------------------------------------------------------------------------
464
/**
465      * Show a list of links to each of your RSS feeds.
466      * @return HTML for RSS feed links.
467      */

468     public String JavaDoc showRSSLinks()
469     {
470         String JavaDoc links = "ERROR: creating RSS links";
471         try
472         {
473             RollerRequest rreq = getRollerRequest();
474             RollerContext rctx = RollerContext.getRollerContext(
475                 rreq.getServletContext());
476                 
477             UserData ud = rreq.getUser();
478
479             String JavaDoc baseUrl = rctx.getContextUrl(
480                 (HttpServletRequest JavaDoc)mPageContext.getRequest());
481             StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
482
483
484             sb.append("<a HREF=\"");
485             sb.append( baseUrl );
486             sb.append("/rss/");
487             sb.append( ud.getUserName() );
488             sb.append("\">All</a> ");
489             sb.append("[<a HREF=\"");
490             sb.append( baseUrl );
491             sb.append("/rss/");
492             sb.append( ud.getUserName() );
493             sb.append("?excerpts=true\">");
494             sb.append("excerpts</a>]");
495             sb.append("<br />");
496
497             List JavaDoc cats = rreq.getRoller().getWeblogManager()
498                 .getWeblogCategories(rreq.getWebsite(), false);
499             for (Iterator JavaDoc wbcItr = cats.iterator(); wbcItr.hasNext();) {
500                 WeblogCategoryData category = (WeblogCategoryData) wbcItr.next();
501                 String JavaDoc catName = category.getName();
502                 sb.append("<a HREF=\"");
503                 sb.append( baseUrl );
504                 sb.append("/rss/");
505                 sb.append( ud.getUserName() );
506                 sb.append("?catname=");
507                 sb.append( catName );
508                 sb.append("\">");
509                 sb.append( catName );
510                 sb.append("</a> ");
511                 sb.append("[<a HREF=\"");
512                 sb.append( baseUrl );
513                 sb.append("/rss/");
514                 sb.append( ud.getUserName() );
515                 sb.append("?catname=");
516                 sb.append( catName );
517                 sb.append("&amp;excerpts=true\">");
518                 sb.append("excerpts</a>]");
519                 sb.append("<br />");
520             }
521             
522             links = sb.toString();
523         }
524         catch (Exception JavaDoc e)
525         {
526             mLogger.error("Unexpected exception",e);
527         }
528         return links;
529     }
530
531     //------------------------------------------------------------------------
532
/**
533      * Show RSS auto-discovery element.
534      * @return HTML for RSS auto-discovery element.
535      */

536     public String JavaDoc showRSSAutodiscoveryLink()
537     {
538         String JavaDoc links = "ERROR: error generating RSS autodiscovery link";
539         try
540         {
541             RollerRequest rreq = RollerRequest.getRollerRequest(
542                 (HttpServletRequest JavaDoc)mPageContext.getRequest());
543             RollerContext rctx = RollerContext.getRollerContext(
544                 rreq.getServletContext());
545              
546             StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
547             sb.append("<link rel=\"alternate\" type=\"application/rss+xml\" ");
548             sb.append("title=\"RSS\" HREF=\"");
549             sb.append( rctx.getContextUrl(
550                 (HttpServletRequest JavaDoc)mPageContext.getRequest()) );
551             sb.append( "/rss/" );
552             sb.append( getUser().getUserName() );
553             sb.append( "\">" );
554             links = sb.toString();
555         }
556         catch (Throwable JavaDoc e)
557         {
558             mLogger.error("Showing RSS link",e);
559         }
560         return links;
561     }
562
563     //------------------------------------------------------------------------
564
/**
565      * Show RSS badge with link to your main RSS feed.
566      * @return HTML for RSS badge with link to your main RSS feed.
567      */

568     public String JavaDoc showRSSBadge()
569     {
570         RssBadgeTag rssTag = new RssBadgeTag();
571         rssTag.setPageContext(mPageContext);
572         return rssTag.emit();
573     }
574
575     //------------------------------------------------------------------------
576
/**
577      * Expand macros in specified page and include the results in this page.
578      * @param Name of page to include.
579      * @return HTML for included page.
580      */

581     public String JavaDoc includePage( String JavaDoc pageName )
582     {
583         String JavaDoc ret = null;
584         try
585         {
586             // protection from recursion
587
if ( mIncludePageTLS.get() == null )
588             {
589                 mIncludePageTLS.set( new Integer JavaDoc(0) );
590             }
591             else
592             {
593                 Integer JavaDoc countObj = (Integer JavaDoc)mIncludePageTLS.get();
594                 int count = countObj.intValue();
595                 if ( count++ > MAX_RECURSION_DEPTH )
596                 {
597                     return "ERROR: recursion level too deep";
598                 }
599                 mIncludePageTLS.set( new Integer JavaDoc(count) );
600             }
601                        
602             // Get included page template
603
RollerRequest rreq = RollerRequest.getRollerRequest(
604                 (HttpServletRequest JavaDoc)mPageContext.getRequest());
605             UserManager userMgr = rreq.getRoller().getUserManager();
606             
607             PageData pd = userMgr.getPageByName(
608                 rreq.getWebsite(), pageName );
609             Template vtemplate = null;
610             if (pd != null)
611             {
612                 vtemplate = RuntimeSingleton.getTemplate( pd.getId() );
613             }
614             else
615             {
616                 // maybe its in preview mode and doesn't exist yet?
617
vtemplate = RuntimeSingleton.getTemplate( pageName );
618             }
619             
620             if (vtemplate == null)
621             {
622                 ret = pageName + " : No Page or Template found.";
623             }
624             else
625             {
626                 // Run it through Velocity
627
StringWriter JavaDoc sw = new StringWriter JavaDoc();
628                 PrintWriter JavaDoc pw = new PrintWriter JavaDoc(sw);
629                 VelocityContext vcontext = new VelocityContext();
630                 ContextLoader.setupContext(vcontext,rreq,
631                     (HttpServletResponse JavaDoc)mPageContext.getResponse());
632                 
633                 vtemplate.merge( vcontext, pw );
634                 ret = sw.toString();
635             }
636         }
637         catch (Exception JavaDoc e)
638         {
639             ret = "ERROR: including page " + pageName;
640         }
641         finally
642         {
643             mIncludePageTLS.set( null );
644         }
645         return ret;
646     }
647
648     //------------------------------------------------------------------------
649
/**
650      * Shows HTML for an image in user's resource directory.
651      * @param fileName File name in resource directory
652      * @param linkUrl URL that image links to, null or empty if none
653      * @param alt Description of image and of link
654      * @param border For IMG tag's border attribute
655      * @param halign For IMG tag's halign attribute
656      * @param valign For IMG tag's valign attribute
657      * @return String HTML for displaying image
658      */

659     public String JavaDoc showResourceImage( String JavaDoc fileName, String JavaDoc linkUrl,
660         String JavaDoc alt, int border, String JavaDoc halign, String JavaDoc valign )
661     {
662         HttpServletRequest JavaDoc request =
663             (HttpServletRequest JavaDoc) mPageContext.getRequest();
664         String JavaDoc username = getRollerRequest().getUser().getUserName();
665         ServletContext JavaDoc app = mPageContext.getServletContext();
666
667         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
668         String JavaDoc uploadPath = null;
669         try {
670             uploadPath = RollerFactory.getRoller().getFileManager().getUploadUrl();
671         } catch(Exception JavaDoc e) {}
672         
673         if ( uploadPath != null && uploadPath.trim().length() > 0 )
674         {
675             sb.append( uploadPath );
676             sb.append( "/");
677             sb.append( username );
678             sb.append( "/");
679             sb.append( fileName);
680         }
681         else
682         {
683             sb.append( request.getContextPath() );
684             sb.append( RollerContext.USER_RESOURCES );
685             sb.append( "/");
686             sb.append( username );
687             sb.append( "/");
688             sb.append( fileName);
689         }
690         return showImage( sb.toString(),linkUrl,alt,border,halign,valign );
691     }
692
693     //------------------------------------------------------------------------
694
/**
695      * Shows HTML for an image in user's resource directory.
696      * @param imageUrl URL to image
697      * @param linkUrl URL that image links to, null or empty if none
698      * @param alt Description of image and of link
699      * @param border For IMG tag's border attribute
700      * @param halign For IMG tag's halign attribute
701      * @param valign For IMG tag's valign attribute
702      * @return String HTML for displaying image
703      */

704     public String JavaDoc showImage( String JavaDoc imageUrl, String JavaDoc linkUrl,
705         String JavaDoc alt, int border, String JavaDoc halign, String JavaDoc valign )
706     {
707         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
708         if ( linkUrl!=null && linkUrl.trim().length()>0 )
709         {
710             sb.append( "<a HREF=\"");
711             sb.append( linkUrl );
712             sb.append( "\" >");
713         }
714
715         sb.append("<img SRC=\"");
716         sb.append( imageUrl );
717         sb.append( "\" alt=\"");
718         sb.append( alt);
719         sb.append( "\" border=\"");
720         sb.append( border);
721         sb.append( "\" halign=\"");
722         sb.append( halign);
723         sb.append( "\" valign=\"");
724         sb.append( valign);
725         sb.append( "\" />");
726
727         if ( linkUrl!=null && linkUrl.trim().length()>0 )
728         {
729             sb.append( "</a>");
730         }
731
732         return sb.toString();
733     }
734
735     //------------------------------------------------------------------------
736
/**
737      * Gets path to images directory on your Roller server.
738      * @return Path to images directory on your Roller server.
739      */

740     public String JavaDoc showImagePath()
741     {
742         HttpServletRequest JavaDoc request =
743             (HttpServletRequest JavaDoc) mPageContext.getRequest();
744             
745         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
746         sb.append( request.getContextPath() );
747         sb.append( "/images" );
748         return sb.toString();
749     }
750
751     //------------------------------------------------------------------------
752
/**
753      * Gets path to your /resources directory, where you may have uploaded
754      * files.
755      * @return Resource path.
756      */

757     public String JavaDoc showResourcePath()
758     {
759         HttpServletRequest JavaDoc request =
760             (HttpServletRequest JavaDoc) mPageContext.getRequest();
761             
762         String JavaDoc username = getRollerRequest().getUser().getUserName();
763         
764         ServletContext JavaDoc app = mPageContext.getServletContext();
765                 
766         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
767         String JavaDoc uploadPath = null;
768         try {
769             uploadPath = RollerFactory.getRoller().getFileManager().getUploadUrl();
770         } catch(Exception JavaDoc e) {}
771         if ( uploadPath != null && uploadPath.trim().length() > 0 )
772         {
773             sb.append( uploadPath );
774         }
775         else
776         {
777             sb.append( request.getContextPath() );
778             sb.append( RollerContext.USER_RESOURCES );
779         }
780         sb.append( "/" );
781         sb.append( username );
782         return sb.toString();
783     }
784
785     //------------------------------------------------------------------------
786
/**
787      * This is a convenience method to calculate the path to a theme. It
788      * basically adds a contextPath and the themes directory.
789      * @param Name of theme.
790      * @return Theme path.
791      */

792     public String JavaDoc showThemePath( String JavaDoc theme )
793     {
794         String JavaDoc themesdir = RollerRuntimeConfig.getProperty("users.themes.path");
795         
796         HttpServletRequest JavaDoc request =
797             (HttpServletRequest JavaDoc)mPageContext.getRequest();
798         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
799         sb.append( request.getContextPath());
800         sb.append(themesdir);
801         sb.append( "/" );
802         sb.append( theme );
803         return sb.toString();
804     }
805
806     //------------------------------------------------------------------------
807
/**
808      * This is a convenience method to calculate the path to a theme image.
809      * @param theme Name of theme.
810      * @param imageName Name of image.
811      * @return Path to image in theme.
812      */

813     public String JavaDoc showThemeImagePath( String JavaDoc theme, String JavaDoc imageName )
814     {
815         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
816         sb.append( showThemePath(theme));
817         sb.append( "/images/");
818         sb.append( imageName);
819         return sb.toString();
820     }
821
822     //------------------------------------------------------------------------
823
/**
824      * Display a theme image.
825      * @param theme Name of theme.
826      * @param imageName Name of image.
827      * @return HTML for image.
828      */

829     public String JavaDoc showThemeImage( String JavaDoc theme, String JavaDoc imageName )
830     {
831         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
832         sb.append( "<img alt=\""+imageName+"\" SRC=\"");
833         sb.append( showThemeImagePath(theme, imageName));
834         sb.append( "\"/>");
835         return sb.toString();
836     }
837
838     //------------------------------------------------------------------------
839
/**
840      * Return the path to a theme's styles directory.
841      * @param theme Name of theme.
842      * @param stylesheet Name of stylesheet.
843      * @return Theme style path.
844      */

845     public String JavaDoc showThemeStylePath( String JavaDoc theme, String JavaDoc stylesheet )
846     {
847         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
848         sb.append( showThemePath(theme));
849         sb.append( "/styles/");
850         sb.append( stylesheet);
851         return sb.toString();
852     }
853
854     //------------------------------------------------------------------------
855
/**
856      * Return HTML for referencing a theme.
857      * @param theme Name of theme
858      * @param stylesheet Name of stylesheet in theme.
859      * @param useImport Use import statement rather than link element.
860      * @return HTML for importing theme.
861      */

862     public String JavaDoc showThemeStyle(
863         String JavaDoc theme, String JavaDoc stylesheet, boolean useImport )
864     {
865         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
866         if (useImport) {
867             sb.append( "<style type=\"text/css\">");
868             sb.append( "@import url(");
869             sb.append( showThemeStylePath(theme, stylesheet));
870             sb.append( ");");
871             sb.append( "</style>");
872         } else {
873             sb.append( "<link rel=\"stylesheet\" type=\"text/css\" HREF=\"");
874             sb.append( showThemeStylePath(theme, stylesheet));
875             sb.append( "\" />");
876         }
877         return sb.toString();
878     }
879
880     //------------------------------------------------------------------------
881
/**
882      * Convenience macro to import a stylesheet using the import statement.
883      * @param theme Theme name.
884      * @param stylesheet Name of stylesheet within theme.
885      * @return HTML for importing theme.
886      */

887     public String JavaDoc showThemeStyleImport( String JavaDoc theme, String JavaDoc stylesheet )
888     {
889         return showThemeStyle(theme, stylesheet, true);
890     }
891
892     //------------------------------------------------------------------------
893
/**
894      * Return the path to a theme's scripts directory.
895      * @param theme Name of theme.
896      * @param scriptFile Name of script in theme.
897      * @return Path to theme.
898      */

899     public String JavaDoc showThemeScriptPath( String JavaDoc theme, String JavaDoc scriptFile )
900     {
901         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
902         sb.append( showThemePath(theme));
903         sb.append( "/scripts/");
904         sb.append( scriptFile);
905         return sb.toString();
906     }
907
908     //------------------------------------------------------------------------
909
/**
910      * Return the full HTML to use a scriptFile, for example:
911      * <pre>
912      * <script type="text/javascript" SRC="../../../../../themes/default/scripts/sample.js">
913      * </script>.
914      * </pre>
915      * @param theme Name of theme.
916      * @param scriptFile Name of script in theme.
917      * @return Path to theme.
918      */

919     public String JavaDoc showThemeScript( String JavaDoc theme, String JavaDoc scriptFile)
920     {
921         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
922         sb.append( "<script type=\"text/javascript\" SRC=\"");
923         sb.append( showThemeScriptPath(theme, scriptFile));
924         sb.append( "\"></script>"); // a /> doesn't work in IE
925
return sb.toString();
926     }
927
928     //------------------------------------------------------------------------
929
/**
930      * Return the title of the current Roller page being processed.
931      * @return Title of the current Roller page being processed.
932      */

933     public String JavaDoc showPageName()
934     {
935         PageData pd = null;
936         RollerRequest rreq = getRollerRequest();
937         try
938         {
939             pd = rreq.getPage();
940         }
941         catch (Exception JavaDoc e) {
942             return "ERROR finding page in request: " + e.toString();
943         }
944         return pd.getName();
945     }
946
947     //------------------------------------------------------------------------
948
/**
949      * Return the description of the current Roller page being processed.
950      * @return Description of the current Roller page being processed.
951      */

952     public String JavaDoc showPageDescription()
953     {
954         PageData pd = null;
955         RollerRequest rreq = getRollerRequest();
956         try
957         {
958             pd = rreq.getPage();
959         }
960         catch (Exception JavaDoc e)
961         {
962             return "ERROR finding page in request: " + e.toString();
963         }
964         return pd.getDescription();
965     }
966
967     //------------------------------------------------------------------------
968
/**
969      * Return the updateTime of the current Roller page being processed.
970      * @return UpdateTime of the current Roller page being processed.
971      */

972     public String JavaDoc showPageUpdateTime()
973     {
974         PageData pd = null;
975         RollerRequest rreq = getRollerRequest();
976         try
977         {
978             pd = rreq.getPage();
979         }
980         catch (Exception JavaDoc e)
981         {
982             return "ERROR finding page in request: " + e.toString();
983         }
984         if (pd.getUpdateTime() == null) return "";
985         return pd.getUpdateTime().toString();
986     }
987
988     //------------------------------------------------------------------------
989
/**
990      * Show list of links to today's biggest referers. Shows up to up
991      * referers and limits each to 20 characters width.
992      * @return HTML to display referers.
993      */

994     public String JavaDoc showReferers()
995     {
996         return showReferers(15,20);
997     }
998
999     //------------------------------------------------------------------------
1000
/**
1001     * Show list of links to today's biggest referers. Shows up to up
1002     * specified number referers and limits each to 20 characters width.
1003     * @param max Maximum number of referers to display.
1004     * @return HTML to display referers.
1005     */

1006    public String JavaDoc showReferers( int max )
1007    {
1008        return showReferers(max,20);
1009    }
1010
1011    //------------------------------------------------------------------------
1012
/**
1013     * Show list of links to today's biggest referers. Shows up to up
1014     * specified number referers and limits each to specified characters width.
1015     * @param max Maximum number of referers to display.
1016     * @param maxWidth Maximum width in characters of each referer.
1017     * @return HTML to display referers.
1018     */

1019    public String JavaDoc showReferers( int max, int maxWidth )
1020    {
1021        try
1022        {
1023            RollerRequest rreq = getRollerRequest();
1024            RefererManager refmgr = rreq.getRoller().getRefererManager();
1025
1026            StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
1027            
1028            sb.append("Today's Page Hits:");
1029            sb.append( refmgr.getDayHits(rreq.getWebsite()) );
1030            sb.append("<br/>");
1031            sb.append("Total Page Hits:");
1032            sb.append( refmgr.getTotalHits(rreq.getWebsite()) );
1033            sb.append("<br/>");
1034
1035            List JavaDoc refs = refmgr.getTodaysReferers(rreq.getWebsite());
1036            sb.append("");
1037            sb.append("<ul class=\"rReferersList\">");
1038            int count = refs.size()>max ? max : refs.size();
1039            for (int i = 0; i < count; i++)
1040            {
1041                RefererData data = (RefererData)refs.get(i);
1042                sb.append("<li class=\"rReferersListItem\">");
1043                sb.append( data.getDisplayUrl( maxWidth, true ) );
1044                sb.append("</li>");
1045            }
1046            sb.append("</ul>");
1047
1048            return sb.toString();
1049        }
1050        catch (Exception JavaDoc e)
1051        {
1052            mLogger.error("Displaying referers list",e);
1053            return "ERROR: displaying referers list";
1054        }
1055    }
1056    
1057    //------------------------------------------------------------------------
1058
/**
1059     * Remove occurences of HTML from a string. Does this by stripping out
1060     * any text that exists between the characters "&lt;" and "&gt;".
1061     * @param s String that may contain some HTML.
1062     * @return String with no HTML.
1063     */

1064    public static String JavaDoc removeHTML(String JavaDoc s)
1065    {
1066        if ( s==null ) return "";
1067        else return Utilities.removeHTML(s);
1068    }
1069
1070    /**
1071     * Escape all characters that need to be escaped for HTML.
1072     * @param s String that may contain some special HTML characters.
1073     * @return String with special HTML characters escaped.
1074     */

1075    public static String JavaDoc escapeHTML( String JavaDoc s )
1076    {
1077        if ( s==null ) return "";
1078        else return Utilities.escapeHTML(s);
1079    }
1080
1081    /** Run both removeHTML and escapeHTML on a string.
1082     * @param s String to be run through removeHTML and escapeHTML.
1083     * @return String with HTML removed and HTML special characters escaped.
1084     */

1085    public static String JavaDoc removeAndEscapeHTML( String JavaDoc s )
1086    {
1087        if ( s==null ) return "";
1088        else return Utilities.escapeHTML( removeHTML(s) );
1089    }
1090}
1091
1092
1093
Popular Tags