KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > blandware > atleap > persistence > hibernate > core > MailTemplateDAOHibernate


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.core;
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.MailTemplate;
30 import com.blandware.atleap.model.core.Page;
31 import com.blandware.atleap.persistence.core.MailTemplateDAO;
32
33 import java.io.ByteArrayInputStream JavaDoc;
34 import java.io.PrintWriter JavaDoc;
35 import java.io.StringWriter JavaDoc;
36 import java.util.ArrayList JavaDoc;
37 import java.util.Date JavaDoc;
38 import java.util.HashSet JavaDoc;
39 import java.util.Iterator JavaDoc;
40 import java.util.List JavaDoc;
41 import java.util.ListIterator JavaDoc;
42 import java.util.Map JavaDoc;
43 import java.util.Set JavaDoc;
44
45 /**
46  * <p>Hibernate implementation of MailTemplateDAO</p>
47  * <p><a HREF="MenuDAOHibernate.java.htm"><i>View Source</i></a></p>
48  *
49  * @author Sergey Zubtcovskii <a HREF="mailto:sergey.zubtcovskii@blandware.com">&lt;sergey.zubtcovskii@blandware.com&gt;</a>
50  * @version $Revision: 1.13 $ $Date: 2005/12/18 16:43:46 $
51  */

52 public class MailTemplateDAOHibernate extends LocalizableDAOHibernate implements MailTemplateDAO {
53
54     /**
55      * Creates new instance of MailTemplateDAOHibernate
56      */

57     public MailTemplateDAOHibernate() {
58     }
59
60     // ~ CRUD Methods ================================================================
61

62     /**
63      * @see com.blandware.atleap.persistence.core.MailTemplateDAO#createMailTemplate(com.blandware.atleap.model.core.MailTemplate)
64      */

65     public Long JavaDoc createMailTemplate(MailTemplate template) {
66         Long JavaDoc templateId = (Long JavaDoc) getHibernateTemplate().save(template);
67
68         // from
69
ContentField fFrom = new ContentField();
70         fFrom.setIdentifier("from");
71         fFrom.setType(ContentField.LINE_TYPE);
72         fFrom.setInternal(Boolean.TRUE);
73         template.addContentField(fFrom);
74         getHibernateTemplate().save(fFrom);
75
76         // subject
77
ContentField fSubject = new ContentField();
78         fSubject.setIdentifier("subject");
79         fSubject.setType(ContentField.LINE_TYPE);
80         fSubject.setInternal(Boolean.TRUE);
81         template.addContentField(fSubject);
82         getHibernateTemplate().save(fSubject);
83
84         // body
85
ContentField fBody = new ContentField();
86         fBody.setIdentifier("body");
87         fBody.setType(ContentField.MULTILINE_TYPE);
88         fBody.setInternal(Boolean.TRUE);
89         template.addContentField(fBody);
90         getHibernateTemplate().save(fBody);
91
92         // charset
93
ContentField fCharset = new ContentField();
94         fCharset.setIdentifier("charset");
95         fCharset.setType(ContentField.LINE_TYPE);
96         fCharset.setInternal(Boolean.TRUE);
97         template.addContentField(fCharset);
98         getHibernateTemplate().save(fCharset);
99
100         // Fill in content field values for from, subject, body and charset
101
// fields for every content locale
102
List JavaDoc contentLocales = executeFind("from ContentLocale l", true, "query.listContentLocales");
103         for ( int i = 0; i < contentLocales.size(); i++ ) {
104             ContentLocale contentLocale = (ContentLocale) contentLocales.get(i);
105             String JavaDoc localeIdentifier = contentLocale.getIdentifier();
106
107             // values for from, subject, body and charset in that locale
108
String JavaDoc valueFrom = (String JavaDoc) template.getFrom().get(localeIdentifier);
109             String JavaDoc valueSubject = (String JavaDoc) template.getSubject().get(localeIdentifier);
110             String JavaDoc valueBody = (String JavaDoc) template.getBody().get(localeIdentifier);
111             String JavaDoc valueCharset = (String JavaDoc) template.getCharset().get(localeIdentifier);
112
113             //from
114
ContentFieldValue fvFrom = new ContentFieldValue();
115             fvFrom.setContentLocale(contentLocale);
116             if ( valueFrom != null ) {
117                 fvFrom.setSimpleValue(valueFrom);
118             } else {
119                 fvFrom.setSimpleValue("");
120             }
121             fvFrom.setLastUpdatedDatetime(new Date JavaDoc());
122             fFrom.addContentFieldValue(fvFrom);
123             getHibernateTemplate().save(fvFrom);
124
125             //subject
126
ContentFieldValue fvSubject = new ContentFieldValue();
127             fvSubject.setContentLocale(contentLocale);
128             if ( valueSubject != null ) {
129                 fvSubject.setSimpleValue(valueSubject);
130             } else {
131                 fvSubject.setSimpleValue("");
132             }
133             fvSubject.setLastUpdatedDatetime(new Date JavaDoc());
134             fSubject.addContentFieldValue(fvSubject);
135             getHibernateTemplate().save(fvSubject);
136
137             //body
138
ContentFieldValue fvBody = new ContentFieldValue();
139             fvBody.setContentLocale(contentLocale);
140             if ( valueBody != null ) {
141                 fvBody.setValue(ConvertUtil.convertToByteArray(valueBody));
142             } else {
143                 fvBody.setValue(new byte[0]);
144             }
145             fvBody.setLastUpdatedDatetime(new Date JavaDoc());
146             fBody.addContentFieldValue(fvBody);
147             getHibernateTemplate().save(fvBody);
148
149             //charset
150
ContentFieldValue fvCharset = new ContentFieldValue();
151             fvCharset.setContentLocale(contentLocale);
152             if ( valueCharset != null ) {
153                 fvCharset.setSimpleValue(valueCharset);
154             } else {
155                 fvCharset.setSimpleValue("");
156             }
157             fvCharset.setLastUpdatedDatetime(new Date JavaDoc());
158             fCharset.addContentFieldValue(fvCharset);
159             getHibernateTemplate().save(fvCharset);
160         }
161
162         return templateId;
163     }
164
165     /**
166      * @see com.blandware.atleap.persistence.core.MailTemplateDAO#retrieveMailTemplate(Long)
167      */

168     public MailTemplate retrieveMailTemplate(Long JavaDoc templateId) {
169         String JavaDoc hql = new StringBuffer JavaDoc("select template, fromValue.contentLocale.identifier, fromValue.simpleValue, subject.simpleValue, charset.simpleValue, body.value ")
170                 .append("from MailTemplate as template left outer join ")
171                 .append("template.contentFields fromField left outer join fromField.contentFieldValues as fromValue left outer join ")
172                 .append("template.contentFields subjectField left outer join subjectField.contentFieldValues as subject ")
173                 .append("left outer join template.contentFields bodyField left outer join bodyField.contentFieldValues as body ")
174                 .append("left outer join template.contentFields charsetField left outer join charsetField.contentFieldValues as charset ")
175                 .append("where ")
176                 .append("((fromValue.contentLocale = subject.contentLocale and fromValue.contentLocale = body.contentLocale and fromValue.contentLocale = charset.contentLocale) or (fromValue is null and subject is null and body is null and charset is null)) ")
177                 .append("and fromField.identifier = 'from' and charsetField.identifier = 'charset' ")
178                 .append("and subjectField.identifier = 'subject' and bodyField.identifier = 'body' and template.id = ?")
179                 .toString();
180
181         // Get a list of tuples (mail template, locale identifier, from value,
182
// subject value, body value, charset value)
183
List JavaDoc list = executeFind(hql, new Object JavaDoc[]{templateId});
184         // Assign those values to corresponding templates -- get list of templates with
185
// from, subject, body and charset correctly assigned
186
List JavaDoc result = setLocalizableFields(list);
187         if ( result == null || result.size() <= 0 ) {
188             return null;
189         } else {
190             return (MailTemplate) result.get(0);
191         }
192     }
193
194     /**
195      * @see com.blandware.atleap.persistence.core.MailTemplateDAO#updateMailTemplate(com.blandware.atleap.model.core.MailTemplate, java.util.Map)
196      */

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

278     public void deleteMailTemplate(MailTemplate template) {
279         getHibernateTemplate().delete(template);
280     }
281
282     /**
283      * @see com.blandware.atleap.persistence.core.MailTemplateDAO#listMailTemplates(com.blandware.atleap.common.util.QueryInfo)
284      */

285     public PartialCollection listMailTemplates(QueryInfo queryInfo) {
286         String JavaDoc whereClause = new String JavaDoc();
287         String JavaDoc orderByClause = new String JavaDoc();
288         if ( queryInfo != null ) {
289             whereClause = queryInfo.getWhereClause();
290             orderByClause = queryInfo.getOrderByClause();
291             if ( whereClause == null || whereClause.length() == 0 ) {
292                 whereClause = new String JavaDoc();
293             }
294             if ( orderByClause != null && orderByClause.length() != 0 ) {
295                 orderByClause = " order by " + orderByClause;
296             } else {
297                 orderByClause = new String JavaDoc();
298             }
299         }
300
301         List JavaDoc list = null;
302         Integer JavaDoc total = null;
303
304         String JavaDoc localeIdentifier = null;
305         if ( queryInfo != null ) {
306             if ( queryInfo.getQueryParameters() != null ) {
307                 localeIdentifier = (String JavaDoc) queryInfo.getQueryParameters().get("localeIdentifier");
308             }
309         }
310
311         boolean localeIdentifierPresent = localeIdentifier != null && localeIdentifier.length() > 0;
312
313         String JavaDoc hqlPart = new String JavaDoc();
314         ArrayList JavaDoc args = new ArrayList JavaDoc();
315         if ( localeIdentifierPresent ) {
316             args.add(localeIdentifier);
317             hqlPart = new StringBuffer JavaDoc("from MailTemplate as template ")
318                     .append("left outer join template.contentFields as fromField ")
319                     .append("left outer join template.contentFields as subjectField ")
320                     .append("left outer join template.contentFields as bodyField ")
321                     .append("left outer join template.contentFields as charsetField ")
322                     .append("left outer join fromField.contentFieldValues as fromValue ")
323                     .append("left outer join subjectField.contentFieldValues as subject ")
324                     .append("left outer join bodyField.contentFieldValues as body ")
325                     .append("left outer join charsetField.contentFieldValues as charset ")
326                     .append("where ")
327                     .append("fromField.identifier = 'from' and subjectField.identifier = 'subject'")
328                     .append("and bodyField.identifier = 'body' and charsetField.identifier = 'charset' ")
329                     .append("and fromValue.contentLocale = subject.contentLocale and fromValue.contentLocale = body.contentLocale ")
330                     .append("and fromValue.contentLocale = charset.contentLocale ")
331                     .append("and fromValue.contentLocale.identifier = ? ")
332                     .toString();
333             if ( whereClause.length() > 0 ) {
334                 hqlPart += "and " + whereClause;
335             }
336         } else {
337             hqlPart = "from MailTemplate template ";
338             if ( whereClause.length() > 0 ) {
339                 hqlPart += "where " + whereClause;
340             }
341         }
342
343         if ( queryInfo != null && (queryInfo.getLimit() != null || queryInfo.getOffset() != null) ) {
344             // query count
345
String JavaDoc hqlForTotal = "select count(distinct template.id) " + hqlPart;
346             total = (Integer JavaDoc) findUniqueResult(hqlForTotal, args.toArray());
347             if ( total == null ) {
348                 total = new Integer JavaDoc(0);
349             }
350         }
351
352         // If we don't have any info about the total number of results yet or
353
// we know that there's something that will be found, then fetch data
354
if ( total == null || total.intValue() > 0 ) {
355             String JavaDoc hql = new String JavaDoc();
356             if ( localeIdentifierPresent ) {
357                 hql = "select distinct template, fromValue.simpleValue, subject.simpleValue, charset.simpleValue " + hqlPart + orderByClause;
358             } else {
359                 hql = "select distinct template " + hqlPart + orderByClause;
360             }
361             list = executeFind(hql, queryInfo, args.toArray());
362             if ( total == null ) {
363                 total = new Integer JavaDoc(list.size());
364             }
365             if ( localeIdentifierPresent ) {
366                 for ( ListIterator JavaDoc i = list.listIterator(); i.hasNext(); ) {
367                     Object JavaDoc[] objects = (Object JavaDoc[]) i.next();
368                     MailTemplate mailTemplate = (MailTemplate) objects[0];
369                     mailTemplate.getFrom().put(localeIdentifier, objects[1]);
370                     mailTemplate.getSubject().put(localeIdentifier, objects[2]);
371                     mailTemplate.getCharset().put(localeIdentifier, objects[3]);
372                     i.set(mailTemplate);
373                 }
374             }
375         } else {
376             list = new ArrayList JavaDoc();
377         }
378
379         return new PartialCollection(list, total);
380
381     }
382
383     // ~ Finders ================================================================
384

385     /**
386      * @see com.blandware.atleap.persistence.core.MailTemplateDAO#findMailTemplateByIdentifier(String)
387      */

388     public MailTemplate findMailTemplateByIdentifier(String JavaDoc identifier) {
389         String JavaDoc hql = new StringBuffer JavaDoc("select template, fromValue.contentLocale.identifier, fromValue.simpleValue, subject.simpleValue, charset.simpleValue, body.value ")
390                 .append("from MailTemplate as template left outer join ")
391                 .append("template.contentFields fromField left outer join fromField.contentFieldValues as fromValue left outer join ")
392                 .append("template.contentFields subjectField left outer join subjectField.contentFieldValues as subject ")
393                 .append("left outer join template.contentFields bodyField left outer join bodyField.contentFieldValues as body ")
394                 .append("left outer join template.contentFields charsetField left outer join charsetField.contentFieldValues as charset ")
395                 .append("where ")
396                 .append("((fromValue.contentLocale = subject.contentLocale and fromValue.contentLocale = body.contentLocale and fromValue.contentLocale = charset.contentLocale) or (fromValue is null and subject is null and body is null and charset is null)) ")
397                 .append("and fromField.identifier = 'from' and charsetField.identifier = 'charset' ")
398                 .append("and subjectField.identifier = 'subject' and bodyField.identifier = 'body' and template.identifier = ?")
399                 .toString();
400
401         // Get a list of tuples (mail template, locale identifier, from value,
402
// subject value, body value, charset value)
403
List JavaDoc list = executeFind(hql, new Object JavaDoc[]{identifier});
404         // Assign those values to corresponding templates -- get list of templates with
405
// from, subject, body and charset correctly assigned
406
List JavaDoc result = setLocalizableFields(list);
407         if ( result == null || result.size() <= 0 ) {
408             return null;
409         } else {
410             return (MailTemplate) result.get(0);
411         }
412     }
413
414
415     /**
416      * Finds template by ID in list of mail templates
417      *
418      * @param mailMessageTemplates list to search through
419      * @param id ID of template
420      * @return template
421      */

422     protected MailTemplate findMailTemplateById(List JavaDoc mailMessageTemplates, Long JavaDoc id) {
423         for ( int i = 0; i < mailMessageTemplates.size(); i++ ) {
424             MailTemplate mailTemplate = (MailTemplate) mailMessageTemplates.get(i);
425             if ( mailTemplate.getId().equals(id) ) {
426                 return mailTemplate;
427             }
428         }
429         return null;
430     }
431
432     // ~ Helper methods ================================================================
433

434     /**
435      * Collapses list by setting up values for different tamplates and locales into template's maps
436      *
437      * @param queryResult query result with 6 objects [template, locale, from, subject, body, charset]
438      * @return collapsed list
439      */

440     protected List JavaDoc setLocalizableFields(List JavaDoc queryResult) {
441         if ( queryResult == null || queryResult.size() <= 0 ) {
442             return null;
443         }
444
445         // First make a list of templates from tuples (assigning from, subject,
446
// body and charset values with specified locale)
447
List JavaDoc mailMessageTemplates = new ArrayList JavaDoc(queryResult.size());
448         for ( int i = 0; i < queryResult.size(); i++ ) {
449             Object JavaDoc[] objects = (Object JavaDoc[]) queryResult.get(i);
450             MailTemplate template = (MailTemplate) objects[0];
451             String JavaDoc locale = (String JavaDoc) objects[1];
452             if ( locale != null && locale.trim().length() > 0 ) {
453                 template.getFrom().put(locale, objects[2]);
454                 template.getSubject().put(locale, objects[3]);
455                 template.getCharset().put(locale, objects[4]);
456                 template.getBody().put(locale, ConvertUtil.convertToString((byte[]) objects[5]));
457             }
458             mailMessageTemplates.add(template);
459         }
460
461         // Now make a such list of templates that each template is encountered maximum
462
// one time (if some template is encountered second time, fore example, its
463
// internal fields' info is added to previous instance)
464
List JavaDoc fullMailMessageTemplates = new ArrayList JavaDoc(mailMessageTemplates.size());
465         for ( int i = 0; i < mailMessageTemplates.size(); i++ ) {
466             MailTemplate newMailTemplate = (MailTemplate) mailMessageTemplates.get(i);
467             MailTemplate existingMailTemplate = findMailTemplateById(fullMailMessageTemplates, newMailTemplate.getId());
468             if ( existingMailTemplate != null ) {
469                 //from
470
Iterator JavaDoc iterator = newMailTemplate.getFrom().keySet().iterator();
471                 while ( iterator.hasNext() ) {
472                     String JavaDoc localeIdentifier = (String JavaDoc) iterator.next();
473                     String JavaDoc value = (String JavaDoc) newMailTemplate.getFrom().get(localeIdentifier);
474                     if ( value == null ) {
475                         continue;
476                     }
477                     existingMailTemplate.getFrom().put(localeIdentifier, value);
478                 }
479
480                 //subject
481
iterator = newMailTemplate.getSubject().keySet().iterator();
482                 while ( iterator.hasNext() ) {
483                     String JavaDoc localeIdentifier = (String JavaDoc) iterator.next();
484                     String JavaDoc value = (String JavaDoc) newMailTemplate.getSubject().get(localeIdentifier);
485                     if ( value == null ) {
486                         continue;
487                     }
488                     existingMailTemplate.getSubject().put(localeIdentifier, value);
489                 }
490
491                 //body
492
iterator = newMailTemplate.getBody().keySet().iterator();
493                 while ( iterator.hasNext() ) {
494                     String JavaDoc localeIdentifier = (String JavaDoc) iterator.next();
495                     Object JavaDoc value = newMailTemplate.getBody().get(localeIdentifier);
496                     if ( value == null ) {
497                         continue;
498                     }
499                     existingMailTemplate.getBody().put(localeIdentifier, value);
500                 }
501
502                 //charset
503
iterator = newMailTemplate.getCharset().keySet().iterator();
504                 while ( iterator.hasNext() ) {
505                     String JavaDoc localeIdentifier = (String JavaDoc) iterator.next();
506                     String JavaDoc value = (String JavaDoc) newMailTemplate.getCharset().get(localeIdentifier);
507                     if ( value == null ) {
508                         continue;
509                     }
510                     existingMailTemplate.getCharset().put(localeIdentifier, value);
511                 }
512
513             } else {
514                 fullMailMessageTemplates.add(newMailTemplate);
515             }
516         }
517
518         return fullMailMessageTemplates;
519     }
520
521
522 }
523
Popular Tags