KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > javabb > dao > hibernate > PostHibernateDAO


1 package org.javabb.dao.hibernate;
2
3 import java.sql.SQLException JavaDoc;
4 import java.text.MessageFormat JavaDoc;
5 import java.util.ArrayList JavaDoc;
6 import java.util.Collections JavaDoc;
7 import java.util.Comparator JavaDoc;
8 import java.util.List JavaDoc;
9
10 import net.sf.hibernate.Criteria;
11 import net.sf.hibernate.HibernateException;
12 import net.sf.hibernate.Query;
13 import net.sf.hibernate.Session;
14 import net.sf.hibernate.expression.Expression;
15 import net.sf.hibernate.expression.Order;
16 import net.sf.hibernate.type.LongType;
17
18 import org.javabb.dao.entity.IPostDAO;
19 import org.javabb.infra.Paging;
20 import org.javabb.lucene.index.Indexer;
21 import org.javabb.lucene.search.LuceneSearcher;
22 import org.javabb.vo.Forum;
23 import org.javabb.vo.Post;
24 import org.javabb.vo.PostText;
25 import org.javabb.vo.Topic;
26 import org.springframework.orm.hibernate.HibernateCallback;
27
28 /*
29  * Copyright 2004 JavaFree.org
30  *
31  * Licensed under the Apache License, Version 2.0 (the "License");
32  * you may not use this file except in compliance with the License.
33  * You may obtain a copy of the License at
34  *
35  * http://www.apache.org/licenses/LICENSE-2.0
36  *
37  * Unless required by applicable law or agreed to in writing, software
38  * distributed under the License is distributed on an "AS IS" BASIS,
39  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
40  * See the License for the specific language governing permissions and
41  * limitations under the License.
42  */

43
44 /**
45  * $Id: PostHibernateDAO.java,v 1.22.2.2.4.3 2006/03/27 12:13:15 daltoncamargo
46  * Exp $
47  *
48  * @author Dalton Camargo - <a HREF="mailto:dalton@javabb.org">dalton@javabb.org
49  * </a> <br>
50  * @author Ronald Tetsuo Miura
51  */

52 public class PostHibernateDAO extends HibernateDAO implements IPostDAO {
53
54     private LuceneSearcher searcher;
55
56     private Indexer indexer;
57
58     private String JavaDoc[] fields = new String JavaDoc[] { "text", "subject" };
59
60     /**
61      * @return Returns the searcher.
62      */

63     public LuceneSearcher getSearcher() {
64
65         return searcher;
66
67     }
68
69     /**
70      * @param searcher
71      * The searcher to set.
72      */

73     public void setSearcher(LuceneSearcher seacher) {
74
75         this.searcher = seacher;
76
77     }
78
79     /**
80      * @param indexer
81      * The indexer to set.
82      */

83     public void setIndexer(Indexer indexer) {
84
85         this.indexer = indexer;
86     }
87
88     /**
89      * @return Returns the indexer.
90      */

91     public Indexer getIndexer() {
92
93         return indexer;
94     }
95
96     /**
97      * @see org.javabb.dao.entity.IPostDAO#load(java.lang.Long)
98      */

99     public Post load(Long JavaDoc id) {
100
101         return (Post) getHibernateTemplate().load(Post.class, id);
102     }
103
104     /**
105      * @see org.javabb.dao.entity.IPostDAO#create(org.javabb.vo.Post)
106      */

107     public Long JavaDoc create(Post post) {
108
109         Long JavaDoc result = (Long JavaDoc) getHibernateTemplate().save(post);
110
111         indexer.index(post);
112
113         return result;
114     }
115
116     /**
117      * @see org.javabb.dao.entity.IPostDAO#delete(java.lang.Long)
118      */

119     public void delete(Long JavaDoc postId) {
120
121         getHibernateTemplate().delete(
122                 "FROM " + Post.class.getName() + " o WHERE o.idPost=?", postId,
123                 new LongType());
124
125         getHibernateTemplate().delete(
126                 "FROM " + PostText.class.getName() + " o WHERE o.idPost=?",
127                 postId, new LongType());
128
129         indexer.delete(postId);
130     }
131
132     /**
133      * @see org.javabb.dao.entity.IPostDAO#countPostsByTopic(java.lang.Long)
134      */

135     public int countPostsByTopic(Long JavaDoc idTopic) {
136
137         return countRowsWhere(Post.class, "o.idPost", "o.topic.idTopic=?",
138                 new Object JavaDoc[] { idTopic });
139     }
140
141     /**
142      * @see org.javabb.dao.entity.IPostDAO#findByTopic(java.lang.Long, int, int)
143      */

144     public List JavaDoc findByTopic(Long JavaDoc topicId, int pageNumber, int itemsPerPage) {
145
146         return find(Post.class, "o.topic.idTopic=?", new Object JavaDoc[] { topicId },
147                 "o.idPost ASC", pageNumber, itemsPerPage);
148     }
149
150     /**
151      * @see org.javabb.dao.entity.IPostDAO#findByUser(java.lang.Long, int, int)
152      */

153     public List JavaDoc findByUser(final Long JavaDoc userId, final int pageNumber,
154             final int itemsPerPage) {
155         return getHibernateTemplate().executeFind(new HibernateCallback() {
156             public Object JavaDoc doInHibernate(Session session)
157                     throws HibernateException, SQLException JavaDoc {
158                 return session.createCriteria(Post.class) //
159
.add(Expression.eq("user.idUser", userId)) //
160
.addOrder(Order.desc("idPost")) //
161
.setFirstResult((pageNumber - 1) * itemsPerPage) //
162
.setMaxResults(itemsPerPage) //
163
.list();
164             }
165         });
166     }
167
168     public int countPostsByUser(Long JavaDoc userId) {
169         return countRowsWhere(Post.class, "o.idPost", "o.user.idUser=?",
170                 new Object JavaDoc[] { userId });
171     }
172
173     /**
174      * @see org.javabb.dao.entity.IPostDAO#findUnanswered(int, int)
175      */

176     public List JavaDoc findUnanswered(int pageNumber, int itemsPerPage) {
177         
178             String JavaDoc hql = "SELECT new Post("
179                     + "post.topic.id, post.topic.pageLastPost, post.id,"
180                     + "post.topic.titleTopic, post.topic.forum.id, post.topic.forum.nome, "
181                     + "post.postDate, post.user.id, post.user.user, post.topic.respostas, "
182                     + "post.topic.visualizacoes) "
183                     + " FROM Post as post where post.topic.respostas = ? ORDER BY post.idPost DESC";
184
185          return find(hql , new Object JavaDoc[] {new Integer JavaDoc(0)}, pageNumber, itemsPerPage);
186     }
187
188     public int countUnanswered() {
189         return countRowsWhere(Post.class, "o.idPost", "o.topic.respostas = ?",
190                 new Object JavaDoc[] { new Integer JavaDoc(0) });
191     }
192
193     /**
194      * @see org.javabb.dao.entity.IPostDAO#update(org.javabb.vo.Post)
195      */

196     public void update(Post post) {
197
198         getHibernateTemplate().update(post);
199
200         indexer.update(post);
201     }
202
203     /**
204      * @see org.javabb.dao.entity.IPostDAO#findByTopicDesc(org.javabb.vo.Topic)
205      */

206     public List JavaDoc findByTopicDesc(Topic topic) {
207
208         String JavaDoc[] whereField = { "topic.idTopic" };
209         String JavaDoc[] whereValue = { String.valueOf(topic.getIdTopic()) };
210         String JavaDoc[] orderBy = { "postDate" };
211         String JavaDoc[] orderType = { "desc" };
212
213         return findAll(PostText.class, whereField, whereValue, orderBy,
214                 orderType);
215
216     }
217
218     /**
219      * @see org.javabb.dao.entity.IPostDAO#findLasPosts(int)
220      */

221     public List JavaDoc findLastPosts(int limit) {
222
223         String JavaDoc[] orderBy = { "idPost" };
224         String JavaDoc[] orderType = { "desc" };
225         return findAll(PostText.class, orderBy, orderType, 1, limit);
226     }
227
228     /**
229      * @see org.javabb.dao.entity.IPostDAO#findLastPost()
230      */

231     public Post findLastPost() {
232
233         String JavaDoc[] orderBy = { "idPost" };
234         String JavaDoc[] orderType = { "desc" };
235         Post p = null;
236         List JavaDoc lst = findAll(Post.class, orderBy, orderType, 1, 1);
237
238         if ((lst != null) && !lst.isEmpty()) {
239             p = (Post) lst.get(0);
240         }
241         return p;
242     }
243
244     /**
245      * @see org.javabb.dao.entity.IPostDAO#findCountOfPostsByForum(org.javabb.vo.Forum)
246      */

247     public Integer JavaDoc findCountOfPostsByForum(Forum forum) {
248
249         String JavaDoc sql = "Post as p where p.topic.forum.idForum ="
250                 + forum.getIdForum();
251
252         return this.countRowsOfTable(sql, "p.idPost");
253
254     }
255
256     public int getTotalRowsOfLucene(String JavaDoc query) {
257         List JavaDoc ids = searchIdsByQueryAndFilds(query, fields);
258         if (ids != null) {
259             return ids.size();
260         }
261         return 0;
262     }
263
264     /**
265      * @see org.javabb.dao.entity.IPostDAO#search(java.lang.String)
266      */

267     public List JavaDoc search(String JavaDoc query, int pageNumber, int itemsPerPage) {
268
269         int first = Math.max(0, pageNumber - 1) * itemsPerPage;
270         first = Math.max(0, first);
271         // int limit = Math.max(first, itemsPerPage) + 1;
272
int limit = Math.round(pageNumber * itemsPerPage);
273
274         List JavaDoc ids = searchIdsByQueryAndFilds(query, fields);
275
276         // // PAGING
277
long postsCount = ids.size();
278         int totalPages = Paging.getNroPages(itemsPerPage, postsCount);
279         Paging.setPageList(pageNumber, totalPages);
280
281         // return search(ids, 1, 3);
282
return search(ids, first, limit);
283     }
284
285     /**
286      *
287      * @param query
288      * @param fields
289      * @return
290      */

291     public List JavaDoc searchIdsByQueryAndFilds(String JavaDoc query, String JavaDoc[] fields) {
292         return searcher.search(query, fields);
293     }
294
295     /**
296      * @param query
297      * @param fields
298      * @param start
299      * @param limit
300      *
301      * @return
302      *
303      * @see org.javabb.dao.entity.IPostDAO#search(java.lang.String)
304      */

305     private List JavaDoc search(final List JavaDoc ids, final int start, final int limit) {
306
307         HibernateCallback callback = new HibernateCallback() {
308             public Object JavaDoc doInHibernate(Session session)
309                     throws HibernateException {
310                 List JavaDoc result = new ArrayList JavaDoc();
311                 if (!ids.isEmpty()) {
312                     int _start = Math.max(0, start);
313                     int _limit = Math.min(limit, ids.size());
314                     List JavaDoc subListIds = ids.subList(_start, _limit);
315                     String JavaDoc hql = "SELECT new PostText("
316                             + "post.topic.id, post.topic.pageLastPost, post.id,"
317                             + "post.topic.titleTopic, post.topic.forum.id, post.topic.forum.nome, "
318                             + "post.postDate, post.user.id, post.user.user, post.topic.respostas, "
319                             + "post.topic.visualizacoes, post.postBody) "
320                             + " FROM PostText as post where post.idPost in";
321
322                     hql += "(";
323                     if (!subListIds.isEmpty()) {
324                         for (int i = 0; i < subListIds.size(); i++) {
325                             hql += subListIds.get(i) + ",";
326                         }
327                         hql = hql.substring(0, hql.length() - 1);
328                         hql += ")";
329
330                         result = session.find(hql);
331                     }
332                 }
333                 return result;
334             }
335         };
336
337         Comparator JavaDoc sorter = new LuceneComparator(ids);
338
339         List JavaDoc result = getHibernateTemplate().executeFind(callback);
340
341         Collections.sort(result, sorter);
342
343         return result;
344
345     }
346
347     public List JavaDoc search(final String JavaDoc query, final int page) {
348         return (List JavaDoc) getHibernateTemplate().execute(new HibernateCallback() {
349             public Object JavaDoc doInHibernate(Session session)
350                     throws HibernateException, SQLException JavaDoc {
351                 Criteria criteria = session.createCriteria(PostText.class);
352
353                 String JavaDoc[] tokens = query.split(" ");
354                 for (int i = 0; i < tokens.length; i++) {
355                     String JavaDoc token = tokens[i];
356                     criteria.add(Expression.like("postBody", token));
357                 }
358                 // criteria.setMaxResults(postsPerPage);
359
return criteria.list();
360             }
361         });
362     }
363
364     /**
365      * @see org.javabb.dao.entity.IPostDAO#countAllPosts()
366      */

367     public int countAllPosts() {
368
369         return countRows(Post.class, "idPost");
370     }
371
372     private static class LuceneComparator implements Comparator JavaDoc {
373
374         private final List JavaDoc ids;
375
376         private LuceneComparator(List JavaDoc ids) {
377
378             this.ids = ids;
379
380         }
381
382         /**
383          * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
384          */

385         public int compare(final Object JavaDoc o1, final Object JavaDoc o2) {
386
387             final Long JavaDoc id1 = ((Post) o1).getId();
388             final Long JavaDoc id2 = ((Post) o2).getId();
389             for (int i = 0; i != ids.size(); i++) {
390                 final Long JavaDoc longId = (Long JavaDoc) ids.get(i);
391                 if (longId.equals(id1)) {
392                     return -1;
393                 }
394                 if (longId.equals(id2)) {
395                     return 1;
396                 }
397             }
398             return 0;
399         }
400
401     }
402
403     public List JavaDoc findByForumDesc(Forum forum) {
404         // TODO Auto-generated method stub
405
return null;
406     }
407
408 }
409
Popular Tags