KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > roller > business > hibernate > HibernateRefererManagerImpl


1 /*
2  * Created on Feb 23, 2003
3  */

4 package org.roller.business.hibernate;
5
6 import java.sql.Connection JavaDoc;
7 import java.sql.PreparedStatement JavaDoc;
8 import java.sql.ResultSet JavaDoc;
9 import java.util.ArrayList JavaDoc;
10 import java.util.Date JavaDoc;
11 import java.util.Iterator JavaDoc;
12 import java.util.List JavaDoc;
13
14 import net.sf.hibernate.Criteria;
15 import net.sf.hibernate.Hibernate;
16 import net.sf.hibernate.HibernateException;
17 import net.sf.hibernate.Session;
18 import net.sf.hibernate.expression.Expression;
19 import net.sf.hibernate.expression.Junction;
20 import net.sf.hibernate.expression.Order;
21 import net.sf.hibernate.type.Type;
22
23 import org.apache.commons.lang.StringUtils;
24 import org.apache.commons.logging.Log;
25 import org.apache.commons.logging.LogFactory;
26 import org.roller.RollerException;
27 import org.roller.business.PersistenceStrategy;
28 import org.roller.business.RefererManagerImpl;
29 import org.roller.config.RollerRuntimeConfig;
30 import org.roller.model.RefererManager;
31 import org.roller.pojos.RefererData;
32 import org.roller.pojos.WebsiteData;
33 import org.roller.pojos.WebsiteDisplayData;
34
35
36 /**
37  * Hibernate queries.
38  * @author David M Johnson
39  */

40 public class HibernateRefererManagerImpl extends RefererManagerImpl
41     implements RefererManager
42 {
43     static final long serialVersionUID = -4966091850482256435L;
44     
45     private static Log mLogger =
46          LogFactory.getFactory().getInstance(HibernateRefererManagerImpl.class);
47
48     //-------------------------------------------------- Startup and Shutdown
49
public HibernateRefererManagerImpl(PersistenceStrategy support)
50         throws RollerException
51     {
52         super();
53         mStrategy = (HibernateStrategy)support;
54                 mLogger.debug("Instantiating Referer Manager");
55     }
56
57     //-----------------------------------------------------------------------
58
/**
59      * Apply ignoreWord/spam filters to all referers in system.
60      */

61     public void applyRefererFilters() throws RollerException
62     {
63         try
64         {
65             Session session = ((HibernateStrategy)mStrategy).getSession();
66             Criteria criteria = session.createCriteria(RefererData.class);
67             
68             String JavaDoc spamwords = RollerRuntimeConfig.getProperty("spam.referers.ignorewords");
69             
70             String JavaDoc[] ignoreWords = StringUtils.split(
71                 StringUtils.deleteWhitespace(spamwords),",");
72             Junction or = Expression.disjunction();
73             for (int i=0; i<ignoreWords.length; i++)
74             {
75                 String JavaDoc ignoreWord = ignoreWords[i].trim();
76                 or.add(Expression.ilike("refererUrl","%"+ignoreWord+"%"));
77             }
78             criteria.add(Expression.conjunction()
79                 .add(Expression.isNull("excerpt"))
80                 .add(or)
81             );
82             
83             Iterator JavaDoc referers = criteria.list().iterator();
84             while (referers.hasNext())
85             {
86                 removeReferer( ((RefererData)referers.next()).getId() );
87             }
88         }
89         catch (HibernateException e)
90         {
91             throw new RollerException(e);
92         }
93     }
94
95     //-----------------------------------------------------------------------
96
/**
97      * Apply ignoreWord/spam filters to all referers in website.
98      */

99     public void applyRefererFilters(WebsiteData website) throws RollerException
100     {
101         if (null == website) throw new RollerException("website is null");
102         if (null == website.getIgnoreWords()) return;
103
104         try
105         {
106             Session session = ((HibernateStrategy)mStrategy).getSession();
107             Criteria criteria = session.createCriteria(RefererData.class);
108             
109             String JavaDoc[] ignoreWords = StringUtils.split(
110                 StringUtils.deleteWhitespace(website.getIgnoreWords()),",");
111             if (ignoreWords.length == 0) return;
112             
113             Junction or = Expression.disjunction();
114             for (int i=0; i<ignoreWords.length; i++)
115             {
116                 String JavaDoc ignoreWord = ignoreWords[i].trim();
117                 or.add(Expression.ilike("refererUrl","%"+ignoreWord+"%"));
118             }
119             criteria.add(Expression.conjunction()
120                 .add(Expression.isNull("excerpt"))
121                 .add(Expression.eq("website",website))
122                 .add(or)
123             );
124             
125             Iterator JavaDoc referers = criteria.list().iterator();
126             while (referers.hasNext())
127             {
128                 removeReferer( ((RefererData)referers.next()).getId() );
129             }
130         }
131         catch (HibernateException e)
132         {
133             throw new RollerException(e);
134         }
135     }
136
137     //-----------------------------------------------------------------------
138

139     /**
140      * Use Hibernate directly because Roller's Query API does too much allocation.
141      */

142     protected List JavaDoc getExistingReferers(WebsiteData website, String JavaDoc dateString,
143                     String JavaDoc permalink) throws RollerException
144     {
145         Session session = ((HibernateStrategy)mStrategy).getSession();
146         Criteria criteria = session.createCriteria(RefererData.class);
147         criteria.add(Expression.conjunction()
148                         .add(Expression.eq("website",website))
149                         .add(Expression.eq("dateString",dateString))
150                         .add(Expression.eq("refererPermalink",permalink)));
151         try
152         {
153             return criteria.list();
154         }
155         catch (HibernateException e)
156         {
157             throw new RollerException(e);
158         }
159     }
160     
161     //-----------------------------------------------------------------------
162

163     /**
164      * Use Hibernate directly because Roller's Query API does too much allocation.
165      */

166     protected List JavaDoc getMatchingReferers(WebsiteData website, String JavaDoc requestUrl,
167                     String JavaDoc refererUrl) throws RollerException
168     {
169         Session session = ((HibernateStrategy)mStrategy).getSession();
170         Criteria criteria = session.createCriteria(RefererData.class);
171         criteria.add(Expression.conjunction()
172                         .add(Expression.eq("website",website))
173                         .add(Expression.eq("requestUrl",requestUrl))
174                         .add(Expression.eq("refererUrl",refererUrl)));
175         try
176         {
177             return criteria.list();
178         }
179         catch (HibernateException e)
180         {
181             throw new RollerException(e);
182         }
183     }
184     
185     //-----------------------------------------------------------------------
186

187     /**
188      * Use raw SQL because Hibernate can't handle sorting by sum.
189      */

190     public List JavaDoc getDaysPopularWebsites(int max) throws RollerException
191     {
192         // TODO Hibernate version of getDaysPopularWebsites
193
// TODO Move to full use of mSupport
194
String JavaDoc msg = "Getting popular websites";
195         Session ses = null; // the session will eventually be release by RequestFilter
196
Connection JavaDoc con = null;
197         try
198         {
199             List JavaDoc list = new ArrayList JavaDoc();
200
201             ses = ((HibernateStrategy)mStrategy).getSession();
202             con = ses.connection();
203
204             final PreparedStatement JavaDoc stmt;
205             if (con.getMetaData().getDriverName().startsWith("HSQL"))
206             {
207                     // special handling for HSQLDB
208
stmt = con.prepareStatement(
209                         "select top ? u.username,w.name,w.name,sum(r.dayhits) as s "+
210                         "from rolleruser as u, website as w, referer as r "+
211                         "where r.websiteid=w.id and w.userid=u.id and w.isenabled=? " +
212                         "group by u.username,w.name,w.id order by s desc");
213                 stmt.setInt(1, max);
214                 stmt.setBoolean(2, true);
215             }
216             else
217             {
218                stmt = con.prepareStatement(
219                     "select u.username,w.name,w.name,sum(r.dayhits) as s "+
220                     "from rolleruser as u, website as w, referer as r "+
221                     "where r.websiteid=w.id and w.userid=u.id and w.isenabled= ? " +
222                     // Ben Walding (a Postgres SQL user): Basically, you have
223
// to have all non-aggregated columns that exist in your
224
// 'SELECT' section, in the 'GROUP BY' section as well:
225
"group by u.username,w.name,w.id order by s desc limit ?");
226                     // and not this: "group by w.id order by s desc");
227
stmt.setBoolean(1, true);
228                 stmt.setInt(2, max);
229             }
230             ResultSet JavaDoc rs = stmt.executeQuery();
231             if ( rs.next() )
232             {
233                 do
234                 {
235                     String JavaDoc userName = rs.getString(1);
236                     String JavaDoc name = rs.getString(2);
237                     String JavaDoc websiteName = rs.getString(3);
238                     Integer JavaDoc hits = new Integer JavaDoc(rs.getInt(4));
239                     list.add(new WebsiteDisplayData(
240                        name,
241                        userName,
242                        websiteName,
243                        hits));
244                 }
245                 while ( rs.next() );
246             }
247             return list;
248         }
249         catch (Throwable JavaDoc pe)
250         {
251             mLogger.error(msg, pe);
252             throw new RollerException(msg, pe);
253         }
254         
255 // Don't close connection, Hibernate is holding it
256
// finally
257
// {
258
// try
259
// {
260
// if (con != null) con.close();
261
// }
262
// catch (Throwable t)
263
// {
264
// mLogger.error("Closing connection",t);
265
// }
266
// }
267

268     }
269     
270     //-----------------------------------------------------------------------
271

272     /**
273      * Use raw SQL because Hibernate can't handle the query.
274      */

275     protected int getHits(WebsiteData website, String JavaDoc type)
276         throws RollerException
277     {
278         int hits = 0;
279         if (mLogger.isDebugEnabled())
280         {
281             mLogger.debug("getHits: " + website.getName());
282         }
283
284         //Question: why not use website.id instead to reduce joins?
285
Object JavaDoc[] args = { Boolean.TRUE, website.getUser().getUserName() };
286         Type[] types = { Hibernate.BOOLEAN, Hibernate.STRING };
287
288         // For a query like this, Hibernate returns a list of lists
289
Session session = ((HibernateStrategy)mStrategy).getSession();
290         List JavaDoc results;
291         try
292         {
293             results = session.find(
294                "select sum(h.dayHits),sum(h.totalHits) from h in class " +
295                "org.roller.pojos.RefererData " +
296                "where h.website.isEnabled=? and h.website.user.userName=? ",
297                args, types);
298         }
299         catch (HibernateException e)
300         {
301             throw new RollerException(e);
302         }
303         Object JavaDoc[] resultsArray = (Object JavaDoc[]) results.get(0);
304
305         if (resultsArray.length > 0 && type.equals(DAYHITS))
306         {
307             if ( resultsArray[0] != null )
308             {
309                 hits = ((Integer JavaDoc) resultsArray[0]).intValue();
310             }
311         }
312         else if ( resultsArray.length > 0 )
313         {
314             if ( resultsArray[0] != null )
315             {
316                 hits = ((Integer JavaDoc) resultsArray[1]).intValue();
317             }
318         }
319         else
320         {
321             hits = 0;
322         }
323
324         return hits;
325     }
326     
327     /**
328      * @see org.roller.pojos.RefererManager#getReferers(java.lang.String)
329      */

330     public List JavaDoc getReferers(WebsiteData website) throws RollerException
331     {
332         if (website==null )
333             throw new RollerException("website is null");
334
335         Session session = ((HibernateStrategy)mStrategy).getSession();
336         Criteria criteria = session.createCriteria(RefererData.class);
337         criteria.add(Expression.eq("website",website));
338         criteria.addOrder(Order.desc("totalHits"));
339         try
340         {
341             return criteria.list();
342         }
343         catch (HibernateException e)
344         {
345             throw new RollerException(e);
346         }
347     }
348
349     //-----------------------------------------------------------------------
350

351     /**
352      * @see org.roller.pojos.RefererManager#getTodaysReferers(String)
353      */

354     public List JavaDoc getTodaysReferers(WebsiteData website)
355         throws RollerException
356     {
357         if (website==null )
358             throw new RollerException("website is null");
359
360         Session session = ((HibernateStrategy)mStrategy).getSession();
361         Criteria criteria = session.createCriteria(RefererData.class);
362         criteria.add(Expression.eq("website", website));
363         criteria.add(Expression.gt("dayHits", new Integer JavaDoc(0)));
364         criteria.addOrder(Order.desc("dayHits"));
365         try
366         {
367             return criteria.list();
368         }
369         catch (HibernateException e)
370         {
371             throw new RollerException(e);
372         }
373     }
374
375     //-----------------------------------------------------------------------
376

377     /**
378      * Returns referers for a specified day. Duplicate enties are not
379      * included in this list so the hit counts may not be accurate.
380      * @see org.roller.pojos.RefererManager#getReferersToDate(
381      * org.roller.pojos.WebsiteData, java.lang.String)
382      */

383     public List JavaDoc getReferersToDate(WebsiteData website, String JavaDoc date)
384         throws RollerException
385     {
386         if (website==null )
387             throw new RollerException("website is null");
388
389         if (date==null )
390             throw new RollerException("Date is null");
391
392         Session session = ((HibernateStrategy)mStrategy).getSession();
393         Criteria criteria = session.createCriteria(RefererData.class);
394         criteria.add(Expression.eq("website", website));
395         criteria.add(Expression.eq("dateString", date));
396         criteria.add(Expression.eq("duplicate", Boolean.FALSE));
397         criteria.addOrder(Order.desc("totalHits"));
398         try
399         {
400             return criteria.list();
401         }
402         catch (HibernateException e)
403         {
404             throw new RollerException(e);
405         }
406     }
407
408     //-----------------------------------------------------------------------
409

410     /**
411      * @see org.roller.pojos.RefererManager#getReferersToEntry(
412      * java.lang.String, java.lang.String)
413      */

414     public List JavaDoc getReferersToEntry(String JavaDoc entryid) throws RollerException
415     {
416         if (null == entryid)
417             throw new RollerException("entryid is null");
418
419         try
420         {
421             Session session = ((HibernateStrategy)mStrategy).getSession();
422             Criteria criteria = session.createCriteria(RefererData.class);
423             criteria.createAlias("weblogEntry","e");
424             
425             criteria.add(Expression.eq("e.id", entryid));
426             criteria.add(Expression.isNotNull("title"));
427             criteria.add(Expression.isNotNull("excerpt"));
428             
429             criteria.addOrder(Order.desc("totalHits"));
430         
431             return criteria.list();
432         }
433         catch (HibernateException e)
434         {
435             throw new RollerException(e);
436         }
437     }
438
439     //-----------------------------------------------------------------------
440

441     /**
442      * @see org.roller.pojos.RefererManager#getReferersToEntry(
443      * java.lang.String, java.lang.String)
444      */

445     public void removeReferersForEntry(String JavaDoc entryid) throws RollerException
446     {
447         if (null == entryid)
448             throw new RollerException("entryid is null");
449
450         try
451         {
452             Session session = ((HibernateStrategy)mStrategy).getSession();
453             Criteria criteria = session.createCriteria(RefererData.class);
454             criteria.createAlias("weblogEntry","e");
455             criteria.add(Expression.eq("e.id", entryid));
456         
457             Iterator JavaDoc referers = criteria.list().iterator();
458             while (referers.hasNext())
459             {
460                 removeReferer( ((RefererData)referers.next()).getId() );
461             }
462         }
463         catch (HibernateException e)
464         {
465             throw new RollerException(e);
466         }
467     }
468
469     //-----------------------------------------------------------------------
470

471     /**
472      * Query for collection of referers.
473      */

474     protected List JavaDoc getReferersToWebsite(WebsiteData website, String JavaDoc refererUrl)
475         throws RollerException
476     {
477         Session session = ((HibernateStrategy)mStrategy).getSession();
478         Criteria criteria = session.createCriteria(RefererData.class);
479         criteria.add(Expression.eq("website", website));
480         criteria.add(Expression.eq("refererUrl", refererUrl));
481         try
482         {
483             return criteria.list();
484         }
485         catch (HibernateException e)
486         {
487             throw new RollerException(e);
488         }
489     }
490
491     //-----------------------------------------------------------------------
492

493     /**
494      * Query for collection of referers.
495      */

496     protected List JavaDoc getReferersWithSameTitle(
497         WebsiteData website,
498         String JavaDoc requestUrl,
499         String JavaDoc title,
500         String JavaDoc excerpt)
501         throws RollerException
502     {
503         try
504         {
505             Session session = ((HibernateStrategy)mStrategy).getSession();
506             Criteria criteria = session.createCriteria(RefererData.class);
507             
508             Junction conjunction = Expression.conjunction();
509             conjunction.add(Expression.eq("website", website));
510             conjunction.add(Expression.eq("requestUrl", requestUrl));
511             
512             Junction disjunction = Expression.conjunction();
513             disjunction.add(Expression.eq("title", title));
514             disjunction.add(Expression.eq("excerpt", excerpt));
515         
516             criteria.add(conjunction);
517             criteria.add(disjunction);
518             
519             return criteria.list();
520         }
521         catch (HibernateException e)
522         {
523             throw new RollerException(e);
524         }
525     }
526     
527     /**
528      * Purge referers at midnight. Zero out all dayHits and remove all
529      * referers that do not have excerpts.
530      */

531     public void checkForTurnover( boolean forceTurnover, String JavaDoc websiteId )
532         throws RollerException
533     {
534         // Note, this method doesn't need to be synchronized anymore since
535
// it's called from the timer task now, and will never be executed
536
// by two threads simultaneously.
537
if (mLogger.isDebugEnabled())
538         {
539             mLogger.debug("checkForTurnover");
540         }
541
542         Date JavaDoc now = new Date JavaDoc();
543
544         if (forceTurnover ||
545                 !mDateFormat.format(now).equals(mDateFormat.format(mRefDate)))
546         {
547             try
548             {
549                 if (websiteId == null) mRefDate = now;
550
551                 List JavaDoc refs;
552                 try
553                 {
554                     Session session = ((HibernateStrategy)mStrategy).getSession();
555                     Criteria criteria = session.createCriteria(RefererData.class);
556                     criteria.add(Expression.gt("dayHits", new Integer JavaDoc(0)));
557                     if (websiteId != null)
558                     {
559                         criteria.add(Expression.eq("website.id", websiteId));
560                     }
561                     refs = criteria.list();
562                 }
563                 catch (HibernateException e1)
564                 {
565                     throw new RollerException(e1);
566                 }
567
568                 Integer JavaDoc zero = new Integer JavaDoc(0);
569                 for (Iterator JavaDoc rdItr = refs.iterator(); rdItr.hasNext();) {
570                     RefererData referer = (RefererData) rdItr.next();
571
572                     if ( (referer.getExcerpt() != null) &&
573                             (referer.getExcerpt().trim().length() > 0))
574                     {
575                         // Zero out dayHits of referers with excerpts
576
referer.setDayHits(zero);
577                         storeReferer(referer);
578                     }
579                     else
580                     {
581                         // Throw away referers without excerpts
582
removeReferer(referer.getId());
583                     }
584                 }
585             }
586             catch (RollerException e)
587             {
588                 mLogger.error("EXCEPTION resetting referers",e);
589             }
590         }
591     }
592
593
594 }
595
Popular Tags