KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > blojsom > fetcher > database > DatabaseFetcher


1 /**
2  * Copyright (c) 2003-2006, David A. Czarnecki
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
8  * Redistributions of source code must retain the above copyright notice, this list of conditions and the
9  * following disclaimer.
10  * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
11  * following disclaimer in the documentation and/or other materials provided with the distribution.
12  * Neither the name of "David A. Czarnecki" and "blojsom" nor the names of its contributors may be used to
13  * endorse or promote products derived from this software without specific prior written permission.
14  * Products derived from this software may not be called "blojsom", nor may "blojsom" appear in their name,
15  * without prior written permission of David A. Czarnecki.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
18  * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
19  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
20  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
21  * EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
27  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
29  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */

31 package org.blojsom.fetcher.database;
32
33 import org.apache.commons.logging.Log;
34 import org.apache.commons.logging.LogFactory;
35 import org.blojsom.blog.*;
36 import org.blojsom.blog.database.*;
37 import org.blojsom.event.Event;
38 import org.blojsom.event.EventBroadcaster;
39 import org.blojsom.event.Listener;
40 import org.blojsom.fetcher.Fetcher;
41 import org.blojsom.fetcher.FetcherException;
42 import org.blojsom.util.BlojsomConstants;
43 import org.blojsom.util.BlojsomMetaDataConstants;
44 import org.blojsom.util.BlojsomUtils;
45 import org.hibernate.*;
46 import org.hibernate.criterion.MatchMode;
47 import org.hibernate.criterion.Order;
48 import org.hibernate.criterion.Projections;
49 import org.hibernate.criterion.Restrictions;
50
51 import javax.servlet.ServletConfig JavaDoc;
52 import javax.servlet.http.HttpServletRequest JavaDoc;
53 import javax.servlet.http.HttpServletResponse JavaDoc;
54 import java.util.*;
55
56 /**
57  * Database fetcher
58  *
59  * @author David Czarnecki
60  * @version $Id: DatabaseFetcher.java,v 1.30 2006/09/26 02:55:24 czarneckid Exp $
61  * @since blojsom 3.0
62  */

63 public class DatabaseFetcher implements Fetcher, Listener {
64
65     protected Log _logger = LogFactory.getLog(DatabaseFetcher.class);
66
67     protected ServletConfig JavaDoc _servletConfig;
68     protected EventBroadcaster _eventBroadcaster;
69     protected SessionFactory _sessionFactory;
70     protected Properties _blojsomProperties;
71
72     /**
73      * Create a new instance of the database fetcher
74      */

75     public DatabaseFetcher() {
76     }
77
78     /**
79      * Set the {@link ServletConfig} for the fetcher to grab initialization parameters
80      *
81      * @param servletConfig {@link ServletConfig}
82      */

83     public void setServletConfig(ServletConfig JavaDoc servletConfig) {
84         _servletConfig = servletConfig;
85     }
86
87     /**
88      * Set the {@link EventBroadcaster} event broadcaster
89      *
90      * @param eventBroadcaster {@link EventBroadcaster}
91      */

92     public void setEventBroadcaster(EventBroadcaster eventBroadcaster) {
93         _eventBroadcaster = eventBroadcaster;
94     }
95
96     /**
97      * Set the {@link SessionFactory}
98      *
99      * @param sessionFactory {@link SessionFactory}
100      */

101     public void setSessionFactory(SessionFactory sessionFactory) {
102         _sessionFactory = sessionFactory;
103     }
104
105     /**
106      * Set the default blojsom properties
107      *
108      * @param blojsomProperties Default blojsom properties
109      */

110     public void setBlojsomProperties(Properties blojsomProperties) {
111         _blojsomProperties = blojsomProperties;
112     }
113
114     /**
115      * Initialize this fetcher. This method only called when the fetcher is instantiated.
116      *
117      * @throws org.blojsom.fetcher.FetcherException
118      * If there is an error initializing the fetcher
119      */

120     public void init() throws FetcherException {
121         _eventBroadcaster.addListener(this);
122
123         if (_logger.isDebugEnabled()) {
124             _logger.debug("Initialized database fetcher");
125         }
126     }
127
128     /**
129      * Return a new {@link org.blojsom.blog.Entry} instance
130      *
131      * @return Blog entry instance
132      */

133     public Entry newEntry() {
134         return new DatabaseEntry();
135     }
136
137     /**
138      * Return a new {@link org.blojsom.blog.Comment} instance
139      *
140      * @return {@link org.blojsom.blog.Comment}
141      */

142     public Comment newComment() {
143         return new DatabaseComment();
144     }
145
146     /**
147      * Return a new {@link org.blojsom.blog.Trackback} instance
148      *
149      * @return {@link org.blojsom.blog.Trackback}
150      */

151     public Trackback newTrackback() {
152         return new DatabaseTrackback();
153     }
154
155     /**
156      * Return a new {@link org.blojsom.blog.Pingback} instance
157      *
158      * @return {@link org.blojsom.blog.Pingback}
159      */

160     public Pingback newPingback() {
161         return new DatabasePingback();
162     }
163
164     /**
165      * Return a new {@link org.blojsom.blog.Category} instance
166      *
167      * @return {@link org.blojsom.blog.Category}
168      */

169     public Category newCategory() {
170         return new DatabaseCategory();
171     }
172
173     /**
174      * Return a new {@link org.blojsom.blog.Blog} instance
175      *
176      * @return {@link org.blojsom.blog.Blog}
177      */

178     public Blog newBlog() {
179         return new DatabaseBlog();
180     }
181
182     /**
183      * Return a new {@link org.blojsom.blog.User} instance
184      *
185      * @return {@link org.blojsom.blog.User}
186      */

187     public User newUser() {
188         return new DatabaseUser();
189     }
190
191     /**
192      * Load the {@link Blog} given the blog ID
193      *
194      * @param blogId Blog ID
195      * @return {@link Blog}
196      * @throws FetcherException If there is an error loading the blog
197      */

198     public Blog loadBlog(String JavaDoc blogId) throws FetcherException {
199         Session session = _sessionFactory.openSession();
200         Transaction tx = null;
201
202         Blog blog = null;
203
204         try {
205             tx = session.beginTransaction();
206             Criteria blogCriteria = session.createCriteria(org.blojsom.blog.database.DatabaseBlog.class);
207             blogCriteria.add(Restrictions.eq("blogId", blogId));
208             blog = (Blog) blogCriteria.uniqueResult();
209
210             tx.commit();
211
212             if (blog == null) {
213                 throw new FetcherException("Blog id: " + blogId + " not found");
214             }
215         } catch (HibernateException e) {
216             if (tx != null) {
217                 tx.rollback();
218             }
219
220             if (_logger.isErrorEnabled()) {
221                 _logger.error(e);
222             }
223
224             throw new FetcherException(e);
225         } finally {
226             session.close();
227         }
228
229         return blog;
230     }
231
232     /**
233      * Save a {@link Blog}
234      *
235      * @param blog {@link Blog}
236      * @throws FetcherException If there is an error saving the blog
237      */

238     public void saveBlog(Blog blog) throws FetcherException {
239         try {
240             Session session = _sessionFactory.openSession();
241             Transaction tx = session.beginTransaction();
242
243             session.saveOrUpdate(blog);
244
245             tx.commit();
246             session.close();
247         } catch (HibernateException e) {
248             if (_logger.isErrorEnabled()) {
249                 _logger.error(e);
250             }
251
252             throw new FetcherException("Unable to save blog inforamtion: " + blog.getBlogId(), e);
253         }
254     }
255
256     /**
257      * Delete a blog
258      *
259      * @param blog {@link Blog}
260      * @throws FetcherException If there is an error deleting the blog
261      */

262     public void deleteBlog(Blog blog) throws FetcherException {
263         try {
264             Session session = _sessionFactory.openSession();
265             Transaction tx = session.beginTransaction();
266
267             session.delete(blog);
268
269             tx.commit();
270             session.close();
271         } catch (HibernateException e) {
272             if (_logger.isErrorEnabled()) {
273                 _logger.error(e);
274             }
275
276             throw new FetcherException("Unable to delete blog inforamtion: " + blog.getBlogId(), e);
277         }
278     }
279
280     /**
281      * Load the blog IDs
282      *
283      * @return List of blog IDs
284      * @throws org.blojsom.fetcher.FetcherException
285      * If there is an error loading the blog IDs
286      */

287     public String JavaDoc[] loadBlogIDs() throws FetcherException {
288         String JavaDoc[] blogIDs;
289
290         try {
291             Session session = _sessionFactory.openSession();
292             Transaction tx = session.beginTransaction();
293
294             List blogIDList = session.getNamedQuery("blog.id.list").list();
295
296             tx.commit();
297             session.close();
298
299             blogIDs = (String JavaDoc[]) blogIDList.toArray(new String JavaDoc[blogIDList.size()]);
300         } catch (HibernateException e) {
301             if (_logger.isErrorEnabled()) {
302                 _logger.error(e);
303             }
304
305             throw new FetcherException("Unable to load blog IDs", e);
306         }
307
308         return blogIDs;
309     }
310
311     /**
312      * Fetch a set of {@link org.blojsom.blog.Entry} objects.
313      *
314      * @param httpServletRequest Request
315      * @param httpServletResponse Response
316      * @param blog {@link org.blojsom.blog.Blog} instance
317      * @param flavor Flavor
318      * @param context Context
319      * @return Blog entries retrieved for the particular request
320      * @throws org.blojsom.fetcher.FetcherException
321      * If there is an error retrieving the blog entries for the request
322      */

323     public Entry[] fetchEntries(HttpServletRequest JavaDoc httpServletRequest, HttpServletResponse JavaDoc httpServletResponse, Blog blog, String JavaDoc flavor, Map context) throws FetcherException {
324         Category category = (Category) context.get(BlojsomConstants.BLOJSOM_REQUESTED_CATEGORY);
325
326         String JavaDoc ignoreFlavors = _blojsomProperties.getProperty("ignore-flavors");
327         // Check to see if the requested flavor should be ignored
328
if (ignoreFlavors.indexOf(flavor) != -1) {
329             return new Entry[0];
330         }
331
332         // Determine if a permalink has been requested
333
String JavaDoc permalink = BlojsomUtils.getRequestValue(BlojsomConstants.PERMALINK_PARAM, httpServletRequest);
334         if (permalink != null) {
335             permalink = BlojsomUtils.urlDecode(permalink);
336             if (_logger.isDebugEnabled()) {
337                 _logger.debug("Permalink request for: " + permalink);
338             }
339         }
340
341         if (permalink != null) {
342             Session session = _sessionFactory.openSession();
343             Transaction tx = session.beginTransaction();
344
345             Criteria permalinkCriteria = session.createCriteria(org.blojsom.blog.database.DatabaseEntry.class);
346             permalinkCriteria.add(Restrictions.eq("blogId", blog.getId()))
347                     .add(Restrictions.eq("postSlug", BlojsomUtils.removeSlashes(permalink)))
348                     .add(Restrictions.eq("status", BlojsomMetaDataConstants.PUBLISHED_STATUS))
349                     .add(Restrictions.lt("date", new Date()));
350
351             List permalinkEntryList = permalinkCriteria.list();
352
353             if (permalinkEntryList.size() == 1) {
354                 DatabaseEntry entry = (DatabaseEntry) permalinkEntryList.get(0);
355                 context.put(BlojsomConstants.BLOJSOM_PERMALINK, entry.getId());
356                 permalinkCriteria = session.createCriteria(org.blojsom.blog.database.DatabaseEntry.class);
357                 permalinkCriteria.add(Restrictions.eq("blogId", blog.getId()))
358                         .add(Restrictions.gt("date", entry.getDate()))
359                         .add(Restrictions.lt("date", new Date()))
360                         .add(Restrictions.eq("status", BlojsomMetaDataConstants.PUBLISHED_STATUS));
361                 permalinkCriteria.addOrder(Order.asc("date"));
362                 permalinkCriteria.setMaxResults(1);
363
364                 List nextList = permalinkCriteria.list();
365                 if (_logger.isDebugEnabled()) {
366                     _logger.debug("Total entries after permalink: " + nextList.size());
367                 }
368
369                 if (nextList.size() == 1) {
370                     context.put(BlojsomConstants.BLOJSOM_PERMALINK_NEXT_ENTRY, nextList.get(0));
371                 } else {
372                     context.put(BlojsomConstants.BLOJSOM_PERMALINK_NEXT_ENTRY, null);
373                 }
374
375                 permalinkCriteria = session.createCriteria(org.blojsom.blog.database.DatabaseEntry.class);
376                 permalinkCriteria.add(Restrictions.eq("blogId", blog.getId()))
377                         .add(Restrictions.lt("date", entry.getDate()))
378                         .add(Restrictions.eq("status", BlojsomMetaDataConstants.PUBLISHED_STATUS));
379                 permalinkCriteria.addOrder(Order.desc("date"));
380                 permalinkCriteria.setMaxResults(1);
381
382                 List prevList = permalinkCriteria.list();
383                 if (_logger.isDebugEnabled()) {
384                     _logger.debug("Total entries before permalink: " + prevList.size());
385                 }
386
387                 if (prevList.size() == 1) {
388                     context.put(BlojsomConstants.BLOJSOM_PERMALINK_PREVIOUS_ENTRY, prevList.get(0));
389                 } else {
390                     context.put(BlojsomConstants.BLOJSOM_PERMALINK_PREVIOUS_ENTRY, null);
391                 }
392             }
393
394             tx.commit();
395             session.close();
396
397             if (permalinkEntryList.size() > 0) {
398                 return new Entry[]{(Entry) permalinkEntryList.get(0)};
399             } else {
400                 return (Entry[]) permalinkEntryList.toArray(new DatabaseEntry[permalinkEntryList.size()]);
401             }
402         } else {
403             String JavaDoc pgNum = BlojsomUtils.getRequestValue(BlojsomConstants.PAGE_NUMBER_PARAM, httpServletRequest);
404             int page;
405             try {
406                 page = Integer.parseInt(pgNum);
407                 page -= 1;
408                 if (page < 0) {
409                     page = 0;
410                 }
411             } catch (NumberFormatException JavaDoc e) {
412                 page = 0;
413             }
414
415             page *= blog.getBlogDisplayEntries();
416
417             if (category != null && !"/".equals(category.getName())) {
418                 Session session = _sessionFactory.openSession();
419                 Transaction tx = session.beginTransaction();
420
421                 Criteria entryCriteria = session.createCriteria(org.blojsom.blog.database.DatabaseEntry.class);
422                 entryCriteria.add(Restrictions.eq("blogId", blog.getId()));
423                 entryCriteria.add(Restrictions.eq("blogCategoryId", category.getId()));
424                 entryCriteria.add(Restrictions.lt("date", new Date()));
425                 entryCriteria.add(Restrictions.eq("status", BlojsomMetaDataConstants.PUBLISHED_STATUS));
426                 entryCriteria.addOrder(Order.desc("date"));
427                 entryCriteria.setMaxResults(blog.getBlogDisplayEntries());
428                 entryCriteria.setFirstResult(page);
429                 entryCriteria.setCacheable(true);
430
431                 List entryList = entryCriteria.list();
432
433                 tx.commit();
434                 session.close();
435
436                 return (DatabaseEntry[]) entryList.toArray(new DatabaseEntry[entryList.size()]);
437             } else {
438                 Session session = _sessionFactory.openSession();
439                 Transaction tx = session.beginTransaction();
440
441                 Criteria entryCriteria = session.createCriteria(org.blojsom.blog.database.DatabaseEntry.class);
442                 entryCriteria.add(Restrictions.eq("blogId", blog.getId()));
443                 entryCriteria.add(Restrictions.lt("date", new Date()));
444                 entryCriteria.add(Restrictions.eq("status", BlojsomMetaDataConstants.PUBLISHED_STATUS));
445                 entryCriteria.addOrder(Order.desc("date"));
446                 entryCriteria.setMaxResults(blog.getBlogDisplayEntries());
447                 entryCriteria.setFirstResult(page);
448                 entryCriteria.setCacheable(true);
449
450                 List entryList = entryCriteria.list();
451
452                 tx.commit();
453                 session.close();
454
455                 return (DatabaseEntry[]) entryList.toArray(new DatabaseEntry[entryList.size()]);
456             }
457         }
458     }
459
460     /**
461      * Load all the entries for a given category
462      *
463      * @param blog {@link Blog}
464      * @param categoryId Category ID
465      * @return Blog entries for a given category
466      * @throws FetcherException If there is an error loading the entries
467      */

468     public Entry[] loadAllEntriesForCategory(Blog blog, Integer JavaDoc categoryId) throws FetcherException {
469         try {
470             Session session = _sessionFactory.openSession();
471             Transaction tx = session.beginTransaction();
472
473             Criteria entryCriteria = session.createCriteria(DatabaseEntry.class);
474             entryCriteria.add(Restrictions.eq("blogId", blog.getId()));
475             entryCriteria.add(Restrictions.eq("blogCategoryId", categoryId));
476             entryCriteria.addOrder(Order.desc("date"));
477             entryCriteria.setCacheable(true);
478
479             List entryList = entryCriteria.list();
480
481             tx.commit();
482             session.close();
483
484             return (DatabaseEntry[]) entryList.toArray(new DatabaseEntry[entryList.size()]);
485         } catch (HibernateException e) {
486             if (_logger.isErrorEnabled()) {
487                 _logger.error(e);
488             }
489
490             throw new FetcherException(e);
491         }
492     }
493
494     /**
495      * Load all the entries for a given category
496      *
497      * @param blog {@link Blog}
498      * @param categoryId Category ID
499      * @param limit Limit on number of entries to return
500      * @return Blog entries for a given category
501      * @throws FetcherException If there is an error loading the entries
502      */

503     public Entry[] loadEntriesForCategory(Blog blog, Integer JavaDoc categoryId, Integer JavaDoc limit) throws FetcherException {
504         try {
505             Session session = _sessionFactory.openSession();
506             Transaction tx = session.beginTransaction();
507
508             Criteria entryCriteria = session.createCriteria(DatabaseEntry.class);
509             entryCriteria.add(Restrictions.eq("blogId", blog.getId()));
510             entryCriteria.add(Restrictions.eq("blogCategoryId", categoryId));
511             entryCriteria.addOrder(Order.desc("date"));
512             entryCriteria.setMaxResults(limit.intValue());
513             entryCriteria.setCacheable(true);
514
515             List entryList = entryCriteria.list();
516
517             tx.commit();
518             session.close();
519
520             return (DatabaseEntry[]) entryList.toArray(new DatabaseEntry[entryList.size()]);
521         } catch (HibernateException e) {
522             if (_logger.isErrorEnabled()) {
523                 _logger.error(e);
524             }
525
526             throw new FetcherException(e);
527         }
528     }
529
530     /**
531      * Load a set of entries using a given page size and page in which to retrieve the entries
532      *
533      * @param blog {@link Blog}
534      * @param pageSize Page size
535      * @param page Page
536      * @return Blog entries
537      * @throws FetcherException If there is an error loading the entries
538      */

539     public Entry[] loadEntries(Blog blog, int pageSize, int page) throws FetcherException {
540         Session session = _sessionFactory.openSession();
541         Transaction tx = session.beginTransaction();
542
543         page -= 1;
544         if (page < 0) {
545             page = 0;
546         }
547
548         if (pageSize < 1) {
549             pageSize = 1;
550         }
551
552         page *= pageSize;
553
554         Criteria entryCriteria = session.createCriteria(org.blojsom.blog.database.DatabaseEntry.class);
555         entryCriteria.add(Restrictions.eq("blogId", blog.getId()));
556         entryCriteria.addOrder(Order.desc("date"));
557         entryCriteria.setMaxResults(pageSize);
558         entryCriteria.setFirstResult(page);
559         entryCriteria.setCacheable(true);
560
561         List entryList = entryCriteria.list();
562
563         tx.commit();
564         session.close();
565
566         return (DatabaseEntry[]) entryList.toArray(new DatabaseEntry[entryList.size()]);
567     }
568
569     /**
570      * Find entries which have the search query in their title or description
571      *
572      * @param blog {@link Blog}
573      * @param query Search query
574      * @return Blog entries which have the search query in their title or descirption
575      * @throws FetcherException If there is an error searching through entries
576      */

577     public Entry[] findEntries(Blog blog, String JavaDoc query) throws FetcherException {
578         Session session = _sessionFactory.openSession();
579         Transaction tx = session.beginTransaction();
580
581         Criteria entryCriteria = session.createCriteria(org.blojsom.blog.database.DatabaseEntry.class);
582         entryCriteria.add(Restrictions.eq("blogId", blog.getId()));
583         entryCriteria.add(Restrictions.or(Restrictions.ilike("title", query, MatchMode.ANYWHERE),
584                 Restrictions.ilike("description", query, MatchMode.ANYWHERE)))
585                 .add(Restrictions.eq("status", BlojsomMetaDataConstants.PUBLISHED_STATUS));
586         entryCriteria.addOrder(Order.desc("date"));
587         entryCriteria.setCacheable(true);
588
589         List entryList = entryCriteria.list();
590
591         tx.commit();
592         session.close();
593
594         return (DatabaseEntry[]) entryList.toArray(new DatabaseEntry[entryList.size()]);
595     }
596
597     /**
598      * Find entries by a metadata key/value pair
599      *
600      * @param blog {@link Blog}
601      * @param metadataKey Metadata key
602      * @param metadataValue Metadata value
603      * @param pre If the search should use % before the metadata value (match anything before)
604      * @param post If the search should use % after the metadata value (match antthing after)
605      * @return Entries matching metadata key and value using LIKE syntax for metadata value
606      * @throws FetcherException If there is an error searching through entries
607      */

608     public Entry[] findEntriesByMetadataKeyValue(Blog blog, String JavaDoc metadataKey, String JavaDoc metadataValue,
609                                                  boolean pre, boolean post) throws FetcherException {
610         Session session = _sessionFactory.openSession();
611         Transaction tx = session.beginTransaction();
612
613         String JavaDoc valueSearch = metadataValue;
614         if (pre) {
615             valueSearch = "%" + valueSearch;
616         }
617         if (post) {
618             valueSearch = valueSearch + "%";
619         }
620
621         List entriesMatchingMetadataKeyValue = session.getNamedQuery("entry.by.metadata.key.value").setCacheable(true)
622                 .setInteger("blogId", blog.getId().intValue())
623                 .setString("metadataKey", metadataKey)
624                 .setString("metadataValue", valueSearch).list();
625
626         tx.commit();
627         session.close();
628
629         return (DatabaseEntry[]) entriesMatchingMetadataKeyValue.toArray(new DatabaseEntry[entriesMatchingMetadataKeyValue.size()]);
630     }
631
632     /**
633      * Find entries with a given metadata key
634      *
635      * @param blog {@link Blog}
636      * @param metadataKey Metadata key
637      * @return Entries with the given metadata key
638      * @throws FetcherException If there is an error searching through entries
639      */

640     public Entry[] findEntriesWithMetadataKey(Blog blog, String JavaDoc metadataKey) throws FetcherException {
641         Session session = _sessionFactory.openSession();
642         Transaction tx = session.beginTransaction();
643
644         List entriesMatchingMetadata = session.getNamedQuery("entry.by.metadata.key").setCacheable(true)
645                 .setInteger("blogId", blog.getId().intValue())
646                 .setString("metadataKey", metadataKey).list();
647
648         tx.commit();
649         session.close();
650
651         return (DatabaseEntry[]) entriesMatchingMetadata.toArray(new DatabaseEntry[entriesMatchingMetadata.size()]);
652     }
653
654     /**
655      * Find entries between a start and end date
656      *
657      * @param blog {@link Blog}
658      * @param startDate Start date
659      * @param endDate End date
660      * @return Entries between a start and end date
661      * @throws FetcherException If there is an error searching for entries between the dates
662      */

663     public Entry[] findEntriesBetweenDates(Blog blog, Date startDate, Date endDate) throws FetcherException {
664         try {
665             Session session = _sessionFactory.openSession();
666             Transaction tx = session.beginTransaction();
667
668             Criteria entryCriteria = session.createCriteria(DatabaseEntry.class);
669             entryCriteria.add(Restrictions.eq("blogId", blog.getId()));
670             entryCriteria.add(Restrictions.between("date", startDate, endDate));
671             entryCriteria.add(Restrictions.eq("status", BlojsomMetaDataConstants.PUBLISHED_STATUS));
672             entryCriteria.addOrder(Order.desc("date"));
673             entryCriteria.setCacheable(true);
674
675             List entryList = entryCriteria.list();
676
677             tx.commit();
678             session.close();
679
680             return (DatabaseEntry[]) entryList.toArray(new DatabaseEntry[entryList.size()]);
681         } catch (HibernateException e) {
682             if (_logger.isErrorEnabled()) {
683                 _logger.error(e);
684             }
685
686             throw new FetcherException(e);
687         }
688     }
689
690     /**
691      * Count the number of entries for a blog
692      *
693      * @param blog {@link Blog}
694      * @return Number of entries
695      * @throws FetcherException If there is an error counting the blog entries
696      */

697     public Integer JavaDoc countEntries(Blog blog) throws FetcherException {
698         Session session = _sessionFactory.openSession();
699         Transaction tx = session.beginTransaction();
700
701         Criteria entryCriteria = session.createCriteria(org.blojsom.blog.database.DatabaseEntry.class);
702         entryCriteria.setProjection(Projections.rowCount());
703         entryCriteria.add(Restrictions.eq("blogId", blog.getId()));
704         entryCriteria.add(Restrictions.lt("date", new Date()));
705         entryCriteria.setCacheable(true);
706
707         List entryList = entryCriteria.list();
708
709         tx.commit();
710         session.close();
711
712         return (Integer JavaDoc) entryList.get(0);
713     }
714
715     /**
716      * Load an {@link Entry} for a given entry ID
717      *
718      * @param blog {@link Blog}
719      * @param entryId Entry ID
720      * @return {@link Entry}
721      * @throws FetcherException If there is an error loading the entry
722      */

723     public Entry loadEntry(Blog blog, Integer JavaDoc entryId) throws FetcherException {
724         try {
725             Session session = _sessionFactory.openSession();
726             Transaction tx = session.beginTransaction();
727
728             Criteria entryCriteria = session.createCriteria(DatabaseEntry.class);
729             entryCriteria.add(Restrictions.eq("blogId", blog.getId()))
730                     .add(Restrictions.eq("id", entryId));
731
732             Entry entry = (DatabaseEntry) entryCriteria.uniqueResult();
733
734             tx.commit();
735             session.close();
736
737             return entry;
738         } catch (HibernateException e) {
739             if (_logger.isErrorEnabled()) {
740                 _logger.error(e);
741             }
742
743             throw new FetcherException(e);
744         }
745     }
746
747     /**
748      * Load an {@link Entry} given a post slug
749      *
750      * @param blog {@link Blog}
751      * @param postSlug Post slug
752      * @return {@link Entry} for the given post slug
753      * @throws org.blojsom.fetcher.FetcherException
754      * If an entry for the blog and post slug cannot be found
755      */

756     public Entry loadEntry(Blog blog, String JavaDoc postSlug) throws FetcherException {
757         try {
758             Session session = _sessionFactory.openSession();
759             Transaction tx = session.beginTransaction();
760
761             Criteria entryCriteria = session.createCriteria(DatabaseEntry.class);
762             entryCriteria.add(Restrictions.eq("blogId", blog.getId()))
763                     .add(Restrictions.eq("postSlug", postSlug));
764
765             Entry entry = (DatabaseEntry) entryCriteria.uniqueResult();
766
767             tx.commit();
768             session.close();
769
770             if (entry == null) {
771                 throw new FetcherException("Entry could not be loaded with post slug: " + postSlug);
772             }
773
774             return entry;
775         } catch (HibernateException e) {
776             if (_logger.isErrorEnabled()) {
777                 _logger.error(e);
778             }
779
780             throw new FetcherException(e);
781         }
782     }
783
784     /**
785      * Determine the blog category based on the request
786      *
787      * @param httpServletRequest Request
788      * @return {@link BlogCategory} of the requested category
789      */

790     protected String JavaDoc getBlogCategory(Blog blog, HttpServletRequest JavaDoc httpServletRequest) {
791         // Determine the user requested category
792
String JavaDoc requestedCategory;
793         httpServletRequest.getPathInfo();
794         String JavaDoc blogIdFromPath = BlojsomUtils.getBlogFromPath(httpServletRequest.getPathInfo());
795         if (blogIdFromPath == null) {
796             requestedCategory = httpServletRequest.getPathInfo();
797         } else {
798             if (blogIdFromPath.equals(blog.getBlogId())) {
799                 requestedCategory = BlojsomUtils.getCategoryFromPath(httpServletRequest.getPathInfo());
800             } else {
801                 requestedCategory = httpServletRequest.getPathInfo();
802             }
803         }
804
805         requestedCategory = BlojsomUtils.normalize(requestedCategory);
806         if (_logger.isDebugEnabled()) {
807             _logger.debug("blojsom path info: " + requestedCategory);
808         }
809
810         String JavaDoc categoryParameter = httpServletRequest.getParameter(BlojsomConstants.CATEGORY_PARAM);
811         if (!(categoryParameter == null) && !("".equals(categoryParameter))) {
812             categoryParameter = BlojsomUtils.normalize(categoryParameter);
813             if (_logger.isDebugEnabled()) {
814                 _logger.debug("Category parameter override: " + categoryParameter);
815             }
816             requestedCategory = categoryParameter;
817         }
818
819         if (requestedCategory == null) {
820             requestedCategory = "/";
821         } else if (!requestedCategory.endsWith("/")) {
822             requestedCategory += "/";
823         }
824
825         requestedCategory = BlojsomUtils.urlDecode(requestedCategory);
826         if (_logger.isDebugEnabled()) {
827             _logger.debug("User requested category: " + requestedCategory);
828         }
829
830         return requestedCategory;
831     }
832
833     /**
834      * Fetch a set of {@link org.blojsom.blog.Category} objects
835      *
836      * @param httpServletRequest Request
837      * @param httpServletResponse Response
838      * @param blog {@link org.blojsom.blog.Blog} instance
839      * @param flavor Flavor
840      * @param context Context
841      * @return Blog categories retrieved for the particular request
842      * @throws org.blojsom.fetcher.FetcherException
843      * If there is an error retrieving the blog categories for the request
844      */

845     public Category[] fetchCategories(HttpServletRequest JavaDoc httpServletRequest, HttpServletResponse JavaDoc httpServletResponse, Blog blog, String JavaDoc flavor, Map context) throws FetcherException {
846         Category[] allCategoriesArray;
847
848         try {
849             Session session = _sessionFactory.openSession();
850             Transaction tx = session.beginTransaction();
851
852             // Get the requested category and put it in the context
853
String JavaDoc requestedCategory = getBlogCategory(blog, httpServletRequest);
854             Criteria requestedCategoryCriteria = session.createCriteria(DatabaseCategory.class);
855             requestedCategoryCriteria.add(Restrictions.and(Restrictions.eq("name", BlojsomUtils.addSlashes(requestedCategory)), Restrictions.eq("blogId", blog.getId())));
856             DatabaseCategory dbCategory = (DatabaseCategory) requestedCategoryCriteria.uniqueResult();
857
858             if (dbCategory != null) {
859                 context.put(BlojsomConstants.BLOJSOM_REQUESTED_CATEGORY, dbCategory);
860             }
861
862             // Get all categories and put them in the context
863
Criteria categoryCriteria = session.createCriteria(DatabaseCategory.class);
864             categoryCriteria.add(Restrictions.eq("blogId", blog.getId()));
865             categoryCriteria.addOrder(Order.asc("name"));
866
867             List allCategories = categoryCriteria.list();
868             allCategoriesArray = (DatabaseCategory[]) allCategories.toArray(new DatabaseCategory[allCategories.size()]);
869
870             context.put(BlojsomConstants.BLOJSOM_ALL_CATEGORIES, allCategoriesArray);
871
872             tx.commit();
873             session.close();
874         } catch (HibernateException e) {
875             if (_logger.isErrorEnabled()) {
876                 _logger.error(e);
877             }
878
879             throw new FetcherException(e);
880         }
881
882         return allCategoriesArray;
883     }
884
885     /**
886      * Load each {@link Category} for a given blog
887      *
888      * @param blog {@link Blog}
889      * @return {@link Category} list for the blog
890      * @throws FetcherException If there is an error loading the categories
891      */

892     public Category[] loadAllCategories(Blog blog) throws FetcherException {
893         try {
894             Session session = _sessionFactory.openSession();
895             Transaction tx = session.beginTransaction();
896
897             Criteria categoryCriteria = session.createCriteria(DatabaseCategory.class);
898             categoryCriteria.add(Restrictions.eq("blogId", blog.getId()));
899             categoryCriteria.addOrder(Order.asc("name"));
900
901             List allCategories = categoryCriteria.list();
902
903             tx.commit();
904             session.close();
905
906             return (DatabaseCategory[]) allCategories.toArray(new DatabaseCategory[allCategories.size()]);
907         } catch (HibernateException e) {
908             if (_logger.isErrorEnabled()) {
909                 _logger.error(e);
910             }
911
912             throw new FetcherException(e);
913         }
914     }
915
916     /**
917      * Load the {@link Category} for a given category ID
918      *
919      * @param blog {@link Blog}
920      * @param categoryId Category ID
921      * @return {@link Category} for the given category ID
922      * @throws FetcherException If there is an error loading the category
923      */

924     public Category loadCategory(Blog blog, Integer JavaDoc categoryId) throws FetcherException {
925         try {
926             Session session = _sessionFactory.openSession();
927             Transaction tx = session.beginTransaction();
928
929             Criteria categoryCriteria = session.createCriteria(DatabaseCategory.class);
930             categoryCriteria.add(Restrictions.eq("blogId", blog.getId()))
931                     .add(Restrictions.eq("id", categoryId));
932
933             Category category = (DatabaseCategory) categoryCriteria.uniqueResult();
934
935             tx.commit();
936             session.close();
937
938             return category;
939         } catch (HibernateException e) {
940             if (_logger.isErrorEnabled()) {
941                 _logger.error(e);
942             }
943
944             throw new FetcherException(e);
945         }
946     }
947
948     /**
949      * Load the {@link Category} for a given category name
950      *
951      * @param blog {@link Blog}
952      * @param name Category name
953      * @return {@link Category} for the given category name
954      * @throws FetcherException If there is an error loading the category
955      */

956     public Category loadCategory(Blog blog, String JavaDoc name) throws FetcherException {
957         try {
958             Session session = _sessionFactory.openSession();
959             Transaction tx = session.beginTransaction();
960
961             Criteria categoryCriteria = session.createCriteria(DatabaseCategory.class);
962             categoryCriteria.add(Restrictions.eq("blogId", blog.getId()))
963                     .add(Restrictions.eq("name", name));
964
965             Category category = (DatabaseCategory) categoryCriteria.uniqueResult();
966
967             tx.commit();
968             session.close();
969
970             return category;
971         } catch (HibernateException e) {
972             if (_logger.isErrorEnabled()) {
973                 _logger.error(e);
974             }
975
976             throw new FetcherException(e);
977         }
978     }
979
980     /**
981      * Create a unique post slug
982      *
983      * @param blog {@link Blog}
984      * @param entry {@link Entry}
985      * @return Unique post slug
986      */

987     protected String JavaDoc createPostSlug(Blog blog, Entry entry) {
988         String JavaDoc postSlug;
989
990         if (BlojsomUtils.checkNullOrBlank(entry.getPostSlug())) {
991             postSlug = BlojsomUtils.getPostSlug(entry.getTitle(), entry.getDescription());
992         } else {
993             postSlug = entry.getPostSlug();
994         }
995
996         int postSlugTag = 1;
997         boolean postSlugOK = false;
998
999         while (!postSlugOK) {
1000            try {
1001                loadEntry(blog, postSlug);
1002                postSlug += ("-" + postSlugTag++);
1003            } catch (FetcherException e) {
1004                postSlugOK = true;
1005            }
1006        }
1007
1008        return postSlug;
1009    }
1010
1011    /**
1012     * Save a given {@link Entry}
1013     *
1014     * @param blog {@link Blog}
1015     * @param entry {@link Entry} to save
1016     * @throws FetcherException If there is an error saving the entry
1017     */

1018    public void saveEntry(Blog blog, Entry entry) throws FetcherException {
1019        try {
1020            Session session = _sessionFactory.openSession();
1021            Transaction tx = session.beginTransaction();
1022
1023            if (entry.getBlogId() == null) {
1024                entry.setBlogId(blog.getId());
1025            }
1026
1027            if (entry.getDate() == null) {
1028                entry.setDate(new Date());
1029            }
1030
1031            if (entry.getModifiedDate() == null) {
1032                entry.setModifiedDate(entry.getDate());
1033            }
1034
1035            if (entry.getId() == null) {
1036                entry.setPostSlug(createPostSlug(blog, entry));
1037                session.save(entry);
1038            } else {
1039                session.update(entry);
1040            }
1041
1042            tx.commit();
1043            session.close();
1044        } catch (HibernateException e) {
1045            if (_logger.isErrorEnabled()) {
1046                _logger.error(e);
1047            }
1048
1049            throw new FetcherException(e);
1050        }
1051    }
1052
1053    /**
1054     * Load a given {@link Entry}
1055     *
1056     * @param blog {@link Blog}
1057     * @param entry {@link Entry} to load
1058     * @throws FetcherException If there is an error loading the entry
1059     */

1060    public void loadEntry(Blog blog, Entry entry) throws FetcherException {
1061        if (entry.getId() == null) {
1062            throw new FetcherException("No ID associated with this entry");
1063        }
1064
1065        try {
1066            Session session = _sessionFactory.openSession();
1067            Transaction tx = session.beginTransaction();
1068
1069            session.load(entry, entry.getId());
1070
1071            tx.commit();
1072            session.close();
1073
1074            if (!blog.getId().equals(entry.getBlogId())) {
1075                throw new FetcherException("Entry blog ID not associated with blog ID from call");
1076            }
1077        } catch (HibernateException e) {
1078            if (_logger.isErrorEnabled()) {
1079                _logger.error(e);
1080            }
1081
1082            throw new FetcherException(e);
1083        }
1084    }
1085
1086    /**
1087     * Delete a given {@link Entry}
1088     *
1089     * @param blog {@link Blog}
1090     * @param entry {@link Entry} to delete
1091     * @throws FetcherException If there is an error deleting the entry
1092     */

1093    public void deleteEntry(Blog blog, Entry entry) throws FetcherException {
1094        if (entry.getId() == null) {
1095            throw new FetcherException("No ID associated with this entry");
1096        }
1097
1098        if (!blog.getId().equals(entry.getBlogId())) {
1099            throw new FetcherException("Entry blog ID not associated with blog ID from call");
1100        }
1101
1102        try {
1103            Session session = _sessionFactory.openSession();
1104            Transaction tx = session.beginTransaction();
1105
1106            session.delete(entry);
1107
1108            tx.commit();
1109            session.close();
1110        } catch (HibernateException e) {
1111            if (_logger.isErrorEnabled()) {
1112                _logger.error(e);
1113            }
1114
1115            throw new FetcherException(e);
1116        }
1117    }
1118
1119    /**
1120     * Save a given {@link Category}
1121     *
1122     * @param blog {@link Blog}
1123     * @param category {@link Category} to save
1124     * @throws FetcherException If there is an error saving the category
1125     */

1126    public void saveCategory(Blog blog, Category category) throws FetcherException {
1127        try {
1128            Session session = _sessionFactory.openSession();
1129            Transaction tx = session.beginTransaction();
1130
1131            if (category.getId() == null) {
1132                session.save(category);
1133            } else {
1134                session.update(category);
1135            }
1136
1137            tx.commit();
1138            session.close();
1139        } catch (HibernateException e) {
1140            if (_logger.isErrorEnabled()) {
1141                _logger.error(e);
1142            }
1143
1144            throw new FetcherException(e);
1145        }
1146    }
1147
1148    /**
1149     * Load a given {@link Category}
1150     *
1151     * @param blog {@link Blog}
1152     * @param category {@link Category} to load
1153     * @throws FetcherException If there is an loading saving the category
1154     */

1155    public void loadCategory(Blog blog, Category category) throws FetcherException {
1156        if (category.getId() == null) {
1157            throw new FetcherException("No ID associated with this category");
1158        }
1159
1160        try {
1161            Session session = _sessionFactory.openSession();
1162            Transaction tx = session.beginTransaction();
1163
1164            session.load(category, category.getId());
1165
1166            tx.commit();
1167            session.close();
1168
1169            if (!blog.getId().equals(category.getBlogId())) {
1170                throw new FetcherException("Category blog ID not associated with blog ID from call");
1171            }
1172        } catch (HibernateException e) {
1173            if (_logger.isErrorEnabled()) {
1174                _logger.error(e);
1175            }
1176
1177            throw new FetcherException(e);
1178        }
1179    }
1180
1181    /**
1182     * Delete a given {@link Category}
1183     *
1184     * @param blog {@link Blog}
1185     * @param category {@link Category} to delete
1186     * @throws FetcherException If there is an error deleting the category
1187     */

1188    public void deleteCategory(Blog blog, Category category) throws FetcherException {
1189        if (category.getId() == null) {
1190            throw new FetcherException("No ID associated with this category");
1191        }
1192
1193        if (!blog.getId().equals(category.getBlogId())) {
1194            throw new FetcherException("Category blog ID not associated with blog ID from call");
1195        }
1196
1197        try {
1198            Session session = _sessionFactory.openSession();
1199            Transaction tx = session.beginTransaction();
1200
1201            session.delete(category);
1202
1203            tx.commit();
1204            session.close();
1205        } catch (HibernateException e) {
1206            if (_logger.isErrorEnabled()) {
1207                _logger.error(e);
1208            }
1209
1210            throw new FetcherException(e);
1211        }
1212    }
1213
1214    /**
1215     * Save a given {@link Comment}
1216     *
1217     * @param blog {@link Blog}
1218     * @param comment {@link Comment} to save
1219     * @throws FetcherException If there is an error saving the comment
1220     */

1221    public void saveComment(Blog blog, Comment comment) throws FetcherException {
1222        try {
1223            Session session = _sessionFactory.openSession();
1224            Transaction tx = session.beginTransaction();
1225
1226            if (comment.getId() == null) {
1227                session.save(comment);
1228            } else {
1229                session.update(comment);
1230            }
1231
1232            tx.commit();
1233            session.close();
1234        } catch (HibernateException e) {
1235            if (_logger.isErrorEnabled()) {
1236                _logger.error(e);
1237            }
1238
1239            throw new FetcherException(e);
1240        }
1241    }
1242
1243    /**
1244     * Load a given {@link Comment}
1245     *
1246     * @param blog {@link Blog}
1247     * @param comment {@link Comment} to load
1248     * @throws FetcherException If there is an error loading the comment
1249     */

1250    public void loadComment(Blog blog, Comment comment) throws FetcherException {
1251        if (comment.getId() == null) {
1252            throw new FetcherException("No ID associated with this comment");
1253        }
1254
1255        try {
1256            Session session = _sessionFactory.openSession();
1257            Transaction tx = session.beginTransaction();
1258
1259            session.load(comment, comment.getId());
1260
1261            tx.commit();
1262            session.close();
1263        } catch (HibernateException e) {
1264            if (_logger.isErrorEnabled()) {
1265                _logger.error(e);
1266            }
1267
1268            throw new FetcherException(e);
1269        }
1270    }
1271
1272    /**
1273     * Delete a given {@link Comment}
1274     *
1275     * @param blog {@link Blog}
1276     * @param comment {@link Comment} to delete
1277     * @throws FetcherException If there is an error deleting the comment
1278     */

1279    public void deleteComment(Blog blog, Comment comment) throws FetcherException {
1280        if (comment.getId() == null) {
1281            throw new FetcherException("No ID associated with this comment");
1282        }
1283
1284        try {
1285            Session session = _sessionFactory.openSession();
1286            Transaction tx = session.beginTransaction();
1287
1288            session.delete(comment);
1289
1290            tx.commit();
1291            session.close();
1292        } catch (HibernateException e) {
1293            if (_logger.isErrorEnabled()) {
1294                _logger.error(e);
1295            }
1296
1297            throw new FetcherException(e);
1298        }
1299    }
1300
1301    /**
1302     * Load the recent comments for a blog
1303     *
1304     * @param blog {@link Blog}
1305     * @throws FetcherException If there is an error retrieving the recent comments
1306     */

1307    public List loadRecentComments(Blog blog) throws FetcherException {
1308        List recentComments;
1309
1310        try {
1311            Session session = _sessionFactory.openSession();
1312            Transaction tx = session.beginTransaction();
1313
1314            Criteria commentsCriteria = session.createCriteria(org.blojsom.blog.database.DatabaseComment.class);
1315            commentsCriteria.add(Restrictions.eq("blogId", blog.getId()))
1316                    .add(Restrictions.eq("status", "approved"))
1317                    .addOrder(Order.desc("commentDate"));
1318            commentsCriteria.setCacheable(true);
1319
1320            String JavaDoc recentCommentsCount = blog.getProperty(BlojsomConstants.RECENT_COMMENTS_COUNT);
1321            int count;
1322            try {
1323                count = Integer.parseInt(recentCommentsCount);
1324            } catch (NumberFormatException JavaDoc e) {
1325                count = BlojsomConstants.DEFAULT_RECENT_COMMENTS_COUNT;
1326            }
1327
1328            if (count > 0) {
1329                commentsCriteria.setMaxResults(count);
1330            }
1331
1332            recentComments = commentsCriteria.list();
1333
1334            tx.commit();
1335            session.close();
1336        } catch (HibernateException e) {
1337            if (_logger.isErrorEnabled()) {
1338                _logger.error(e);
1339            }
1340
1341            throw new FetcherException(e);
1342        }
1343
1344        return recentComments;
1345    }
1346
1347    /**
1348     * Save a given {@link Trackback}
1349     *
1350     * @param blog {@link Blog}
1351     * @param trackback {@link Trackback} to save
1352     * @throws FetcherException If there is an error saving the trackback
1353     */

1354    public void saveTrackback(Blog blog, Trackback trackback) throws FetcherException {
1355        try {
1356            Session session = _sessionFactory.openSession();
1357            Transaction tx = session.beginTransaction();
1358
1359            if (trackback.getId() == null) {
1360                session.save(trackback);
1361            } else {
1362                session.update(trackback);
1363            }
1364
1365            tx.commit();
1366            session.close();
1367        } catch (HibernateException e) {
1368            if (_logger.isErrorEnabled()) {
1369                _logger.error(e);
1370            }
1371
1372            throw new FetcherException(e);
1373        }
1374    }
1375
1376    /**
1377     * Load a given {@link Trackback}
1378     *
1379     * @param blog {@link Blog}
1380     * @param trackback {@link Trackback} to load
1381     * @throws FetcherException If there is an error loading the trackback
1382     */

1383    public void loadTrackback(Blog blog, Trackback trackback) throws FetcherException {
1384        if (trackback.getId() == null) {
1385            throw new FetcherException("No ID associated with this trackback");
1386        }
1387
1388        try {
1389            Session session = _sessionFactory.openSession();
1390            Transaction tx = session.beginTransaction();
1391
1392            session.load(trackback, trackback.getId());
1393
1394            tx.commit();
1395
1396            session.close();
1397        } catch (HibernateException e) {
1398            if (_logger.isErrorEnabled()) {
1399                _logger.error(e);
1400            }
1401
1402            throw new FetcherException(e);
1403        }
1404    }
1405
1406    /**
1407     * Delete a given {@link Trackback}
1408     *
1409     * @param blog {@link Blog}
1410     * @param trackback {@link Trackback} to delete
1411     * @throws FetcherException If there is an error deleting the trackback
1412     */

1413    public void deleteTrackback(Blog blog, Trackback trackback) throws FetcherException {
1414        if (trackback.getId() == null) {
1415            throw new FetcherException("No ID associated with this trackback");
1416        }
1417
1418        try {
1419            Session session = _sessionFactory.openSession();
1420            Transaction tx = session.beginTransaction();
1421
1422            session.delete(trackback);
1423
1424            tx.commit();
1425            session.close();
1426        } catch (HibernateException e) {
1427            if (_logger.isErrorEnabled()) {
1428                _logger.error(e);
1429            }
1430
1431            throw new FetcherException(e);
1432        }
1433    }
1434
1435    /**
1436     * Load the recent trackbacks for a blog
1437     *
1438     * @param blog {@link Blog}
1439     * @throws FetcherException If there is an error retrieving the recent trackbacks
1440     */

1441    public List loadRecentTrackbacks(Blog blog) throws FetcherException {
1442        List recentTrackbacks;
1443
1444        try {
1445            Session session = _sessionFactory.openSession();
1446            Transaction tx = session.beginTransaction();
1447
1448            Criteria trackbacksCriteria = session.createCriteria(org.blojsom.blog.database.DatabaseTrackback.class);
1449            trackbacksCriteria.add(Restrictions.eq("blogId", blog.getId()))
1450                    .add(Restrictions.eq("status", "approved"))
1451                    .addOrder(Order.desc("trackbackDate"));
1452            trackbacksCriteria.setCacheable(true);
1453
1454            String JavaDoc recentTrackbacksCount = blog.getProperty(BlojsomConstants.RECENT_TRACKBACKS_COUNT);
1455            int count;
1456            try {
1457                count = Integer.parseInt(recentTrackbacksCount);
1458            } catch (NumberFormatException JavaDoc e) {
1459                count = BlojsomConstants.DEFAULT_RECENT_TRACKBACKS_COUNT;
1460            }
1461
1462            if (count > 0) {
1463                trackbacksCriteria.setMaxResults(count);
1464            }
1465
1466            recentTrackbacks = trackbacksCriteria.list();
1467
1468            tx.commit();
1469            session.close();
1470        } catch (HibernateException e) {
1471            if (_logger.isErrorEnabled()) {
1472                _logger.error(e);
1473            }
1474
1475            throw new FetcherException(e);
1476        }
1477
1478        return recentTrackbacks;
1479    }
1480
1481    /**
1482     * Save a given {@link Pingback}
1483     *
1484     * @param blog {@link Blog}
1485     * @param pingback {@link Pingback} to save
1486     * @throws FetcherException If there is an error saving the pingback
1487     */

1488    public void savePingback(Blog blog, Pingback pingback) throws FetcherException {
1489        try {
1490            Session session = _sessionFactory.openSession();
1491            Transaction tx = session.beginTransaction();
1492
1493            if (pingback.getId() == null) {
1494                session.save(pingback);
1495            } else {
1496                session.update(pingback);
1497            }
1498
1499            tx.commit();
1500            session.close();
1501        } catch (HibernateException e) {
1502            if (_logger.isErrorEnabled()) {
1503                _logger.error(e);
1504            }
1505
1506            throw new FetcherException(e);
1507        }
1508    }
1509
1510    /**
1511     * Load a given {@link Pingback}
1512     *
1513     * @param blog {@link Blog}
1514     * @param pingback {@link Pingback} to load
1515     * @throws FetcherException If there is an error loading the pingback
1516     */

1517    public void loadPingback(Blog blog, Pingback pingback) throws FetcherException {
1518        if (pingback.getId() == null) {
1519            throw new FetcherException("No ID associated with this pingback");
1520        }
1521
1522        try {
1523            Session session = _sessionFactory.openSession();
1524            Transaction tx = session.beginTransaction();
1525
1526            session.load(pingback, pingback.getId());
1527
1528            tx.commit();
1529
1530            session.close();
1531        } catch (HibernateException e) {
1532            if (_logger.isErrorEnabled()) {
1533                _logger.error(e);
1534            }
1535
1536            throw new FetcherException(e);
1537        }
1538    }
1539
1540    /**
1541     * Load a pingback given the source URI and target URI
1542     *
1543     * @param blog {@link Blog}
1544     * @param sourceURI Source URI
1545     * @param targetURI Target URI
1546     * @return {@link Pingback} given the source and target URIs or <code>null</code> if not found
1547     * @throws FetcherException If there was an erorr loading the pingback
1548     */

1549    public Pingback loadPingback(Blog blog, String JavaDoc sourceURI, String JavaDoc targetURI) throws FetcherException {
1550        Pingback pingback;
1551
1552        try {
1553            Session session = _sessionFactory.openSession();
1554            Transaction tx = session.beginTransaction();
1555
1556            Criteria pingbackCriteria = session.createCriteria(org.blojsom.blog.database.DatabasePingback.class);
1557            pingbackCriteria.add(Restrictions.eq("blogId", blog.getId()))
1558                    .add(Restrictions.eq("sourceURI", sourceURI))
1559                    .add(Restrictions.eq("targetURI", targetURI));
1560
1561            pingback = (Pingback) pingbackCriteria.uniqueResult();
1562
1563            tx.commit();
1564            session.close();
1565        } catch (HibernateException e) {
1566            if (_logger.isErrorEnabled()) {
1567                _logger.error(e);
1568            }
1569
1570            throw new FetcherException(e);
1571        }
1572
1573        return pingback;
1574    }
1575
1576    /**
1577     * Delete a given {@link Pingback}
1578     *
1579     * @param blog {@link Blog}
1580     * @param pingback {@link Pingback} to delete
1581     * @throws FetcherException If there is an error deleting the pingback
1582     */

1583    public void deletePingback(Blog blog, Pingback pingback) throws FetcherException {
1584        if (pingback.getId() == null) {
1585            throw new FetcherException("No ID associated with this pingback");
1586        }
1587
1588        try {
1589            Session session = _sessionFactory.openSession();
1590            Transaction tx = session.beginTransaction();
1591
1592            session.delete(pingback);
1593
1594            tx.commit();
1595            session.close();
1596        } catch (HibernateException e) {
1597            if (_logger.isErrorEnabled()) {
1598                _logger.error(e);
1599            }
1600
1601            throw new FetcherException(e);
1602        }
1603    }
1604
1605    /**
1606     * Load the recent pingbacks for a blog
1607     *
1608     * @param blog {@link Blog}
1609     * @throws FetcherException If there is an error retrieving the recent pingbacks
1610     */

1611    public List loadRecentPingbacks(Blog blog) throws FetcherException {
1612        List recentPingbacks;
1613
1614        try {
1615            Session session = _sessionFactory.openSession();
1616            Transaction tx = session.beginTransaction();
1617
1618            Criteria pingbacksCriteria = session.createCriteria(org.blojsom.blog.database.DatabasePingback.class);
1619            pingbacksCriteria.add(Restrictions.eq("blogId", blog.getId()))
1620                    .add(Restrictions.eq("status", "approved"))
1621                    .addOrder(Order.desc("trackbackDate"));
1622            pingbacksCriteria.setCacheable(true);
1623
1624            String JavaDoc recentPingbacksCount = blog.getProperty(BlojsomConstants.RECENT_PINGBACKS_COUNT);
1625            int count;
1626            try {
1627                count = Integer.parseInt(recentPingbacksCount);
1628            } catch (NumberFormatException JavaDoc e) {
1629                count = BlojsomConstants.DEFAULT_RECENT_PINGBACKS_COUNT;
1630            }
1631
1632            if (count > 0) {
1633                pingbacksCriteria.setMaxResults(count);
1634            }
1635
1636            recentPingbacks = pingbacksCriteria.list();
1637
1638            tx.commit();
1639            session.close();
1640        } catch (HibernateException e) {
1641            if (_logger.isErrorEnabled()) {
1642                _logger.error(e);
1643            }
1644
1645            throw new FetcherException(e);
1646        }
1647
1648        return recentPingbacks;
1649    }
1650
1651    /**
1652     * Load a {@link User} from a blog
1653     *
1654     * @param blog {@link Blog}
1655     * @param userLogin Login ID
1656     * @throws FetcherException If there is an error loading the {@link User} from the blog
1657     */

1658    public User loadUser(Blog blog, String JavaDoc userLogin) throws FetcherException {
1659        try {
1660            Session session = _sessionFactory.openSession();
1661            Transaction tx = session.beginTransaction();
1662
1663            Criteria userCriteria = session.createCriteria(DatabaseUser.class);
1664            userCriteria.add(Restrictions.eq("userLogin", userLogin)).add(Restrictions.eq("blogId", blog.getId()));
1665
1666            DatabaseUser user = (DatabaseUser) userCriteria.uniqueResult();
1667
1668            tx.commit();
1669            session.close();
1670
1671            if (user == null) {
1672                throw new FetcherException("Unable to load user login: " + userLogin + " for blog: " + blog.getBlogId());
1673            }
1674
1675            return user;
1676        } catch (HibernateException e) {
1677            if (_logger.isErrorEnabled()) {
1678                _logger.error(e);
1679            }
1680
1681            throw new FetcherException(e);
1682        }
1683    }
1684
1685    /**
1686     * Retrieve the users for a given blog
1687     *
1688     * @param blog {@link Blog}
1689     * @return List of {@link User}s for a blog
1690     */

1691    public User[] getUsers(Blog blog) {
1692        Session session = _sessionFactory.openSession();
1693        Transaction tx = session.beginTransaction();
1694
1695        Criteria userCriteria = session.createCriteria(org.blojsom.blog.database.DatabaseUser.class);
1696        userCriteria.add(Restrictions.eq("blogId", blog.getId()));
1697        userCriteria.addOrder(Order.asc("userLogin"));
1698
1699        List userList = userCriteria.list();
1700
1701        tx.commit();
1702        session.close();
1703
1704        try {
1705            return (DatabaseUser[]) userList.toArray(new DatabaseUser[userList.size()]);
1706        } catch (Exception JavaDoc e) {
1707            if (_logger.isErrorEnabled()) {
1708                _logger.error(e);
1709            }
1710
1711            return new DatabaseUser[0];
1712        }
1713    }
1714
1715    /**
1716     * Load a given {@link User} from a blog given their ID
1717     *
1718     * @param blog {@link Blog}
1719     * @param userID User ID
1720     * @return {@link User}
1721     * @throws FetcherException If there is an error loading the user
1722     */

1723    public User loadUser(Blog blog, Integer JavaDoc userID) throws FetcherException {
1724        if (userID == null) {
1725            return new DatabaseUser();
1726        } else {
1727            try {
1728                Session session = _sessionFactory.openSession();
1729                Transaction tx = session.beginTransaction();
1730
1731                User user = (DatabaseUser) session.load(DatabaseUser.class, userID);
1732                if (!user.getBlogId().equals(blog.getId())) {
1733                    tx.commit();
1734                    session.close();
1735
1736                    throw new FetcherException("User ID: " + userID + " not from current blog: " + blog.getBlogId());
1737                }
1738
1739                tx.commit();
1740                session.close();
1741
1742                return user;
1743            } catch (HibernateException e) {
1744                if (_logger.isErrorEnabled()) {
1745                    _logger.error(e);
1746                }
1747
1748                throw new FetcherException("Unable to load user ID: " + userID + " from blog: " + blog.getBlogId(), e);
1749            }
1750        }
1751    }
1752
1753    /**
1754     * Save a given {@link User} to the blog
1755     *
1756     * @param blog {@link Blog}
1757     * @param user {@link User}
1758     * @return {@link User}
1759     * @throws FetcherException If there is an error saving the user to the blog
1760     */

1761    public User saveUser(Blog blog, User user) throws FetcherException {
1762        try {
1763            Session session = _sessionFactory.openSession();
1764            Transaction tx = session.beginTransaction();
1765
1766            if (user.getId() == null) {
1767                session.save(user);
1768            } else {
1769                session.update(user);
1770            }
1771
1772            tx.commit();
1773            session.close();
1774
1775            return user;
1776        } catch (HibernateException e) {
1777            if (_logger.isErrorEnabled()) {
1778                _logger.error(e);
1779            }
1780
1781            throw new FetcherException("Unable to save user login: " + user.getUserLogin() + " to blog: " + blog.getBlogId(), e);
1782        }
1783    }
1784
1785    /**
1786     * Delete a given user from a blog
1787     *
1788     * @param blog {@link Blog}
1789     * @param userID User ID
1790     * @throws FetcherException If there is an error deleting the user from the blog
1791     */

1792    public void deleteUser(Blog blog, Integer JavaDoc userID) throws FetcherException {
1793        try {
1794            Session session = _sessionFactory.openSession();
1795            Transaction tx = session.beginTransaction();
1796
1797            User userToDelete = (DatabaseUser) session.load(DatabaseUser.class, userID);
1798            if (!userToDelete.getBlogId().equals(blog.getId())) {
1799                tx.commit();
1800                session.close();
1801
1802                throw new FetcherException("User ID: " + userID + " not from current blog: " + blog.getBlogId());
1803            }
1804
1805            session.delete(userToDelete);
1806
1807            tx.commit();
1808            session.close();
1809        } catch (HibernateException e) {
1810            if (_logger.isErrorEnabled()) {
1811                _logger.error(e);
1812            }
1813
1814            throw new FetcherException("Unable to delete user ID: " + userID + " from blog: " + blog.getBlogId(), e);
1815        }
1816    }
1817
1818    /**
1819     * Load the responses (comments, trackbacks, pingbacks) for a given {@link Blog} matching one of a set of status codes
1820     *
1821     * @param blog {@link Blog}
1822     * @param status List of status codes to load
1823     * @return List of responses (comments, trackbacks, pingbacks) matching one of a set of status codes
1824     * @throws FetcherException If there is an error loading the responses
1825     */

1826    public List findResponsesByStatus(Blog blog, String JavaDoc[] status) throws FetcherException {
1827        List responses = new ArrayList();
1828
1829        try {
1830            Session session = _sessionFactory.openSession();
1831            Transaction tx = session.beginTransaction();
1832
1833            Criteria commentsCriteria = session.createCriteria(org.blojsom.blog.database.DatabaseComment.class);
1834            commentsCriteria.add(Restrictions.eq("blogId", blog.getId()))
1835                    .add(Restrictions.in("status", status));
1836
1837            responses.addAll(commentsCriteria.list());
1838
1839            Criteria trackbacksCriteria = session.createCriteria(org.blojsom.blog.database.DatabaseTrackback.class);
1840            trackbacksCriteria.add(Restrictions.eq("blogId", blog.getId()))
1841                    .add(Restrictions.in("status", status));
1842
1843            responses.addAll(trackbacksCriteria.list());
1844
1845            tx.commit();
1846            session.close();
1847        } catch (HibernateException e) {
1848            if (_logger.isErrorEnabled()) {
1849                _logger.error(e);
1850            }
1851
1852            throw new FetcherException(e);
1853        }
1854
1855        Collections.sort(responses, BlojsomUtils.RESPONSE_COMPARATOR);
1856        return responses;
1857    }
1858
1859    /**
1860     * Find the responses (comments, trackbacks, pingbacks) for a given {@link Blog} matching some query
1861     *
1862     * @param blog {@link Blog}
1863     * @param query Query which will match on various items such as commenter name, e-mail, IP address, etc.
1864     * @return List of responses (comments, trackbacks, pingbacks) matching query
1865     * @throws FetcherException If there is an error loading the responses
1866     */

1867    public List findResponsesByQuery(Blog blog, String JavaDoc query) throws FetcherException {
1868        List responses = new ArrayList();
1869
1870        try {
1871            Session session = _sessionFactory.openSession();
1872            Transaction tx = session.beginTransaction();
1873
1874            Criteria commentsCriteria = session.createCriteria(org.blojsom.blog.database.DatabaseComment.class);
1875            commentsCriteria.add(Restrictions.eq("blogId", blog.getId()))
1876                    .add(Restrictions.disjunction()
1877                            .add(Restrictions.ilike("author", query, MatchMode.ANYWHERE))
1878                            .add(Restrictions.ilike("authorURL", query, MatchMode.ANYWHERE))
1879                            .add(Restrictions.ilike("authorEmail", query, MatchMode.ANYWHERE))
1880                            .add(Restrictions.ilike("comment", query, MatchMode.ANYWHERE))
1881                            .add(Restrictions.ilike("ip", query, MatchMode.ANYWHERE)));
1882
1883            responses.addAll(commentsCriteria.list());
1884
1885            Criteria trackbacksCriteria = session.createCriteria(org.blojsom.blog.database.DatabaseTrackback.class);
1886            trackbacksCriteria.add(Restrictions.eq("blogId", blog.getId()))
1887                    .add(Restrictions.disjunction()
1888                            .add(Restrictions.ilike("title", query, MatchMode.ANYWHERE))
1889                            .add(Restrictions.ilike("excerpt", query, MatchMode.ANYWHERE))
1890                            .add(Restrictions.ilike("url", query, MatchMode.ANYWHERE))
1891                            .add(Restrictions.ilike("blogName", query, MatchMode.ANYWHERE))
1892                            .add(Restrictions.ilike("ip", query, MatchMode.ANYWHERE)));
1893
1894            responses.addAll(trackbacksCriteria.list());
1895
1896            tx.commit();
1897            session.close();
1898        } catch (HibernateException e) {
1899            if (_logger.isErrorEnabled()) {
1900                _logger.error(e);
1901            }
1902
1903            throw new FetcherException(e);
1904        }
1905
1906        Collections.sort(responses, BlojsomUtils.RESPONSE_COMPARATOR);
1907        return responses;
1908    }
1909
1910    /**
1911     * Handle an event broadcast from another component
1912     *
1913     * @param event {@link org.blojsom.event.Event} to be handled
1914     */

1915    public void handleEvent(Event event) {
1916    }
1917
1918    /**
1919     * Process an event from another component
1920     *
1921     * @param event {@link org.blojsom.event.Event} to be handled
1922     */

1923    public void processEvent(Event event) {
1924    }
1925
1926    /**
1927     * Called when {@link org.blojsom.servlet.BlojsomServlet} is taken out of service
1928     *
1929     * @throws org.blojsom.fetcher.FetcherException
1930     * If there is an error in finalizing this fetcher
1931     */

1932    public void destroy() throws FetcherException {
1933        try {
1934            _sessionFactory.close();
1935        } catch (HibernateException e) {
1936            if (_logger.isErrorEnabled()) {
1937                _logger.error(e);
1938            }
1939        }
1940
1941        if (_logger.isDebugEnabled()) {
1942            _logger.debug("Destroyed database fetcher");
1943        }
1944    }
1945}
1946
Popular Tags