Source Code Cross Referenced for DatabaseFetcher.java in  » Blogger-System » blojsom-3.1 » org » blojsom » fetcher » database » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Blogger System » blojsom 3.1 » org.blojsom.fetcher.database 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


0001:        /**
0002:         * Copyright (c) 2003-2007, David A. Czarnecki
0003:         * All rights reserved.
0004:         *
0005:         * Redistribution and use in source and binary forms, with or without
0006:         * modification, are permitted provided that the following conditions are met:
0007:         *
0008:         * Redistributions of source code must retain the above copyright notice, this list of conditions and the
0009:         *     following disclaimer.
0010:         * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
0011:         *     following disclaimer in the documentation and/or other materials provided with the distribution.
0012:         * Neither the name of "David A. Czarnecki" and "blojsom" nor the names of its contributors may be used to
0013:         *     endorse or promote products derived from this software without specific prior written permission.
0014:         * Products derived from this software may not be called "blojsom", nor may "blojsom" appear in their name,
0015:         *     without prior written permission of David A. Czarnecki.
0016:         *
0017:         * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
0018:         * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
0019:         * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
0020:         * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
0021:         * EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
0022:         * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
0023:         * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
0024:         * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
0025:         * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
0026:         * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
0027:         * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
0028:         * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
0029:         * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
0030:         */package org.blojsom.fetcher.database;
0031:
0032:        import org.apache.commons.logging.Log;
0033:        import org.apache.commons.logging.LogFactory;
0034:        import org.blojsom.blog.*;
0035:        import org.blojsom.blog.database.*;
0036:        import org.blojsom.event.Event;
0037:        import org.blojsom.event.EventBroadcaster;
0038:        import org.blojsom.event.Listener;
0039:        import org.blojsom.fetcher.Fetcher;
0040:        import org.blojsom.fetcher.FetcherException;
0041:        import org.blojsom.util.BlojsomConstants;
0042:        import org.blojsom.util.BlojsomMetaDataConstants;
0043:        import org.blojsom.util.BlojsomUtils;
0044:        import org.hibernate.*;
0045:        import org.hibernate.criterion.MatchMode;
0046:        import org.hibernate.criterion.Order;
0047:        import org.hibernate.criterion.Projections;
0048:        import org.hibernate.criterion.Restrictions;
0049:
0050:        import javax.servlet.ServletConfig;
0051:        import javax.servlet.http.HttpServletRequest;
0052:        import javax.servlet.http.HttpServletResponse;
0053:        import java.util.*;
0054:
0055:        /**
0056:         * Database fetcher
0057:         *
0058:         * @author David Czarnecki
0059:         * @version $Id: DatabaseFetcher.java,v 1.34 2007/01/17 02:35:17 czarneckid Exp $
0060:         * @since blojsom 3.0
0061:         */
0062:        public class DatabaseFetcher implements  Fetcher, Listener {
0063:
0064:            protected Log _logger = LogFactory.getLog(DatabaseFetcher.class);
0065:
0066:            protected ServletConfig _servletConfig;
0067:            protected EventBroadcaster _eventBroadcaster;
0068:            protected SessionFactory _sessionFactory;
0069:            protected Properties _blojsomProperties;
0070:
0071:            /**
0072:             * Create a new instance of the database fetcher
0073:             */
0074:            public DatabaseFetcher() {
0075:            }
0076:
0077:            /**
0078:             * Set the {@link ServletConfig} for the fetcher to grab initialization parameters
0079:             *
0080:             * @param servletConfig {@link ServletConfig}
0081:             */
0082:            public void setServletConfig(ServletConfig servletConfig) {
0083:                _servletConfig = servletConfig;
0084:            }
0085:
0086:            /**
0087:             * Set the {@link EventBroadcaster} event broadcaster
0088:             *
0089:             * @param eventBroadcaster {@link EventBroadcaster}
0090:             */
0091:            public void setEventBroadcaster(EventBroadcaster eventBroadcaster) {
0092:                _eventBroadcaster = eventBroadcaster;
0093:            }
0094:
0095:            /**
0096:             * Set the {@link SessionFactory}
0097:             *
0098:             * @param sessionFactory {@link SessionFactory}
0099:             */
0100:            public void setSessionFactory(SessionFactory sessionFactory) {
0101:                _sessionFactory = sessionFactory;
0102:            }
0103:
0104:            /**
0105:             * Set the default blojsom properties
0106:             *
0107:             * @param blojsomProperties Default blojsom properties
0108:             */
0109:            public void setBlojsomProperties(Properties blojsomProperties) {
0110:                _blojsomProperties = blojsomProperties;
0111:            }
0112:
0113:            /**
0114:             * Initialize this fetcher. This method only called when the fetcher is instantiated.
0115:             *
0116:             * @throws org.blojsom.fetcher.FetcherException
0117:             *          If there is an error initializing the fetcher
0118:             */
0119:            public void init() throws FetcherException {
0120:                _eventBroadcaster.addListener(this );
0121:
0122:                if (_logger.isDebugEnabled()) {
0123:                    _logger.debug("Initialized database fetcher");
0124:                }
0125:            }
0126:
0127:            /**
0128:             * Return a new {@link org.blojsom.blog.Entry} instance
0129:             *
0130:             * @return Blog entry instance
0131:             */
0132:            public Entry newEntry() {
0133:                return new DatabaseEntry();
0134:            }
0135:
0136:            /**
0137:             * Return a new {@link org.blojsom.blog.Comment} instance
0138:             *
0139:             * @return {@link org.blojsom.blog.Comment} object
0140:             */
0141:            public Comment newComment() {
0142:                return new DatabaseComment();
0143:            }
0144:
0145:            /**
0146:             * Return a new {@link org.blojsom.blog.Trackback} instance
0147:             *
0148:             * @return {@link org.blojsom.blog.Trackback} object
0149:             */
0150:            public Trackback newTrackback() {
0151:                return new DatabaseTrackback();
0152:            }
0153:
0154:            /**
0155:             * Return a new {@link org.blojsom.blog.Pingback} instance
0156:             *
0157:             * @return {@link org.blojsom.blog.Pingback} object
0158:             */
0159:            public Pingback newPingback() {
0160:                return new DatabasePingback();
0161:            }
0162:
0163:            /**
0164:             * Return a new {@link org.blojsom.blog.Category} instance
0165:             *
0166:             * @return {@link org.blojsom.blog.Category} object
0167:             */
0168:            public Category newCategory() {
0169:                return new DatabaseCategory();
0170:            }
0171:
0172:            /**
0173:             * Return a new {@link org.blojsom.blog.Blog} instance
0174:             *
0175:             * @return {@link org.blojsom.blog.Blog} object
0176:             */
0177:            public Blog newBlog() {
0178:                return new DatabaseBlog();
0179:            }
0180:
0181:            /**
0182:             * Return a new {@link org.blojsom.blog.User} instance
0183:             *
0184:             * @return {@link org.blojsom.blog.User} object
0185:             */
0186:            public User newUser() {
0187:                return new DatabaseUser();
0188:            }
0189:
0190:            /**
0191:             * Load the {@link Blog} given the blog ID
0192:             *
0193:             * @param blogId Blog ID
0194:             * @return {@link Blog} object
0195:             * @throws FetcherException If there is an error loading the blog
0196:             */
0197:            public Blog loadBlog(String blogId) throws FetcherException {
0198:                Session session = _sessionFactory.openSession();
0199:                Transaction tx = null;
0200:
0201:                Blog blog = null;
0202:
0203:                try {
0204:                    tx = session.beginTransaction();
0205:                    Criteria blogCriteria = session
0206:                            .createCriteria(org.blojsom.blog.database.DatabaseBlog.class);
0207:                    blogCriteria.add(Restrictions.eq("blogId", blogId));
0208:                    blog = (Blog) blogCriteria.uniqueResult();
0209:
0210:                    tx.commit();
0211:
0212:                    if (blog == null) {
0213:                        throw new FetcherException("Blog id: " + blogId
0214:                                + " not found");
0215:                    }
0216:                } catch (HibernateException e) {
0217:                    if (tx != null) {
0218:                        tx.rollback();
0219:                    }
0220:
0221:                    if (_logger.isErrorEnabled()) {
0222:                        _logger.error(e);
0223:                    }
0224:
0225:                    throw new FetcherException(e);
0226:                } finally {
0227:                    session.close();
0228:                }
0229:
0230:                return blog;
0231:            }
0232:
0233:            /**
0234:             * Load the {@link Blog} given the ID
0235:             *
0236:             * @param id ID
0237:             * @return {@link Blog} blog
0238:             * @throws FetcherException If there is an error loading the blog
0239:             */
0240:            public Blog loadBlog(Integer id) throws FetcherException {
0241:                Session session = _sessionFactory.openSession();
0242:                Transaction tx = null;
0243:
0244:                Blog blog = null;
0245:
0246:                try {
0247:                    tx = session.beginTransaction();
0248:                    Criteria blogCriteria = session
0249:                            .createCriteria(org.blojsom.blog.database.DatabaseBlog.class);
0250:                    blogCriteria.add(Restrictions.eq("id", id));
0251:                    blog = (Blog) blogCriteria.uniqueResult();
0252:
0253:                    tx.commit();
0254:
0255:                    if (blog == null) {
0256:                        throw new FetcherException("Blog id: " + id
0257:                                + " not found");
0258:                    }
0259:                } catch (HibernateException e) {
0260:                    if (tx != null) {
0261:                        tx.rollback();
0262:                    }
0263:
0264:                    if (_logger.isErrorEnabled()) {
0265:                        _logger.error(e);
0266:                    }
0267:
0268:                    throw new FetcherException(e);
0269:                } finally {
0270:                    session.close();
0271:                }
0272:
0273:                return blog;
0274:            }
0275:
0276:            /**
0277:             * Save a {@link Blog}
0278:             *
0279:             * @param blog {@link Blog}
0280:             * @throws FetcherException If there is an error saving the blog
0281:             */
0282:            public void saveBlog(Blog blog) throws FetcherException {
0283:                try {
0284:                    Session session = _sessionFactory.openSession();
0285:                    Transaction tx = session.beginTransaction();
0286:
0287:                    session.saveOrUpdate(blog);
0288:
0289:                    tx.commit();
0290:                    session.close();
0291:                } catch (HibernateException e) {
0292:                    if (_logger.isErrorEnabled()) {
0293:                        _logger.error(e);
0294:                    }
0295:
0296:                    throw new FetcherException(
0297:                            "Unable to save blog inforamtion: "
0298:                                    + blog.getBlogId(), e);
0299:                }
0300:            }
0301:
0302:            /**
0303:             * Delete a blog
0304:             *
0305:             * @param blog {@link Blog}
0306:             * @throws FetcherException If there is an error deleting the blog
0307:             */
0308:            public void deleteBlog(Blog blog) throws FetcherException {
0309:                try {
0310:                    Session session = _sessionFactory.openSession();
0311:                    Transaction tx = session.beginTransaction();
0312:
0313:                    session.delete(blog);
0314:
0315:                    tx.commit();
0316:                    session.close();
0317:                } catch (HibernateException e) {
0318:                    if (_logger.isErrorEnabled()) {
0319:                        _logger.error(e);
0320:                    }
0321:
0322:                    throw new FetcherException(
0323:                            "Unable to delete blog inforamtion: "
0324:                                    + blog.getBlogId(), e);
0325:                }
0326:            }
0327:
0328:            /**
0329:             * Load the blog IDs
0330:             *
0331:             * @return List of blog IDs
0332:             * @throws org.blojsom.fetcher.FetcherException
0333:             *          If there is an error loading the blog IDs
0334:             */
0335:            public String[] loadBlogIDs() throws FetcherException {
0336:                String[] blogIDs;
0337:
0338:                try {
0339:                    Session session = _sessionFactory.openSession();
0340:                    Transaction tx = session.beginTransaction();
0341:
0342:                    List blogIDList = session.getNamedQuery("blog.id.list")
0343:                            .list();
0344:
0345:                    tx.commit();
0346:                    session.close();
0347:
0348:                    blogIDs = (String[]) blogIDList
0349:                            .toArray(new String[blogIDList.size()]);
0350:                } catch (HibernateException e) {
0351:                    if (_logger.isErrorEnabled()) {
0352:                        _logger.error(e);
0353:                    }
0354:
0355:                    throw new FetcherException("Unable to load blog IDs", e);
0356:                }
0357:
0358:                return blogIDs;
0359:            }
0360:
0361:            /**
0362:             * Fetch a set of {@link org.blojsom.blog.Entry} objects.
0363:             *
0364:             * @param httpServletRequest  Request
0365:             * @param httpServletResponse Response
0366:             * @param blog                {@link org.blojsom.blog.Blog} instance
0367:             * @param flavor              Flavor
0368:             * @param context             Context
0369:             * @return Blog entries retrieved for the particular request
0370:             * @throws org.blojsom.fetcher.FetcherException
0371:             *          If there is an error retrieving the blog entries for the request
0372:             */
0373:            public Entry[] fetchEntries(HttpServletRequest httpServletRequest,
0374:                    HttpServletResponse httpServletResponse, Blog blog,
0375:                    String flavor, Map context) throws FetcherException {
0376:                Category category = (Category) context
0377:                        .get(BlojsomConstants.BLOJSOM_REQUESTED_CATEGORY);
0378:
0379:                String ignoreFlavors = _blojsomProperties
0380:                        .getProperty("ignore-flavors");
0381:                // Check to see if the requested flavor should be ignored
0382:                if (ignoreFlavors.indexOf(flavor) != -1) {
0383:                    return new Entry[0];
0384:                }
0385:
0386:                // Determine if a permalink has been requested
0387:                String permalink = BlojsomUtils.getRequestValue(
0388:                        BlojsomConstants.PERMALINK_PARAM, httpServletRequest);
0389:                if (permalink != null) {
0390:                    permalink = BlojsomUtils.urlDecode(permalink);
0391:                    if (_logger.isDebugEnabled()) {
0392:                        _logger.debug("Permalink request for: " + permalink);
0393:                    }
0394:                }
0395:
0396:                if (permalink != null) {
0397:                    Session session = _sessionFactory.openSession();
0398:                    Transaction tx = session.beginTransaction();
0399:
0400:                    Criteria permalinkCriteria = session
0401:                            .createCriteria(org.blojsom.blog.database.DatabaseEntry.class);
0402:                    permalinkCriteria.add(
0403:                            Restrictions.eq("blogId", blog.getId())).add(
0404:                            Restrictions.eq("postSlug", BlojsomUtils
0405:                                    .removeSlashes(permalink))).add(
0406:                            Restrictions.eq("status",
0407:                                    BlojsomMetaDataConstants.PUBLISHED_STATUS))
0408:                            .add(Restrictions.lt("date", new Date()));
0409:
0410:                    List permalinkEntryList = permalinkCriteria.list();
0411:
0412:                    if (permalinkEntryList.size() == 1) {
0413:                        DatabaseEntry entry = (DatabaseEntry) permalinkEntryList
0414:                                .get(0);
0415:                        context.put(BlojsomConstants.BLOJSOM_PERMALINK, entry
0416:                                .getId());
0417:                        permalinkCriteria = session
0418:                                .createCriteria(org.blojsom.blog.database.DatabaseEntry.class);
0419:                        permalinkCriteria
0420:                                .add(Restrictions.eq("blogId", blog.getId()))
0421:                                .add(Restrictions.gt("date", entry.getDate()))
0422:                                .add(Restrictions.lt("date", new Date()))
0423:                                .add(
0424:                                        Restrictions
0425:                                                .eq(
0426:                                                        "status",
0427:                                                        BlojsomMetaDataConstants.PUBLISHED_STATUS));
0428:                        permalinkCriteria.addOrder(Order.asc("date"));
0429:                        permalinkCriteria.setMaxResults(1);
0430:
0431:                        List nextList = permalinkCriteria.list();
0432:                        if (_logger.isDebugEnabled()) {
0433:                            _logger.debug("Total entries after permalink: "
0434:                                    + nextList.size());
0435:                        }
0436:
0437:                        if (nextList.size() == 1) {
0438:                            context
0439:                                    .put(
0440:                                            BlojsomConstants.BLOJSOM_PERMALINK_NEXT_ENTRY,
0441:                                            nextList.get(0));
0442:                        } else {
0443:                            context
0444:                                    .put(
0445:                                            BlojsomConstants.BLOJSOM_PERMALINK_NEXT_ENTRY,
0446:                                            null);
0447:                        }
0448:
0449:                        permalinkCriteria = session
0450:                                .createCriteria(org.blojsom.blog.database.DatabaseEntry.class);
0451:                        permalinkCriteria
0452:                                .add(Restrictions.eq("blogId", blog.getId()))
0453:                                .add(Restrictions.lt("date", entry.getDate()))
0454:                                .add(
0455:                                        Restrictions
0456:                                                .eq(
0457:                                                        "status",
0458:                                                        BlojsomMetaDataConstants.PUBLISHED_STATUS));
0459:                        permalinkCriteria.addOrder(Order.desc("date"));
0460:                        permalinkCriteria.setMaxResults(1);
0461:
0462:                        List prevList = permalinkCriteria.list();
0463:                        if (_logger.isDebugEnabled()) {
0464:                            _logger.debug("Total entries before permalink: "
0465:                                    + prevList.size());
0466:                        }
0467:
0468:                        if (prevList.size() == 1) {
0469:                            context
0470:                                    .put(
0471:                                            BlojsomConstants.BLOJSOM_PERMALINK_PREVIOUS_ENTRY,
0472:                                            prevList.get(0));
0473:                        } else {
0474:                            context
0475:                                    .put(
0476:                                            BlojsomConstants.BLOJSOM_PERMALINK_PREVIOUS_ENTRY,
0477:                                            null);
0478:                        }
0479:                    }
0480:
0481:                    tx.commit();
0482:                    session.close();
0483:
0484:                    if (permalinkEntryList.size() > 0) {
0485:                        return new Entry[] { (Entry) permalinkEntryList.get(0) };
0486:                    } else {
0487:                        return (Entry[]) permalinkEntryList
0488:                                .toArray(new DatabaseEntry[permalinkEntryList
0489:                                        .size()]);
0490:                    }
0491:                } else {
0492:                    String pgNum = BlojsomUtils.getRequestValue(
0493:                            BlojsomConstants.PAGE_NUMBER_PARAM,
0494:                            httpServletRequest);
0495:                    int page;
0496:                    try {
0497:                        page = Integer.parseInt(pgNum);
0498:                        page -= 1;
0499:                        if (page < 0) {
0500:                            page = 0;
0501:                        }
0502:                    } catch (NumberFormatException e) {
0503:                        page = 0;
0504:                    }
0505:
0506:                    page *= blog.getBlogDisplayEntries();
0507:
0508:                    if (category != null && !"/".equals(category.getName())) {
0509:                        Session session = _sessionFactory.openSession();
0510:                        Transaction tx = session.beginTransaction();
0511:
0512:                        Criteria entryCriteria = session
0513:                                .createCriteria(org.blojsom.blog.database.DatabaseEntry.class);
0514:                        entryCriteria.add(Restrictions.eq("blogId", blog
0515:                                .getId()));
0516:                        entryCriteria.add(Restrictions.eq("blogCategoryId",
0517:                                category.getId()));
0518:                        entryCriteria.add(Restrictions.lt("date", new Date()));
0519:                        entryCriteria.add(Restrictions.eq("status",
0520:                                BlojsomMetaDataConstants.PUBLISHED_STATUS));
0521:                        entryCriteria.addOrder(Order.desc("date"));
0522:                        entryCriteria.setMaxResults(blog
0523:                                .getBlogDisplayEntries());
0524:                        entryCriteria.setFirstResult(page);
0525:                        entryCriteria.setCacheable(true);
0526:
0527:                        List entryList = entryCriteria.list();
0528:
0529:                        tx.commit();
0530:                        session.close();
0531:
0532:                        return (DatabaseEntry[]) entryList
0533:                                .toArray(new DatabaseEntry[entryList.size()]);
0534:                    } else {
0535:                        Session session = _sessionFactory.openSession();
0536:                        Transaction tx = session.beginTransaction();
0537:
0538:                        Criteria entryCriteria = session
0539:                                .createCriteria(org.blojsom.blog.database.DatabaseEntry.class);
0540:                        entryCriteria.add(Restrictions.eq("blogId", blog
0541:                                .getId()));
0542:                        entryCriteria.add(Restrictions.lt("date", new Date()));
0543:                        entryCriteria.add(Restrictions.eq("status",
0544:                                BlojsomMetaDataConstants.PUBLISHED_STATUS));
0545:                        entryCriteria.addOrder(Order.desc("date"));
0546:                        entryCriteria.setMaxResults(blog
0547:                                .getBlogDisplayEntries());
0548:                        entryCriteria.setFirstResult(page);
0549:                        entryCriteria.setCacheable(true);
0550:
0551:                        List entryList = entryCriteria.list();
0552:
0553:                        tx.commit();
0554:                        session.close();
0555:
0556:                        return (DatabaseEntry[]) entryList
0557:                                .toArray(new DatabaseEntry[entryList.size()]);
0558:                    }
0559:                }
0560:            }
0561:
0562:            /**
0563:             * Load all the entries for a given category
0564:             *
0565:             * @param blog {@link Blog}
0566:             * @param categoryId Category ID
0567:             * @return Blog entries for a given category
0568:             * @throws FetcherException If there is an error loading the entries
0569:             */
0570:            public Entry[] loadAllEntriesForCategory(Blog blog,
0571:                    Integer categoryId) throws FetcherException {
0572:                try {
0573:                    Session session = _sessionFactory.openSession();
0574:                    Transaction tx = session.beginTransaction();
0575:
0576:                    Criteria entryCriteria = session
0577:                            .createCriteria(DatabaseEntry.class);
0578:                    entryCriteria.add(Restrictions.eq("blogId", blog.getId()));
0579:                    entryCriteria.add(Restrictions.eq("blogCategoryId",
0580:                            categoryId));
0581:                    entryCriteria.addOrder(Order.desc("date"));
0582:                    entryCriteria.setCacheable(true);
0583:
0584:                    List entryList = entryCriteria.list();
0585:
0586:                    tx.commit();
0587:                    session.close();
0588:
0589:                    return (DatabaseEntry[]) entryList
0590:                            .toArray(new DatabaseEntry[entryList.size()]);
0591:                } catch (HibernateException e) {
0592:                    if (_logger.isErrorEnabled()) {
0593:                        _logger.error(e);
0594:                    }
0595:
0596:                    throw new FetcherException(e);
0597:                }
0598:            }
0599:
0600:            /**
0601:             * Load all the entries for a given category
0602:             *
0603:             * @param blog {@link Blog}
0604:             * @param categoryId Category ID
0605:             * @param limit Limit on number of entries to return
0606:             * @return Blog entries for a given category
0607:             * @throws FetcherException If there is an error loading the entries
0608:             */
0609:            public Entry[] loadEntriesForCategory(Blog blog,
0610:                    Integer categoryId, Integer limit) throws FetcherException {
0611:                try {
0612:                    Session session = _sessionFactory.openSession();
0613:                    Transaction tx = session.beginTransaction();
0614:
0615:                    Criteria entryCriteria = session
0616:                            .createCriteria(DatabaseEntry.class);
0617:                    entryCriteria.add(Restrictions.eq("blogId", blog.getId()));
0618:                    entryCriteria.add(Restrictions.eq("blogCategoryId",
0619:                            categoryId));
0620:                    entryCriteria.addOrder(Order.desc("date"));
0621:                    entryCriteria.setMaxResults(limit.intValue());
0622:                    entryCriteria.setCacheable(true);
0623:
0624:                    List entryList = entryCriteria.list();
0625:
0626:                    tx.commit();
0627:                    session.close();
0628:
0629:                    return (DatabaseEntry[]) entryList
0630:                            .toArray(new DatabaseEntry[entryList.size()]);
0631:                } catch (HibernateException e) {
0632:                    if (_logger.isErrorEnabled()) {
0633:                        _logger.error(e);
0634:                    }
0635:
0636:                    throw new FetcherException(e);
0637:                }
0638:            }
0639:
0640:            /**
0641:             * Load a set of entries using a given page size and page in which to retrieve the entries
0642:             *
0643:             * @param blog     {@link Blog}
0644:             * @param pageSize Page size
0645:             * @param page     Page
0646:             * @return Blog entries
0647:             * @throws FetcherException If there is an error loading the entries
0648:             */
0649:            public Entry[] loadEntries(Blog blog, int pageSize, int page)
0650:                    throws FetcherException {
0651:                Session session = _sessionFactory.openSession();
0652:                Transaction tx = session.beginTransaction();
0653:
0654:                page -= 1;
0655:                if (page < 0) {
0656:                    page = 0;
0657:                }
0658:
0659:                if (pageSize < 1) {
0660:                    pageSize = 1;
0661:                }
0662:
0663:                page *= pageSize;
0664:
0665:                Criteria entryCriteria = session
0666:                        .createCriteria(org.blojsom.blog.database.DatabaseEntry.class);
0667:                entryCriteria.add(Restrictions.eq("blogId", blog.getId()));
0668:                entryCriteria.addOrder(Order.desc("date"));
0669:                entryCriteria.setMaxResults(pageSize);
0670:                entryCriteria.setFirstResult(page);
0671:                entryCriteria.setCacheable(true);
0672:
0673:                List entryList = entryCriteria.list();
0674:
0675:                tx.commit();
0676:                session.close();
0677:
0678:                return (DatabaseEntry[]) entryList
0679:                        .toArray(new DatabaseEntry[entryList.size()]);
0680:            }
0681:
0682:            /**
0683:             * Load a set of entries using a given page size and page in which to retrieve the entries
0684:             *
0685:             * @param pageSize Page size
0686:             * @param page     Page
0687:             * @param specificCategory Category
0688:             * @param defaultCategories Default categories to use for requesting entries from the blogs
0689:             * @return Blog entries
0690:             * @throws FetcherException If there is an error loading the entries
0691:             */
0692:            public Entry[] loadEntries(int pageSize, int page,
0693:                    Category specificCategory, Category[] defaultCategories)
0694:                    throws FetcherException {
0695:                Session session = _sessionFactory.openSession();
0696:                Transaction tx = session.beginTransaction();
0697:
0698:                page -= 1;
0699:                if (page < 0) {
0700:                    page = 0;
0701:                }
0702:
0703:                if (pageSize < 1) {
0704:                    pageSize = 1;
0705:                }
0706:
0707:                page *= pageSize;
0708:
0709:                Criteria entryCriteria = session
0710:                        .createCriteria(org.blojsom.blog.database.DatabaseEntry.class);
0711:                entryCriteria.add(Restrictions.eq("status",
0712:                        BlojsomMetaDataConstants.PUBLISHED_STATUS));
0713:                entryCriteria.addOrder(Order.desc("date"));
0714:                entryCriteria.setMaxResults(pageSize);
0715:                entryCriteria.setFirstResult(page);
0716:                entryCriteria.setCacheable(true);
0717:
0718:                if (specificCategory != null) {
0719:                    entryCriteria.createCriteria("blogCategory")
0720:                            .add(
0721:                                    Restrictions.eq("name", specificCategory
0722:                                            .getName()));
0723:                } else {
0724:                    entryCriteria = entryCriteria
0725:                            .createCriteria("blogCategory");
0726:
0727:                    ArrayList names = new ArrayList();
0728:                    for (int i = 0; i < defaultCategories.length; i++) {
0729:                        Category defaultCategory = defaultCategories[i];
0730:                        names.add(defaultCategory.getName());
0731:                    }
0732:
0733:                    entryCriteria.add(Restrictions.in("name", names.toArray()));
0734:                }
0735:
0736:                List entryList = entryCriteria.list();
0737:
0738:                tx.commit();
0739:                session.close();
0740:
0741:                return (DatabaseEntry[]) entryList
0742:                        .toArray(new DatabaseEntry[entryList.size()]);
0743:            }
0744:
0745:            /**
0746:             * Find entries which have the search query in their title or description
0747:             *
0748:             * @param blog  {@link Blog}
0749:             * @param query Search query
0750:             * @return Blog entries which have the search query in their title or descirption
0751:             * @throws FetcherException If there is an error searching through entries
0752:             */
0753:            public Entry[] findEntries(Blog blog, String query)
0754:                    throws FetcherException {
0755:                Session session = _sessionFactory.openSession();
0756:                Transaction tx = session.beginTransaction();
0757:
0758:                Criteria entryCriteria = session
0759:                        .createCriteria(org.blojsom.blog.database.DatabaseEntry.class);
0760:                entryCriteria.add(Restrictions.eq("blogId", blog.getId()));
0761:                entryCriteria
0762:                        .add(
0763:                                Restrictions.or(Restrictions.ilike("title",
0764:                                        query, MatchMode.ANYWHERE),
0765:                                        Restrictions.ilike("description",
0766:                                                query, MatchMode.ANYWHERE)))
0767:                        .add(
0768:                                Restrictions
0769:                                        .eq(
0770:                                                "status",
0771:                                                BlojsomMetaDataConstants.PUBLISHED_STATUS));
0772:                entryCriteria.addOrder(Order.desc("date"));
0773:                entryCriteria.setCacheable(true);
0774:
0775:                List entryList = entryCriteria.list();
0776:
0777:                tx.commit();
0778:                session.close();
0779:
0780:                return (DatabaseEntry[]) entryList
0781:                        .toArray(new DatabaseEntry[entryList.size()]);
0782:            }
0783:
0784:            /**
0785:             * Find entries by a metadata key/value pair
0786:             *
0787:             * @param blog {@link Blog}
0788:             * @param metadataKey Metadata key
0789:             * @param metadataValue Metadata value
0790:             * @param pre If the search should use % before the metadata value (match anything before)
0791:             * @param post If the search should use % after the metadata value (match antthing after)
0792:             * @return Entries matching metadata key and value using LIKE syntax for metadata value
0793:             * @throws FetcherException If there is an error searching through entries
0794:             */
0795:            public Entry[] findEntriesByMetadataKeyValue(Blog blog,
0796:                    String metadataKey, String metadataValue, boolean pre,
0797:                    boolean post) throws FetcherException {
0798:                Session session = _sessionFactory.openSession();
0799:                Transaction tx = session.beginTransaction();
0800:
0801:                String valueSearch = metadataValue;
0802:                if (pre) {
0803:                    valueSearch = "%" + valueSearch;
0804:                }
0805:                if (post) {
0806:                    valueSearch = valueSearch + "%";
0807:                }
0808:
0809:                List entriesMatchingMetadataKeyValue = session.getNamedQuery(
0810:                        "entry.by.metadata.key.value").setCacheable(true)
0811:                        .setInteger("blogId", blog.getId().intValue())
0812:                        .setString("metadataKey", metadataKey).setString(
0813:                                "metadataValue", valueSearch).list();
0814:
0815:                tx.commit();
0816:                session.close();
0817:
0818:                return (DatabaseEntry[]) entriesMatchingMetadataKeyValue
0819:                        .toArray(new DatabaseEntry[entriesMatchingMetadataKeyValue
0820:                                .size()]);
0821:            }
0822:
0823:            /**
0824:             * Find entries with a given metadata key
0825:             *
0826:             * @param blog        {@link Blog}
0827:             * @param metadataKey Metadata key
0828:             * @return Entries with the given metadata key
0829:             * @throws FetcherException If there is an error searching through entries
0830:             */
0831:            public Entry[] findEntriesWithMetadataKey(Blog blog,
0832:                    String metadataKey) throws FetcherException {
0833:                Session session = _sessionFactory.openSession();
0834:                Transaction tx = session.beginTransaction();
0835:
0836:                List entriesMatchingMetadata = session.getNamedQuery(
0837:                        "entry.by.metadata.key").setCacheable(true).setInteger(
0838:                        "blogId", blog.getId().intValue()).setString(
0839:                        "metadataKey", metadataKey).list();
0840:
0841:                tx.commit();
0842:                session.close();
0843:
0844:                return (DatabaseEntry[]) entriesMatchingMetadata
0845:                        .toArray(new DatabaseEntry[entriesMatchingMetadata
0846:                                .size()]);
0847:            }
0848:
0849:            /**
0850:             * Find entries between a start and end date
0851:             *
0852:             * @param blog      {@link Blog}
0853:             * @param startDate Start date
0854:             * @param endDate   End date
0855:             * @return Entries between a start and end date
0856:             * @throws FetcherException If there is an error searching for entries between the dates
0857:             */
0858:            public Entry[] findEntriesBetweenDates(Blog blog, Date startDate,
0859:                    Date endDate) throws FetcherException {
0860:                try {
0861:                    Session session = _sessionFactory.openSession();
0862:                    Transaction tx = session.beginTransaction();
0863:
0864:                    Criteria entryCriteria = session
0865:                            .createCriteria(DatabaseEntry.class);
0866:                    entryCriteria.add(Restrictions.eq("blogId", blog.getId()));
0867:                    entryCriteria.add(Restrictions.between("date", startDate,
0868:                            endDate));
0869:                    entryCriteria.add(Restrictions.eq("status",
0870:                            BlojsomMetaDataConstants.PUBLISHED_STATUS));
0871:                    entryCriteria.addOrder(Order.desc("date"));
0872:                    entryCriteria.setCacheable(true);
0873:
0874:                    List entryList = entryCriteria.list();
0875:
0876:                    tx.commit();
0877:                    session.close();
0878:
0879:                    return (DatabaseEntry[]) entryList
0880:                            .toArray(new DatabaseEntry[entryList.size()]);
0881:                } catch (HibernateException e) {
0882:                    if (_logger.isErrorEnabled()) {
0883:                        _logger.error(e);
0884:                    }
0885:
0886:                    throw new FetcherException(e);
0887:                }
0888:            }
0889:
0890:            /**
0891:             * Count the number of entries for a blog
0892:             *
0893:             * @param blog {@link Blog}
0894:             * @return Number of entries
0895:             * @throws FetcherException If there is an error counting the blog entries
0896:             */
0897:            public Integer countEntries(Blog blog) throws FetcherException {
0898:                Session session = _sessionFactory.openSession();
0899:                Transaction tx = session.beginTransaction();
0900:
0901:                Criteria entryCriteria = session
0902:                        .createCriteria(org.blojsom.blog.database.DatabaseEntry.class);
0903:                entryCriteria.setProjection(Projections.rowCount());
0904:                entryCriteria.add(Restrictions.eq("blogId", blog.getId()));
0905:                entryCriteria.add(Restrictions.lt("date", new Date()));
0906:                entryCriteria.add(Restrictions.eq("status",
0907:                        BlojsomMetaDataConstants.PUBLISHED_STATUS));
0908:                entryCriteria.setCacheable(true);
0909:
0910:                List entryList = entryCriteria.list();
0911:
0912:                tx.commit();
0913:                session.close();
0914:
0915:                return (Integer) entryList.get(0);
0916:            }
0917:
0918:            /**
0919:             * Load an {@link Entry} for a given entry ID
0920:             *
0921:             * @param blog {@link Blog}
0922:             * @param entryId Entry ID
0923:             * @return {@link Entry} object
0924:             * @throws FetcherException If there is an error loading the entry
0925:             */
0926:            public Entry loadEntry(Blog blog, Integer entryId)
0927:                    throws FetcherException {
0928:                try {
0929:                    Session session = _sessionFactory.openSession();
0930:                    Transaction tx = session.beginTransaction();
0931:
0932:                    Criteria entryCriteria = session
0933:                            .createCriteria(DatabaseEntry.class);
0934:                    entryCriteria.add(Restrictions.eq("blogId", blog.getId()))
0935:                            .add(Restrictions.eq("id", entryId));
0936:
0937:                    Entry entry = (DatabaseEntry) entryCriteria.uniqueResult();
0938:
0939:                    tx.commit();
0940:                    session.close();
0941:
0942:                    return entry;
0943:                } catch (HibernateException e) {
0944:                    if (_logger.isErrorEnabled()) {
0945:                        _logger.error(e);
0946:                    }
0947:
0948:                    throw new FetcherException(e);
0949:                }
0950:            }
0951:
0952:            /**
0953:             * Load an {@link Entry} given a post slug
0954:             *
0955:             * @param blog     {@link Blog}
0956:             * @param postSlug Post slug
0957:             * @return {@link Entry} for the given post slug
0958:             * @throws org.blojsom.fetcher.FetcherException
0959:             *          If an entry for the blog and post slug cannot be found
0960:             */
0961:            public Entry loadEntry(Blog blog, String postSlug)
0962:                    throws FetcherException {
0963:                try {
0964:                    Session session = _sessionFactory.openSession();
0965:                    Transaction tx = session.beginTransaction();
0966:
0967:                    Criteria entryCriteria = session
0968:                            .createCriteria(DatabaseEntry.class);
0969:                    entryCriteria.add(Restrictions.eq("blogId", blog.getId()))
0970:                            .add(Restrictions.eq("postSlug", postSlug));
0971:
0972:                    Entry entry = (DatabaseEntry) entryCriteria.uniqueResult();
0973:
0974:                    tx.commit();
0975:                    session.close();
0976:
0977:                    if (entry == null) {
0978:                        throw new FetcherException(
0979:                                "Entry could not be loaded with post slug: "
0980:                                        + postSlug);
0981:                    }
0982:
0983:                    return entry;
0984:                } catch (HibernateException e) {
0985:                    if (_logger.isErrorEnabled()) {
0986:                        _logger.error(e);
0987:                    }
0988:
0989:                    throw new FetcherException(e);
0990:                }
0991:            }
0992:
0993:            /**
0994:             * Determine the blog category based on the request
0995:             *
0996:             * @param blog {@link Blog}
0997:             * @param httpServletRequest Request
0998:             * @return {@link Category} of the requested category
0999:             */
1000:            protected String getBlogCategory(Blog blog,
1001:                    HttpServletRequest httpServletRequest) {
1002:                // Determine the user requested category
1003:                String requestedCategory;
1004:                httpServletRequest.getPathInfo();
1005:                String blogIdFromPath = BlojsomUtils
1006:                        .getBlogFromPath(httpServletRequest.getPathInfo());
1007:                if (blogIdFromPath == null) {
1008:                    requestedCategory = httpServletRequest.getPathInfo();
1009:                } else {
1010:                    if (blogIdFromPath.equals(blog.getBlogId())) {
1011:                        requestedCategory = BlojsomUtils
1012:                                .getCategoryFromPath(httpServletRequest
1013:                                        .getPathInfo());
1014:                    } else {
1015:                        requestedCategory = httpServletRequest.getPathInfo();
1016:                    }
1017:                }
1018:
1019:                requestedCategory = BlojsomUtils.normalize(requestedCategory);
1020:                if (_logger.isDebugEnabled()) {
1021:                    _logger.debug("blojsom path info: " + requestedCategory);
1022:                }
1023:
1024:                String categoryParameter = httpServletRequest
1025:                        .getParameter(BlojsomConstants.CATEGORY_PARAM);
1026:                if (!(categoryParameter == null)
1027:                        && !("".equals(categoryParameter))) {
1028:                    categoryParameter = BlojsomUtils
1029:                            .normalize(categoryParameter);
1030:                    if (_logger.isDebugEnabled()) {
1031:                        _logger.debug("Category parameter override: "
1032:                                + categoryParameter);
1033:                    }
1034:                    requestedCategory = categoryParameter;
1035:                }
1036:
1037:                if (requestedCategory == null) {
1038:                    requestedCategory = "/";
1039:                } else if (!requestedCategory.endsWith("/")) {
1040:                    requestedCategory += "/";
1041:                }
1042:
1043:                requestedCategory = BlojsomUtils.urlDecode(requestedCategory);
1044:                if (_logger.isDebugEnabled()) {
1045:                    _logger.debug("User requested category: "
1046:                            + requestedCategory);
1047:                }
1048:
1049:                return requestedCategory;
1050:            }
1051:
1052:            /**
1053:             * Fetch a set of {@link org.blojsom.blog.Category} objects
1054:             *
1055:             * @param httpServletRequest  Request
1056:             * @param httpServletResponse Response
1057:             * @param blog                {@link org.blojsom.blog.Blog} instance
1058:             * @param flavor              Flavor
1059:             * @param context             Context
1060:             * @return Blog categories retrieved for the particular request
1061:             * @throws org.blojsom.fetcher.FetcherException
1062:             *          If there is an error retrieving the blog categories for the request
1063:             */
1064:            public Category[] fetchCategories(
1065:                    HttpServletRequest httpServletRequest,
1066:                    HttpServletResponse httpServletResponse, Blog blog,
1067:                    String flavor, Map context) throws FetcherException {
1068:                Category[] allCategoriesArray;
1069:
1070:                try {
1071:                    Session session = _sessionFactory.openSession();
1072:                    Transaction tx = session.beginTransaction();
1073:
1074:                    // Get the requested category and put it in the context
1075:                    String requestedCategory = getBlogCategory(blog,
1076:                            httpServletRequest);
1077:                    Criteria requestedCategoryCriteria = session
1078:                            .createCriteria(DatabaseCategory.class);
1079:                    requestedCategoryCriteria.add(Restrictions.and(Restrictions
1080:                            .eq("name", BlojsomUtils
1081:                                    .addSlashes(requestedCategory)),
1082:                            Restrictions.eq("blogId", blog.getId())));
1083:                    DatabaseCategory dbCategory = (DatabaseCategory) requestedCategoryCriteria
1084:                            .uniqueResult();
1085:
1086:                    if (dbCategory != null) {
1087:                        context.put(
1088:                                BlojsomConstants.BLOJSOM_REQUESTED_CATEGORY,
1089:                                dbCategory);
1090:                    }
1091:
1092:                    // Get all categories and put them in the context
1093:                    Criteria categoryCriteria = session
1094:                            .createCriteria(DatabaseCategory.class);
1095:                    categoryCriteria.add(Restrictions
1096:                            .eq("blogId", blog.getId()));
1097:                    categoryCriteria.addOrder(Order.asc("name"));
1098:
1099:                    List allCategories = categoryCriteria.list();
1100:                    allCategoriesArray = (DatabaseCategory[]) allCategories
1101:                            .toArray(new DatabaseCategory[allCategories.size()]);
1102:
1103:                    context.put(BlojsomConstants.BLOJSOM_ALL_CATEGORIES,
1104:                            allCategoriesArray);
1105:
1106:                    tx.commit();
1107:                    session.close();
1108:                } catch (HibernateException e) {
1109:                    if (_logger.isErrorEnabled()) {
1110:                        _logger.error(e);
1111:                    }
1112:
1113:                    throw new FetcherException(e);
1114:                }
1115:
1116:                return allCategoriesArray;
1117:            }
1118:
1119:            /**
1120:             * Load each {@link Category} for a given blog
1121:             *
1122:             * @param blog {@link Blog}
1123:             * @return {@link Category} list for the blog
1124:             * @throws FetcherException If there is an error loading the categories
1125:             */
1126:            public Category[] loadAllCategories(Blog blog)
1127:                    throws FetcherException {
1128:                try {
1129:                    Session session = _sessionFactory.openSession();
1130:                    Transaction tx = session.beginTransaction();
1131:
1132:                    Criteria categoryCriteria = session
1133:                            .createCriteria(DatabaseCategory.class);
1134:                    categoryCriteria.add(Restrictions
1135:                            .eq("blogId", blog.getId()));
1136:                    categoryCriteria.addOrder(Order.asc("name"));
1137:
1138:                    List allCategories = categoryCriteria.list();
1139:
1140:                    tx.commit();
1141:                    session.close();
1142:
1143:                    return (DatabaseCategory[]) allCategories
1144:                            .toArray(new DatabaseCategory[allCategories.size()]);
1145:                } catch (HibernateException e) {
1146:                    if (_logger.isErrorEnabled()) {
1147:                        _logger.error(e);
1148:                    }
1149:
1150:                    throw new FetcherException(e);
1151:                }
1152:            }
1153:
1154:            /**
1155:             * Load the {@link Category} for a given category ID
1156:             *
1157:             * @param blog {@link Blog}
1158:             * @param categoryId Category ID
1159:             * @return {@link Category} for the given category ID
1160:             * @throws FetcherException If there is an error loading the category
1161:             */
1162:            public Category loadCategory(Blog blog, Integer categoryId)
1163:                    throws FetcherException {
1164:                try {
1165:                    Session session = _sessionFactory.openSession();
1166:                    Transaction tx = session.beginTransaction();
1167:
1168:                    Criteria categoryCriteria = session
1169:                            .createCriteria(DatabaseCategory.class);
1170:                    categoryCriteria.add(
1171:                            Restrictions.eq("blogId", blog.getId())).add(
1172:                            Restrictions.eq("id", categoryId));
1173:
1174:                    Category category = (DatabaseCategory) categoryCriteria
1175:                            .uniqueResult();
1176:
1177:                    tx.commit();
1178:                    session.close();
1179:
1180:                    return category;
1181:                } catch (HibernateException e) {
1182:                    if (_logger.isErrorEnabled()) {
1183:                        _logger.error(e);
1184:                    }
1185:
1186:                    throw new FetcherException(e);
1187:                }
1188:            }
1189:
1190:            /**
1191:             * Load the {@link Category} for a given category name
1192:             *
1193:             * @param blog {@link Blog}
1194:             * @param name Category name
1195:             * @return {@link Category} for the given category name
1196:             * @throws FetcherException If there is an error loading the category
1197:             */
1198:            public Category loadCategory(Blog blog, String name)
1199:                    throws FetcherException {
1200:                try {
1201:                    Session session = _sessionFactory.openSession();
1202:                    Transaction tx = session.beginTransaction();
1203:
1204:                    Criteria categoryCriteria = session
1205:                            .createCriteria(DatabaseCategory.class);
1206:                    categoryCriteria.add(
1207:                            Restrictions.eq("blogId", blog.getId())).add(
1208:                            Restrictions.eq("name", name));
1209:
1210:                    Category category = (DatabaseCategory) categoryCriteria
1211:                            .uniqueResult();
1212:
1213:                    tx.commit();
1214:                    session.close();
1215:
1216:                    return category;
1217:                } catch (HibernateException e) {
1218:                    if (_logger.isErrorEnabled()) {
1219:                        _logger.error(e);
1220:                    }
1221:
1222:                    throw new FetcherException(e);
1223:                }
1224:            }
1225:
1226:            /**
1227:             * Create a unique post slug
1228:             *
1229:             * @param blog {@link Blog}
1230:             * @param entry {@link Entry}
1231:             * @return Unique post slug
1232:             */
1233:            protected String createPostSlug(Blog blog, Entry entry) {
1234:                String postSlug;
1235:
1236:                if (BlojsomUtils.checkNullOrBlank(entry.getPostSlug())) {
1237:                    postSlug = BlojsomUtils.getPostSlug(entry.getTitle(), entry
1238:                            .getDescription());
1239:                } else {
1240:                    postSlug = entry.getPostSlug();
1241:                }
1242:
1243:                int postSlugTag = 1;
1244:                boolean postSlugOK = false;
1245:
1246:                while (!postSlugOK) {
1247:                    try {
1248:                        loadEntry(blog, postSlug);
1249:                        postSlug += ("-" + postSlugTag++);
1250:                    } catch (FetcherException e) {
1251:                        postSlugOK = true;
1252:                    }
1253:                }
1254:
1255:                return postSlug;
1256:            }
1257:
1258:            /**
1259:             * Save a given {@link Entry}
1260:             *
1261:             * @param blog {@link Blog}
1262:             * @param entry {@link Entry} to save
1263:             * @throws FetcherException If there is an error saving the entry
1264:             */
1265:            public void saveEntry(Blog blog, Entry entry)
1266:                    throws FetcherException {
1267:                try {
1268:                    Session session = _sessionFactory.openSession();
1269:                    Transaction tx = session.beginTransaction();
1270:
1271:                    if (entry.getBlogId() == null) {
1272:                        entry.setBlogId(blog.getId());
1273:                    }
1274:
1275:                    if (entry.getDate() == null) {
1276:                        entry.setDate(new Date());
1277:                    }
1278:
1279:                    if (entry.getModifiedDate() == null) {
1280:                        entry.setModifiedDate(entry.getDate());
1281:                    }
1282:
1283:                    if (entry.getId() == null) {
1284:                        entry.setPostSlug(createPostSlug(blog, entry));
1285:                        session.save(entry);
1286:                    } else {
1287:                        session.update(entry);
1288:                    }
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 a given {@link Entry}
1303:             *
1304:             * @param blog {@link Blog}
1305:             * @param entry {@link Entry} to load
1306:             * @throws FetcherException If there is an error loading the entry
1307:             */
1308:            public void loadEntry(Blog blog, Entry entry)
1309:                    throws FetcherException {
1310:                if (entry.getId() == null) {
1311:                    throw new FetcherException(
1312:                            "No ID associated with this entry");
1313:                }
1314:
1315:                try {
1316:                    Session session = _sessionFactory.openSession();
1317:                    Transaction tx = session.beginTransaction();
1318:
1319:                    session.load(entry, entry.getId());
1320:
1321:                    tx.commit();
1322:                    session.close();
1323:
1324:                    if (!blog.getId().equals(entry.getBlogId())) {
1325:                        throw new FetcherException(
1326:                                "Entry blog ID not associated with blog ID from call");
1327:                    }
1328:                } catch (HibernateException e) {
1329:                    if (_logger.isErrorEnabled()) {
1330:                        _logger.error(e);
1331:                    }
1332:
1333:                    throw new FetcherException(e);
1334:                }
1335:            }
1336:
1337:            /**
1338:             * Delete a given {@link Entry}
1339:             *
1340:             * @param blog {@link Blog}
1341:             * @param entry {@link Entry} to delete
1342:             * @throws FetcherException If there is an error deleting the entry
1343:             */
1344:            public void deleteEntry(Blog blog, Entry entry)
1345:                    throws FetcherException {
1346:                if (entry.getId() == null) {
1347:                    throw new FetcherException(
1348:                            "No ID associated with this entry");
1349:                }
1350:
1351:                if (!blog.getId().equals(entry.getBlogId())) {
1352:                    throw new FetcherException(
1353:                            "Entry blog ID not associated with blog ID from call");
1354:                }
1355:
1356:                try {
1357:                    Session session = _sessionFactory.openSession();
1358:                    Transaction tx = session.beginTransaction();
1359:
1360:                    session.delete(entry);
1361:
1362:                    tx.commit();
1363:                    session.close();
1364:                } catch (HibernateException e) {
1365:                    if (_logger.isErrorEnabled()) {
1366:                        _logger.error(e);
1367:                    }
1368:
1369:                    throw new FetcherException(e);
1370:                }
1371:            }
1372:
1373:            /**
1374:             * Save a given {@link Category}
1375:             *
1376:             * @param blog {@link Blog}
1377:             * @param category {@link Category} to save
1378:             * @throws FetcherException If there is an error saving the category
1379:             */
1380:            public void saveCategory(Blog blog, Category category)
1381:                    throws FetcherException {
1382:                try {
1383:                    Session session = _sessionFactory.openSession();
1384:                    Transaction tx = session.beginTransaction();
1385:
1386:                    if (category.getId() == null) {
1387:                        session.save(category);
1388:                    } else {
1389:                        session.update(category);
1390:                    }
1391:
1392:                    tx.commit();
1393:                    session.close();
1394:                } catch (HibernateException e) {
1395:                    if (_logger.isErrorEnabled()) {
1396:                        _logger.error(e);
1397:                    }
1398:
1399:                    throw new FetcherException(e);
1400:                }
1401:            }
1402:
1403:            /**
1404:             * Load a given {@link Category}
1405:             *
1406:             * @param blog {@link Blog}
1407:             * @param category {@link Category} to load
1408:             * @throws FetcherException If there is an loading saving the category
1409:             */
1410:            public void loadCategory(Blog blog, Category category)
1411:                    throws FetcherException {
1412:                if (category.getId() == null) {
1413:                    throw new FetcherException(
1414:                            "No ID associated with this category");
1415:                }
1416:
1417:                try {
1418:                    Session session = _sessionFactory.openSession();
1419:                    Transaction tx = session.beginTransaction();
1420:
1421:                    session.load(category, category.getId());
1422:
1423:                    tx.commit();
1424:                    session.close();
1425:
1426:                    if (!blog.getId().equals(category.getBlogId())) {
1427:                        throw new FetcherException(
1428:                                "Category blog ID not associated with blog ID from call");
1429:                    }
1430:                } catch (HibernateException e) {
1431:                    if (_logger.isErrorEnabled()) {
1432:                        _logger.error(e);
1433:                    }
1434:
1435:                    throw new FetcherException(e);
1436:                }
1437:            }
1438:
1439:            /**
1440:             * Delete a given {@link Category}
1441:             *
1442:             * @param blog {@link Blog}
1443:             * @param category {@link Category} to delete
1444:             * @throws FetcherException If there is an error deleting the category
1445:             */
1446:            public void deleteCategory(Blog blog, Category category)
1447:                    throws FetcherException {
1448:                if (category.getId() == null) {
1449:                    throw new FetcherException(
1450:                            "No ID associated with this category");
1451:                }
1452:
1453:                if (!blog.getId().equals(category.getBlogId())) {
1454:                    throw new FetcherException(
1455:                            "Category blog ID not associated with blog ID from call");
1456:                }
1457:
1458:                try {
1459:                    Session session = _sessionFactory.openSession();
1460:                    Transaction tx = session.beginTransaction();
1461:
1462:                    session.delete(category);
1463:
1464:                    tx.commit();
1465:                    session.close();
1466:                } catch (HibernateException e) {
1467:                    if (_logger.isErrorEnabled()) {
1468:                        _logger.error(e);
1469:                    }
1470:
1471:                    throw new FetcherException(e);
1472:                }
1473:            }
1474:
1475:            /**
1476:             * Save a given {@link Comment}
1477:             *
1478:             * @param blog {@link Blog}
1479:             * @param comment {@link Comment} to save
1480:             * @throws FetcherException If there is an error saving the comment
1481:             */
1482:            public void saveComment(Blog blog, Comment comment)
1483:                    throws FetcherException {
1484:                try {
1485:                    Session session = _sessionFactory.openSession();
1486:                    Transaction tx = session.beginTransaction();
1487:
1488:                    if (comment.getId() == null) {
1489:                        session.save(comment);
1490:                    } else {
1491:                        session.update(comment);
1492:                    }
1493:
1494:                    tx.commit();
1495:                    session.close();
1496:                } catch (HibernateException e) {
1497:                    if (_logger.isErrorEnabled()) {
1498:                        _logger.error(e);
1499:                    }
1500:
1501:                    throw new FetcherException(e);
1502:                }
1503:            }
1504:
1505:            /**
1506:             * Load a given {@link Comment}
1507:             *
1508:             * @param blog {@link Blog}
1509:             * @param comment {@link Comment} to load
1510:             * @throws FetcherException If there is an error loading the comment
1511:             */
1512:            public void loadComment(Blog blog, Comment comment)
1513:                    throws FetcherException {
1514:                if (comment.getId() == null) {
1515:                    throw new FetcherException(
1516:                            "No ID associated with this comment");
1517:                }
1518:
1519:                try {
1520:                    Session session = _sessionFactory.openSession();
1521:                    Transaction tx = session.beginTransaction();
1522:
1523:                    session.load(comment, comment.getId());
1524:
1525:                    tx.commit();
1526:                    session.close();
1527:                } catch (HibernateException e) {
1528:                    if (_logger.isErrorEnabled()) {
1529:                        _logger.error(e);
1530:                    }
1531:
1532:                    throw new FetcherException(e);
1533:                }
1534:            }
1535:
1536:            /**
1537:             * Delete a given {@link Comment}
1538:             *
1539:             * @param blog {@link Blog}
1540:             * @param comment {@link Comment} to delete
1541:             * @throws FetcherException If there is an error deleting the comment
1542:             */
1543:            public void deleteComment(Blog blog, Comment comment)
1544:                    throws FetcherException {
1545:                if (comment.getId() == null) {
1546:                    throw new FetcherException(
1547:                            "No ID associated with this comment");
1548:                }
1549:
1550:                try {
1551:                    Session session = _sessionFactory.openSession();
1552:                    Transaction tx = session.beginTransaction();
1553:
1554:                    session.delete(comment);
1555:
1556:                    tx.commit();
1557:                    session.close();
1558:                } catch (HibernateException e) {
1559:                    if (_logger.isErrorEnabled()) {
1560:                        _logger.error(e);
1561:                    }
1562:
1563:                    throw new FetcherException(e);
1564:                }
1565:            }
1566:
1567:            /**
1568:             * Load the recent comments for a blog
1569:             *
1570:             * @param blog  {@link Blog}
1571:             * @throws FetcherException If there is an error retrieving the recent comments
1572:             */
1573:            public List loadRecentComments(Blog blog) throws FetcherException {
1574:                List recentComments;
1575:
1576:                try {
1577:                    Session session = _sessionFactory.openSession();
1578:                    Transaction tx = session.beginTransaction();
1579:
1580:                    Criteria commentsCriteria = session
1581:                            .createCriteria(org.blojsom.blog.database.DatabaseComment.class);
1582:                    commentsCriteria.add(
1583:                            Restrictions.eq("blogId", blog.getId())).add(
1584:                            Restrictions.eq("status", "approved")).addOrder(
1585:                            Order.desc("commentDate"));
1586:                    commentsCriteria.setCacheable(true);
1587:
1588:                    String recentCommentsCount = blog
1589:                            .getProperty(BlojsomConstants.RECENT_COMMENTS_COUNT);
1590:                    int count;
1591:                    try {
1592:                        count = Integer.parseInt(recentCommentsCount);
1593:                    } catch (NumberFormatException e) {
1594:                        count = BlojsomConstants.DEFAULT_RECENT_COMMENTS_COUNT;
1595:                    }
1596:
1597:                    if (count > 0) {
1598:                        commentsCriteria.setMaxResults(count);
1599:                    }
1600:
1601:                    recentComments = commentsCriteria.list();
1602:
1603:                    tx.commit();
1604:                    session.close();
1605:                } catch (HibernateException e) {
1606:                    if (_logger.isErrorEnabled()) {
1607:                        _logger.error(e);
1608:                    }
1609:
1610:                    throw new FetcherException(e);
1611:                }
1612:
1613:                return recentComments;
1614:            }
1615:
1616:            /**
1617:             * Save a given {@link Trackback}
1618:             *
1619:             * @param blog {@link Blog}
1620:             * @param trackback {@link Trackback} to save
1621:             * @throws FetcherException If there is an error saving the trackback
1622:             */
1623:            public void saveTrackback(Blog blog, Trackback trackback)
1624:                    throws FetcherException {
1625:                try {
1626:                    Session session = _sessionFactory.openSession();
1627:                    Transaction tx = session.beginTransaction();
1628:
1629:                    if (trackback.getId() == null) {
1630:                        session.save(trackback);
1631:                    } else {
1632:                        session.update(trackback);
1633:                    }
1634:
1635:                    tx.commit();
1636:                    session.close();
1637:                } catch (HibernateException e) {
1638:                    if (_logger.isErrorEnabled()) {
1639:                        _logger.error(e);
1640:                    }
1641:
1642:                    throw new FetcherException(e);
1643:                }
1644:            }
1645:
1646:            /**
1647:             * Load a given {@link Trackback}
1648:             *
1649:             * @param blog {@link Blog}
1650:             * @param trackback {@link Trackback} to load
1651:             * @throws FetcherException If there is an error loading the trackback
1652:             */
1653:            public void loadTrackback(Blog blog, Trackback trackback)
1654:                    throws FetcherException {
1655:                if (trackback.getId() == null) {
1656:                    throw new FetcherException(
1657:                            "No ID associated with this trackback");
1658:                }
1659:
1660:                try {
1661:                    Session session = _sessionFactory.openSession();
1662:                    Transaction tx = session.beginTransaction();
1663:
1664:                    session.load(trackback, trackback.getId());
1665:
1666:                    tx.commit();
1667:
1668:                    session.close();
1669:                } catch (HibernateException e) {
1670:                    if (_logger.isErrorEnabled()) {
1671:                        _logger.error(e);
1672:                    }
1673:
1674:                    throw new FetcherException(e);
1675:                }
1676:            }
1677:
1678:            /**
1679:             * Delete a given {@link Trackback}
1680:             *
1681:             * @param blog {@link Blog}
1682:             * @param trackback {@link Trackback} to delete
1683:             * @throws FetcherException If there is an error deleting the trackback
1684:             */
1685:            public void deleteTrackback(Blog blog, Trackback trackback)
1686:                    throws FetcherException {
1687:                if (trackback.getId() == null) {
1688:                    throw new FetcherException(
1689:                            "No ID associated with this trackback");
1690:                }
1691:
1692:                try {
1693:                    Session session = _sessionFactory.openSession();
1694:                    Transaction tx = session.beginTransaction();
1695:
1696:                    session.delete(trackback);
1697:
1698:                    tx.commit();
1699:                    session.close();
1700:                } catch (HibernateException e) {
1701:                    if (_logger.isErrorEnabled()) {
1702:                        _logger.error(e);
1703:                    }
1704:
1705:                    throw new FetcherException(e);
1706:                }
1707:            }
1708:
1709:            /**
1710:             * Load the recent trackbacks for a blog
1711:             *
1712:             * @param blog {@link Blog}
1713:             * @throws FetcherException If there is an error retrieving the recent trackbacks
1714:             */
1715:            public List loadRecentTrackbacks(Blog blog) throws FetcherException {
1716:                List recentTrackbacks;
1717:
1718:                try {
1719:                    Session session = _sessionFactory.openSession();
1720:                    Transaction tx = session.beginTransaction();
1721:
1722:                    Criteria trackbacksCriteria = session
1723:                            .createCriteria(org.blojsom.blog.database.DatabaseTrackback.class);
1724:                    trackbacksCriteria.add(
1725:                            Restrictions.eq("blogId", blog.getId())).add(
1726:                            Restrictions.eq("status", "approved")).addOrder(
1727:                            Order.desc("trackbackDate"));
1728:                    trackbacksCriteria.setCacheable(true);
1729:
1730:                    String recentTrackbacksCount = blog
1731:                            .getProperty(BlojsomConstants.RECENT_TRACKBACKS_COUNT);
1732:                    int count;
1733:                    try {
1734:                        count = Integer.parseInt(recentTrackbacksCount);
1735:                    } catch (NumberFormatException e) {
1736:                        count = BlojsomConstants.DEFAULT_RECENT_TRACKBACKS_COUNT;
1737:                    }
1738:
1739:                    if (count > 0) {
1740:                        trackbacksCriteria.setMaxResults(count);
1741:                    }
1742:
1743:                    recentTrackbacks = trackbacksCriteria.list();
1744:
1745:                    tx.commit();
1746:                    session.close();
1747:                } catch (HibernateException e) {
1748:                    if (_logger.isErrorEnabled()) {
1749:                        _logger.error(e);
1750:                    }
1751:
1752:                    throw new FetcherException(e);
1753:                }
1754:
1755:                return recentTrackbacks;
1756:            }
1757:
1758:            /**
1759:             * Save a given {@link Pingback}
1760:             *
1761:             * @param blog {@link Blog}
1762:             * @param pingback {@link Pingback} to save
1763:             * @throws FetcherException If there is an error saving the pingback
1764:             */
1765:            public void savePingback(Blog blog, Pingback pingback)
1766:                    throws FetcherException {
1767:                try {
1768:                    Session session = _sessionFactory.openSession();
1769:                    Transaction tx = session.beginTransaction();
1770:
1771:                    if (pingback.getId() == null) {
1772:                        session.save(pingback);
1773:                    } else {
1774:                        session.update(pingback);
1775:                    }
1776:
1777:                    tx.commit();
1778:                    session.close();
1779:                } catch (HibernateException e) {
1780:                    if (_logger.isErrorEnabled()) {
1781:                        _logger.error(e);
1782:                    }
1783:
1784:                    throw new FetcherException(e);
1785:                }
1786:            }
1787:
1788:            /**
1789:             * Load a given {@link Pingback}
1790:             *
1791:             * @param blog {@link Blog}
1792:             * @param pingback {@link Pingback} to load
1793:             * @throws FetcherException If there is an error loading the pingback
1794:             */
1795:            public void loadPingback(Blog blog, Pingback pingback)
1796:                    throws FetcherException {
1797:                if (pingback.getId() == null) {
1798:                    throw new FetcherException(
1799:                            "No ID associated with this pingback");
1800:                }
1801:
1802:                try {
1803:                    Session session = _sessionFactory.openSession();
1804:                    Transaction tx = session.beginTransaction();
1805:
1806:                    session.load(pingback, pingback.getId());
1807:
1808:                    tx.commit();
1809:
1810:                    session.close();
1811:                } catch (HibernateException e) {
1812:                    if (_logger.isErrorEnabled()) {
1813:                        _logger.error(e);
1814:                    }
1815:
1816:                    throw new FetcherException(e);
1817:                }
1818:            }
1819:
1820:            /**
1821:             * Load a pingback given the source URI and target URI
1822:             *
1823:             * @param blog {@link Blog}
1824:             * @param sourceURI Source URI
1825:             * @param targetURI Target URI
1826:             * @return {@link Pingback} given the source and target URIs or <code>null</code> if not found
1827:             * @throws FetcherException If there was an erorr loading the pingback
1828:             */
1829:            public Pingback loadPingback(Blog blog, String sourceURI,
1830:                    String targetURI) throws FetcherException {
1831:                Pingback pingback;
1832:
1833:                try {
1834:                    Session session = _sessionFactory.openSession();
1835:                    Transaction tx = session.beginTransaction();
1836:
1837:                    Criteria pingbackCriteria = session
1838:                            .createCriteria(org.blojsom.blog.database.DatabasePingback.class);
1839:                    pingbackCriteria.add(
1840:                            Restrictions.eq("blogId", blog.getId())).add(
1841:                            Restrictions.eq("sourceURI", sourceURI)).add(
1842:                            Restrictions.eq("targetURI", targetURI));
1843:
1844:                    pingback = (Pingback) pingbackCriteria.uniqueResult();
1845:
1846:                    tx.commit();
1847:                    session.close();
1848:                } catch (HibernateException e) {
1849:                    if (_logger.isErrorEnabled()) {
1850:                        _logger.error(e);
1851:                    }
1852:
1853:                    throw new FetcherException(e);
1854:                }
1855:
1856:                return pingback;
1857:            }
1858:
1859:            /**
1860:             * Delete a given {@link Pingback}
1861:             *
1862:             * @param blog {@link Blog}
1863:             * @param pingback {@link Pingback} to delete
1864:             * @throws FetcherException If there is an error deleting the pingback
1865:             */
1866:            public void deletePingback(Blog blog, Pingback pingback)
1867:                    throws FetcherException {
1868:                if (pingback.getId() == null) {
1869:                    throw new FetcherException(
1870:                            "No ID associated with this pingback");
1871:                }
1872:
1873:                try {
1874:                    Session session = _sessionFactory.openSession();
1875:                    Transaction tx = session.beginTransaction();
1876:
1877:                    session.delete(pingback);
1878:
1879:                    tx.commit();
1880:                    session.close();
1881:                } catch (HibernateException e) {
1882:                    if (_logger.isErrorEnabled()) {
1883:                        _logger.error(e);
1884:                    }
1885:
1886:                    throw new FetcherException(e);
1887:                }
1888:            }
1889:
1890:            /**
1891:             * Load the recent pingbacks for a blog
1892:             *
1893:             * @param blog {@link Blog}
1894:             * @throws FetcherException If there is an error retrieving the recent pingbacks
1895:             */
1896:            public List loadRecentPingbacks(Blog blog) throws FetcherException {
1897:                List recentPingbacks;
1898:
1899:                try {
1900:                    Session session = _sessionFactory.openSession();
1901:                    Transaction tx = session.beginTransaction();
1902:
1903:                    Criteria pingbacksCriteria = session
1904:                            .createCriteria(org.blojsom.blog.database.DatabasePingback.class);
1905:                    pingbacksCriteria.add(
1906:                            Restrictions.eq("blogId", blog.getId())).add(
1907:                            Restrictions.eq("status", "approved")).addOrder(
1908:                            Order.desc("trackbackDate"));
1909:                    pingbacksCriteria.setCacheable(true);
1910:
1911:                    String recentPingbacksCount = blog
1912:                            .getProperty(BlojsomConstants.RECENT_PINGBACKS_COUNT);
1913:                    int count;
1914:                    try {
1915:                        count = Integer.parseInt(recentPingbacksCount);
1916:                    } catch (NumberFormatException e) {
1917:                        count = BlojsomConstants.DEFAULT_RECENT_PINGBACKS_COUNT;
1918:                    }
1919:
1920:                    if (count > 0) {
1921:                        pingbacksCriteria.setMaxResults(count);
1922:                    }
1923:
1924:                    recentPingbacks = pingbacksCriteria.list();
1925:
1926:                    tx.commit();
1927:                    session.close();
1928:                } catch (HibernateException e) {
1929:                    if (_logger.isErrorEnabled()) {
1930:                        _logger.error(e);
1931:                    }
1932:
1933:                    throw new FetcherException(e);
1934:                }
1935:
1936:                return recentPingbacks;
1937:            }
1938:
1939:            /**
1940:             * Load a {@link User} from a blog
1941:             *
1942:             * @param blog      {@link Blog}
1943:             * @param userLogin Login ID
1944:             * @throws FetcherException If there is an error loading the {@link User} from the blog
1945:             */
1946:            public User loadUser(Blog blog, String userLogin)
1947:                    throws FetcherException {
1948:                try {
1949:                    Session session = _sessionFactory.openSession();
1950:                    Transaction tx = session.beginTransaction();
1951:
1952:                    Criteria userCriteria = session
1953:                            .createCriteria(DatabaseUser.class);
1954:                    userCriteria.add(Restrictions.eq("userLogin", userLogin))
1955:                            .add(Restrictions.eq("blogId", blog.getId()));
1956:
1957:                    DatabaseUser user = (DatabaseUser) userCriteria
1958:                            .uniqueResult();
1959:
1960:                    tx.commit();
1961:                    session.close();
1962:
1963:                    if (user == null) {
1964:                        throw new FetcherException(
1965:                                "Unable to load user login: " + userLogin
1966:                                        + " for blog: " + blog.getBlogId());
1967:                    }
1968:
1969:                    return user;
1970:                } catch (HibernateException e) {
1971:                    if (_logger.isErrorEnabled()) {
1972:                        _logger.error(e);
1973:                    }
1974:
1975:                    throw new FetcherException(e);
1976:                }
1977:            }
1978:
1979:            /**
1980:             * Retrieve the users for a given blog
1981:             *
1982:             * @param blog {@link Blog}
1983:             * @return List of {@link User}s for a blog
1984:             */
1985:            public User[] getUsers(Blog blog) {
1986:                Session session = _sessionFactory.openSession();
1987:                Transaction tx = session.beginTransaction();
1988:
1989:                Criteria userCriteria = session
1990:                        .createCriteria(org.blojsom.blog.database.DatabaseUser.class);
1991:                userCriteria.add(Restrictions.eq("blogId", blog.getId()));
1992:                userCriteria.addOrder(Order.asc("userLogin"));
1993:
1994:                List userList = userCriteria.list();
1995:
1996:                tx.commit();
1997:                session.close();
1998:
1999:                try {
2000:                    return (DatabaseUser[]) userList
2001:                            .toArray(new DatabaseUser[userList.size()]);
2002:                } catch (Exception e) {
2003:                    if (_logger.isErrorEnabled()) {
2004:                        _logger.error(e);
2005:                    }
2006:
2007:                    return new DatabaseUser[0];
2008:                }
2009:            }
2010:
2011:            /**
2012:             * Load a given {@link User} from a blog given their ID
2013:             *
2014:             * @param blog   {@link Blog}
2015:             * @param userID User ID
2016:             * @return {@link User} object
2017:             * @throws FetcherException If there is an error loading the user
2018:             */
2019:            public User loadUser(Blog blog, Integer userID)
2020:                    throws FetcherException {
2021:                if (userID == null) {
2022:                    return new DatabaseUser();
2023:                } else {
2024:                    try {
2025:                        Session session = _sessionFactory.openSession();
2026:                        Transaction tx = session.beginTransaction();
2027:
2028:                        User user = (DatabaseUser) session.load(
2029:                                DatabaseUser.class, userID);
2030:                        if (!user.getBlogId().equals(blog.getId())) {
2031:                            tx.commit();
2032:                            session.close();
2033:
2034:                            throw new FetcherException("User ID: " + userID
2035:                                    + " not from current blog: "
2036:                                    + blog.getBlogId());
2037:                        }
2038:
2039:                        tx.commit();
2040:                        session.close();
2041:
2042:                        return user;
2043:                    } catch (HibernateException e) {
2044:                        if (_logger.isErrorEnabled()) {
2045:                            _logger.error(e);
2046:                        }
2047:
2048:                        throw new FetcherException("Unable to load user ID: "
2049:                                + userID + " from blog: " + blog.getBlogId(), e);
2050:                    }
2051:                }
2052:            }
2053:
2054:            /**
2055:             * Save a given {@link User} to the blog
2056:             *
2057:             * @param blog {@link Blog}
2058:             * @param user {@link User}
2059:             * @return {@link User} object
2060:             * @throws FetcherException If there is an error saving the user to the blog
2061:             */
2062:            public User saveUser(Blog blog, User user) throws FetcherException {
2063:                try {
2064:                    Session session = _sessionFactory.openSession();
2065:                    Transaction tx = session.beginTransaction();
2066:
2067:                    if (user.getId() == null) {
2068:                        session.save(user);
2069:                    } else {
2070:                        session.update(user);
2071:                    }
2072:
2073:                    tx.commit();
2074:                    session.close();
2075:
2076:                    return user;
2077:                } catch (HibernateException e) {
2078:                    if (_logger.isErrorEnabled()) {
2079:                        _logger.error(e);
2080:                    }
2081:
2082:                    throw new FetcherException("Unable to save user login: "
2083:                            + user.getUserLogin() + " to blog: "
2084:                            + blog.getBlogId(), e);
2085:                }
2086:            }
2087:
2088:            /**
2089:             * Delete a given user from a blog
2090:             *
2091:             * @param blog   {@link Blog}
2092:             * @param userID User ID
2093:             * @throws FetcherException If there is an error deleting the user from the blog
2094:             */
2095:            public void deleteUser(Blog blog, Integer userID)
2096:                    throws FetcherException {
2097:                try {
2098:                    Session session = _sessionFactory.openSession();
2099:                    Transaction tx = session.beginTransaction();
2100:
2101:                    User userToDelete = (DatabaseUser) session.load(
2102:                            DatabaseUser.class, userID);
2103:                    if (!userToDelete.getBlogId().equals(blog.getId())) {
2104:                        tx.commit();
2105:                        session.close();
2106:
2107:                        throw new FetcherException("User ID: " + userID
2108:                                + " not from current blog: " + blog.getBlogId());
2109:                    }
2110:
2111:                    session.delete(userToDelete);
2112:
2113:                    tx.commit();
2114:                    session.close();
2115:                } catch (HibernateException e) {
2116:                    if (_logger.isErrorEnabled()) {
2117:                        _logger.error(e);
2118:                    }
2119:
2120:                    throw new FetcherException("Unable to delete user ID: "
2121:                            + userID + " from blog: " + blog.getBlogId(), e);
2122:                }
2123:            }
2124:
2125:            /**
2126:             * Load the responses (comments, trackbacks, pingbacks) for a given {@link Blog} matching one of a set of status codes
2127:             *
2128:             * @param blog {@link Blog}
2129:             * @param status List of status codes to load
2130:             * @return List of responses (comments, trackbacks, pingbacks) matching one of a set of status codes
2131:             * @throws FetcherException If there is an error loading the responses
2132:             */
2133:            public List findResponsesByStatus(Blog blog, String[] status)
2134:                    throws FetcherException {
2135:                List responses = new ArrayList();
2136:
2137:                try {
2138:                    Session session = _sessionFactory.openSession();
2139:                    Transaction tx = session.beginTransaction();
2140:
2141:                    Criteria commentsCriteria = session
2142:                            .createCriteria(org.blojsom.blog.database.DatabaseComment.class);
2143:                    commentsCriteria.add(
2144:                            Restrictions.eq("blogId", blog.getId())).add(
2145:                            Restrictions.in("status", status));
2146:
2147:                    responses.addAll(commentsCriteria.list());
2148:
2149:                    Criteria trackbacksCriteria = session
2150:                            .createCriteria(org.blojsom.blog.database.DatabaseTrackback.class);
2151:                    trackbacksCriteria.add(
2152:                            Restrictions.eq("blogId", blog.getId())).add(
2153:                            Restrictions.in("status", status));
2154:
2155:                    responses.addAll(trackbacksCriteria.list());
2156:
2157:                    tx.commit();
2158:                    session.close();
2159:                } catch (HibernateException e) {
2160:                    if (_logger.isErrorEnabled()) {
2161:                        _logger.error(e);
2162:                    }
2163:
2164:                    throw new FetcherException(e);
2165:                }
2166:
2167:                Collections.sort(responses, BlojsomUtils.RESPONSE_COMPARATOR);
2168:                return responses;
2169:            }
2170:
2171:            /**
2172:             * Find the responses (comments, trackbacks, pingbacks) for a given {@link Blog} matching some query
2173:             *
2174:             * @param blog {@link Blog}
2175:             * @param query Query which will match on various items such as commenter name, e-mail, IP address, etc.
2176:             * @return List of responses (comments, trackbacks, pingbacks) matching query
2177:             * @throws FetcherException If there is an error loading the responses
2178:             */
2179:            public List findResponsesByQuery(Blog blog, String query)
2180:                    throws FetcherException {
2181:                List responses = new ArrayList();
2182:
2183:                try {
2184:                    Session session = _sessionFactory.openSession();
2185:                    Transaction tx = session.beginTransaction();
2186:
2187:                    Criteria commentsCriteria = session
2188:                            .createCriteria(org.blojsom.blog.database.DatabaseComment.class);
2189:                    commentsCriteria.add(
2190:                            Restrictions.eq("blogId", blog.getId())).add(
2191:                            Restrictions.disjunction().add(
2192:                                    Restrictions.ilike("author", query,
2193:                                            MatchMode.ANYWHERE)).add(
2194:                                    Restrictions.ilike("authorURL", query,
2195:                                            MatchMode.ANYWHERE)).add(
2196:                                    Restrictions.ilike("authorEmail", query,
2197:                                            MatchMode.ANYWHERE)).add(
2198:                                    Restrictions.ilike("comment", query,
2199:                                            MatchMode.ANYWHERE)).add(
2200:                                    Restrictions.ilike("ip", query,
2201:                                            MatchMode.ANYWHERE)));
2202:
2203:                    responses.addAll(commentsCriteria.list());
2204:
2205:                    Criteria trackbacksCriteria = session
2206:                            .createCriteria(org.blojsom.blog.database.DatabaseTrackback.class);
2207:                    trackbacksCriteria.add(
2208:                            Restrictions.eq("blogId", blog.getId())).add(
2209:                            Restrictions.disjunction().add(
2210:                                    Restrictions.ilike("title", query,
2211:                                            MatchMode.ANYWHERE)).add(
2212:                                    Restrictions.ilike("excerpt", query,
2213:                                            MatchMode.ANYWHERE)).add(
2214:                                    Restrictions.ilike("url", query,
2215:                                            MatchMode.ANYWHERE)).add(
2216:                                    Restrictions.ilike("blogName", query,
2217:                                            MatchMode.ANYWHERE)).add(
2218:                                    Restrictions.ilike("ip", query,
2219:                                            MatchMode.ANYWHERE)));
2220:
2221:                    responses.addAll(trackbacksCriteria.list());
2222:
2223:                    tx.commit();
2224:                    session.close();
2225:                } catch (HibernateException e) {
2226:                    if (_logger.isErrorEnabled()) {
2227:                        _logger.error(e);
2228:                    }
2229:
2230:                    throw new FetcherException(e);
2231:                }
2232:
2233:                Collections.sort(responses, BlojsomUtils.RESPONSE_COMPARATOR);
2234:                return responses;
2235:            }
2236:
2237:            /**
2238:             * Handle an event broadcast from another component
2239:             *
2240:             * @param event {@link org.blojsom.event.Event} to be handled
2241:             */
2242:            public void handleEvent(Event event) {
2243:            }
2244:
2245:            /**
2246:             * Process an event from another component
2247:             *
2248:             * @param event {@link org.blojsom.event.Event} to be handled
2249:             */
2250:            public void processEvent(Event event) {
2251:            }
2252:
2253:            /**
2254:             * Called when {@link org.blojsom.servlet.BlojsomServlet} is taken out of service
2255:             *
2256:             * @throws org.blojsom.fetcher.FetcherException
2257:             *          If there is an error in finalizing this fetcher
2258:             */
2259:            public void destroy() throws FetcherException {
2260:                try {
2261:                    _sessionFactory.close();
2262:                } catch (HibernateException e) {
2263:                    if (_logger.isErrorEnabled()) {
2264:                        _logger.error(e);
2265:                    }
2266:                }
2267:
2268:                if (_logger.isDebugEnabled()) {
2269:                    _logger.debug("Destroyed database fetcher");
2270:                }
2271:            }
2272:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.