KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > info > magnolia > cms > taglibs > util > SimpleMailTag


1 /**
2  *
3  * Magnolia and its source-code is licensed under the LGPL.
4  * You may copy, adapt, and redistribute this file for commercial or non-commercial use.
5  * When copying, adapting, or redistributing this document in keeping with the guidelines above,
6  * you are required to provide proper attribution to obinary.
7  * If you reproduce or distribute the document without making any substantive modifications to its content,
8  * please use the following attribution line:
9  *
10  * Copyright 1993-2006 obinary Ltd. (http://www.obinary.com) All rights reserved.
11  *
12  */

13 package info.magnolia.cms.taglibs.util;
14
15 import info.magnolia.cms.core.Content;
16 import info.magnolia.cms.mail.MailConstants;
17 import info.magnolia.cms.mail.MgnlMailFactory;
18 import info.magnolia.cms.mail.templates.MgnlEmail;
19 import info.magnolia.cms.util.ExclusiveWrite;
20 import info.magnolia.cms.util.Resource;
21
22 import java.io.File JavaDoc;
23 import java.io.FileOutputStream JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.text.DateFormat JavaDoc;
26 import java.util.Date JavaDoc;
27 import java.util.GregorianCalendar JavaDoc;
28 import java.util.HashMap JavaDoc;
29 import java.util.Iterator JavaDoc;
30 import java.util.Map JavaDoc;
31
32 import javax.jcr.RepositoryException;
33 import javax.servlet.http.HttpServletRequest JavaDoc;
34 import javax.servlet.http.HttpServletResponse JavaDoc;
35 import javax.servlet.jsp.JspException JavaDoc;
36 import javax.servlet.jsp.tagext.TagSupport JavaDoc;
37
38 import org.apache.commons.lang.StringUtils;
39 import org.apache.commons.lang.exception.NestableRuntimeException;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43
44 /**
45  * Quick way to send a mail
46  * @author Fabrizio Giustina
47  * @version $Revision: 6484 $ ($Author: philipp $)
48  */

49 public class SimpleMailTag extends TagSupport JavaDoc {
50
51     /**
52      * Stable serialVersionUID.
53      */

54     private static final long serialVersionUID = 222L;
55
56     private String JavaDoc nodeCollectionName = "mainColumnParagraphs";
57
58     private String JavaDoc from;
59
60     private String JavaDoc to;
61
62     private String JavaDoc cc;
63
64     private String JavaDoc bcc;
65
66     private String JavaDoc replyTo;
67
68     private String JavaDoc subject;
69
70     private String JavaDoc redirect;
71
72     private String JavaDoc type;
73     
74     /**
75      * Alternatively to the type you can use a template to render the email dynamically.
76      */

77     private String JavaDoc template;
78
79     /**
80      * log the mails
81      */

82     private boolean logging;
83
84     /**
85      * encoding of the log file
86      */

87     private String JavaDoc loggingEncoding = "UTF8";
88
89     /**
90      * directory to place the log files
91      */

92     private String JavaDoc loggingDirectory = "/mailtracking";
93
94     /**
95      * The extension for the log files
96      */

97     private String JavaDoc loggingExtension = "log";
98     
99     /**
100      * Name of the file. Prefix only.
101      */

102     private String JavaDoc loggingFilename;
103     
104     /**
105      * Logger.
106      */

107     private static Logger log = LoggerFactory.getLogger(SimpleMailTag.class);
108
109     /**
110      * Setter for <code>bcc</code>.
111      * @param bcc The bcc to set.
112      */

113     public void setBcc(String JavaDoc bcc) {
114         this.bcc = bcc;
115     }
116     
117     /**
118      * Setter for <code>replyTo</code>.
119      * @param replyTo The replyTo to set.
120      */

121     public void setReplyTo(String JavaDoc replyTo) {
122         this.replyTo = replyTo;
123     }
124
125     /**
126      * Setter for <code>cc</code>.
127      * @param cc The cc to set.
128      */

129     public void setCc(String JavaDoc cc) {
130         this.cc = cc;
131     }
132
133     /**
134      * Setter for <code>from</code>.
135      * @param from The from to set.
136      */

137     public void setFrom(String JavaDoc from) {
138         this.from = from;
139     }
140
141     /**
142      * Setter for <code>nodeCollectionName</code>.
143      * @param nodeCollectionName The nodeCollectionName to set.
144      */

145     public void setNodeCollectionName(String JavaDoc nodeCollectionName) {
146         this.nodeCollectionName = nodeCollectionName;
147     }
148
149     /**
150      * Setter for <code>to</code>.
151      * @param to The to to set.
152      */

153     public void setTo(String JavaDoc to) {
154         this.to = to;
155     }
156
157     /**
158      * Setter for <code>subject</code>.
159      * @param subject The subject to set.
160      */

161     public void setSubject(String JavaDoc subject) {
162         this.subject = subject;
163     }
164
165     /**
166      * Setter for <code>redirect</code>.
167      * @param redirect The redirect to set.
168      */

169     public void setRedirect(String JavaDoc redirect) {
170         this.redirect = redirect;
171     }
172
173     /**
174      * Setter for <code>type</code>.
175      * @param type The type to set.
176      */

177     public void setType(String JavaDoc type) {
178         this.type = type;
179     }
180     
181     public void setLogging(boolean trackMail) {
182         this.logging = trackMail;
183     }
184
185     
186     public String JavaDoc getTemplate() {
187         return template;
188     }
189
190     
191     public void setTemplate(String JavaDoc template) {
192         this.template = template;
193     }
194
195
196     /**
197      * @see javax.servlet.jsp.tagext.TagSupport#doEndTag()
198      */

199     public int doEndTag() throws JspException JavaDoc {
200
201         HttpServletRequest JavaDoc request = (HttpServletRequest JavaDoc) pageContext.getRequest();
202
203         StringBuffer JavaDoc body = new StringBuffer JavaDoc(); // build and send email
204

205         // tracking mail: Excel friendly csv format
206
StringBuffer JavaDoc mailTitles = new StringBuffer JavaDoc();
207         StringBuffer JavaDoc mailValues = new StringBuffer JavaDoc();
208         // timestamp
209
mailValues.append(DateFormat.getDateTimeInstance().format(new Date(System.currentTimeMillis()))).append(';');
210         
211         if(nodeCollectionName == null){
212             this.nodeCollectionName = Resource.getLocalContentNodeCollectionName(request);
213         }
214         
215         Content activePage = Resource.getActivePage(request);
216         Content fieldsNode = null;
217         Iterator JavaDoc it;
218         try {
219             Content localContentNode = Resource.getLocalContentNode(request);
220             if(localContentNode != null && localContentNode.hasContent(nodeCollectionName)){
221                 fieldsNode = localContentNode.getContent(nodeCollectionName);
222             }
223             else{
224                 fieldsNode = activePage.getContent(nodeCollectionName);
225             }
226             it = fieldsNode.getChildren().iterator();
227         }
228         catch (RepositoryException e) {
229             throw new NestableRuntimeException(e);
230         }
231
232         while (it.hasNext()) {
233             Content node = (Content) it.next();
234             String JavaDoc[] values = request.getParameterValues("field_" + node.getName());
235             if (values == null) {
236                 values = request.getParameterValues(node.getName());
237             }
238             if (values != null) {
239                 body.append(node.getNodeData("title").getString()).append('\n');
240                 mailTitles.append(excelCSVFormat(node.getNodeData("title").getString())).append(';');
241                 StringBuffer JavaDoc csvValue = new StringBuffer JavaDoc();
242                 for (int i = 0; i < values.length; i++) {
243                     body.append(values[i]).append('\n');
244                     csvValue.append(values[i]);
245                     if(i < values.length-1){
246                         csvValue.append('\n');
247                     }
248                 }
249                 mailValues.append(excelCSVFormat(csvValue.toString())).append(';');
250                 body.append("\n");
251             }
252         }
253
254         if(logging){
255             trackMail(request, activePage.getHandle(), mailTitles, mailValues);
256         }
257         
258         String JavaDoc mailType = type;
259         if (StringUtils.isEmpty(mailType)) {
260             mailType = MailConstants.MAIL_TEMPLATE_TEXT;
261         }
262
263         MgnlEmail email;
264         try {
265             // TODO: avoid those kinds of redundacies in the mail system
266
if(StringUtils.isEmpty(template)){
267                 email = MgnlMailFactory.getInstance().getEmailFromType(mailType);
268                 email.setBody(body.toString(), null);
269             }
270             else{
271                 Map JavaDoc parameters = new HashMap JavaDoc(request.getParameterMap());
272                 parameters.put("all", body.toString());
273                 email = MgnlMailFactory.getInstance().getEmailFromTemplate(template, parameters);
274             }
275             email.setToList(to);
276             email.setCcList(cc);
277             email.setBccList(bcc);
278             email.setReplyToList(replyTo);
279             email.setFrom(from);
280             email.setSubject(subject);
281             MgnlMailFactory.getInstance().getEmailHandler().prepareAndSendMail(email);
282         }
283         catch (Exception JavaDoc e) {
284             // you may want to warn the user redirecting him to a different page...
285
log.error(e.getMessage(), e);
286         }
287
288         if (StringUtils.isNotEmpty(redirect)) {
289             HttpServletResponse JavaDoc response = (HttpServletResponse JavaDoc) pageContext.getResponse();
290             try {
291                 response.sendRedirect(request.getContextPath() + redirect);
292             }
293             catch (IOException JavaDoc e) {
294                 // should never happen
295
log.error(e.getMessage(), e);
296             }
297         }
298         release();
299         return super.doEndTag();
300     }
301
302     protected String JavaDoc excelCSVFormat(String JavaDoc str) {
303         if(!StringUtils.containsNone(str, "\n;")){
304             return "\"" + StringUtils.replace(str, "\"","\"\"") + "\"";
305         }
306         return str;
307     }
308     
309     protected void trackMail(HttpServletRequest JavaDoc request, String JavaDoc activePagePath, StringBuffer JavaDoc titles, StringBuffer JavaDoc values){
310         String JavaDoc fileName = this.getLoggingFilename();
311         if(StringUtils.isEmpty(fileName)){
312             activePagePath = StringUtils.removeStart(activePagePath, "/");
313             fileName = StringUtils.replace(activePagePath, "/", "_");
314         }
315         
316         fileName = fileName + "_" + new GregorianCalendar JavaDoc().get(GregorianCalendar.WEEK_OF_YEAR) + "." + getLoggingExtension();
317         String JavaDoc folder = pageContext.getServletContext().getRealPath(this.getLoggingDirectory());
318         
319         synchronized (ExclusiveWrite.getInstance()) {
320             new File JavaDoc(folder).mkdirs();
321             
322             File JavaDoc file = new File JavaDoc(folder + File.separator + fileName);
323             boolean exists = file.exists();
324             
325             
326             try {
327                 FileOutputStream JavaDoc out = new FileOutputStream JavaDoc(file, true);
328                 if(!exists){
329                     out.write("Timestamp;".toString().getBytes(this.getLoggingEncoding()));
330                     titles.replace(titles.length()-1, titles.length(), "\n");
331                     out.write(titles.toString().getBytes(this.getLoggingEncoding()));
332                 }
333                 values.replace(values.length()-1, values.length(), "\n");
334                 out.write(values.toString().getBytes(this.getLoggingEncoding()));
335                 out.flush();
336                 out.close();
337                 
338             } catch (Exception JavaDoc e) {
339                 log.error("Exception while tracking mail", e);
340             }
341         }
342     }
343
344     /**
345      * @see javax.servlet.jsp.tagext.TagSupport#release()
346      */

347     public void release() {
348         this.nodeCollectionName = null;
349         this.to = null;
350         this.from = null;
351         this.cc = null;
352         this.bcc = null;
353         this.subject = null;
354         this.type = null;
355         this.template = null;
356         super.release();
357     }
358
359     
360     public String JavaDoc getLoggingDirectory() {
361         return loggingDirectory;
362     }
363
364     
365     public void setLoggingDirectory(String JavaDoc loggingDirectory) {
366         this.loggingDirectory = loggingDirectory;
367     }
368
369     
370     public String JavaDoc getLoggingEncoding() {
371         return loggingEncoding;
372     }
373
374     
375     public void setLoggingEncoding(String JavaDoc loggingEncoding) {
376         this.loggingEncoding = loggingEncoding;
377     }
378
379     
380     public boolean isLogging() {
381         return logging;
382     }
383
384     public void setLoggingExtension(String JavaDoc loggingExtension) {
385         this.loggingExtension = loggingExtension;
386     }
387
388     public String JavaDoc getLoggingExtension() {
389         return loggingExtension;
390     }
391
392     public void setLoggingFilename(String JavaDoc loggingFilename) {
393         this.loggingFilename = loggingFilename;
394     }
395
396     public String JavaDoc getLoggingFilename() {
397         return loggingFilename;
398     }
399
400
401 }
402
Popular Tags