KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > blandware > atleap > persistence > hibernate > testimonials > TestimonialDAOHibernate


1 /*
2  * Copyright 2004 Blandware (http://www.blandware.com)
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package com.blandware.atleap.persistence.hibernate.testimonials;
17
18 import com.blandware.atleap.common.Constants;
19 import com.blandware.atleap.common.parsers.exception.PlainTextExtractorException;
20 import com.blandware.atleap.common.parsers.html.HTMLPlainTextExtractor;
21 import com.blandware.atleap.common.util.ConvertUtil;
22 import com.blandware.atleap.common.util.PartialCollection;
23 import com.blandware.atleap.common.util.QueryInfo;
24 import com.blandware.atleap.model.core.BaseObject;
25 import com.blandware.atleap.model.core.ContentField;
26 import com.blandware.atleap.model.core.ContentFieldValue;
27 import com.blandware.atleap.model.core.ContentLocale;
28 import com.blandware.atleap.model.core.ContentResource;
29 import com.blandware.atleap.model.core.Page;
30 import com.blandware.atleap.model.testimonials.Testimonial;
31 import com.blandware.atleap.persistence.exception.DeleteException;
32 import com.blandware.atleap.persistence.hibernate.core.PageDAOHibernate;
33 import com.blandware.atleap.persistence.testimonials.TestimonialDAO;
34
35 import java.io.ByteArrayInputStream JavaDoc;
36 import java.io.PrintWriter JavaDoc;
37 import java.io.StringWriter JavaDoc;
38 import java.util.ArrayList JavaDoc;
39 import java.util.Date JavaDoc;
40 import java.util.HashSet JavaDoc;
41 import java.util.Iterator JavaDoc;
42 import java.util.List JavaDoc;
43 import java.util.ListIterator JavaDoc;
44 import java.util.Map JavaDoc;
45 import java.util.Set JavaDoc;
46
47 /**
48  * <p>Hibernate implementation of TestimonialDAO</p>
49  * <p><a HREF="TestimonialDAOHibernate.java.htm"><i>View Source</i></a></p>
50  *
51  * @author Andrey Grebnev <a HREF="mailto:andrey.grebnev@blandware.com">&lt;andrey.grebnev@blandware.com&gt;</a>
52  * @version $Revision: 1.5 $ $Date: 2005/09/27 08:48:26 $
53  */

54 public class TestimonialDAOHibernate extends PageDAOHibernate implements TestimonialDAO {
55
56     /**
57      * Creates new instance of TestimonialDAOHibernate
58      */

59     public TestimonialDAOHibernate() {
60     }
61
62     /**
63      * @see com.blandware.atleap.persistence.testimonials.TestimonialDAO#createTestimonial(com.blandware.atleap.model.testimonials.Testimonial, java.util.Map)
64      */

65     public Long JavaDoc createTestimonial(Testimonial testimonial, Map JavaDoc linkedObjects) {
66         testimonial.setUsageCounter(new Integer JavaDoc(0));
67         Long JavaDoc testimonialId = (Long JavaDoc) getHibernateTemplate().save(testimonial);
68
69         // title
70
ContentField fTitle = new ContentField();
71         fTitle.setIdentifier("title");
72         fTitle.setType(ContentField.LINE_TYPE);
73         fTitle.setInternal(Boolean.TRUE);
74         testimonial.addContentField(fTitle);
75         getHibernateTemplate().save(fTitle);
76
77         // body
78
ContentField fBody = new ContentField();
79         fBody.setIdentifier("body");
80         fBody.setType(ContentField.HTML_TYPE);
81         fBody.setInternal(Boolean.TRUE);
82         testimonial.addContentField(fBody);
83         getHibernateTemplate().save(fBody);
84
85         // Fill in content field values for title and body fields for every
86
// content locale
87
List JavaDoc contentLocales = executeFind("from ContentLocale l", true, "query.listContentLocales");
88         HTMLPlainTextExtractor extractor = new HTMLPlainTextExtractor();
89         for ( int i = 0; i < contentLocales.size(); i++ ) {
90             ContentLocale contentLocale = (ContentLocale) contentLocales.get(i);
91             String JavaDoc localeIdentifier = contentLocale.getIdentifier();
92
93             // values for title and body in that locale
94
String JavaDoc valueTitle = (String JavaDoc) testimonial.getTitle().get(localeIdentifier);
95             String JavaDoc valueBody = (String JavaDoc) testimonial.getBody().get(localeIdentifier);
96
97             if ( (valueTitle == null || valueTitle.trim().length() == 0) && (valueBody == null || valueBody.trim().length() == 0) ) {
98                 continue;
99             }
100
101             //title
102
ContentFieldValue fvTitle = new ContentFieldValue();
103             fvTitle.setContentLocale(contentLocale);
104             if ( valueTitle != null ) {
105                 fvTitle.setSimpleValue(valueTitle);
106             } else {
107                 fvTitle.setSimpleValue("");
108             }
109             fvTitle.setLastUpdatedDatetime(new Date JavaDoc());
110             fTitle.addContentFieldValue(fvTitle);
111             getHibernateTemplate().save(fvTitle);
112
113             //body
114
ContentFieldValue fvBody = new ContentFieldValue();
115             fvBody.setContentLocale(contentLocale);
116             if ( valueBody != null ) {
117                 byte[] bodyBytes = ConvertUtil.convertToByteArray(valueBody);
118                 fvBody.setValue(bodyBytes);
119                 // get linked objects
120
try {
121                     Set JavaDoc refs = new HashSet JavaDoc(extractor.extractAllRefs(new ByteArrayInputStream JavaDoc(bodyBytes), Constants.DEFAULT_ENCODING));
122                     List JavaDoc linkedPages = new ArrayList JavaDoc();
123                     List JavaDoc linkedResources = new ArrayList JavaDoc();
124                     for ( Iterator JavaDoc j = refs.iterator(); j.hasNext(); ) {
125                         String JavaDoc ref = (String JavaDoc) j.next();
126                         BaseObject linkedObject = (BaseObject) linkedObjects.get(ref);
127                         if ( linkedObject != null ) {
128                             if ( linkedObject instanceof ContentResource ) {
129                                 linkedResources.add(linkedObject);
130                             } else if ( linkedObject instanceof Page ) {
131                                 linkedPages.add(linkedObject);
132                             }
133                         }
134                     }
135                     fvBody.setLinkedResources(linkedResources);
136                     fvBody.setLinkedPages(linkedPages);
137                 } catch ( PlainTextExtractorException e ) {
138                     // log exception
139
if ( log.isErrorEnabled() ) {
140                         StringWriter JavaDoc sw = new StringWriter JavaDoc();
141                         e.printStackTrace(new PrintWriter JavaDoc(sw));
142                         log.error(sw.toString());
143                     }
144                 }
145             } else {
146                 fvBody.setValue(new byte[0]);
147             }
148             fvBody.setLastUpdatedDatetime(new Date JavaDoc());
149             fBody.addContentFieldValue(fvBody);
150             getHibernateTemplate().save(fvBody);
151         }
152
153         return testimonialId;
154     }
155
156     /**
157      * @see com.blandware.atleap.persistence.testimonials.TestimonialDAO#retrieveTestimonial(Long)
158      */

159     public Testimonial retrieveTestimonial(Long JavaDoc testimonialId) {
160         String JavaDoc hql = new StringBuffer JavaDoc("select testimonial, title.contentLocale.identifier, title.simpleValue, body.value ")
161                 .append("from Testimonial as testimonial left outer join ")
162                 .append("testimonial.contentFields titleField left outer join titleField.contentFieldValues as title left outer join ")
163                 .append("testimonial.contentFields bodyField left outer join bodyField.contentFieldValues as body ")
164                 .append("where ")
165                 .append("((title.contentLocale = body.contentLocale) or (title is null and body is null)) ")
166                 .append("and titleField.identifier = 'title' ")
167                 .append("and bodyField.identifier = 'body' and testimonial.id = ?")
168                 .toString();
169
170         // Get a list of quadruples (testimonial, locale identifier, title value,
171
// body value)
172
List JavaDoc list = executeFind(hql, new Object JavaDoc[]{testimonialId});
173         // Assign those values to corresponding testimonials -- get list of
174
// testimonials with title and body correctly assigned
175
List JavaDoc result = setLocalizableFields(list);
176         if ( result == null || result.size() <= 0 ) {
177             return null;
178         } else {
179             return (Testimonial) result.get(0);
180         }
181     }
182
183     /**
184      * @see com.blandware.atleap.persistence.testimonials.TestimonialDAO#retrieveTestimonialLite(Long)
185      */

186     public Testimonial retrieveTestimonialLite(Long JavaDoc testimonialId) {
187         return (Testimonial) getHibernateTemplate().get(Testimonial.class, testimonialId);
188     }
189
190     /**
191      * @see com.blandware.atleap.persistence.testimonials.TestimonialDAO#updateTestimonial(com.blandware.atleap.model.testimonials.Testimonial, java.util.Map)
192      */

193     public void updateTestimonial(Testimonial testimonial, Map JavaDoc linkedObjects) {
194
195         getHibernateTemplate().update(testimonial);
196
197         HTMLPlainTextExtractor extractor = new HTMLPlainTextExtractor();
198
199         // Update internal fields (title and body) of this page
200
for ( int i = 0; i < testimonial.getContentFields().size(); i++ ) {
201             ContentField contentField = (ContentField) testimonial.getContentFields().get(i);
202             Map JavaDoc values = null;
203             boolean blob = true;
204             if ( "title".equalsIgnoreCase(contentField.getIdentifier()) ) {
205                 values = testimonial.getTitle();
206                 blob = false;
207             } else if ( "body".equalsIgnoreCase(contentField.getIdentifier()) ) {
208                 values = testimonial.getBody();
209             } else {
210                 continue;
211             }
212             for ( int j = 0; j < contentField.getContentFieldValues().size(); j++ ) {
213                 ContentFieldValue contentFieldValue = (ContentFieldValue) contentField.getContentFieldValues().get(j);
214                 String JavaDoc localeIdentifier = contentFieldValue.getContentLocale().getIdentifier();
215                 String JavaDoc value = (String JavaDoc) values.get(localeIdentifier);
216                 if ( value != null ) {
217                     if ( !blob ) {
218                         contentFieldValue.setSimpleValue(value);
219                     } else {
220                         byte[] valueBytes = ConvertUtil.convertToByteArray(value);
221                         contentFieldValue.setValue(valueBytes);
222                         if ( linkedObjects != null ) {
223                             // get linked objects
224
try {
225                                 Set JavaDoc refs = new HashSet JavaDoc(extractor.extractAllRefs(new ByteArrayInputStream JavaDoc(valueBytes), Constants.DEFAULT_ENCODING));
226                                 List JavaDoc linkedPages = new ArrayList JavaDoc();
227                                 List JavaDoc linkedResources = new ArrayList JavaDoc();
228                                 for ( Iterator JavaDoc k = refs.iterator(); k.hasNext(); ) {
229                                     String JavaDoc ref = (String JavaDoc) k.next();
230                                     BaseObject linkedObject = (BaseObject) linkedObjects.get(ref);
231                                     if ( linkedObject != null ) {
232                                         if ( linkedObject instanceof ContentResource ) {
233                                             linkedResources.add(linkedObject);
234                                         } else if ( linkedObject instanceof Page ) {
235                                             linkedPages.add(linkedObject);
236                                         }
237                                     }
238                                 }
239                                 contentFieldValue.setLinkedResources(linkedResources);
240                                 contentFieldValue.setLinkedPages(linkedPages);
241                             } catch ( PlainTextExtractorException e ) {
242                                 // log exception
243
if ( log.isErrorEnabled() ) {
244                                     StringWriter JavaDoc sw = new StringWriter JavaDoc();
245                                     e.printStackTrace(new PrintWriter JavaDoc(sw));
246                                     log.error(sw.toString());
247                                 }
248                             }
249                         }
250                     }
251                 } else {
252                     if ( !blob ) {
253                         contentFieldValue.setSimpleValue("");
254                     } else {
255                         contentFieldValue.setValue(new byte[0]);
256                     }
257                 }
258                 contentFieldValue.setLastUpdatedDatetime(new Date JavaDoc());
259                 contentFieldValue.getContentField().updateContentFieldValue(contentFieldValue);
260                 getHibernateTemplate().update(contentFieldValue);
261             }
262         }
263     }
264
265     /**
266      * @see com.blandware.atleap.persistence.testimonials.TestimonialDAO#deleteTestimonial(com.blandware.atleap.model.testimonials.Testimonial)
267      */

268     public void deleteTestimonial(Testimonial testimonial) throws DeleteException {
269         getHibernateTemplate().delete(testimonial);
270     }
271
272     // ~ Additional methods ================================================================
273

274     /**
275      * @see com.blandware.atleap.persistence.testimonials.TestimonialDAO#listTestimonials(com.blandware.atleap.common.util.QueryInfo)
276      */

277     public PartialCollection listTestimonials(QueryInfo queryInfo) {
278         String JavaDoc whereClause = new String JavaDoc();
279         String JavaDoc orderByClause = new String JavaDoc();
280         if ( queryInfo != null ) {
281             whereClause = queryInfo.getWhereClause();
282             orderByClause = queryInfo.getOrderByClause();
283             if ( whereClause == null || whereClause.length() == 0 ) {
284                 whereClause = new String JavaDoc();
285             }
286             if ( orderByClause != null && orderByClause.length() != 0 ) {
287                 orderByClause = " order by " + orderByClause;
288             } else {
289                 orderByClause = new String JavaDoc();
290             }
291         }
292
293         List JavaDoc list = null;
294         Integer JavaDoc total = null;
295
296         String JavaDoc localeIdentifier = null;
297         if ( queryInfo != null ) {
298             if ( queryInfo.getQueryParameters() != null ) {
299                 localeIdentifier = (String JavaDoc) queryInfo.getQueryParameters().get("localeIdentifier");
300             }
301         }
302
303         boolean localeIdentifierPresent = localeIdentifier != null && localeIdentifier.length() > 0;
304
305         String JavaDoc hqlPart = new String JavaDoc();
306         ArrayList JavaDoc args = new ArrayList JavaDoc();
307         if ( localeIdentifierPresent ) {
308             args.add(localeIdentifier);
309             hqlPart = new StringBuffer JavaDoc("from Testimonial as testimonial ")
310                     .append("left outer join testimonial.contentFields as titleField ")
311                     .append("left outer join testimonial.contentFields as bodyField ")
312                     .append("left outer join titleField.contentFieldValues as title ")
313                     .append("left outer join bodyField.contentFieldValues as body ")
314                     .append("left outer join testimonial.roles as role ")
315                     .append("where ")
316                     .append("titleField.identifier = 'title' and bodyField.identifier = 'body' ")
317                     .append("and title.contentLocale = body.contentLocale ")
318                     .append("and title.contentLocale.identifier = ? ")
319                     .toString();
320             if ( whereClause.length() > 0 ) {
321                 hqlPart += "and " + whereClause;
322             }
323         } else {
324             hqlPart = "from Testimonial testimonial ";
325             if ( whereClause.length() > 0 ) {
326                 hqlPart += "where " + whereClause;
327             }
328         }
329
330         if ( queryInfo != null && queryInfo.getLimit() != null && queryInfo.getOffset() != null ) {
331             // query count
332
String JavaDoc hqlForTotal = "select count(testimonial.id) " + hqlPart;
333             total = (Integer JavaDoc) findUniqueResult(hqlForTotal, args.toArray());
334             if ( total == null ) {
335                 total = new Integer JavaDoc(0);
336             }
337         }
338
339         // If we don't have any info about the total number of results yet or
340
// we know that there's something that will be found, then fetch data
341
if ( total == null || total.intValue() > 0 ) {
342             String JavaDoc hql = new String JavaDoc();
343             if ( localeIdentifierPresent ) {
344                 hql = "select testimonial, title.simpleValue, body.value " + hqlPart + orderByClause;
345             } else {
346                 hql = "select testimonial " + hqlPart + orderByClause;
347             }
348             list = executeFind(hql, queryInfo, args.toArray());
349             if ( total == null ) {
350                 total = new Integer JavaDoc(list.size());
351             }
352             if ( localeIdentifierPresent ) {
353                 for ( ListIterator JavaDoc i = list.listIterator(); i.hasNext(); ) {
354                     Object JavaDoc[] objects = (Object JavaDoc[]) i.next();
355                     Testimonial testimonial = (Testimonial) objects[0];
356                     testimonial.getTitle().put(localeIdentifier, objects[1]);
357                     byte[] body = (byte[]) objects[2];
358                     testimonial.getBody().put(localeIdentifier, ConvertUtil.convertToString(body));
359                     i.set(testimonial);
360                 }
361             }
362         } else {
363             list = new ArrayList JavaDoc();
364         }
365
366
367         return new PartialCollection(list, total);
368
369     }
370
371     /**
372      * @see com.blandware.atleap.persistence.testimonials.TestimonialDAO#getRandomTestimonial()
373      */

374     public Testimonial getRandomTestimonial() {
375         String JavaDoc hql = "select testimonial.id from Testimonial testimonial where testimonial.active = 'T'";
376         List JavaDoc list = executeFind(hql);
377         if ( list != null && list.size() > 0 ) {
378             int position = (int) Math.floor(Math.random() * list.size());
379             Long JavaDoc id = (Long JavaDoc) list.get(position);
380             return retrieveTestimonial(id);
381         } else {
382             return null;
383         }
384     }
385
386
387     // ~ Finders ================================================================
388

389     /**
390      * @see com.blandware.atleap.persistence.testimonials.TestimonialDAO#findTestimonialByUri(String)
391      */

392     public Testimonial findTestimonialByUri(String JavaDoc testimonialUri) {
393         return (Testimonial) findUniqueResult("from Testimonial testimonial where testimonial.uri = ?", new Object JavaDoc[]{testimonialUri});
394     }
395
396     // ~ Helper methods
397

398     /**
399      * Finds content testimonial by id in list
400      *
401      * @param testimonials list to search
402      * @param id id of content testimonial
403      * @return menu item
404      */

405     protected Testimonial findTestimonialById(List JavaDoc testimonials, Long JavaDoc id) {
406         for ( int i = 0; i < testimonials.size(); i++ ) {
407             Testimonial testimonial = (Testimonial) testimonials.get(i);
408             if ( testimonial.getId().equals(id) ) {
409                 return testimonial;
410             }
411         }
412         return null;
413     }
414
415     /**
416      * Collapses list by setting up content testimonials for different locales into one menu item maps
417      *
418      * @param queryResult query result with 4 objects (testimonial, locale, title, body)
419      * @return collapsed list
420      */

421     protected List JavaDoc setLocalizableFields(List JavaDoc queryResult) {
422         if ( queryResult == null || queryResult.size() <= 0 ) {
423             return null;
424         }
425
426         // First make a list of testimonials from tuples (assigning title
427
// and body values with specified locale)
428
List JavaDoc testimonials = new ArrayList JavaDoc(queryResult.size());
429         Set JavaDoc processedLocales = new HashSet JavaDoc();
430         for ( int i = 0; i < queryResult.size(); i++ ) {
431             Object JavaDoc[] objects = (Object JavaDoc[]) queryResult.get(i);
432             Testimonial testimonial = (Testimonial) objects[0];
433             String JavaDoc locale = (String JavaDoc) objects[1];
434             if ( locale != null && locale.trim().length() > 0 && !processedLocales.contains(locale) ) {
435                 processedLocales.add(locale);
436                 testimonial.getTitle().put(locale, objects[2]);
437                 testimonial.getBody().put(locale, ConvertUtil.convertToString((byte[]) objects[3]));
438             }
439
440             testimonials.add(testimonial);
441         }
442
443         // Now make a such list of testimonials that each testimonial is encountered maximum
444
// one time (if some testimnial is encountered second time, fore example, its
445
// internal fields' info is added to previous instance)
446
List JavaDoc fullTestimonials = new ArrayList JavaDoc(testimonials.size());
447         for ( int i = 0; i < testimonials.size(); i++ ) {
448             Testimonial newItem = (Testimonial) testimonials.get(i);
449             Testimonial existingItem = findTestimonialById(fullTestimonials, newItem.getId());
450             if ( existingItem != null ) {
451                 //title
452
Iterator JavaDoc iterator = newItem.getTitle().keySet().iterator();
453                 while ( iterator.hasNext() ) {
454                     String JavaDoc localeIdentifier = (String JavaDoc) iterator.next();
455                     Object JavaDoc value = newItem.getTitle().get(localeIdentifier);
456                     if ( value == null ) {
457                         continue;
458                     }
459                     existingItem.getTitle().put(localeIdentifier, value);
460                 }
461
462                 //body
463
iterator = newItem.getBody().keySet().iterator();
464                 while ( iterator.hasNext() ) {
465                     String JavaDoc localeIdentifier = (String JavaDoc) iterator.next();
466                     Object JavaDoc value = newItem.getBody().get(localeIdentifier);
467                     if ( value == null ) {
468                         continue;
469                     }
470                     existingItem.getBody().put(localeIdentifier, value);
471                 }
472
473             } else {
474                 fullTestimonials.add(newItem);
475             }
476         }
477
478         return fullTestimonials;
479     }
480
481 }
482
Popular Tags