Source Code Cross Referenced for HibernateWeblogManagerImpl.java in  » Blogger-System » apache-roller-3.1 » org » apache » roller » business » hibernate » 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 » apache roller 3.1 » org.apache.roller.business.hibernate 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


0001:        /*
0002:         * Licensed to the Apache Software Foundation (ASF) under one or more
0003:         *  contributor license agreements.  The ASF licenses this file to You
0004:         * under the Apache License, Version 2.0 (the "License"); you may not
0005:         * use this file except in compliance with the License.
0006:         * You may obtain a copy of the License at
0007:         *
0008:         *     http://www.apache.org/licenses/LICENSE-2.0
0009:         *
0010:         * Unless required by applicable law or agreed to in writing, software
0011:         * distributed under the License is distributed on an "AS IS" BASIS,
0012:         * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0013:         * See the License for the specific language governing permissions and
0014:         * limitations under the License.  For additional information regarding
0015:         * copyright in this work, please see the NOTICE file in the top level
0016:         * directory of this distribution.
0017:         */
0018:
0019:        package org.apache.roller.business.hibernate;
0020:
0021:        import java.sql.Timestamp;
0022:        import java.text.SimpleDateFormat;
0023:        import java.util.ArrayList;
0024:        import java.util.Calendar;
0025:        import java.util.Collections;
0026:        import java.util.Comparator;
0027:        import java.util.Date;
0028:        import java.util.Hashtable;
0029:        import java.util.Iterator;
0030:        import java.util.LinkedList;
0031:        import java.util.List;
0032:        import java.util.Map;
0033:        import java.util.TreeMap;
0034:
0035:        import org.apache.commons.collections.comparators.ReverseComparator;
0036:        import org.apache.commons.lang.StringUtils;
0037:        import org.apache.commons.logging.Log;
0038:        import org.apache.commons.logging.LogFactory;
0039:        import org.apache.roller.RollerException;
0040:        import org.apache.roller.business.RollerFactory;
0041:        import org.apache.roller.business.WeblogManager;
0042:        import org.apache.roller.pojos.Assoc;
0043:        import org.apache.roller.pojos.CommentData;
0044:        import org.apache.roller.pojos.HitCountData;
0045:        import org.apache.roller.pojos.RefererData;
0046:        import org.apache.roller.pojos.StatCount;
0047:        import org.apache.roller.pojos.TagStat;
0048:        import org.apache.roller.pojos.TagStatComparator;
0049:        import org.apache.roller.pojos.UserData;
0050:        import org.apache.roller.pojos.WeblogCategoryAssoc;
0051:        import org.apache.roller.pojos.WeblogCategoryData;
0052:        import org.apache.roller.pojos.WeblogEntryData;
0053:        import org.apache.roller.pojos.WeblogEntryTagData;
0054:        import org.apache.roller.pojos.WeblogEntryTagAggregateData;
0055:        import org.apache.roller.pojos.WebsiteData;
0056:        import org.apache.roller.util.DateUtil;
0057:        import org.apache.roller.util.Utilities;
0058:        import org.hibernate.Criteria;
0059:        import org.hibernate.HibernateException;
0060:        import org.hibernate.Query;
0061:        import org.hibernate.Session;
0062:        import org.hibernate.criterion.Expression;
0063:        import org.hibernate.criterion.Junction;
0064:        import org.hibernate.criterion.MatchMode;
0065:        import org.hibernate.criterion.Order;
0066:        import org.hibernate.criterion.Restrictions;
0067:
0068:        /**
0069:         * Hibernate implementation of the WeblogManager.
0070:         */
0071:        public class HibernateWeblogManagerImpl implements  WeblogManager {
0072:
0073:            static final long serialVersionUID = -3730860865389981439L;
0074:
0075:            private static Log log = LogFactory
0076:                    .getLog(HibernateWeblogManagerImpl.class);
0077:
0078:            private HibernatePersistenceStrategy strategy = null;
0079:
0080:            // cached mapping of entryAnchors -> entryIds
0081:            private Hashtable entryAnchorToIdMap = new Hashtable();
0082:
0083:            /* inline creation of reverse comparator, anonymous inner class */
0084:            private Comparator reverseComparator = new ReverseComparator();
0085:
0086:            private Comparator tagStatComparator = new TagStatComparator();
0087:
0088:            public HibernateWeblogManagerImpl(HibernatePersistenceStrategy strat) {
0089:                log.debug("Instantiating Hibernate Weblog Manager");
0090:
0091:                this .strategy = strat;
0092:            }
0093:
0094:            public void saveWeblogCategory(WeblogCategoryData cat)
0095:                    throws RollerException {
0096:
0097:                if (this .isDuplicateWeblogCategoryName(cat)) {
0098:                    throw new RollerException(
0099:                            "Duplicate category name, cannot save category");
0100:                }
0101:
0102:                // update weblog last modified date.  date updated by saveWebsite()
0103:                RollerFactory.getRoller().getUserManager().saveWebsite(
0104:                        cat.getWebsite());
0105:
0106:                this .strategy.store(cat);
0107:            }
0108:
0109:            public void removeWeblogCategory(WeblogCategoryData cat)
0110:                    throws RollerException {
0111:
0112:                if (cat.retrieveWeblogEntries(true).size() > 0) {
0113:                    throw new RollerException(
0114:                            "Cannot remove category with entries");
0115:                }
0116:
0117:                // remove cat
0118:                this .strategy.remove(cat);
0119:
0120:                // update website default cats if needed
0121:                if (cat.getWebsite().getBloggerCategory().equals(cat)) {
0122:                    WeblogCategoryData rootCat = this .getRootWeblogCategory(cat
0123:                            .getWebsite());
0124:                    cat.getWebsite().setBloggerCategory(rootCat);
0125:                    this .strategy.store(cat.getWebsite());
0126:                }
0127:
0128:                if (cat.getWebsite().getDefaultCategory().equals(cat)) {
0129:                    WeblogCategoryData rootCat = this .getRootWeblogCategory(cat
0130:                            .getWebsite());
0131:                    cat.getWebsite().setDefaultCategory(rootCat);
0132:                    this .strategy.store(cat.getWebsite());
0133:                }
0134:
0135:                // update weblog last modified date.  date updated by saveWebsite()
0136:                RollerFactory.getRoller().getUserManager().saveWebsite(
0137:                        cat.getWebsite());
0138:            }
0139:
0140:            public void moveWeblogCategoryContents(WeblogCategoryData srcCat,
0141:                    WeblogCategoryData destCat) throws RollerException {
0142:
0143:                // TODO: this check should be made before calling this method?
0144:                if (destCat.descendentOf(srcCat)) {
0145:                    throw new RollerException(
0146:                            "ERROR cannot move parent category into it's own child");
0147:                }
0148:
0149:                // get all entries in category and subcats
0150:                List results = srcCat.retrieveWeblogEntries(true);
0151:
0152:                // Loop through entries in src cat, assign them to dest cat
0153:                Iterator iter = results.iterator();
0154:                WebsiteData website = destCat.getWebsite();
0155:                while (iter.hasNext()) {
0156:                    WeblogEntryData entry = (WeblogEntryData) iter.next();
0157:                    entry.setCategory(destCat);
0158:                    entry.setWebsite(website);
0159:                    this .strategy.store(entry);
0160:                }
0161:
0162:                // Make sure website's default and bloggerapi categories
0163:                // are valid after the move
0164:
0165:                if (srcCat.getWebsite().getDefaultCategory().getId().equals(
0166:                        srcCat.getId())
0167:                        || srcCat.getWebsite().getDefaultCategory()
0168:                                .descendentOf(srcCat)) {
0169:                    srcCat.getWebsite().setDefaultCategory(destCat);
0170:                    this .strategy.store(srcCat.getWebsite());
0171:                }
0172:
0173:                if (srcCat.getWebsite().getBloggerCategory().getId().equals(
0174:                        srcCat.getId())
0175:                        || srcCat.getWebsite().getBloggerCategory()
0176:                                .descendentOf(srcCat)) {
0177:                    srcCat.getWebsite().setBloggerCategory(destCat);
0178:                    this .strategy.store(srcCat.getWebsite());
0179:                }
0180:            }
0181:
0182:            public void saveComment(CommentData comment) throws RollerException {
0183:                this .strategy.store(comment);
0184:
0185:                // update weblog last modified date.  date updated by saveWebsite()
0186:                RollerFactory.getRoller().getUserManager().saveWebsite(
0187:                        comment.getWeblogEntry().getWebsite());
0188:            }
0189:
0190:            public void removeComment(CommentData comment)
0191:                    throws RollerException {
0192:                this .strategy.remove(comment);
0193:
0194:                // update weblog last modified date.  date updated by saveWebsite()
0195:                RollerFactory.getRoller().getUserManager().saveWebsite(
0196:                        comment.getWeblogEntry().getWebsite());
0197:            }
0198:
0199:            // TODO: perhaps the createAnchor() and queuePings() items should go outside this method?
0200:            public void saveWeblogEntry(WeblogEntryData entry)
0201:                    throws RollerException {
0202:
0203:                if (entry.getAnchor() == null
0204:                        || entry.getAnchor().trim().equals("")) {
0205:                    entry.setAnchor(this .createAnchor(entry));
0206:                }
0207:
0208:                for (Iterator it = entry.getAddedTags().iterator(); it
0209:                        .hasNext();) {
0210:                    String name = (String) it.next();
0211:                    updateTagCount(name, entry.getWebsite(), 1);
0212:                }
0213:
0214:                for (Iterator it = entry.getRemovedTags().iterator(); it
0215:                        .hasNext();) {
0216:                    String name = (String) it.next();
0217:                    updateTagCount(name, entry.getWebsite(), -1);
0218:                }
0219:
0220:                this .strategy.store(entry);
0221:
0222:                // update weblog last modified date.  date updated by saveWebsite()
0223:                if (entry.isPublished()) {
0224:                    RollerFactory.getRoller().getUserManager().saveWebsite(
0225:                            entry.getWebsite());
0226:                }
0227:
0228:                if (entry.isPublished()) {
0229:                    // Queue applicable pings for this update.
0230:                    RollerFactory.getRoller().getAutopingManager()
0231:                            .queueApplicableAutoPings(entry);
0232:                }
0233:            }
0234:
0235:            public void removeWeblogEntry(WeblogEntryData entry)
0236:                    throws RollerException {
0237:
0238:                Session session = ((HibernatePersistenceStrategy) this .strategy)
0239:                        .getSession();
0240:
0241:                // remove referers
0242:                Criteria refererQuery = session
0243:                        .createCriteria(RefererData.class);
0244:                refererQuery.add(Expression.eq("weblogEntry", entry));
0245:                List referers = refererQuery.list();
0246:                for (Iterator iter = referers.iterator(); iter.hasNext();) {
0247:                    RefererData referer = (RefererData) iter.next();
0248:                    this .strategy.remove(referer);
0249:                }
0250:
0251:                // remove comments
0252:                List comments = getComments(null, // website
0253:                        entry, null, // search String
0254:                        null, // startDate
0255:                        null, // endDate
0256:                        null, // pending
0257:                        null, // approved
0258:                        null, // spam
0259:                        true, // reverse chrono order (not that it matters)
0260:                        0, // offset
0261:                        -1); // no limit
0262:                Iterator commentsIT = comments.iterator();
0263:                while (commentsIT.hasNext()) {
0264:                    this .strategy.remove((CommentData) commentsIT.next());
0265:                }
0266:
0267:                // remove tags aggregates
0268:                if (entry.getTags() != null) {
0269:                    for (Iterator it = entry.getTags().iterator(); it.hasNext();) {
0270:                        WeblogEntryTagData tag = (WeblogEntryTagData) it.next();
0271:                        updateTagCount(tag.getName(), entry.getWebsite(), -1);
0272:                    }
0273:                }
0274:
0275:                // remove entry
0276:                this .strategy.remove(entry);
0277:
0278:                // update weblog last modified date.  date updated by saveWebsite()
0279:                if (entry.isPublished()) {
0280:                    RollerFactory.getRoller().getUserManager().saveWebsite(
0281:                            entry.getWebsite());
0282:                }
0283:
0284:                // remove entry from cache mapping
0285:                this .entryAnchorToIdMap.remove(entry.getWebsite().getHandle()
0286:                        + ":" + entry.getAnchor());
0287:            }
0288:
0289:            public List getNextPrevEntries(WeblogEntryData current,
0290:                    String catName, String locale, int maxEntries, boolean next)
0291:                    throws RollerException {
0292:
0293:                Junction conjunction = Expression.conjunction();
0294:                conjunction.add(Expression.eq("website", current.getWebsite()));
0295:                conjunction.add(Expression.eq("status",
0296:                        WeblogEntryData.PUBLISHED));
0297:
0298:                if (next) {
0299:                    conjunction.add(Expression.gt("pubTime", current
0300:                            .getPubTime()));
0301:                } else {
0302:                    conjunction.add(Expression.lt("pubTime", current
0303:                            .getPubTime()));
0304:                }
0305:
0306:                if (catName != null && !catName.trim().equals("/")) {
0307:                    WeblogCategoryData category = getWeblogCategoryByPath(
0308:                            current.getWebsite(), null, catName);
0309:                    if (category != null) {
0310:                        conjunction.add(Expression.eq("category", category));
0311:                    } else {
0312:                        throw new RollerException("Cannot find category: "
0313:                                + catName);
0314:                    }
0315:                }
0316:
0317:                if (locale != null) {
0318:                    conjunction.add(Expression.ilike("locale", locale,
0319:                            MatchMode.START));
0320:                }
0321:
0322:                try {
0323:                    Session session = ((HibernatePersistenceStrategy) this .strategy)
0324:                            .getSession();
0325:                    Criteria criteria = session
0326:                            .createCriteria(WeblogEntryData.class);
0327:                    criteria.addOrder(next ? Order.asc("pubTime") : Order
0328:                            .desc("pubTime"));
0329:                    criteria.add(conjunction);
0330:                    criteria.setMaxResults(maxEntries);
0331:                    List results = criteria.list();
0332:                    return results;
0333:                } catch (HibernateException e) {
0334:                    throw new RollerException(e);
0335:                }
0336:            }
0337:
0338:            public WeblogCategoryData getRootWeblogCategory(WebsiteData website)
0339:                    throws RollerException {
0340:                if (website == null)
0341:                    throw new RollerException("website is null");
0342:
0343:                try {
0344:                    Session session = ((HibernatePersistenceStrategy) this .strategy)
0345:                            .getSession();
0346:                    Criteria criteria = session
0347:                            .createCriteria(WeblogCategoryAssoc.class);
0348:                    criteria.createAlias("category", "c");
0349:
0350:                    criteria.add(Expression.eq("c.website", website));
0351:                    criteria.add(Expression.isNull("ancestorCategory"));
0352:                    criteria.add(Expression.eq("relation",
0353:                            WeblogCategoryAssoc.PARENT));
0354:
0355:                    criteria.setMaxResults(1);
0356:
0357:                    List list = criteria.list();
0358:                    return ((WeblogCategoryAssoc) list.get(0)).getCategory();
0359:                } catch (HibernateException e) {
0360:                    throw new RollerException(e);
0361:                }
0362:            }
0363:
0364:            public List getWeblogCategories(WebsiteData website,
0365:                    boolean includeRoot) throws RollerException {
0366:                if (website == null)
0367:                    throw new RollerException("website is null");
0368:
0369:                if (includeRoot)
0370:                    return getWeblogCategories(website);
0371:
0372:                try {
0373:                    Session session = ((HibernatePersistenceStrategy) this .strategy)
0374:                            .getSession();
0375:                    Criteria criteria = session
0376:                            .createCriteria(WeblogCategoryAssoc.class);
0377:                    criteria.createAlias("category", "c");
0378:                    criteria.add(Expression.eq("c.website", website));
0379:                    criteria.add(Expression.isNotNull("ancestorCategory"));
0380:                    criteria.add(Expression.eq("relation", "PARENT"));
0381:                    Iterator assocs = criteria.list().iterator();
0382:                    List cats = new ArrayList();
0383:                    while (assocs.hasNext()) {
0384:                        WeblogCategoryAssoc assoc = (WeblogCategoryAssoc) assocs
0385:                                .next();
0386:                        cats.add(assoc.getCategory());
0387:                    }
0388:                    return cats;
0389:                } catch (HibernateException e) {
0390:                    throw new RollerException(e);
0391:                }
0392:            }
0393:
0394:            public List getWeblogCategories(WebsiteData website)
0395:                    throws RollerException {
0396:                if (website == null)
0397:                    throw new RollerException("website is null");
0398:
0399:                try {
0400:                    Session session = ((HibernatePersistenceStrategy) this .strategy)
0401:                            .getSession();
0402:                    Criteria criteria = session
0403:                            .createCriteria(WeblogCategoryData.class);
0404:                    criteria.add(Expression.eq("website", website));
0405:                    return criteria.list();
0406:                } catch (HibernateException e) {
0407:                    throw new RollerException(e);
0408:                }
0409:            }
0410:
0411:            public List getWeblogEntries(WebsiteData website, UserData user,
0412:                    Date startDate, Date endDate, String catName, List tags,
0413:                    String status, String sortby, String locale, int offset,
0414:                    int length) throws RollerException {
0415:
0416:                WeblogCategoryData cat = null;
0417:                if (StringUtils.isNotEmpty(catName) && website != null) {
0418:                    cat = getWeblogCategoryByPath(website, catName);
0419:                    if (cat == null)
0420:                        catName = null;
0421:                }
0422:                if (catName != null && catName.trim().equals("/")) {
0423:                    catName = null;
0424:                }
0425:
0426:                try {
0427:                    Session session = ((HibernatePersistenceStrategy) this .strategy)
0428:                            .getSession();
0429:
0430:                    ArrayList params = new ArrayList();
0431:                    StringBuffer queryString = new StringBuffer();
0432:                    queryString.append("from WeblogEntryData e where ");
0433:
0434:                    if (website != null) {
0435:                        queryString.append("website.id = ? ");
0436:                        params.add(website.getId());
0437:                    } else {
0438:                        queryString.append("website.enabled = ? ");
0439:                        params.add(Boolean.TRUE);
0440:                    }
0441:
0442:                    if (user != null) {
0443:                        queryString.append("and creator.id = ? ");
0444:                        params.add(user.getId());
0445:                    }
0446:
0447:                    if (startDate != null) {
0448:                        queryString.append("and pubTime >= ? ");
0449:                        params.add(startDate);
0450:                    }
0451:
0452:                    if (endDate != null) {
0453:                        queryString.append("and pubTime <= ? ");
0454:                        params.add(endDate);
0455:                    }
0456:
0457:                    if (cat != null && website != null) {
0458:                        queryString.append("and category.id = ? ");
0459:                        params.add(cat.getId());
0460:                    }
0461:
0462:                    if (tags != null && tags.size() > 0) {
0463:                        for (int i = 0; i < tags.size(); i++) {
0464:                            queryString.append(" and tags.name = ?");
0465:                            params.add(tags.get(i));
0466:                        }
0467:                    }
0468:
0469:                    if (status != null) {
0470:                        queryString.append("and status = ? ");
0471:                        params.add(status);
0472:                    }
0473:
0474:                    if (locale != null) {
0475:                        queryString.append("and locale like ? ");
0476:                        params.add(locale + '%');
0477:                    }
0478:
0479:                    if (sortby != null && sortby.equals("updateTime")) {
0480:                        queryString.append("order by updateTime desc ");
0481:                    } else {
0482:                        queryString.append("order by pubTime desc ");
0483:                    }
0484:
0485:                    Query query = session.createQuery(queryString.toString());
0486:
0487:                    // set params
0488:                    for (int i = 0; i < params.size(); i++) {
0489:                        query.setParameter(i, params.get(i));
0490:                    }
0491:
0492:                    if (offset != 0) {
0493:                        query.setFirstResult(offset);
0494:                    }
0495:                    if (length != -1) {
0496:                        query.setMaxResults(length);
0497:                    }
0498:                    return query.list();
0499:
0500:                } catch (HibernateException e) {
0501:                    log.error(e);
0502:                    throw new RollerException(e);
0503:                }
0504:            }
0505:
0506:            public List getWeblogEntriesPinnedToMain(Integer max)
0507:                    throws RollerException {
0508:                try {
0509:                    Session session = ((HibernatePersistenceStrategy) this .strategy)
0510:                            .getSession();
0511:                    Criteria criteria = session
0512:                            .createCriteria(WeblogEntryData.class);
0513:                    criteria.add(Expression.eq("pinnedToMain", Boolean.TRUE));
0514:                    criteria.addOrder(Order.desc("pubTime"));
0515:                    if (max != null) {
0516:                        criteria.setMaxResults(max.intValue());
0517:                    }
0518:                    return criteria.list();
0519:                } catch (HibernateException e) {
0520:                    log.error(e);
0521:                    throw new RollerException(e);
0522:                }
0523:            }
0524:
0525:            public WeblogEntryData getWeblogEntryByAnchor(WebsiteData website,
0526:                    String anchor) throws RollerException {
0527:
0528:                if (website == null)
0529:                    throw new RollerException("Website is null");
0530:
0531:                if (anchor == null)
0532:                    throw new RollerException("Anchor is null");
0533:
0534:                // mapping key is combo of weblog + anchor
0535:                String mappingKey = website.getHandle() + ":" + anchor;
0536:
0537:                // check cache first
0538:                // NOTE: if we ever allow changing anchors then this needs updating
0539:                if (this .entryAnchorToIdMap.containsKey(mappingKey)) {
0540:
0541:                    WeblogEntryData entry = this 
0542:                            .getWeblogEntry((String) this .entryAnchorToIdMap
0543:                                    .get(mappingKey));
0544:                    if (entry != null) {
0545:                        log.debug("entryAnchorToIdMap CACHE HIT - "
0546:                                + mappingKey);
0547:                        return entry;
0548:                    } else {
0549:                        // mapping hit with lookup miss?  mapping must be old, remove it
0550:                        this .entryAnchorToIdMap.remove(mappingKey);
0551:                    }
0552:                }
0553:
0554:                // cache failed, do lookup
0555:                try {
0556:                    Session session = ((HibernatePersistenceStrategy) this .strategy)
0557:                            .getSession();
0558:                    Criteria criteria = session
0559:                            .createCriteria(WeblogEntryData.class);
0560:                    criteria.add(Expression.conjunction().add(
0561:                            Expression.eq("website", website)).add(
0562:                            Expression.eq("anchor", anchor)));
0563:                    criteria.addOrder(Order.desc("pubTime"));
0564:                    criteria.setMaxResults(1);
0565:
0566:                    List list = criteria.list();
0567:
0568:                    WeblogEntryData entry = null;
0569:                    if (list.size() != 0) {
0570:                        entry = (WeblogEntryData) criteria.uniqueResult();
0571:                    }
0572:
0573:                    // add mapping to cache
0574:                    if (entry != null) {
0575:                        log.debug("entryAnchorToIdMap CACHE MISS - "
0576:                                + mappingKey);
0577:                        this .entryAnchorToIdMap.put(mappingKey, entry.getId());
0578:                    }
0579:
0580:                    return entry;
0581:                } catch (HibernateException e) {
0582:                    throw new RollerException(e);
0583:                }
0584:            }
0585:
0586:            public Date getWeblogLastPublishTime(WebsiteData website,
0587:                    String catName) throws RollerException {
0588:                WeblogCategoryData cat = null;
0589:
0590:                if (catName != null && website != null) {
0591:                    cat = getWeblogCategoryByPath(website, null, catName);
0592:                    if (cat == null)
0593:                        catName = null;
0594:                }
0595:                if (catName != null && catName.trim().equals("/")) {
0596:                    catName = null;
0597:                }
0598:
0599:                try {
0600:                    Session session = ((HibernatePersistenceStrategy) this .strategy)
0601:                            .getSession();
0602:                    Criteria criteria = session
0603:                            .createCriteria(WeblogEntryData.class);
0604:                    criteria.add(Expression.eq("status",
0605:                            WeblogEntryData.PUBLISHED));
0606:                    criteria.add(Expression.le("pubTime", new Date()));
0607:
0608:                    if (website != null) {
0609:                        criteria.add(Expression.eq("website", website));
0610:                    }
0611:
0612:                    if (cat != null) {
0613:                        criteria.add(Expression.eq("category", cat));
0614:                    }
0615:
0616:                    criteria.addOrder(Order.desc("pubTime"));
0617:                    criteria.setMaxResults(1);
0618:                    List list = criteria.list();
0619:                    if (list.size() > 0) {
0620:                        return ((WeblogEntryData) list.get(0)).getPubTime();
0621:                    } else {
0622:                        return null;
0623:                    }
0624:                } catch (HibernateException e) {
0625:                    throw new RollerException(e);
0626:                }
0627:            }
0628:
0629:            public List getWeblogEntries(WeblogCategoryData cat, boolean subcats)
0630:                    throws RollerException {
0631:                try {
0632:                    Session session = ((HibernatePersistenceStrategy) this .strategy)
0633:                            .getSession();
0634:                    List entries = new LinkedList();
0635:
0636:                    if (subcats) {
0637:                        // Get entries in subcategories
0638:                        Criteria assocsQuery = session
0639:                                .createCriteria(WeblogCategoryAssoc.class);
0640:                        assocsQuery.add(Expression.eq("ancestorCategory", cat));
0641:                        Iterator assocs = assocsQuery.list().iterator();
0642:                        while (assocs.hasNext()) {
0643:                            WeblogCategoryAssoc assoc = (WeblogCategoryAssoc) assocs
0644:                                    .next();
0645:                            Criteria entriesQuery = session
0646:                                    .createCriteria(WeblogEntryData.class);
0647:                            entriesQuery.add(Expression.eq("category", assoc
0648:                                    .getCategory()));
0649:                            Iterator entryIter = entriesQuery.list().iterator();
0650:                            while (entryIter.hasNext()) {
0651:                                WeblogEntryData entry = (WeblogEntryData) entryIter
0652:                                        .next();
0653:                                entries.add(entry);
0654:                            }
0655:                        }
0656:                    }
0657:
0658:                    // Get entries in category
0659:                    Criteria entriesQuery = session
0660:                            .createCriteria(WeblogEntryData.class);
0661:                    entriesQuery.add(Expression.eq("category", cat));
0662:                    Iterator entryIter = entriesQuery.list().iterator();
0663:                    while (entryIter.hasNext()) {
0664:                        WeblogEntryData entry = (WeblogEntryData) entryIter
0665:                                .next();
0666:                        entries.add(entry);
0667:                    }
0668:                    return entries;
0669:                } catch (HibernateException e) {
0670:                    throw new RollerException(e);
0671:                }
0672:            }
0673:
0674:            public String createAnchor(WeblogEntryData entry)
0675:                    throws RollerException {
0676:                try {
0677:                    // Check for uniqueness of anchor
0678:                    String base = entry.createAnchorBase();
0679:                    String name = base;
0680:                    int count = 0;
0681:
0682:                    while (true) {
0683:                        if (count > 0) {
0684:                            name = base + count;
0685:                        }
0686:
0687:                        Session session = ((HibernatePersistenceStrategy) this .strategy)
0688:                                .getSession();
0689:                        Criteria criteria = session
0690:                                .createCriteria(WeblogEntryData.class);
0691:                        criteria.add(Expression.eq("website", entry
0692:                                .getWebsite()));
0693:                        criteria.add(Expression.eq("anchor", name));
0694:
0695:                        List results = criteria.list();
0696:
0697:                        if (results.size() < 1) {
0698:                            break;
0699:                        } else {
0700:                            count++;
0701:                        }
0702:                    }
0703:                    return name;
0704:                } catch (HibernateException e) {
0705:                    throw new RollerException(e);
0706:                }
0707:            }
0708:
0709:            public boolean isDuplicateWeblogCategoryName(WeblogCategoryData cat)
0710:                    throws RollerException {
0711:                // ensure that no sibling categories share the same name
0712:                WeblogCategoryData parent = null == cat.getId() ? (WeblogCategoryData) cat
0713:                        .getNewParent()
0714:                        : cat.getParent();
0715:
0716:                if (null != parent) // don't worry about root
0717:                {
0718:                    List sameNames;
0719:                    try {
0720:                        Session session = ((HibernatePersistenceStrategy) this .strategy)
0721:                                .getSession();
0722:                        Criteria criteria = session
0723:                                .createCriteria(WeblogCategoryAssoc.class);
0724:                        criteria.createAlias("category", "c");
0725:                        criteria.add(Expression.ne("c.id", cat.getId()));
0726:                        criteria.add(Expression.eq("c.name", cat.getName()));
0727:                        criteria.add(Expression.eq("ancestorCategory", parent));
0728:                        criteria.add(Expression.eq("relation", Assoc.PARENT));
0729:                        sameNames = criteria.list();
0730:                    } catch (HibernateException e) {
0731:                        throw new RollerException(e);
0732:                    }
0733:                    if (sameNames.size() > 0) {
0734:                        return true;
0735:                    }
0736:                }
0737:                return false;
0738:            }
0739:
0740:            public boolean isWeblogCategoryInUse(WeblogCategoryData cat)
0741:                    throws RollerException {
0742:                try {
0743:                    Session session = ((HibernatePersistenceStrategy) this .strategy)
0744:                            .getSession();
0745:                    Criteria criteria = session
0746:                            .createCriteria(WeblogEntryData.class);
0747:                    criteria.add(Expression.eq("category", cat));
0748:                    criteria.setMaxResults(1);
0749:                    int entryCount = criteria.list().size();
0750:
0751:                    if (entryCount > 0) {
0752:                        return true;
0753:                    }
0754:
0755:                    Iterator cats = cat.getWeblogCategories().iterator();
0756:                    while (cats.hasNext()) {
0757:                        WeblogCategoryData childCat = (WeblogCategoryData) cats
0758:                                .next();
0759:                        if (childCat.isInUse()) {
0760:                            return true;
0761:                        }
0762:                    }
0763:
0764:                    if (cat.getWebsite().getBloggerCategory().equals(cat)) {
0765:                        return true;
0766:                    }
0767:
0768:                    if (cat.getWebsite().getDefaultCategory().equals(cat)) {
0769:                        return true;
0770:                    }
0771:
0772:                    return false;
0773:                } catch (HibernateException e) {
0774:                    throw new RollerException(e);
0775:                }
0776:            }
0777:
0778:            public boolean isDescendentOf(WeblogCategoryData child,
0779:                    WeblogCategoryData ancestor) throws RollerException {
0780:                boolean ret = false;
0781:                try {
0782:                    Session session = ((HibernatePersistenceStrategy) this .strategy)
0783:                            .getSession();
0784:                    Criteria criteria = session
0785:                            .createCriteria(WeblogCategoryAssoc.class);
0786:                    criteria.add(Expression.eq("category", child));
0787:                    criteria.add(Expression.eq("ancestorCategory", ancestor));
0788:                    ret = criteria.list().size() > 0;
0789:                } catch (HibernateException e) {
0790:                    throw new RollerException(e);
0791:                }
0792:                return ret;
0793:            }
0794:
0795:            public Assoc getWeblogCategoryParentAssoc(WeblogCategoryData cat)
0796:                    throws RollerException {
0797:                try {
0798:                    Session session = ((HibernatePersistenceStrategy) this .strategy)
0799:                            .getSession();
0800:                    Criteria criteria = session
0801:                            .createCriteria(WeblogCategoryAssoc.class);
0802:                    criteria.add(Expression.eq("category", cat));
0803:                    criteria.add(Expression.eq("relation", Assoc.PARENT));
0804:                    List parents = criteria.list();
0805:                    if (parents.size() > 1) {
0806:                        throw new RollerException("ERROR: more than one parent");
0807:                    } else if (parents.size() == 1) {
0808:                        return (Assoc) parents.get(0);
0809:                    } else {
0810:                        return null;
0811:                    }
0812:                } catch (HibernateException e) {
0813:                    throw new RollerException(e);
0814:                }
0815:            }
0816:
0817:            public List getWeblogCategoryChildAssocs(WeblogCategoryData cat)
0818:                    throws RollerException {
0819:                try {
0820:                    Session session = ((HibernatePersistenceStrategy) this .strategy)
0821:                            .getSession();
0822:                    Criteria criteria = session
0823:                            .createCriteria(WeblogCategoryAssoc.class);
0824:                    criteria.add(Expression.eq("ancestorCategory", cat));
0825:                    criteria.add(Expression.eq("relation", Assoc.PARENT));
0826:                    return criteria.list();
0827:                } catch (HibernateException e) {
0828:                    throw new RollerException(e);
0829:                }
0830:            }
0831:
0832:            public List getAllWeblogCategoryDecscendentAssocs(
0833:                    WeblogCategoryData cat) throws RollerException {
0834:                try {
0835:                    Session session = ((HibernatePersistenceStrategy) this .strategy)
0836:                            .getSession();
0837:                    Criteria criteria = session
0838:                            .createCriteria(WeblogCategoryAssoc.class);
0839:                    criteria.add(Expression.eq("ancestorCategory", cat));
0840:                    return criteria.list();
0841:                } catch (HibernateException e) {
0842:                    throw new RollerException(e);
0843:                }
0844:            }
0845:
0846:            public List getWeblogCategoryAncestorAssocs(WeblogCategoryData cat)
0847:                    throws RollerException {
0848:                try {
0849:                    Session session = ((HibernatePersistenceStrategy) this .strategy)
0850:                            .getSession();
0851:                    Criteria criteria = session
0852:                            .createCriteria(WeblogCategoryAssoc.class);
0853:                    criteria.add(Expression.eq("category", cat));
0854:                    return criteria.list();
0855:                } catch (HibernateException e) {
0856:                    throw new RollerException(e);
0857:                }
0858:            }
0859:
0860:            public List getComments(WebsiteData website, WeblogEntryData entry,
0861:                    String searchString, Date startDate, Date endDate,
0862:                    Boolean pending, Boolean approved, Boolean spam,
0863:                    boolean reverseChrono, int offset, int length)
0864:                    throws RollerException {
0865:
0866:                try {
0867:                    Session session = ((HibernatePersistenceStrategy) this .strategy)
0868:                            .getSession();
0869:                    Criteria criteria = session
0870:                            .createCriteria(CommentData.class);
0871:
0872:                    if (entry != null) {
0873:                        criteria.add(Expression.eq("weblogEntry", entry));
0874:                    } else if (website != null) {
0875:                        criteria.createAlias("weblogEntry", "e");
0876:                        criteria.add(Expression.eq("e.website", website));
0877:                    }
0878:
0879:                    if (searchString != null) {
0880:                        criteria.add(Expression.disjunction().add(
0881:                                Expression.like("url", searchString,
0882:                                        MatchMode.ANYWHERE)).add(
0883:                                Expression.like("content", searchString,
0884:                                        MatchMode.ANYWHERE)));
0885:                    }
0886:
0887:                    if (startDate != null) {
0888:                        criteria.add(Expression.ge("postTime", startDate));
0889:                    }
0890:
0891:                    if (endDate != null) {
0892:                        criteria.add(Expression.le("postTime", endDate));
0893:                    }
0894:
0895:                    if (pending != null) {
0896:                        criteria.add(Expression.eq("pending", pending));
0897:                    }
0898:
0899:                    if (approved != null) {
0900:                        criteria.add(Expression.eq("approved", approved));
0901:                    }
0902:
0903:                    if (spam != null) {
0904:                        criteria.add(Expression.eq("spam", spam));
0905:                    }
0906:
0907:                    if (length != -1) {
0908:                        criteria.setMaxResults(offset + length);
0909:                    }
0910:
0911:                    if (reverseChrono) {
0912:                        criteria.addOrder(Order.desc("postTime"));
0913:                    } else {
0914:                        criteria.addOrder(Order.asc("postTime"));
0915:                    }
0916:
0917:                    List comments = criteria.list();
0918:                    if (offset == 0 || comments.size() < offset) {
0919:                        return comments;
0920:                    }
0921:                    List range = new ArrayList();
0922:                    for (int i = offset; i < comments.size(); i++) {
0923:                        range.add(comments.get(i));
0924:                    }
0925:                    return range;
0926:
0927:                } catch (HibernateException e) {
0928:                    log.error(e);
0929:                    throw new RollerException(e);
0930:                }
0931:            }
0932:
0933:            public int removeMatchingComments(WebsiteData website,
0934:                    WeblogEntryData entry, String searchString, Date startDate,
0935:                    Date endDate, Boolean pending, Boolean approved,
0936:                    Boolean spam) throws RollerException {
0937:
0938:                try {
0939:                    List comments = getComments(website, entry, searchString,
0940:                            startDate, endDate, pending, approved, spam, true,
0941:                            0, -1);
0942:                    int count = 0;
0943:                    for (Iterator it = comments.iterator(); it.hasNext();) {
0944:                        CommentData comment = (CommentData) it.next();
0945:                        removeComment(comment);
0946:                        count++;
0947:                    }
0948:                    return count;
0949:
0950:                    /* I'd MUCH rather use a bulk delete, but MySQL says "General error,  
0951:                       message from server: "You can't specify target table 'roller_comment' 
0952:                       for update in FROM clause"
0953:
0954:                        Session session = ((HibernatePersistenceStrategy)this.strategy).getSession();
0955:                     
0956:                        // Can't use Criteria API to do bulk delete, so we build string     
0957:                        StringBuffer queryString = new StringBuffer();
0958:                        ArrayList params = new ArrayList();
0959:                     
0960:                        // Can't use join in a bulk delete query, but can use a sub-query      
0961:                        queryString.append(
0962:                            "delete CommentData cmt where cmt.id in "
0963:                          + "(select c.id from CommentData as c where ");
0964:                            
0965:                        if (entry != null) {
0966:                            queryString.append("c.weblogEntry.anchor = ? and c.weblogEntry.website.handle = ? ");
0967:                            params.add(entry.getAnchor());
0968:                            params.add(entry.getWebsite().getHandle());
0969:                        } else if (website != null) {
0970:                            queryString.append("c.weblogEntry.website.handle = ? ");
0971:                            params.add(website.getHandle());
0972:                        } 
0973:                        
0974:                        if (searchString != null) {
0975:                            if (!queryString.toString().trim().endsWith("where")) {
0976:                                queryString.append("and ");
0977:                            }
0978:                            queryString.append("(c.url like ? or c.content like ?) ");
0979:                            searchString = '%' + searchString + '%';
0980:                            params.add(searchString);
0981:                            params.add(searchString);
0982:                        }
0983:                        
0984:                        if (startDate != null) {
0985:                            if (!queryString.toString().trim().endsWith("where")) {
0986:                                queryString.append("and ");
0987:                            }
0988:                            queryString.append("c.postTime > ? ");
0989:                            params.add(startDate);
0990:                        }
0991:                        
0992:                        if (endDate != null) {
0993:                            if (!queryString.toString().trim().endsWith("where")) {
0994:                                queryString.append("and ");
0995:                            }
0996:                            queryString.append("c.postTime < ? ");
0997:                            params.add(endDate);
0998:                        }
0999:                        
1000:                        if (pending != null) {
1001:                            if (!queryString.toString().trim().endsWith("where")) {
1002:                                queryString.append("and ");
1003:                            }
1004:                            queryString.append("c.pending = ? ");
1005:                            params.add(pending);
1006:                        }
1007:                        
1008:                        if (approved != null) {
1009:                            if (!queryString.toString().trim().endsWith("where")) {
1010:                                queryString.append("and ");
1011:                            }
1012:                            queryString.append("c.approved = ? ");
1013:                            params.add(approved);
1014:                        }
1015:                        
1016:                        if (spam != null) {
1017:                            if (!queryString.toString().trim().endsWith("where")) {
1018:                                queryString.append("and ");
1019:                            }
1020:                            queryString.append("c.spam = ? ");
1021:                            params.add(spam);
1022:                        }
1023:                        queryString.append(")");
1024:                        
1025:                        Query query = session.createQuery(queryString.toString());
1026:                        for(int i = 0; i < params.size(); i++) {
1027:                          query.setParameter(i, params.get(i));
1028:                        }
1029:                        return query.executeUpdate(); 
1030:                     */
1031:
1032:                } catch (HibernateException e) {
1033:                    log.error(e);
1034:                    throw new RollerException(e);
1035:                }
1036:            }
1037:
1038:            public WeblogCategoryData getWeblogCategory(String id)
1039:                    throws RollerException {
1040:                return (WeblogCategoryData) this .strategy.load(id,
1041:                        WeblogCategoryData.class);
1042:            }
1043:
1044:            //--------------------------------------------- WeblogCategoryData Queries
1045:
1046:            public WeblogCategoryData getWeblogCategoryByPath(
1047:                    WebsiteData website, String categoryPath)
1048:                    throws RollerException {
1049:                return getWeblogCategoryByPath(website, null, categoryPath);
1050:            }
1051:
1052:            public String getPath(WeblogCategoryData category)
1053:                    throws RollerException {
1054:                if (null == category.getParent()) {
1055:                    return "/";
1056:                } else {
1057:                    String parentPath = getPath(category.getParent());
1058:                    parentPath = "/".equals(parentPath) ? "" : parentPath;
1059:                    return parentPath + "/" + category.getName();
1060:                }
1061:            }
1062:
1063:            public WeblogCategoryData getWeblogCategoryByPath(
1064:                    WebsiteData website, WeblogCategoryData category,
1065:                    String path) throws RollerException {
1066:                final Iterator cats;
1067:                final String[] pathArray = Utilities.stringToStringArray(path,
1068:                        "/");
1069:
1070:                if (category == null
1071:                        && (null == path || "".equals(path.trim()))) {
1072:                    throw new RollerException("Bad arguments.");
1073:                }
1074:
1075:                if (path.trim().equals("/")) {
1076:                    return getRootWeblogCategory(website);
1077:                } else if (category == null || path.trim().startsWith("/")) {
1078:                    cats = getRootWeblogCategory(website).getWeblogCategories()
1079:                            .iterator();
1080:                } else {
1081:                    cats = category.getWeblogCategories().iterator();
1082:                }
1083:
1084:                while (cats.hasNext()) {
1085:                    WeblogCategoryData possibleMatch = (WeblogCategoryData) cats
1086:                            .next();
1087:                    if (possibleMatch.getName().equals(pathArray[0])) {
1088:                        if (pathArray.length == 1) {
1089:                            return possibleMatch;
1090:                        } else {
1091:                            String[] subpath = new String[pathArray.length - 1];
1092:                            System.arraycopy(pathArray, 1, subpath, 0,
1093:                                    subpath.length);
1094:
1095:                            String pathString = Utilities.stringArrayToString(
1096:                                    subpath, "/");
1097:                            return getWeblogCategoryByPath(website,
1098:                                    possibleMatch, pathString);
1099:                        }
1100:                    }
1101:                }
1102:
1103:                // The category did not match and neither did any sub-categories
1104:                return null;
1105:            }
1106:
1107:            public CommentData getComment(String id) throws RollerException {
1108:                return (CommentData) this .strategy.load(id, CommentData.class);
1109:            }
1110:
1111:            public WeblogEntryData getWeblogEntry(String id)
1112:                    throws RollerException {
1113:                return (WeblogEntryData) this .strategy.load(id,
1114:                        WeblogEntryData.class);
1115:            }
1116:
1117:            /**
1118:             * Gets the Date of the latest Entry publish time, before the end of today,
1119:             * for all WeblogEntries
1120:             */
1121:            public Date getWeblogLastPublishTime(WebsiteData website)
1122:                    throws RollerException {
1123:                return getWeblogLastPublishTime(website, null);
1124:            }
1125:
1126:            public Map getWeblogEntryObjectMap(WebsiteData website,
1127:                    Date startDate, Date endDate, String catName, List tags,
1128:                    String status, String locale, int offset, int length)
1129:                    throws RollerException {
1130:                return getWeblogEntryMap(website, startDate, endDate, catName,
1131:                        tags, status, false, locale, offset, length);
1132:            }
1133:
1134:            public Map getWeblogEntryStringMap(WebsiteData website,
1135:                    Date startDate, Date endDate, String catName, List tags,
1136:                    String status, String locale, int offset, int length)
1137:                    throws RollerException {
1138:                return getWeblogEntryMap(website, startDate, endDate, catName,
1139:                        tags, status, true, locale, offset, length);
1140:            }
1141:
1142:            private Map getWeblogEntryMap(WebsiteData website, Date startDate,
1143:                    Date endDate, String catName, List tags, String status,
1144:                    boolean stringsOnly, String locale, int offset, int length)
1145:                    throws RollerException {
1146:
1147:                TreeMap map = new TreeMap(reverseComparator);
1148:
1149:                List entries = getWeblogEntries(website, null, startDate,
1150:                        endDate, catName, tags, status, null, locale, offset,
1151:                        length);
1152:
1153:                Calendar cal = Calendar.getInstance();
1154:                if (website != null) {
1155:                    cal.setTimeZone(website.getTimeZoneInstance());
1156:                }
1157:
1158:                SimpleDateFormat formatter = DateUtil.get8charDateFormat();
1159:                for (Iterator wbItr = entries.iterator(); wbItr.hasNext();) {
1160:                    WeblogEntryData entry = (WeblogEntryData) wbItr.next();
1161:                    Date sDate = DateUtil.getNoonOfDay(entry.getPubTime(), cal);
1162:                    if (stringsOnly) {
1163:                        if (map.get(sDate) == null)
1164:                            map.put(sDate, formatter.format(sDate));
1165:                    } else {
1166:                        List dayEntries = (List) map.get(sDate);
1167:                        if (dayEntries == null) {
1168:                            dayEntries = new ArrayList();
1169:                            map.put(sDate, dayEntries);
1170:                        }
1171:                        dayEntries.add(entry);
1172:                    }
1173:                }
1174:                return map;
1175:            }
1176:
1177:            public List getMostCommentedWeblogEntries(WebsiteData website,
1178:                    Date startDate, Date endDate, int offset, int length)
1179:                    throws RollerException {
1180:                // TODO: ATLAS getMostCommentedWeblogEntries DONE
1181:                String msg = "Getting most commented weblog entres";
1182:                if (endDate == null)
1183:                    endDate = new Date();
1184:                try {
1185:                    Session session = ((HibernatePersistenceStrategy) strategy)
1186:                            .getSession();
1187:                    Query query = null;
1188:                    if (website != null) {
1189:                        StringBuffer sb = new StringBuffer();
1190:                        sb
1191:                                .append("select count(distinct c), c.weblogEntry.id, c.weblogEntry.anchor, c.weblogEntry.title from CommentData c ");
1192:                        sb
1193:                                .append("where c.weblogEntry.website=:website and c.weblogEntry.pubTime < :endDate ");
1194:                        if (startDate != null) {
1195:                            sb
1196:                                    .append("and c.weblogEntry.pubTime > :startDate ");
1197:                        }
1198:                        sb
1199:                                .append("group by c.weblogEntry.id, c.weblogEntry.anchor, c.weblogEntry.title ");
1200:                        sb.append("order by col_0_0_ desc");
1201:                        query = session.createQuery(sb.toString());
1202:                        query.setParameter("website", website);
1203:                        query.setParameter("endDate", endDate);
1204:                        if (startDate != null) {
1205:                            query.setParameter("startDate", startDate);
1206:                        }
1207:                    } else {
1208:                        StringBuffer sb = new StringBuffer();
1209:                        sb
1210:                                .append("select count(distinct c), c.weblogEntry.id, c.weblogEntry.anchor, c.weblogEntry.title ");
1211:                        sb
1212:                                .append("from CommentData c group by c.weblogEntry.id, c.weblogEntry.anchor, c.weblogEntry.title ");
1213:                        sb.append("where c.weblogEntry.pubTime < :endDate ");
1214:                        if (startDate != null) {
1215:                            sb
1216:                                    .append("and c.weblogEntry.pubTime > :startDate ");
1217:                        }
1218:                        sb.append("order by col_0_0_ desc");
1219:                        query = session.createQuery(sb.toString());
1220:                        if (startDate != null) {
1221:                            query.setParameter("startDate", startDate);
1222:                        }
1223:                    }
1224:                    if (offset != 0) {
1225:                        query.setFirstResult(offset);
1226:                    }
1227:                    if (length != -1) {
1228:                        query.setMaxResults(length);
1229:                    }
1230:                    List results = new ArrayList();
1231:                    for (Iterator iter = query.list().iterator(); iter
1232:                            .hasNext();) {
1233:                        Object[] row = (Object[]) iter.next();
1234:                        results.add(new StatCount((String) row[1],
1235:                                (String) row[2], (String) row[3],
1236:                                "statCount.weblogEntryCommentCountType",
1237:                                ((Number) row[0]).longValue()));
1238:                    }
1239:                    return results;
1240:                } catch (Throwable pe) {
1241:                    log.error(msg, pe);
1242:                    throw new RollerException(msg, pe);
1243:                }
1244:            }
1245:
1246:            public List getNextEntries(WeblogEntryData current, String catName,
1247:                    String locale, int maxEntries) throws RollerException {
1248:
1249:                return getNextPrevEntries(current, catName, locale, maxEntries,
1250:                        true);
1251:            }
1252:
1253:            public List getPreviousEntries(WeblogEntryData current,
1254:                    String catName, String locale, int maxEntries)
1255:                    throws RollerException {
1256:
1257:                return getNextPrevEntries(current, catName, locale, maxEntries,
1258:                        false);
1259:            }
1260:
1261:            public WeblogEntryData getNextEntry(WeblogEntryData current,
1262:                    String catName, String locale) throws RollerException {
1263:
1264:                WeblogEntryData entry = null;
1265:                List entryList = getNextEntries(current, catName, locale, 1);
1266:                if (entryList != null && entryList.size() > 0) {
1267:                    entry = (WeblogEntryData) entryList.get(0);
1268:                }
1269:                return entry;
1270:            }
1271:
1272:            public WeblogEntryData getPreviousEntry(WeblogEntryData current,
1273:                    String catName, String locale) throws RollerException {
1274:
1275:                WeblogEntryData entry = null;
1276:                List entryList = getPreviousEntries(current, catName, locale, 1);
1277:                if (entryList != null && entryList.size() > 0) {
1278:                    entry = (WeblogEntryData) entryList.get(0);
1279:                }
1280:                return entry;
1281:            }
1282:
1283:            public void release() {
1284:            }
1285:
1286:            /**
1287:             * Apply comment defaults (defaultAllowComments and defaultCommentDays) to
1288:             * all existing entries in a website using a single HQL query.
1289:             * @param website Website where comment defaults are from/to be applied.
1290:             */
1291:            public void applyCommentDefaultsToEntries(WebsiteData website)
1292:                    throws RollerException {
1293:                if (log.isDebugEnabled()) {
1294:                    log.debug("applyCommentDefaults");
1295:                }
1296:                try {
1297:                    Session session = strategy.getSession();
1298:                    String updateString = "update WeblogEntryData set "
1299:                            + "allowComments=:allowed, commentDays=:days, "
1300:                            + "pubTime=pubTime, updateTime=updateTime " // ensure timestamps are NOT reset
1301:                            + "where website=:site";
1302:                    Query update = session.createQuery(updateString);
1303:                    update.setParameter("allowed", website
1304:                            .getDefaultAllowComments());
1305:                    update.setParameter("days", new Integer(website
1306:                            .getDefaultCommentDays()));
1307:                    update.setParameter("site", website);
1308:                    update.executeUpdate();
1309:                } catch (Exception e) {
1310:                    log.error("EXCEPTION applying comment defaults", e);
1311:                }
1312:            }
1313:
1314:            /* (non-Javadoc)
1315:             * @see org.apache.roller.model.WeblogManager#getPopularTags(org.apache.roller.pojos.WebsiteData, java.util.Date, int)
1316:             */
1317:            public List getPopularTags(WebsiteData website, Date startDate,
1318:                    int limit) throws RollerException {
1319:                try {
1320:                    Session session = ((HibernatePersistenceStrategy) strategy)
1321:                            .getSession();
1322:
1323:                    ArrayList params = new ArrayList();
1324:                    StringBuffer queryString = new StringBuffer();
1325:                    queryString.append("select name, sum(total) ");
1326:                    queryString
1327:                            .append("from WeblogEntryTagAggregateData where ");
1328:                    if (website != null) {
1329:                        queryString.append("weblog.id = ? ");
1330:                        params.add(website.getId());
1331:                    } else {
1332:                        queryString.append("weblog = NULL ");
1333:                    }
1334:                    if (startDate != null) {
1335:                        queryString.append("and lastUsed >= ? ");
1336:                        params.add(startDate);
1337:                    }
1338:
1339:                    queryString
1340:                            .append("group by name, total order by total desc");
1341:
1342:                    Query query = session.createQuery(queryString.toString());
1343:                    if (limit > 0)
1344:                        query.setMaxResults(limit);
1345:
1346:                    // set params
1347:                    for (int i = 0; i < params.size(); i++) {
1348:                        query.setParameter(i, params.get(i));
1349:                    }
1350:
1351:                    double min = Integer.MAX_VALUE;
1352:                    double max = Integer.MIN_VALUE;
1353:
1354:                    List results = new ArrayList(limit);
1355:
1356:                    for (Iterator iter = query.list().iterator(); iter
1357:                            .hasNext();) {
1358:                        Object[] row = (Object[]) iter.next();
1359:                        TagStat t = new TagStat();
1360:                        t.setName((String) row[0]);
1361:                        t.setCount(((Number) row[1]).intValue());
1362:
1363:                        min = Math.min(min, t.getCount());
1364:                        max = Math.max(max, t.getCount());
1365:                        results.add(t);
1366:                    }
1367:
1368:                    min = Math.log(1 + min);
1369:                    max = Math.log(1 + max);
1370:
1371:                    double range = Math.max(.01, max - min) * 1.0001;
1372:
1373:                    for (Iterator iter = results.iterator(); iter.hasNext();) {
1374:                        TagStat t = (TagStat) iter.next();
1375:                        t.setIntensity((int) (1 + Math.floor(5
1376:                                * (Math.log(1 + t.getCount()) - min) / range)));
1377:                    }
1378:
1379:                    // sort results by name, because query had to sort by total
1380:                    Collections.sort(results, tagStatComparator);
1381:
1382:                    return results;
1383:
1384:                } catch (HibernateException e) {
1385:                    throw new RollerException(e);
1386:                }
1387:            }
1388:
1389:            /*
1390:             * (non-Javadoc)
1391:             * 
1392:             * @see org.apache.roller.model.WeblogManager#getTags(org.apache.roller.pojos.WebsiteData,
1393:             *      java.lang.String, java.lang.String, int)
1394:             */
1395:            public List getTags(WebsiteData website, String sortBy,
1396:                    String startsWith, int limit) throws RollerException {
1397:                try {
1398:                    List results = new ArrayList();
1399:
1400:                    Session session = ((HibernatePersistenceStrategy) strategy)
1401:                            .getSession();
1402:
1403:                    if (sortBy != null && sortBy.equals("count")) {
1404:                        sortBy = "total desc";
1405:                    } else {
1406:                        sortBy = "name";
1407:                    }
1408:
1409:                    StringBuffer queryString = new StringBuffer();
1410:                    queryString.append("select name, sum(total) ");
1411:                    queryString
1412:                            .append("from WeblogEntryTagAggregateData where ");
1413:                    if (website != null)
1414:                        queryString.append("weblog.id = '" + website.getId()
1415:                                + "' ");
1416:                    else
1417:                        queryString.append("weblog = NULL ");
1418:                    if (startsWith != null && startsWith.length() > 0)
1419:                        queryString.append("and name like '" + startsWith
1420:                                + "%' ");
1421:
1422:                    queryString.append("group by name, total order by "
1423:                            + sortBy);
1424:
1425:                    Query query = session.createQuery(queryString.toString());
1426:                    if (limit > 0)
1427:                        query.setMaxResults(limit);
1428:
1429:                    for (Iterator iter = query.list().iterator(); iter
1430:                            .hasNext();) {
1431:                        Object[] row = (Object[]) iter.next();
1432:                        TagStat ce = new TagStat();
1433:                        ce.setName((String) row[0]);
1434:                        ce.setCount(((Number) row[1]).intValue());
1435:                        results.add(ce);
1436:                    }
1437:
1438:                    return results;
1439:
1440:                } catch (HibernateException e) {
1441:                    throw new RollerException(e);
1442:                }
1443:
1444:            }
1445:
1446:            /**
1447:             * Remember, this checks that the exact tag intersection specified by the
1448:             * list of tags exists either site-wide or for a given weblog.  So if the
1449:             * list of tags is "foo", "bar" and we only find "foo" then that's a
1450:             * miss and we return false.
1451:             */
1452:            public boolean getTagComboExists(List tags, WebsiteData weblog)
1453:                    throws RollerException {
1454:
1455:                boolean comboExists = false;
1456:
1457:                if (tags == null) {
1458:                    return false;
1459:                }
1460:
1461:                try {
1462:                    Session session = ((HibernatePersistenceStrategy) strategy)
1463:                            .getSession();
1464:
1465:                    StringBuffer queryString = new StringBuffer();
1466:                    queryString.append("select distinct name ");
1467:                    queryString.append("from WeblogEntryTagAggregateData ");
1468:                    queryString.append("where name in ( :tags ) ");
1469:
1470:                    // are we checking a specific weblog, or site-wide?
1471:                    if (weblog != null)
1472:                        queryString.append("and weblog.id = '" + weblog.getId()
1473:                                + "' ");
1474:                    else
1475:                        queryString.append("and weblog is null ");
1476:
1477:                    Query query = session.createQuery(queryString.toString());
1478:                    query.setParameterList("tags", tags);
1479:
1480:                    List results = query.list();
1481:                    comboExists = (results != null && results.size() == tags
1482:                            .size());
1483:
1484:                } catch (HibernateException ex) {
1485:                    throw new RollerException(ex);
1486:                }
1487:
1488:                return comboExists;
1489:            }
1490:
1491:            public void updateTagCount(String name, WebsiteData website,
1492:                    int amount) throws RollerException {
1493:
1494:                Session session = ((HibernatePersistenceStrategy) strategy)
1495:                        .getSession();
1496:
1497:                if (amount == 0) {
1498:                    throw new RollerException(
1499:                            "Tag increment amount cannot be zero.");
1500:                }
1501:
1502:                if (website == null) {
1503:                    throw new RollerException("Website cannot be NULL.");
1504:                }
1505:
1506:                Junction conjunction = Expression.conjunction();
1507:                conjunction.add(Expression.eq("name", name));
1508:                conjunction.add(Expression.eq("weblog", website));
1509:
1510:                // The reason why add order lastUsed desc is to make sure we keep picking the most recent
1511:                // one in the case where we have multiple rows (clustered environment)
1512:                // eventually that second entry will have a very low total (most likely 1) and
1513:                // won't matter
1514:
1515:                Criteria criteria = session.createCriteria(
1516:                        WeblogEntryTagAggregateData.class).add(conjunction)
1517:                        .addOrder(Order.desc("lastUsed")).setMaxResults(1);
1518:
1519:                WeblogEntryTagAggregateData weblogTagData = (WeblogEntryTagAggregateData) criteria
1520:                        .uniqueResult();
1521:
1522:                conjunction = Expression.conjunction();
1523:                conjunction.add(Restrictions.eq("name", name));
1524:                conjunction.add(Restrictions.isNull("weblog"));
1525:
1526:                criteria = session.createCriteria(
1527:                        WeblogEntryTagAggregateData.class).add(conjunction)
1528:                        .addOrder(Order.desc("lastUsed")).setMaxResults(1);
1529:
1530:                WeblogEntryTagAggregateData siteTagData = (WeblogEntryTagAggregateData) criteria
1531:                        .uniqueResult();
1532:
1533:                Timestamp lastUsed = new Timestamp((new Date()).getTime());
1534:
1535:                // create it only if we are going to need it.
1536:                if (weblogTagData == null && amount > 0) {
1537:                    weblogTagData = new WeblogEntryTagAggregateData(null,
1538:                            website, name, amount);
1539:                    weblogTagData.setLastUsed(lastUsed);
1540:                    session.save(weblogTagData);
1541:                } else if (weblogTagData != null) {
1542:                    session
1543:                            .createQuery(
1544:                                    "update WeblogEntryTagAggregateData set total = total + ?, lastUsed = current_timestamp() where name = ? and weblog = ?")
1545:                            .setInteger(0, amount).setString(1,
1546:                                    weblogTagData.getName()).setParameter(2,
1547:                                    website).executeUpdate();
1548:                }
1549:
1550:                // create it only if we are going to need it.        
1551:                if (siteTagData == null && amount > 0) {
1552:                    siteTagData = new WeblogEntryTagAggregateData(null, null,
1553:                            name, amount);
1554:                    siteTagData.setLastUsed(lastUsed);
1555:                    session.save(siteTagData);
1556:                } else if (siteTagData != null) {
1557:                    session
1558:                            .createQuery(
1559:                                    "update WeblogEntryTagAggregateData set total = total + ?, lastUsed = current_timestamp() where name = ? and weblog is null")
1560:                            .setInteger(0, amount).setString(1,
1561:                                    siteTagData.getName()).executeUpdate();
1562:                }
1563:
1564:                // delete all bad counts
1565:                session
1566:                        .createQuery(
1567:                                "delete from WeblogEntryTagAggregateData where total <= 0")
1568:                        .executeUpdate();
1569:            }
1570:
1571:            public HitCountData getHitCount(String id) throws RollerException {
1572:
1573:                // do lookup
1574:                try {
1575:                    Session session = ((HibernatePersistenceStrategy) this .strategy)
1576:                            .getSession();
1577:                    Criteria criteria = session
1578:                            .createCriteria(HitCountData.class);
1579:
1580:                    criteria.add(Expression.eq("id", id));
1581:                    HitCountData hitCount = (HitCountData) criteria
1582:                            .uniqueResult();
1583:
1584:                    return hitCount;
1585:                } catch (HibernateException e) {
1586:                    throw new RollerException(e);
1587:                }
1588:            }
1589:
1590:            public HitCountData getHitCountByWeblog(WebsiteData weblog)
1591:                    throws RollerException {
1592:
1593:                // do lookup
1594:                try {
1595:                    Session session = ((HibernatePersistenceStrategy) this .strategy)
1596:                            .getSession();
1597:                    Criteria criteria = session
1598:                            .createCriteria(HitCountData.class);
1599:
1600:                    criteria.add(Expression.eq("weblog", weblog));
1601:                    HitCountData hitCount = (HitCountData) criteria
1602:                            .uniqueResult();
1603:
1604:                    return hitCount;
1605:                } catch (HibernateException e) {
1606:                    throw new RollerException(e);
1607:                }
1608:            }
1609:
1610:            public List getHotWeblogs(int sinceDays, int offset, int length)
1611:                    throws RollerException {
1612:
1613:                // figure out start date
1614:                Calendar cal = Calendar.getInstance();
1615:                cal.setTime(new Date());
1616:                cal.add(Calendar.DATE, -1 * sinceDays);
1617:                Date startDate = cal.getTime();
1618:
1619:                try {
1620:                    Session session = ((HibernatePersistenceStrategy) strategy)
1621:                            .getSession();
1622:                    Query query = session.createQuery("from HitCountData hcd "
1623:                            + "where hcd.weblog.enabled=true "
1624:                            + "and hcd.weblog.active=true "
1625:                            + "and hcd.weblog.lastModified > :startDate "
1626:                            + "and hcd.dailyHits > 0 "
1627:                            + "order by hcd.dailyHits desc");
1628:                    query.setParameter("startDate", startDate);
1629:
1630:                    if (offset != 0) {
1631:                        query.setFirstResult(offset);
1632:                    }
1633:                    if (length != -1) {
1634:                        query.setMaxResults(length);
1635:                    }
1636:
1637:                    return query.list();
1638:
1639:                } catch (Throwable pe) {
1640:                    throw new RollerException(pe);
1641:                }
1642:            }
1643:
1644:            public void saveHitCount(HitCountData hitCount)
1645:                    throws RollerException {
1646:                this .strategy.store(hitCount);
1647:            }
1648:
1649:            public void removeHitCount(HitCountData hitCount)
1650:                    throws RollerException {
1651:                this .strategy.remove(hitCount);
1652:            }
1653:
1654:            public void incrementHitCount(WebsiteData weblog, int amount)
1655:                    throws RollerException {
1656:
1657:                Session session = ((HibernatePersistenceStrategy) strategy)
1658:                        .getSession();
1659:
1660:                if (amount == 0) {
1661:                    throw new RollerException(
1662:                            "Tag increment amount cannot be zero.");
1663:                }
1664:
1665:                if (weblog == null) {
1666:                    throw new RollerException("Website cannot be NULL.");
1667:                }
1668:
1669:                Criteria criteria = session.createCriteria(HitCountData.class);
1670:                criteria.add(Expression.eq("weblog", weblog));
1671:                criteria.setMaxResults(1);
1672:
1673:                HitCountData hitCount = (HitCountData) criteria.uniqueResult();
1674:
1675:                // create it if it doesn't exist
1676:                if (hitCount == null && amount > 0) {
1677:                    hitCount = new HitCountData();
1678:                    hitCount.setWeblog(weblog);
1679:                    hitCount.setDailyHits(amount);
1680:                    strategy.store(hitCount);
1681:                } else if (hitCount != null) {
1682:                    hitCount.setDailyHits(hitCount.getDailyHits() + amount);
1683:                    strategy.store(hitCount);
1684:                }
1685:            }
1686:
1687:            public void resetAllHitCounts() throws RollerException {
1688:
1689:                try {
1690:                    Session session = ((HibernatePersistenceStrategy) strategy)
1691:                            .getSession();
1692:                    session
1693:                            .createQuery(
1694:                                    "update HitCountData set dailyHits = 0")
1695:                            .executeUpdate();
1696:                } catch (Exception e) {
1697:                    throw new RollerException(e);
1698:                }
1699:            }
1700:
1701:            public void resetHitCount(WebsiteData weblog)
1702:                    throws RollerException {
1703:
1704:                try {
1705:                    Session session = ((HibernatePersistenceStrategy) strategy)
1706:                            .getSession();
1707:                    String query = "update HitCountData set dailyHits = 0 where weblog = ?";
1708:                    session.createQuery(query).setParameter(0, weblog)
1709:                            .executeUpdate();
1710:                } catch (Exception e) {
1711:                    throw new RollerException(e);
1712:                }
1713:            }
1714:
1715:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.