KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > roller > business > hibernate > HibernateWeblogManagerImpl


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

18
19 package org.apache.roller.business.hibernate;
20
21 import java.text.SimpleDateFormat JavaDoc;
22 import java.util.ArrayList JavaDoc;
23 import java.util.Calendar JavaDoc;
24 import java.util.Comparator JavaDoc;
25 import java.util.Date JavaDoc;
26 import java.util.Hashtable JavaDoc;
27 import java.util.Iterator JavaDoc;
28 import java.util.LinkedList JavaDoc;
29 import java.util.List JavaDoc;
30 import java.util.Map JavaDoc;
31 import java.util.TreeMap JavaDoc;
32 import org.apache.commons.collections.comparators.ReverseComparator;
33 import org.apache.commons.logging.Log;
34 import org.apache.commons.logging.LogFactory;
35 import org.apache.roller.RollerException;
36 import org.apache.roller.model.Roller;
37 import org.apache.roller.model.RollerFactory;
38 import org.apache.roller.model.WeblogManager;
39 import org.apache.roller.pojos.Assoc;
40 import org.apache.roller.pojos.CommentData;
41 import org.apache.roller.pojos.RefererData;
42 import org.apache.roller.pojos.StatCount;
43 import org.apache.roller.pojos.UserData;
44 import org.apache.roller.pojos.WeblogCategoryAssoc;
45 import org.apache.roller.pojos.WeblogCategoryData;
46 import org.apache.roller.pojos.WeblogEntryData;
47 import org.apache.roller.pojos.WebsiteData;
48 import org.apache.roller.util.DateUtil;
49 import org.apache.commons.lang.StringUtils;
50 import org.apache.roller.util.Utilities;
51 import org.hibernate.Criteria;
52 import org.hibernate.HibernateException;
53 import org.hibernate.Query;
54 import org.hibernate.Session;
55 import org.hibernate.criterion.Expression;
56 import org.hibernate.criterion.Junction;
57 import org.hibernate.criterion.MatchMode;
58 import org.hibernate.criterion.Order;
59
60
61 /**
62  * Hibernate implementation of the WeblogManager.
63  */

64 public class HibernateWeblogManagerImpl implements WeblogManager {
65     
66     static final long serialVersionUID = -3730860865389981439L;
67     
68     private static Log log = LogFactory.getLog(HibernateWeblogManagerImpl.class);
69     
70     private HibernatePersistenceStrategy strategy = null;
71     
72     // cached mapping of entryAnchors -> entryIds
73
private Hashtable JavaDoc entryAnchorToIdMap = new Hashtable JavaDoc();
74     
75     /* inline creation of reverse comparator, anonymous inner class */
76     private Comparator JavaDoc reverseComparator = new ReverseComparator();
77     
78     
79     public HibernateWeblogManagerImpl(HibernatePersistenceStrategy strat) {
80         log.debug("Instantiating Hibernate Weblog Manager");
81         
82         this.strategy = strat;
83     }
84     
85     
86     public void saveWeblogCategory(WeblogCategoryData cat) throws RollerException {
87         
88         if (StringUtils.isEmpty(cat.getId()) && isDuplicateWeblogCategoryName(cat)) {
89             throw new RollerException("Duplicate category name, cannot save new category");
90         }
91         
92         // update weblog last modified date. date updated by saveWebsite()
93
RollerFactory.getRoller().getUserManager().saveWebsite(cat.getWebsite());
94         
95         this.strategy.store(cat);
96     }
97     
98     
99     public void removeWeblogCategory(WeblogCategoryData cat) throws RollerException {
100         
101         if(cat.retrieveWeblogEntries(true).size() > 0) {
102             throw new RollerException("Cannot remove category with entries");
103         }
104         
105         // remove cat
106
this.strategy.remove(cat);
107         
108         // update website default cats if needed
109
if(cat.getWebsite().getBloggerCategory().equals(cat)) {
110             WeblogCategoryData rootCat = this.getRootWeblogCategory(cat.getWebsite());
111             cat.getWebsite().setBloggerCategory(rootCat);
112             this.strategy.store(cat.getWebsite());
113         }
114         
115         if(cat.getWebsite().getDefaultCategory().equals(cat)) {
116             WeblogCategoryData rootCat = this.getRootWeblogCategory(cat.getWebsite());
117             cat.getWebsite().setDefaultCategory(rootCat);
118             this.strategy.store(cat.getWebsite());
119         }
120         
121         // update weblog last modified date. date updated by saveWebsite()
122
RollerFactory.getRoller().getUserManager().saveWebsite(cat.getWebsite());
123     }
124     
125     
126     public void moveWeblogCategoryContents(WeblogCategoryData srcCat, WeblogCategoryData destCat)
127             throws RollerException {
128                 
129         // TODO: this check should be made before calling this method?
130
if (destCat.descendentOf(srcCat)) {
131             throw new RollerException(
132                     "ERROR cannot move parent category into it's own child");
133         }
134         
135         // get all entries in category and subcats
136
List JavaDoc results = srcCat.retrieveWeblogEntries(true);
137         
138         // Loop through entries in src cat, assign them to dest cat
139
Iterator JavaDoc iter = results.iterator();
140         WebsiteData website = destCat.getWebsite();
141         while (iter.hasNext()) {
142             WeblogEntryData entry = (WeblogEntryData) iter.next();
143             entry.setCategory(destCat);
144             entry.setWebsite(website);
145             this.strategy.store(entry);
146         }
147         
148         // Make sure website's default and bloggerapi categories
149
// are valid after the move
150

151         if (srcCat.getWebsite().getDefaultCategory().getId().equals(srcCat.getId())
152         || srcCat.getWebsite().getDefaultCategory().descendentOf(srcCat)) {
153             srcCat.getWebsite().setDefaultCategory(destCat);
154             this.strategy.store(srcCat.getWebsite());
155         }
156         
157         if (srcCat.getWebsite().getBloggerCategory().getId().equals(srcCat.getId())
158         || srcCat.getWebsite().getBloggerCategory().descendentOf(srcCat)) {
159             srcCat.getWebsite().setBloggerCategory(destCat);
160             this.strategy.store(srcCat.getWebsite());
161         }
162     }
163     
164     
165     public void saveComment(CommentData comment) throws RollerException {
166         this.strategy.store(comment);
167         
168         // update weblog last modified date. date updated by saveWebsite()
169
RollerFactory.getRoller().getUserManager().saveWebsite(comment.getWeblogEntry().getWebsite());
170     }
171     
172     
173     public void removeComment(CommentData comment) throws RollerException {
174         this.strategy.remove(comment);
175         
176         // update weblog last modified date. date updated by saveWebsite()
177
RollerFactory.getRoller().getUserManager().saveWebsite(comment.getWeblogEntry().getWebsite());
178     }
179     
180     
181     // TODO: perhaps the createAnchor() and queuePings() items should go outside this method?
182
public void saveWeblogEntry(WeblogEntryData entry) throws RollerException {
183         
184         if (entry.getAnchor() == null || entry.getAnchor().trim().equals("")) {
185             entry.setAnchor(this.createAnchor(entry));
186         }
187         
188         this.strategy.store(entry);
189         
190         // update weblog last modified date. date updated by saveWebsite()
191
if(entry.isPublished()) {
192             RollerFactory.getRoller().getUserManager().saveWebsite(entry.getWebsite());
193         }
194         
195         if(entry.isPublished()) {
196             // Queue applicable pings for this update.
197
RollerFactory.getRoller().getAutopingManager().queueApplicableAutoPings(entry);
198         }
199     }
200     
201     
202     public void removeWeblogEntry(WeblogEntryData entry) throws RollerException {
203         
204         Session session = ((HibernatePersistenceStrategy)this.strategy).getSession();
205         
206         // remove referers
207
Criteria refererQuery = session.createCriteria(RefererData.class);
208         refererQuery.add(Expression.eq("weblogEntry", entry));
209         List JavaDoc referers = refererQuery.list();
210         for (Iterator JavaDoc iter = referers.iterator(); iter.hasNext();) {
211             RefererData referer = (RefererData) iter.next();
212             this.strategy.remove(referer);
213         }
214         
215         // remove comments
216
List JavaDoc comments = getComments(
217                 null, // website
218
entry,
219                 null, // search String
220
null, // startDate
221
null, // endDate
222
null, // pending
223
null, // approved
224
null, // spam
225
true, // reverse chrono order (not that it matters)
226
0, // offset
227
-1); // no limit
228
Iterator JavaDoc commentsIT = comments.iterator();
229         while (commentsIT.hasNext()) {
230             this.strategy.remove((CommentData) commentsIT.next());
231         }
232         
233         // remove entry
234
this.strategy.remove(entry);
235         
236         // update weblog last modified date. date updated by saveWebsite()
237
if(entry.isPublished()) {
238             RollerFactory.getRoller().getUserManager().saveWebsite(entry.getWebsite());
239         }
240         
241         // remove entry from cache mapping
242
this.entryAnchorToIdMap.remove(entry.getWebsite().getHandle()+":"+entry.getAnchor());
243     }
244     
245     
246     private void removeWeblogEntryContents(WeblogEntryData entry) throws RollerException {
247         
248         if(entry == null) {
249             throw new RollerException("cannot remove null entry");
250         }
251         
252         Session session = ((HibernatePersistenceStrategy)this.strategy).getSession();
253         
254         // remove referers
255
Criteria refererQuery = session.createCriteria(RefererData.class);
256         refererQuery.add(Expression.eq("weblogEntry", entry));
257         List JavaDoc referers = refererQuery.list();
258         for (Iterator JavaDoc iter = referers.iterator(); iter.hasNext();) {
259             RefererData referer = (RefererData) iter.next();
260             this.strategy.remove(referer);
261         }
262         
263         // remove comments
264
List JavaDoc comments = getComments(
265                 null, // website
266
entry,
267                 null, // search String
268
null, // startDate
269
null, // endDate
270
null, // pending
271
null, // approved
272
null, // spam
273
true, // reverse chrono order (not that it matters)
274
0, // offset
275
-1); // no limit
276
Iterator JavaDoc commentsIT = comments.iterator();
277         while (commentsIT.hasNext()) {
278             this.strategy.remove((CommentData) commentsIT.next());
279         }
280     }
281     
282     
283     public List JavaDoc getNextPrevEntries(WeblogEntryData current, String JavaDoc catName,
284                                    String JavaDoc locale, int maxEntries, boolean next)
285             throws RollerException {
286         
287         Junction conjunction = Expression.conjunction();
288         conjunction.add(Expression.eq("website", current.getWebsite()));
289         conjunction.add(Expression.eq("status", WeblogEntryData.PUBLISHED));
290         
291         if (next) {
292             conjunction.add(Expression.gt("pubTime", current.getPubTime()));
293         } else {
294             conjunction.add(Expression.lt("pubTime", current.getPubTime()));
295         }
296         
297         if (catName != null && !catName.trim().equals("/")) {
298             WeblogCategoryData category =
299                     getWeblogCategoryByPath(current.getWebsite(), null, catName);
300             if (category != null) {
301                 conjunction.add(Expression.eq("category", category));
302             } else {
303                 throw new RollerException("Cannot find category: "+catName);
304             }
305         }
306         
307         if(locale != null) {
308             conjunction.add(Expression.ilike("locale", locale, MatchMode.START));
309         }
310         
311         try {
312             Session session = ((HibernatePersistenceStrategy)this.strategy).getSession();
313             Criteria criteria = session.createCriteria(WeblogEntryData.class);
314             criteria.addOrder(next ? Order.asc("pubTime") : Order.desc("pubTime"));
315             criteria.add(conjunction);
316             criteria.setMaxResults(maxEntries);
317             List JavaDoc results = criteria.list();
318             return results;
319         } catch (HibernateException e) {
320             throw new RollerException(e);
321         }
322     }
323     
324     public WeblogCategoryData getRootWeblogCategory(WebsiteData website)
325     throws RollerException {
326         if (website == null)
327             throw new RollerException("website is null");
328         
329         try {
330             Session session = ((HibernatePersistenceStrategy)this.strategy).getSession();
331             Criteria criteria = session.createCriteria(WeblogCategoryAssoc.class);
332             criteria.createAlias("category","c");
333             
334             criteria.add(Expression.eq("c.website", website));
335             criteria.add(Expression.isNull("ancestorCategory"));
336             criteria.add(Expression.eq("relation", WeblogCategoryAssoc.PARENT));
337             
338             criteria.setMaxResults(1);
339             
340             List JavaDoc list = criteria.list();
341             return ((WeblogCategoryAssoc)list.get(0)).getCategory();
342         } catch (HibernateException e) {
343             throw new RollerException(e);
344         }
345     }
346     
347     public List JavaDoc getWeblogCategories(WebsiteData website, boolean includeRoot)
348     throws RollerException {
349         if (website == null)
350             throw new RollerException("website is null");
351         
352         if (includeRoot) return getWeblogCategories(website);
353         
354         try {
355             Session session = ((HibernatePersistenceStrategy)this.strategy).getSession();
356             Criteria criteria = session.createCriteria(WeblogCategoryAssoc.class);
357             criteria.createAlias("category", "c");
358             criteria.add(Expression.eq("c.website", website));
359             criteria.add(Expression.isNotNull("ancestorCategory"));
360             criteria.add(Expression.eq("relation", "PARENT"));
361             Iterator JavaDoc assocs = criteria.list().iterator();
362             List JavaDoc cats = new ArrayList JavaDoc();
363             while (assocs.hasNext()) {
364                 WeblogCategoryAssoc assoc = (WeblogCategoryAssoc) assocs.next();
365                 cats.add(assoc.getCategory());
366             }
367             return cats;
368         } catch (HibernateException e) {
369             throw new RollerException(e);
370         }
371     }
372     
373     public List JavaDoc getWeblogCategories(WebsiteData website) throws RollerException {
374         if (website == null)
375             throw new RollerException("website is null");
376         
377         try {
378             Session session = ((HibernatePersistenceStrategy)this.strategy).getSession();
379             Criteria criteria = session.createCriteria(WeblogCategoryData.class);
380             criteria.add(Expression.eq("website", website));
381             return criteria.list();
382         } catch (HibernateException e) {
383             throw new RollerException(e);
384         }
385     }
386     
387     public List JavaDoc getWeblogEntries(
388             WebsiteData website,
389             UserData user,
390             Date JavaDoc startDate,
391             Date JavaDoc endDate,
392             String JavaDoc catName,
393             String JavaDoc status,
394             String JavaDoc sortby,
395             String JavaDoc locale,
396             int offset,
397             int length) throws RollerException {
398         
399         WeblogCategoryData cat = null;
400         if (StringUtils.isNotEmpty(catName) && website != null) {
401             cat = getWeblogCategoryByPath(website, catName);
402             if (cat == null) catName = null;
403         }
404         if (catName != null && catName.trim().equals("/")) {
405             catName = null;
406         }
407         
408         try {
409             Session session = ((HibernatePersistenceStrategy)this.strategy).getSession();
410             Criteria criteria = session.createCriteria(WeblogEntryData.class);
411             
412             if (website != null) {
413                 criteria.add(Expression.eq("website", website));
414             } else {
415                 criteria.createAlias("website","w");
416                 criteria.add(Expression.eq("w.enabled", Boolean.TRUE));
417             }
418             
419             if (user != null) {
420                 criteria.add(Expression.eq("creator", user));
421             }
422
423             if (startDate != null) {
424                 criteria.add(
425                         Expression.ge("pubTime", startDate));
426             }
427             
428             if (endDate != null) {
429                 criteria.add(
430                         Expression.le("pubTime", endDate));
431             }
432             
433             if (cat != null && website != null) {
434                 criteria.add(Expression.eq("category", cat));
435             }
436             
437             if (status != null) {
438                 criteria.add(Expression.eq("status", status));
439             }
440             
441             if (locale != null) {
442                 criteria.add(Expression.ilike("locale", locale, MatchMode.START));
443             }
444             
445             if (sortby != null && sortby.equals("updateTime")) {
446                 criteria.addOrder(Order.desc("updateTime"));
447             } else {
448                 criteria.addOrder(Order.desc("pubTime"));
449             }
450             
451             if (offset != 0) {
452                 criteria.setFirstResult(offset);
453             }
454             if (length != -1) {
455                 criteria.setMaxResults(length);
456             }
457             return criteria.list();
458             
459         } catch (HibernateException e) {
460             log.error(e);
461             throw new RollerException(e);
462         }
463     }
464     
465     public List JavaDoc getWeblogEntriesPinnedToMain(Integer JavaDoc max) throws RollerException {
466         try {
467             Session session = ((HibernatePersistenceStrategy)this.strategy).getSession();
468             Criteria criteria = session.createCriteria(WeblogEntryData.class);
469             criteria.add(Expression.eq("pinnedToMain", Boolean.TRUE));
470             criteria.addOrder(Order.desc("pubTime"));
471             if (max != null) {
472                 criteria.setMaxResults(max.intValue());
473             }
474             return criteria.list();
475         } catch (HibernateException e) {
476             log.error(e);
477             throw new RollerException(e);
478         }
479     }
480     
481     
482     public WeblogEntryData getWeblogEntryByAnchor(WebsiteData website, String JavaDoc anchor)
483             throws RollerException {
484         
485         if (website == null)
486             throw new RollerException("Website is null");
487         
488         if (anchor == null)
489             throw new RollerException("Anchor is null");
490         
491         // mapping key is combo of weblog + anchor
492
String JavaDoc mappingKey = website.getHandle()+":"+anchor;
493         
494         // check cache first
495
// NOTE: if we ever allow changing anchors then this needs updating
496
if(this.entryAnchorToIdMap.containsKey(mappingKey)) {
497             
498             WeblogEntryData entry = this.getWeblogEntry((String JavaDoc) this.entryAnchorToIdMap.get(mappingKey));
499             if(entry != null) {
500                 log.debug("entryAnchorToIdMap CACHE HIT - "+mappingKey);
501                 return entry;
502             } else {
503                 // mapping hit with lookup miss? mapping must be old, remove it
504
this.entryAnchorToIdMap.remove(mappingKey);
505             }
506         }
507         
508         // cache failed, do lookup
509
try {
510             Session session = ((HibernatePersistenceStrategy)this.strategy).getSession();
511             Criteria criteria = session.createCriteria(WeblogEntryData.class);
512             criteria.add(Expression.conjunction()
513             .add(Expression.eq("website",website))
514             .add(Expression.eq("anchor",anchor)));
515             criteria.addOrder(Order.desc("pubTime"));
516             criteria.setMaxResults(1);
517             
518             List JavaDoc list = criteria.list();
519             
520             WeblogEntryData entry = null;
521             if(list.size() != 0) {
522                 entry = (WeblogEntryData) criteria.uniqueResult();
523             }
524             
525             // add mapping to cache
526
if(entry != null) {
527                 log.debug("entryAnchorToIdMap CACHE MISS - "+mappingKey);
528                 this.entryAnchorToIdMap.put(mappingKey, entry.getId());
529             }
530             
531             return entry;
532         } catch (HibernateException e) {
533             throw new RollerException(e);
534         }
535     }
536     
537     public Date JavaDoc getWeblogLastPublishTime(WebsiteData website, String JavaDoc catName)
538     throws RollerException {
539         WeblogCategoryData cat = null;
540         Roller mRoller = RollerFactory.getRoller();
541         if (catName != null && website != null) {
542             cat = getWeblogCategoryByPath(website, null, catName);
543             if (cat == null) catName = null;
544         }
545         if (catName != null && catName.trim().equals("/")) {
546             catName = null;
547         }
548         
549         try {
550             Session session = ((HibernatePersistenceStrategy)this.strategy).getSession();
551             Criteria criteria = session.createCriteria(WeblogEntryData.class);
552             criteria.add(Expression.eq("status", WeblogEntryData.PUBLISHED));
553             criteria.add(Expression.le("pubTime", new Date JavaDoc()));
554             
555             if (website != null) {
556                 criteria.add(Expression.eq("website", website));
557             }
558             
559             if ( cat != null ) {
560                 criteria.add(Expression.eq("category", cat));
561             }
562             
563             criteria.addOrder(Order.desc("pubTime"));
564             criteria.setMaxResults(1);
565             List JavaDoc list = criteria.list();
566             if (list.size() > 0) {
567                 return ((WeblogEntryData)list.get(0)).getPubTime();
568             } else {
569                 return null;
570             }
571         } catch (HibernateException e) {
572             throw new RollerException(e);
573         }
574     }
575         
576     public List JavaDoc getWeblogEntries(WeblogCategoryData cat, boolean subcats)
577     throws RollerException {
578         try {
579             Session session = ((HibernatePersistenceStrategy)this.strategy).getSession();
580             List JavaDoc entries = new LinkedList JavaDoc();
581             
582             if (subcats) {
583                 // Get entries in subcategories
584
Criteria assocsQuery =
585                         session.createCriteria(WeblogCategoryAssoc.class);
586                 assocsQuery.add(Expression.eq("ancestorCategory", cat));
587                 Iterator JavaDoc assocs = assocsQuery.list().iterator();
588                 while (assocs.hasNext()) {
589                     WeblogCategoryAssoc assoc = (WeblogCategoryAssoc)assocs.next();
590                     Criteria entriesQuery =
591                             session.createCriteria(WeblogEntryData.class);
592                     entriesQuery.add(
593                             Expression.eq("category", assoc.getCategory()));
594                     Iterator JavaDoc entryIter = entriesQuery.list().iterator();
595                     while (entryIter.hasNext()) {
596                         WeblogEntryData entry = (WeblogEntryData)entryIter.next();
597                         entries.add(entry);
598                     }
599                 }
600             }
601             
602             // Get entries in category
603
Criteria entriesQuery =
604                     session.createCriteria(WeblogEntryData.class);
605             entriesQuery.add(Expression.eq("category", cat));
606             Iterator JavaDoc entryIter = entriesQuery.list().iterator();
607             while (entryIter.hasNext()) {
608                 WeblogEntryData entry = (WeblogEntryData)entryIter.next();
609                 entries.add(entry);
610             }
611             return entries;
612         } catch (HibernateException e) {
613             throw new RollerException(e);
614         }
615     }
616         
617     public String JavaDoc createAnchor(WeblogEntryData entry) throws RollerException {
618         try {
619             // Check for uniqueness of anchor
620
String JavaDoc base = entry.createAnchorBase();
621             String JavaDoc name = base;
622             int count = 0;
623             
624             while (true) {
625                 if (count > 0) {
626                     name = base + count;
627                 }
628                 
629                 Session session = ((HibernatePersistenceStrategy)this.strategy).getSession();
630                 Criteria criteria = session.createCriteria(WeblogEntryData.class);
631                 criteria.add(Expression.eq("website", entry.getWebsite()));
632                 criteria.add(Expression.eq("anchor", name));
633                 
634                 List JavaDoc results = criteria.list();
635                 
636                 if (results.size() < 1) {
637                     break;
638                 } else {
639                     count++;
640                 }
641             }
642             return name;
643         } catch (HibernateException e) {
644             throw new RollerException(e);
645         }
646     }
647     
648     public boolean isDuplicateWeblogCategoryName(WeblogCategoryData cat)
649     throws RollerException {
650         // ensure that no sibling categories share the same name
651
WeblogCategoryData parent =
652                 null == cat.getId() ? (WeblogCategoryData)cat.getNewParent() : cat.getParent();
653         
654         if (null != parent) // don't worry about root
655
{
656             List JavaDoc sameNames;
657             try {
658                 Session session = ((HibernatePersistenceStrategy)this.strategy).getSession();
659                 Criteria criteria = session.createCriteria(WeblogCategoryAssoc.class);
660                 criteria.createAlias("category", "c");
661                 criteria.add(Expression.eq("c.name", cat.getName()));
662                 criteria.add(Expression.eq("ancestorCategory", parent));
663                 criteria.add(Expression.eq("relation", Assoc.PARENT));
664                 sameNames = criteria.list();
665             } catch (HibernateException e) {
666                 throw new RollerException(e);
667             }
668             if (sameNames.size() > 0) {
669                 return true;
670             }
671         }
672         return false;
673     }
674     
675     public boolean isWeblogCategoryInUse(WeblogCategoryData cat)
676     throws RollerException {
677         try {
678             Session session = ((HibernatePersistenceStrategy)this.strategy).getSession();
679             Criteria criteria = session.createCriteria(WeblogEntryData.class);
680             criteria.add(Expression.eq("category", cat));
681             criteria.setMaxResults(1);
682             int entryCount = criteria.list().size();
683             
684             if (entryCount > 0) {
685                 return true;
686             }
687             
688             Iterator JavaDoc cats = cat.getWeblogCategories().iterator();
689             while (cats.hasNext()) {
690                 WeblogCategoryData childCat = (WeblogCategoryData)cats.next();
691                 if (childCat.isInUse()) {
692                     return true;
693                 }
694             }
695             
696             if (cat.getWebsite().getBloggerCategory().equals(cat)) {
697                 return true;
698             }
699             
700             if (cat.getWebsite().getDefaultCategory().equals(cat)) {
701                 return true;
702             }
703             
704             return false;
705         } catch (HibernateException e) {
706             throw new RollerException(e);
707         }
708     }
709     
710     public boolean isDescendentOf(
711             WeblogCategoryData child, WeblogCategoryData ancestor)
712             throws RollerException {
713         boolean ret = false;
714         try {
715             Session session = ((HibernatePersistenceStrategy)this.strategy).getSession();
716             Criteria criteria = session.createCriteria(WeblogCategoryAssoc.class);
717             criteria.add(Expression.eq("category", child));
718             criteria.add(Expression.eq("ancestorCategory", ancestor));
719             ret = criteria.list().size() > 0;
720         } catch (HibernateException e) {
721             throw new RollerException(e);
722         }
723         return ret;
724     }
725     
726     public Assoc getWeblogCategoryParentAssoc(WeblogCategoryData cat)
727     throws RollerException {
728         try {
729             Session session = ((HibernatePersistenceStrategy)this.strategy).getSession();
730             Criteria criteria = session.createCriteria(WeblogCategoryAssoc.class);
731             criteria.add(Expression.eq("category", cat));
732             criteria.add(Expression.eq("relation", Assoc.PARENT));
733             List JavaDoc parents = criteria.list();
734             if (parents.size() > 1) {
735                 throw new RollerException("ERROR: more than one parent");
736             } else if (parents.size() == 1) {
737                 return (Assoc) parents.get(0);
738             } else {
739                 return null;
740             }
741         } catch (HibernateException e) {
742             throw new RollerException(e);
743         }
744     }
745     
746     public List JavaDoc getWeblogCategoryChildAssocs(WeblogCategoryData cat)
747     throws RollerException {
748         try {
749             Session session = ((HibernatePersistenceStrategy)this.strategy).getSession();
750             Criteria criteria = session.createCriteria(WeblogCategoryAssoc.class);
751             criteria.add(Expression.eq("ancestorCategory", cat));
752             criteria.add(Expression.eq("relation", Assoc.PARENT));
753             return criteria.list();
754         } catch (HibernateException e) {
755             throw new RollerException(e);
756         }
757     }
758     
759     public List JavaDoc getAllWeblogCategoryDecscendentAssocs(WeblogCategoryData cat)
760     throws RollerException {
761         try {
762             Session session = ((HibernatePersistenceStrategy)this.strategy).getSession();
763             Criteria criteria = session.createCriteria(WeblogCategoryAssoc.class);
764             criteria.add(Expression.eq("ancestorCategory", cat));
765             return criteria.list();
766         } catch (HibernateException e) {
767             throw new RollerException(e);
768         }
769     }
770     
771     public List JavaDoc getWeblogCategoryAncestorAssocs(WeblogCategoryData cat)
772     throws RollerException {
773         try {
774             Session session = ((HibernatePersistenceStrategy)this.strategy).getSession();
775             Criteria criteria = session.createCriteria(WeblogCategoryAssoc.class);
776             criteria.add(Expression.eq("category", cat));
777             return criteria.list();
778         } catch (HibernateException e) {
779             throw new RollerException(e);
780         }
781     }
782     
783     public List JavaDoc getComments(
784             WebsiteData website,
785             WeblogEntryData entry,
786             String JavaDoc searchString,
787             Date JavaDoc startDate,
788             Date JavaDoc endDate,
789             Boolean JavaDoc pending,
790             Boolean JavaDoc approved,
791             Boolean JavaDoc spam,
792             boolean reverseChrono,
793             int offset,
794             int length
795             ) throws RollerException {
796         
797         try {
798             Session session = ((HibernatePersistenceStrategy)this.strategy).getSession();
799             Criteria criteria = session.createCriteria(CommentData.class);
800             
801             if (entry != null) {
802                 criteria.add(Expression.eq("weblogEntry", entry));
803             } else if (website != null) {
804                 criteria.createAlias("weblogEntry","e");
805                 criteria.add(Expression.eq("e.website", website));
806             }
807             
808             if (searchString != null) {
809                 criteria.add(Expression.disjunction()
810                 .add(Expression.like("url", searchString, MatchMode.ANYWHERE))
811                 .add(Expression.like("content", searchString, MatchMode.ANYWHERE)));
812             }
813             
814             if (startDate != null) {
815                 criteria.add(Expression.ge("postTime", startDate));
816             }
817             
818             if (endDate != null) {
819                 criteria.add(Expression.le("postTime", endDate));
820             }
821             
822             if (pending != null) {
823                 criteria.add(Expression.eq("pending", pending));
824             }
825             
826             if (approved != null) {
827                 criteria.add(Expression.eq("approved", approved));
828             }
829             
830             if (spam != null) {
831                 criteria.add(Expression.eq("spam", spam));
832             }
833             
834             if (length != -1) {
835                 criteria.setMaxResults(offset + length);
836             }
837             
838             if (reverseChrono) {
839                 criteria.addOrder(Order.desc("postTime"));
840             } else {
841                 criteria.addOrder(Order.asc("postTime"));
842             }
843             
844             List JavaDoc comments = criteria.list();
845             if (offset==0 || comments.size() < offset) {
846                 return comments;
847             }
848             List JavaDoc range = new ArrayList JavaDoc();
849             for (int i=offset; i<comments.size(); i++) {
850                 range.add(comments.get(i));
851             }
852             return range;
853             
854         } catch (HibernateException e) {
855             log.error(e);
856             throw new RollerException(e);
857         }
858     }
859     
860     
861     public WeblogCategoryData getWeblogCategory(String JavaDoc id)
862     throws RollerException {
863         return (WeblogCategoryData) this.strategy.load(
864                 id,
865                 WeblogCategoryData.class);
866     }
867     
868     //--------------------------------------------- WeblogCategoryData Queries
869

870     public WeblogCategoryData getWeblogCategoryByPath(
871             WebsiteData website, String JavaDoc categoryPath) throws RollerException {
872         return getWeblogCategoryByPath(website, null, categoryPath);
873     }
874     
875     public String JavaDoc getPath(WeblogCategoryData category) throws RollerException {
876         if (null == category.getParent()) {
877             return "/";
878         } else {
879             String JavaDoc parentPath = getPath(category.getParent());
880             parentPath = "/".equals(parentPath) ? "" : parentPath;
881             return parentPath + "/" + category.getName();
882         }
883     }
884     
885     public WeblogCategoryData getWeblogCategoryByPath(
886             WebsiteData website, WeblogCategoryData category, String JavaDoc path)
887             throws RollerException {
888         final Iterator JavaDoc cats;
889         final String JavaDoc[] pathArray = Utilities.stringToStringArray(path, "/");
890         
891         if (category == null && (null == path || "".equals(path.trim()))) {
892             throw new RollerException("Bad arguments.");
893         }
894         
895         if (path.trim().equals("/")) {
896             return getRootWeblogCategory(website);
897         } else if (category == null || path.trim().startsWith("/")) {
898             cats = getRootWeblogCategory(website).getWeblogCategories().iterator();
899         } else {
900             cats = category.getWeblogCategories().iterator();
901         }
902         
903         while (cats.hasNext()) {
904             WeblogCategoryData possibleMatch = (WeblogCategoryData)cats.next();
905             if (possibleMatch.getName().equals(pathArray[0])) {
906                 if (pathArray.length == 1) {
907                     return possibleMatch;
908                 } else {
909                     String JavaDoc[] subpath = new String JavaDoc[pathArray.length - 1];
910                     System.arraycopy(pathArray, 1, subpath, 0, subpath.length);
911                     
912                     String JavaDoc pathString= Utilities.stringArrayToString(subpath,"/");
913                     return getWeblogCategoryByPath(website, possibleMatch, pathString);
914                 }
915             }
916         }
917         
918         // The category did not match and neither did any sub-categories
919
return null;
920     }
921         
922     public CommentData getComment(String JavaDoc id) throws RollerException {
923         return (CommentData) this.strategy.load(id, CommentData.class);
924     }
925         
926     public WeblogEntryData getWeblogEntry(String JavaDoc id)
927     throws RollerException {
928         return (WeblogEntryData) this.strategy.load(
929                 id, WeblogEntryData.class);
930     }
931             
932     /**
933      * Gets the Date of the latest Entry publish time, before the end of today,
934      * for all WeblogEntries
935      */

936     public Date JavaDoc getWeblogLastPublishTime(WebsiteData website)
937     throws RollerException {
938         return getWeblogLastPublishTime(website, null);
939     }
940     
941     public Map JavaDoc getWeblogEntryObjectMap(
942             WebsiteData website,
943             Date JavaDoc startDate,
944             Date JavaDoc endDate,
945             String JavaDoc catName,
946             String JavaDoc status,
947             String JavaDoc locale,
948             int offset,
949             int length) throws RollerException {
950         return getWeblogEntryMap(
951             website,
952             startDate,
953             endDate,
954             catName,
955             status,
956             false,
957             locale,
958             offset,
959             length);
960     }
961     
962     public Map JavaDoc getWeblogEntryStringMap(
963             WebsiteData website,
964             Date JavaDoc startDate,
965             Date JavaDoc endDate,
966             String JavaDoc catName,
967             String JavaDoc status,
968             String JavaDoc locale,
969             int offset,
970             int length
971             ) throws RollerException {
972         return getWeblogEntryMap(
973             website,
974             startDate,
975             endDate,
976             catName,
977             status,
978             true,
979             locale,
980             offset,
981             length
982             );
983     }
984     
985     private Map JavaDoc getWeblogEntryMap(
986             WebsiteData website,
987             Date JavaDoc startDate,
988             Date JavaDoc endDate,
989             String JavaDoc catName,
990             String JavaDoc status,
991             boolean stringsOnly,
992             String JavaDoc locale,
993             int offset,
994             int length
995             ) throws RollerException {
996         
997         TreeMap JavaDoc map = new TreeMap JavaDoc(reverseComparator);
998         
999         List JavaDoc entries = getWeblogEntries(
1000            website,
1001            null,
1002            startDate,
1003            endDate,
1004            catName,
1005            status,
1006            null,
1007locale, offset,
1008            length);
1009        
1010        Calendar JavaDoc cal = Calendar.getInstance();
1011        if (website != null) {
1012            cal.setTimeZone(website.getTimeZoneInstance());
1013        }
1014        
1015        SimpleDateFormat JavaDoc formatter = DateUtil.get8charDateFormat();
1016        for (Iterator JavaDoc wbItr = entries.iterator(); wbItr.hasNext();) {
1017            WeblogEntryData entry = (WeblogEntryData) wbItr.next();
1018            Date JavaDoc sDate = DateUtil.getNoonOfDay(entry.getPubTime(), cal);
1019            if (stringsOnly) {
1020                if (map.get(sDate) == null)
1021                    map.put(sDate, formatter.format(sDate));
1022            } else {
1023                List JavaDoc dayEntries = (List JavaDoc) map.get(sDate);
1024                if (dayEntries == null) {
1025                    dayEntries = new ArrayList JavaDoc();
1026                    map.put(sDate, dayEntries);
1027                }
1028                dayEntries.add(entry);
1029            }
1030        }
1031        return map;
1032    }
1033    
1034    public List JavaDoc getMostCommentedWeblogEntries(
1035            WebsiteData website, Date JavaDoc startDate, Date JavaDoc endDate, int offset, int length)
1036            throws RollerException {
1037        // TODO: ATLAS getMostCommentedWeblogEntries DONE
1038
String JavaDoc msg = "Getting most commented weblog entres";
1039        if (endDate == null) endDate = new Date JavaDoc();
1040        try {
1041            Session session =
1042                ((HibernatePersistenceStrategy)strategy).getSession();
1043            Query query = null;
1044            if (website != null) {
1045                StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
1046                sb.append("select count(distinct c), c.weblogEntry.id, c.weblogEntry.anchor, c.weblogEntry.title from CommentData c ");
1047                sb.append("where c.weblogEntry.website=:website and c.weblogEntry.pubTime < :endDate ");
1048                if (startDate != null) {
1049                    sb.append("and c.weblogEntry.pubTime > :startDate ");
1050                }
1051                sb.append("group by c.weblogEntry.id, c.weblogEntry.anchor, c.weblogEntry.title ");
1052                sb.append("order by col_0_0_ desc");
1053                query = session.createQuery(sb.toString());
1054                query.setParameter("website", website);
1055                query.setParameter("endDate", endDate);
1056                if (startDate != null) {
1057                    query.setParameter("startDate", startDate);
1058                }
1059            } else {
1060                StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
1061                sb.append("select count(distinct c), c.weblogEntry.id, c.weblogEntry.anchor, c.weblogEntry.title ");
1062                sb.append("from CommentData c group by c.weblogEntry.id, c.weblogEntry.anchor, c.weblogEntry.title ");
1063                sb.append("where c.weblogEntry.pubTime < :endDate ");
1064                if (startDate != null) {
1065                    sb.append("and c.weblogEntry.pubTime > :startDate ");
1066                }
1067                sb.append("order by col_0_0_ desc");
1068                query = session.createQuery(sb.toString());
1069                if (startDate != null) {
1070                    query.setParameter("startDate", startDate);
1071                }
1072            }
1073            if (offset != 0) {
1074                query.setFirstResult(offset);
1075            }
1076            if (length != -1) {
1077                query.setMaxResults(length);
1078            }
1079            List JavaDoc results = new ArrayList JavaDoc();
1080            for (Iterator JavaDoc iter = query.list().iterator(); iter.hasNext();) {
1081                Object JavaDoc[] row = (Object JavaDoc[]) iter.next();
1082                results.add(new StatCount(
1083                    (String JavaDoc)row[1],
1084                    (String JavaDoc)row[2],
1085                    (String JavaDoc)row[3],
1086                    "statCount.weblogEntryCommentCountType",
1087                    new Long JavaDoc(((Integer JavaDoc)row[0]).intValue()).longValue()));
1088            }
1089            return results;
1090        } catch (Throwable JavaDoc pe) {
1091            log.error(msg, pe);
1092            throw new RollerException(msg, pe);
1093        }
1094    }
1095    
1096    
1097    public List JavaDoc getNextEntries(WeblogEntryData current, String JavaDoc catName,
1098                               String JavaDoc locale, int maxEntries)
1099            throws RollerException {
1100        
1101        return getNextPrevEntries(current, catName, locale, maxEntries, true);
1102    }
1103    
1104    
1105    public List JavaDoc getPreviousEntries(WeblogEntryData current, String JavaDoc catName,
1106                                   String JavaDoc locale, int maxEntries)
1107            throws RollerException {
1108        
1109        return getNextPrevEntries(current, catName, locale, maxEntries, false);
1110    }
1111    
1112    
1113    public WeblogEntryData getNextEntry(WeblogEntryData current, String JavaDoc catName,
1114                                        String JavaDoc locale)
1115            throws RollerException {
1116        
1117        WeblogEntryData entry = null;
1118        List JavaDoc entryList = getNextEntries(current, catName, locale, 1);
1119        if (entryList != null && entryList.size() > 0) {
1120            entry = (WeblogEntryData)entryList.get(0);
1121        }
1122        return entry;
1123    }
1124    
1125    
1126    public WeblogEntryData getPreviousEntry(WeblogEntryData current, String JavaDoc catName,
1127                                            String JavaDoc locale)
1128            throws RollerException {
1129        
1130        WeblogEntryData entry = null;
1131        List JavaDoc entryList = getPreviousEntries(current, catName, locale, 1);
1132        if (entryList != null && entryList.size() > 0) {
1133            entry = (WeblogEntryData)entryList.get(0);
1134        }
1135        return entry;
1136    }
1137    
1138    
1139    public void release() {}
1140
1141    /**
1142     * Apply comment defaults (defaultAllowComments and defaultCommentDays) to
1143     * all existing entries in a website using a single HQL query.
1144     * @param website Website where comment defaults are from/to be applied.
1145     */

1146    public void applyCommentDefaultsToEntries(WebsiteData website) throws RollerException {
1147        if (log.isDebugEnabled()) {
1148            log.debug("applyCommentDefaults");
1149        }
1150        try {
1151            Session session = strategy.getSession();
1152            String JavaDoc updateString = "update WeblogEntryData set "
1153                +"allowComments=:allowed, commentDays=:days, "
1154                +"pubTime=pubTime, updateTime=updateTime " // ensure timestamps are NOT reset
1155
+"where website=:site";
1156            Query update = session.createQuery(updateString);
1157            update.setParameter("allowed", website.getDefaultAllowComments());
1158            update.setParameter("days", new Integer JavaDoc(website.getDefaultCommentDays()));
1159            update.setParameter("site", website);
1160            update.executeUpdate();
1161        } catch (Exception JavaDoc e) {
1162            log.error("EXCEPTION applying comment defaults",e);
1163        }
1164    }
1165
1166}
1167
Popular Tags