KickJava   Java API By Example, From Geeks To Geeks.

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


1 package org.roller.presentation.velocity;
2
3 import java.util.ArrayList JavaDoc;
4 import java.util.Collection JavaDoc;
5 import java.util.Collections JavaDoc;
6 import java.util.Date JavaDoc;
7 import java.util.HashMap JavaDoc;
8 import java.util.Iterator JavaDoc;
9 import java.util.List JavaDoc;
10 import java.util.Map JavaDoc;
11
12 import org.apache.commons.logging.Log;
13 import org.apache.commons.logging.LogFactory;
14 import org.roller.RollerException;
15 import org.roller.config.RollerRuntimeConfig;
16 import org.roller.model.BookmarkManager;
17 import org.roller.model.RefererManager;
18 import org.roller.model.UserManager;
19 import org.roller.model.WeblogManager;
20 import org.roller.pojos.BookmarkComparator;
21 import org.roller.pojos.FolderData;
22 import org.roller.pojos.PageData;
23 import org.roller.pojos.RefererData;
24 import org.roller.pojos.UserData;
25 import org.roller.pojos.WeblogCategoryData;
26 import org.roller.pojos.WeblogEntryData;
27 import org.roller.pojos.WebsiteData;
28 import org.roller.presentation.RollerRequest;
29 import org.roller.util.StringUtils;
30
31 /**
32  * Provides Roller page templates with access to Roller domain model objects.
33  *
34  * @author llavandowska
35  * @author David M Johnson
36  */

37 public class PageModel
38 {
39     public final static String JavaDoc VELOCITY_NULL = "nil";
40     
41     protected static Log mLogger =
42        LogFactory.getFactory().getInstance(PageModel.class);
43     
44     private BookmarkManager mBookmarkMgr = null;
45     private WeblogManager mWeblogMgr = null;
46     private UserManager mUserMgr = null;
47     private RefererManager mRefererMgr = null;
48
49     private Map JavaDoc mCategories = new HashMap JavaDoc();
50     private HashMap JavaDoc mPageMap = new HashMap JavaDoc();
51     private RollerRequest mRollerReq = null;
52     private String JavaDoc mUsername = null;
53     
54     private WeblogEntryData mNextEntry = null;
55     private WeblogEntryData mPreviousEntry = null;
56
57     private WeblogEntryData mLastEntry = null;
58
59     private WeblogEntryData mFirstEntry;
60         
61     //------------------------------------------------------------------------
62

63     /** init() must be called to complete construction */
64     public PageModel() {}
65     
66     /**
67      * Initialize PageModel and allow PageModel to initialized VelocityContext.
68      * @param rreq
69      * @param ctx
70      */

71     public void init(RollerRequest rreq)
72     {
73         mRollerReq = rreq;
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         try
90         {
91             mBookmarkMgr = rreq.getRoller().getBookmarkManager();
92             mRefererMgr = rreq.getRoller().getRefererManager();
93             mUserMgr = rreq.getRoller().getUserManager();
94             mWeblogMgr = rreq.getRoller().getWeblogManager();
95             
96             /**
97              * Preload what we can for encapsulation. What we cannot preload we
98              * will use the Managers later to fetch.
99              */

100             if ( mUsername != null )
101             {
102                 // Get the pages, put into context & load map
103
WebsiteData website = mUserMgr.getWebsite(user.getUserName());
104                 List JavaDoc pages = mUserMgr.getPages(website);
105                 Iterator JavaDoc pageIter = pages.iterator();
106                 while (pageIter.hasNext())
107                 {
108                     PageData page = (PageData) pageIter.next();
109                     mPageMap.put(page.getName(), page);
110                 }
111             }
112             
113         }
114         catch (RollerException e)
115         {
116             mLogger.error("PageModel Roller get*Manager Exception", e);
117         }
118     }
119     
120     //------------------------------------------------------------------------
121

122     /** Encapsulates folder.getBookmarks() & sorting */
123     public Collection JavaDoc getBookmarks(FolderData folder)
124     {
125         Collection JavaDoc bookmarks = folder.getBookmarks();
126         List JavaDoc list = new ArrayList JavaDoc(bookmarks);
127         Collections.sort( list, new BookmarkComparator() );
128         return list;
129     }
130     
131     //------------------------------------------------------------------------
132

133     /** Get top level bookmark folders. */
134     public Collection JavaDoc getTopLevelFolders()
135     {
136         Collection JavaDoc tops = null;
137         try
138         {
139          tops= mBookmarkMgr.getRootFolder(
140                     mUserMgr.getWebsite(mUsername)).getFolders();
141         }
142         catch (RollerException e)
143         {
144             tops = new ArrayList JavaDoc();
145         }
146         return tops;
147     }
148     
149     //------------------------------------------------------------------------
150

151     /** Encapsulates WeblogManager.getComments().size() */
152     public int getCommentCount(String JavaDoc entryId)
153     {
154         try
155         {
156             return mWeblogMgr.getComments( entryId ).size();
157         }
158         catch (RollerException e)
159         {
160             mLogger.error("PageModel getCommentCount()", e);
161         }
162         return 0;
163     }
164     
165     //------------------------------------------------------------------------
166

167     /** Get comments for weblog entry specified by request */
168     public List JavaDoc getComments( WeblogEntryData entry )
169     {
170         try
171         {
172             return mWeblogMgr.getComments( entry.getId() );
173         }
174         catch (RollerException e)
175         {
176             mLogger.error("PageModel getComments()", e);
177         }
178         return new ArrayList JavaDoc();
179     }
180     
181     //------------------------------------------------------------------------
182

183     /** Encapsulates RefererManager */
184     public int getDayHits()
185     {
186         try
187         {
188             return mRefererMgr.getDayHits(mRollerReq.getWebsite());
189         }
190         catch (RollerException e)
191         {
192             mLogger.error("PageModel getDayHits()", e);
193         }
194         return 0;
195     }
196     
197     //------------------------------------------------------------------------
198

199     /** Encapsulates BookmarkManager.getFolder() */
200     public FolderData getFolder(String JavaDoc folderPath)
201     {
202         try
203         {
204             return mBookmarkMgr.getFolder(
205                 mUserMgr.getWebsite(mUsername), folderPath);
206         }
207         catch (RollerException e)
208         {
209             mLogger.error("PageModel getFolder()", e);
210         }
211         return null;
212     }
213         
214     //------------------------------------------------------------------------
215

216     /** Encapsulates UserManager.getPageByName() */
217     public PageData getUsersPageByName(WebsiteData website, String JavaDoc pageName)
218     {
219         PageData page = null;
220         try
221         {
222             if (website == null)
223                 throw new NullPointerException JavaDoc("website is null");
224                 
225             if (pageName == null)
226                 throw new NullPointerException JavaDoc("pageName is null");
227                 
228             page = mUserMgr.getPageByName(website, pageName);
229         }
230         catch (NullPointerException JavaDoc npe)
231         {
232             mLogger.warn(npe.getMessage());
233         }
234         catch (RollerException e)
235         {
236             mLogger.error("ERROR getting user's page by name: " + e.getMessage(),e);
237         }
238         return page;
239     }
240     
241     //------------------------------------------------------------------------
242

243     /** Encapsulates UserManager.getPageByName() */
244     public PageData getPageByName(String JavaDoc pageName)
245     {
246         return (PageData)mPageMap.get(pageName);
247     }
248     
249     //------------------------------------------------------------------------
250

251     /** Encapsulates UserManager.getPageByName() */
252     public String JavaDoc getPageIdByName(String JavaDoc pageName)
253     {
254         PageData pd = (PageData)mPageMap.get(pageName);
255         if ( pd != null )
256         {
257             return pd.getId();
258         }
259         else
260         {
261             return null;
262         }
263     }
264     
265     //------------------------------------------------------------------------
266

267     /**
268      * Get collection of user pages.
269      * @return
270      */

271     public Object JavaDoc getPages()
272     {
273         return mPageMap.values();
274     }
275     
276     //------------------------------------------------------------------------
277

278     /**
279      * Returns a map of up to 100 recent weblog entries for the user and day
280      * specified in the request, filtered by the category specified by the
281      * request, limited by the 'maxEntries' argument, and sorted by reverse
282      * chronological order.
283      *
284      * <p>This method will look for a category name in the following places
285      * and in the following order:</p>
286      * <ul>
287      * <li>The request via RollerRequest.getWeblogCategory().</li>
288      * <li>The categoryName argument to this method.</li>
289      * <li>The default category for the website specified by the request via
290      * RollerRequest.getWebsite().getDefaultCategory().</li>
291      * <li></li>
292      * </ul>
293      *
294      * @param maxEntries Maximum number of entries to be returned.
295      * @param categoryName Only return entries from this category and it's
296      * subcategories. If null, returns all categories of entry.
297      * @return Map of Lists of WeblogEntryData, keyed by 8-char date strings.
298      */

299     public Map JavaDoc getRecentWeblogEntries(int maxEntries, String JavaDoc categoryName)
300     {
301         if (VELOCITY_NULL.equals(categoryName)) categoryName = null;
302         Map JavaDoc ret = new HashMap JavaDoc();
303         try
304         {
305             Date JavaDoc day = mRollerReq.getDate();
306             if (day == null) day = new Date JavaDoc();
307             
308             // If request specifies a category, then use that
309
String JavaDoc catParam = null;
310             if (mRollerReq.getWeblogCategory() != null)
311             {
312                 catParam = mRollerReq.getWeblogCategory().getPath();
313             }
314             else if (categoryName != null)
315             {
316                 // use category argument instead
317
catParam = categoryName;
318             }
319             else if (mRollerReq.getWebsite() != null) // MAIN
320
{
321                 catParam = mRollerReq.getWebsite().getDefaultCategory().getPath();
322                 if (catParam.equals("/"))
323                 {
324                     catParam = null;
325                 }
326             }
327             
328             ret = mRollerReq.getRoller().getWeblogManager().getWeblogEntryObjectMap(
329                             mRollerReq.getWebsite(),
330                             null, // startDate
331
day, // endDate
332
catParam, // catName
333
WeblogManager.PUB_ONLY, // status
334
new Integer JavaDoc(maxEntries)); // maxEntries
335

336             setFirstAndLastEntries( ret );
337         }
338         catch (Exception JavaDoc e)
339         {
340             mLogger.error("PageModel getRecentWeblogEntries()", e);
341         }
342         return ret;
343     }
344     
345     //------------------------------------------------------------------------
346

347     /**
348      * Pull the last WeblogEntryData out of the Map.
349      * @param ret
350      */

351     private void setFirstAndLastEntries(Map JavaDoc days)
352     {
353         int numDays = days.keySet().size();
354         if (numDays > 0) // there is at least one day
355
{
356             // get first entry in map
357
Object JavaDoc[] keys = days.keySet().toArray(new Object JavaDoc[numDays]);
358             List JavaDoc vals = (List JavaDoc)days.get( keys[0] );
359             int valSize = vals.size();
360             if (valSize > 0)
361             {
362                 mFirstEntry = (WeblogEntryData)vals.get(0);
363             }
364             
365             // get last entry in map
366
vals = (List JavaDoc)days.get( keys[--numDays] );
367             valSize = vals.size();
368             if (valSize > 0)
369             {
370                 mLastEntry = (WeblogEntryData)vals.get(--valSize);
371             }
372         }
373     }
374
375     //------------------------------------------------------------------------
376

377     /**
378      * Returns list of recent weblog entries for the user and day specified in
379      * the request, filtered by the category specified by the request, limited
380      * by the 'maxEntries' argument, and sorted by reverse chronological order.
381      *
382      * <p>This method will look for a category name in the same places and
383      * same order as does the getRecentWeblogEntries() method.</p>
384      *
385      * @param maxEntries Maximum number of entries to be returned.
386      * @param categoryName Only return entries from this category and it's
387      * subcategories. If null, returns all categories of entry.
388      * @return List of WeblogEntryData objects in revese chronological order.
389      */

390     public List JavaDoc getRecentWeblogEntriesArray(int maxEntries, String JavaDoc categoryName)
391     {
392         if (VELOCITY_NULL.equals(categoryName)) categoryName = null;
393         List JavaDoc ret = new ArrayList JavaDoc();
394         try
395         {
396             Date JavaDoc day = mRollerReq.getDate();
397             if (day == null) day = new Date JavaDoc();
398             
399             // If request specifies a category, then use that
400
String JavaDoc catParam = null;
401             if (mRollerReq.getWeblogCategory() != null)
402             {
403                 catParam = mRollerReq.getWeblogCategory().getPath();
404             }
405             else if (categoryName != null)
406             {
407                 // use category argument instead
408
catParam = categoryName;
409             }
410             else if (mRollerReq.getWebsite() != null) // MAIN
411
{
412                 catParam = mRollerReq.getWebsite().getDefaultCategory().getPath();
413                 if (catParam.equals("/"))
414                 {
415                     catParam = null;
416                 }
417             }
418             WeblogManager mgr = mRollerReq.getRoller().getWeblogManager();
419             
420             //ret = mgr.getRecentWeblogEntriesArray(
421
//name, day, catParam, maxEntries, true );
422

423             ret = mgr.getWeblogEntries(
424                             mRollerReq.getWebsite(),
425                             null, // startDate
426
day, // endDate
427
catParam, // catName
428
WeblogManager.PUB_ONLY, // status
429
new Integer JavaDoc(maxEntries)); // maxEntries
430
}
431         catch (Exception JavaDoc e)
432         {
433             mLogger.error("PageModel getRecentWeblogEntries()", e);
434         }
435         return ret;
436     }
437     
438     //------------------------------------------------------------------------
439

440     /** Encapsulates RefererManager **/
441     public List JavaDoc getReferers(String JavaDoc date)
442     {
443         date = date.trim();
444         ArrayList JavaDoc referers = new ArrayList JavaDoc();
445         try
446         {
447             List JavaDoc refs =
448                 mRefererMgr.getReferersToDate(mRollerReq.getWebsite(), date);
449             
450             for (Iterator JavaDoc rdItr = refs.iterator(); rdItr.hasNext();) {
451                 RefererData referer = (RefererData) rdItr.next();
452                 String JavaDoc title =referer.getTitle();
453                 String JavaDoc excerpt = referer.getExcerpt();
454                 if ( StringUtils.isNotEmpty(title)
455                     && StringUtils.isNotEmpty(excerpt) )
456                 {
457                     if ( referer.getVisible().booleanValue()
458                         || this.mRollerReq.isUserAuthorizedToEdit() )
459                     {
460                         referers.add(referer);
461                     }
462                 }
463             }
464             
465         }
466         catch (Exception JavaDoc e)
467         {
468             mLogger.error("PageModel getReferersToDate() fails with URL"
469                             + mRollerReq.getRequestURL(), e);
470         }
471         return referers;
472     }
473     
474     //------------------------------------------------------------------------
475

476     /** Encapsulates RefererManager */
477     public List JavaDoc getTodaysReferers()
478     {
479         List JavaDoc referers = null;
480         try
481         {
482             referers = mRefererMgr.getTodaysReferers(mRollerReq.getWebsite());
483          
484         }
485         catch (RollerException e)
486         {
487             mLogger.error("PageModel getTodaysReferers()", e);
488         }
489         return (referers == null ? Collections.EMPTY_LIST : referers);
490     }
491     
492     //------------------------------------------------------------------------
493

494     /** Encapsulates RefererManager */
495     public int getTotalHits()
496     {
497         try
498         {
499             return mRefererMgr.getTotalHits(mRollerReq.getWebsite());
500         }
501         catch (RollerException e)
502         {
503             mLogger.error("PageModel getTotalHits()", e);
504         }
505         return 0;
506     }
507     
508     //------------------------------------------------------------------------
509
/**
510      * Returns most recent update time of collection of weblog entries.
511      * @param weblogEntries Collection of weblog entries.
512      * @return Most recent update time.
513      */

514     public static Date JavaDoc getUpdateTime( ArrayList JavaDoc weblogEntries )
515     {
516         Date JavaDoc updateTime = null;
517         Iterator JavaDoc iter = weblogEntries.iterator();
518         while (iter.hasNext())
519         {
520             WeblogEntryData wd = (WeblogEntryData)iter.next();
521             if ( updateTime == null )
522             {
523                 updateTime = wd.getUpdateTime();
524             }
525             //else if ( updateTime.compareTo(wd.getUpdateTime()) < 0 )
526
else if (updateTime.before( wd.getUpdateTime() ))
527             {
528                 updateTime = wd.getUpdateTime();
529             }
530         }
531         return updateTime;
532     }
533
534     //------------------------------------------------------------------------
535

536     /** Encapsulates WeblogManager.getWeblogCategories() */
537     public List JavaDoc getWeblogCategories(String JavaDoc categoryName)
538     {
539         List JavaDoc ret = null;
540         if (VELOCITY_NULL.equals(categoryName)) categoryName = null;
541         
542         // Make sure we have not already fetched this category.
543
if (categoryName != null)
544         {
545             ret = (List JavaDoc)mCategories.get(categoryName);
546         }
547         
548         if (null == ret)
549         {
550             try
551             {
552                 WeblogCategoryData category = null;
553                 if (categoryName != null)
554                 {
555                     category = mWeblogMgr.getWeblogCategoryByPath(
556                                   mRollerReq.getWebsite(), null, categoryName);
557                 }
558                 else
559                 {
560                     category = mRollerReq.getWebsite().getDefaultCategory();
561                 }
562                 ret = category.getWeblogCategories();
563                 mCategories.put(categoryName, ret);
564             }
565             catch (RollerException e)
566             {
567                 mLogger.error(e);
568             }
569         }
570         return ret;
571     }
572     
573     //------------------------------------------------------------------------
574

575     /** Encapsulates RollerRequest.getWeblogEntry() */
576     public WeblogEntryData getWeblogEntry()
577     {
578         return mRollerReq.getWeblogEntry();
579     }
580     
581     //------------------------------------------------------------------------
582

583     /**
584      * Get the next occurring Entry.
585      */

586     public WeblogEntryData getNextEntry()
587     {
588         WeblogEntryData currentEntry = getWeblogEntry();
589         if (mFirstEntry != null) currentEntry = mFirstEntry;
590         if (mNextEntry == null && currentEntry != null)
591         {
592             String JavaDoc catName = null;
593             if (mRollerReq.getWeblogCategory() != null)
594             {
595                 catName = mRollerReq.getWeblogCategory().getName();
596             }
597             try
598             {
599                 mNextEntry = mWeblogMgr.getNextEntry(currentEntry, catName);
600                 
601                 // make sure that mNextEntry is not published to future
602
if (mNextEntry != null &&
603                     mNextEntry.getPubTime().after( new Date JavaDoc() ))
604                 {
605                     mNextEntry = null;
606                 }
607             }
608             catch (RollerException e)
609             {
610                 mLogger.error("PageModel.getNextEntry)", e);
611             }
612         }
613         return mNextEntry;
614     }
615
616     //------------------------------------------------------------------------
617

618     /**
619      * Get the previous occurring Entry.
620      */

621     public WeblogEntryData getPreviousEntry()
622     {
623         WeblogEntryData currentEntry = getWeblogEntry();
624         if (mLastEntry != null) currentEntry = mLastEntry;
625         if (mPreviousEntry == null && currentEntry != null )
626         {
627             String JavaDoc catName = null;
628             if (mRollerReq.getWeblogCategory() != null)
629             {
630                 catName = mRollerReq.getWeblogCategory().getName();
631             }
632             try
633             {
634                 mPreviousEntry = mWeblogMgr.getPreviousEntry(currentEntry, catName);
635             }
636             catch (RollerException e)
637             {
638                 mLogger.error("PageModel.getPreviousEntry)", e);
639             }
640         }
641         return mPreviousEntry;
642     }
643
644     //------------------------------------------------------------------------
645

646     public boolean isUserAuthorizedToEdit()
647     {
648         try
649         {
650             return mRollerReq.isUserAuthorizedToEdit();
651         }
652         catch (Exception JavaDoc e)
653         {
654             mLogger.warn("PageModel.isUserAuthorizedToEdit)", e);
655         }
656         return false;
657     }
658     
659     //------------------------------------------------------------------------
660

661     public String JavaDoc getRequestParameter(String JavaDoc key)
662     {
663         return mRollerReq.getRequest().getParameter(key);
664     }
665     
666     //------------------------------------------------------------------------
667

668     public FolderData getFolderByPath(String JavaDoc path)
669     {
670         try
671         {
672             return mBookmarkMgr.getFolderByPath(
673                 mUserMgr.getWebsite(mUsername), null, path);
674         }
675         catch (RollerException e)
676         {
677             mLogger.error(e);
678             return null;
679         }
680     }
681
682     /**
683      * Facade for WeblogManager.getRecentComments().
684      * Get the most recent (chronologically) posted Comments
685      * for this website, limited to maxCount.
686      * @return List of Comments.
687      */

688     public List JavaDoc getRecentComments(int maxCount)
689     {
690         try
691         {
692             return mWeblogMgr.getRecentComments(mRollerReq.getWebsite(), maxCount);
693         }
694         catch (RollerException e)
695         {
696             mLogger.error(e);
697             return new ArrayList JavaDoc();
698         }
699     }
700  
701     public boolean getEmailComments()
702     {
703         WebsiteData website = mRollerReq.getWebsite();
704         boolean emailComments = RollerRuntimeConfig.getBooleanProperty("users.comments.emailnotify");
705         
706         return (website.getEmailComments().booleanValue() && emailComments);
707     }
708 }
709
Popular Tags