KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > info > magnolia > cms > mail > servlets > MgnlMailServlet


1 package info.magnolia.cms.mail.servlets;
2
3 import info.magnolia.cms.beans.runtime.Document;
4 import info.magnolia.cms.beans.runtime.MultipartForm;
5 import info.magnolia.cms.mail.MailConstants;
6 import info.magnolia.cms.mail.MgnlMailFactory;
7 import info.magnolia.cms.mail.commands.MailCommand;
8 import info.magnolia.cms.mail.templates.MailAttachment;
9 import info.magnolia.cms.servlets.ContextSensitiveServlet;
10 import info.magnolia.cms.util.RequestFormUtil;
11 import info.magnolia.context.Context;
12 import info.magnolia.context.MgnlContext;
13
14 import java.io.ByteArrayInputStream JavaDoc;
15 import java.io.IOException JavaDoc;
16 import java.io.PrintWriter JavaDoc;
17 import java.util.HashMap JavaDoc;
18 import java.util.Iterator JavaDoc;
19 import java.util.List JavaDoc;
20 import java.util.Properties JavaDoc;
21
22 import javax.servlet.ServletException JavaDoc;
23 import javax.servlet.http.HttpServletRequest JavaDoc;
24 import javax.servlet.http.HttpServletResponse JavaDoc;
25
26 import org.apache.commons.lang.StringUtils;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29
30
31 /**
32  * Servlet to send email using the email module. Date: Mar 31, 2006 Time: 10:12:45 AM
33  * @author <a HREF="mailto:niko@macnica.com">Nicolas Modrzyk</a>
34  */

35 public class MgnlMailServlet extends ContextSensitiveServlet {
36
37     /**
38      * Stable serialVersionUID.
39      */

40     private static final long serialVersionUID = 222L;
41
42     static Logger log = LoggerFactory.getLogger(MgnlMailServlet.class);
43
44     private static final String JavaDoc TYPE = "type";
45
46     private static final String JavaDoc SUBJECT = "subject";
47
48     private static final String JavaDoc FROM = "from";
49
50     private static final String JavaDoc TEXT = "text";
51
52     private static final String JavaDoc TORECIPIENTS = "torecipients";
53
54     private static final String JavaDoc CCRECIPIENTS = "ccrecipients";
55
56     private static final String JavaDoc PARAMETERS = "parameters";
57
58     private static final String JavaDoc FILE = "file";
59
60     private static final String JavaDoc TEMPLATE = "template";
61
62     private static final String JavaDoc ATT_ID = "att";
63
64     private static final String JavaDoc ACTION = "action";
65
66     private static final String JavaDoc HTML_TEXT_AREA = "textarea";
67
68     private static final String JavaDoc HTML_SMALL_TEXT_AREA = "smalltextarea";
69
70     private static final String JavaDoc HTML_BIG_TEXT_AREA = "bigtextarea";
71
72     private static final String JavaDoc HTML_TEXT = "text";
73
74     private static final String JavaDoc HTML_SELECT = "select";
75
76     private static final String JavaDoc HTML_FILE = "file";
77
78     private static final String JavaDoc NONE = "<none>";
79
80     protected void doPost(HttpServletRequest JavaDoc httpServletRequest, HttpServletResponse JavaDoc httpServletResponse)
81         throws ServletException JavaDoc, IOException JavaDoc {
82         super.doPost(httpServletRequest, httpServletResponse);
83
84         RequestFormUtil request = new RequestFormUtil(httpServletRequest);
85
86         if (request.getParameter(ACTION) == null) {
87             this.doGet(httpServletRequest, httpServletResponse);
88             return;
89         }
90
91         try {
92             // Retrieve the context
93
Context ctx = MgnlContext.getInstance();
94
95             // get any possible attachment
96
MultipartForm form = (MultipartForm) httpServletRequest.getAttribute(MultipartForm.REQUEST_ATTRIBUTE_NAME);
97             Document doc = form.getDocument("file");
98
99             if (doc != null) {
100                 MailAttachment attachment = new MailAttachment(doc.getFile().toURL(), ATT_ID);
101                 ctx.put(MailConstants.ATTRIBUTE_ATTACHMENT, attachment);
102             }
103
104             // add all possible parameters to the context
105
String JavaDoc template = request.getParameter(TEMPLATE);
106             String JavaDoc parameters = request.getParameter(PARAMETERS);
107             String JavaDoc to = request.getParameter(TORECIPIENTS);
108             String JavaDoc cc = request.getParameter(CCRECIPIENTS);
109
110             if (to != null) {
111                 ctx.put(MailConstants.ATTRIBUTE_TO, to);
112             }
113             if (cc != null) {
114                 ctx.put(MailConstants.ATTRIBUTE_CC, cc);
115             }
116
117             // convert optional parameters and add them to the context
118
if (log.isDebugEnabled()) {
119                 log.info(ctx.getAttributes().toString());
120             }
121             HashMap JavaDoc map = convertToMap(parameters);
122             ctx.putAll(map);
123
124             if (isTemplate(template)) {
125                 // this is a template based email, just add the template
126
ctx.put(MailConstants.ATTRIBUTE_TEMPLATE, template);
127             }
128             else {
129                 // this is a static email, add all parameters
130
String JavaDoc type = request.getParameter(TYPE);
131                 String JavaDoc subject = request.getParameter(SUBJECT);
132                 String JavaDoc from = request.getParameter(FROM);
133                 String JavaDoc text = request.getParameter(TEXT);
134
135                 if (type != null) {
136                     ctx.put(MailConstants.ATTRIBUTE_TYPE, type);
137                 }
138                 if (subject != null) {
139                     ctx.put(MailConstants.ATTRIBUTE_SUBJECT, subject);
140                 }
141                 if (from != null) {
142                     ctx.put(MailConstants.ATTRIBUTE_FROM, from);
143                 }
144                 if (text != null) {
145                     ctx.put(MailConstants.ATTRIBUTE_TEXT, text);
146                 }
147             }
148
149             // execute the command
150
MailCommand command = new MailCommand();
151             command.execute(ctx);
152
153             setMessage(false, null, "Mail was sent to " + to, httpServletResponse);
154         }
155         catch (Exception JavaDoc e) {
156             setMessage(true, e, "Error while sending email ", httpServletResponse);
157         }
158         finally {
159             doGet(httpServletRequest, httpServletResponse);
160         }
161     }
162
163     private boolean isTemplate(String JavaDoc template) {
164         return StringUtils.isNotEmpty(template) && (!template.trim().equalsIgnoreCase(NONE));
165     }
166
167     private void setMessage(boolean error, Exception JavaDoc e, String JavaDoc message, HttpServletResponse JavaDoc response)
168         throws IOException JavaDoc {
169         PrintWriter JavaDoc writer = response.getWriter();
170         writer.write("<h1>Message</h1>");
171         if (!error) {
172             writer.write("<p class=\"success\">");
173         }
174         else {
175             writer.write("<p class=\"error\">");
176             e.printStackTrace(writer);
177         }
178         writer.write(message);
179         writer.write("</p>");
180         writer.flush();
181     }
182
183     /**
184      * Convert the string of parameters retrieved from the form into a HashMap.
185      * @param parameters string from the text area of the form
186      * @return <code>HashMap</code>
187      * @throws IOException if fails
188      */

189     private HashMap JavaDoc convertToMap(String JavaDoc parameters) throws IOException JavaDoc {
190         HashMap JavaDoc map = new HashMap JavaDoc();
191         ByteArrayInputStream JavaDoc string = new ByteArrayInputStream JavaDoc(parameters.getBytes());
192         Properties JavaDoc props = new Properties JavaDoc();
193         props.load(string);
194
195         Iterator JavaDoc iter = props.keySet().iterator();
196         while (iter.hasNext()) {
197             String JavaDoc key = (String JavaDoc) iter.next();
198             map.put(key, props.get(key));
199         }
200         log.info(map.toString());
201         return map;
202     }
203
204     /**
205      * CSS portion of the form
206      * @return <code>String</code> containing the CSS portion of the form
207      */

208     private String JavaDoc getServletStyle() {
209         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
210         buffer
211             .append(""
212                 + "<style type=\"text/css\">\n"
213                 + "<!--\n "
214                 + "body { background-color: rgb(255,255,255); color: rgb(0,0,0); margin: 0px 0px; font-size: 10pt ; font-family: verdana}"
215                 + "p.error { font-size: 8pt; color: red; }"
216                 + "p.success { font-size: 8pt; color: green; }"
217                 + "p.comments { font-size: 7pt; }"
218                 + "textArea {color: blue }"
219                 + "input {background-color:white ; font-size: 10pt ; width: 400px}"
220                 + "textarea {background-color:white ; font-size: 10pt ; width: 400px}"
221                 + "table {font-size: 10pt ; width: 90%}"
222                 + "tr {font-size: 10pt}"
223                 + "td {font-size: 10pt}"
224                 + "h1 {font-family: verdana ; font-size : 12pt}"
225                 + "-->\n "
226                 + "</style>"
227                 + "");
228         return buffer.toString();
229     }
230
231     protected void doGet(HttpServletRequest JavaDoc httpServletRequest, HttpServletResponse JavaDoc httpServletResponse)
232         throws ServletException JavaDoc, IOException JavaDoc {
233         super.doGet(httpServletRequest, httpServletResponse);
234         StringBuffer JavaDoc sb = displayForm();
235
236         PrintWriter JavaDoc writer = httpServletResponse.getWriter();
237         writer.write(sb.toString());
238         writer.flush();
239     }
240
241     /**
242      * Display the mail form
243      */

244     private StringBuffer JavaDoc displayForm() {
245         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
246
247         sb.append(getServletStyle());
248         sb.append("<center><h1>Email Servlet</h1></center>");
249
250         sb.append("<form method=\"post\" enctype=\"multipart/form-data\">");
251         sb.append("<input type=\"hidden\" width=\"80%\" name=\"" + ACTION + "\" value=\"action\"/>");
252
253         sb.append("<h1>Options for all emails</h1>");
254
255         sb.append("<table>");
256         addSection("To", TORECIPIENTS, HTML_TEXT, "The main recipients of the email", sb);
257         addSection(
258             "Parameters",
259             PARAMETERS,
260             HTML_TEXT_AREA,
261             "Parameters that can be used when processing the email",
262             sb);
263         addSection(
264             "Template",
265             TEMPLATE,
266             HTML_SELECT,
267             "If a template is set, the type of the mail, the content and subject are retrieved from the repository.<br>"
268                 + "The configuration for template us under the following node (/modules/mail/config/templates)",
269             sb);
270         sb.append("</table>");
271
272         sb.append("<h1>Options for statically defined emails</h1>");
273         sb.append("<table>");
274         addSection("From", FROM, HTML_TEXT, "The sender of the email", sb);
275         addSection("Subject", SUBJECT, HTML_TEXT, "The subject of the email", sb);
276         addSection(
277             "Text",
278             TEXT,
279             HTML_BIG_TEXT_AREA,
280             "The content of the email. Note that this is not used if a template is set",
281             sb);
282         addSection("Cc", CCRECIPIENTS, HTML_TEXT, "The cc recipients of the email", sb);
283         addSection("Attach", FILE, HTML_FILE, "The attachment has a default id of '"
284             + ATT_ID
285             + "'. This is only limited in the servlet", sb);
286         addSection(
287             "Email Type",
288             TYPE,
289             HTML_SELECT,
290             "This define the format of the email. In the future more implementation can be added",
291             sb);
292         sb.append("</table>");
293         sb.append("<center><input type=\"submit\" value=\"send\"/></center>");
294         sb.append("</form>");
295
296         return sb;
297     }
298
299     /**
300      * Factorized code for the form
301      * @param label description of the entry
302      * @param name to use for parameter
303      * @param htmlInputType the type of the input
304      * @param comments if needed for explanations
305      * @param sb the stringbuffer to append the code to
306      * @return the same string buffer as sb, appended with the form section
307      */

308     private StringBuffer JavaDoc addSection(String JavaDoc label, String JavaDoc name, String JavaDoc htmlInputType, String JavaDoc comments, StringBuffer JavaDoc sb) {
309         sb.append("<tr>");
310         sb.append("<td width=\"40%\">").append(label).append(" :</td>");
311         sb.append("<td>");
312         if (htmlInputType.equals(HTML_SMALL_TEXT_AREA)) {
313             sb.append("<textArea cols=\"80\" width=\"80%\"rows=\"2\" name=\"").append(name).append("\"></textArea>");
314         }
315         else if (htmlInputType.equals(HTML_SELECT)) {
316             sb.append(getSelectBox(name));
317         }
318         else if (htmlInputType.equals(HTML_BIG_TEXT_AREA)) {
319             sb.append("<textArea cols=\"80\" width=\"80%\"rows=\"5\" name=\"").append(name).append("\"/></textArea>");
320         }
321         else if (htmlInputType.equals(HTML_TEXT_AREA)) {
322             sb.append("<textArea cols=\"80\" width=\"80%\"rows=\"4\" name=\"").append(name).append("\"/></textArea>");
323         }
324         else if (htmlInputType.equals(HTML_TEXT)) {
325             sb.append("<input type=\"text\" width=\"80%\"cols=\"80\" name=\"").append(name).append("\"/>");
326         }
327         else if (htmlInputType.equals(HTML_FILE)) {
328             sb.append("<input cols=\"80\" width=\"80%\" type=\"file\" name=\"").append(name).append("\"/>");
329         }
330         sb.append("<p class=\"comments\">").append(comments).append("</p>");
331         sb.append("</td>");
332         sb.append("</tr>");
333         return sb;
334     }
335
336     /**
337      * Get an html select box string
338      * @param type <code>TYPE</code> or <code>TEMPLATE</code>
339      * @return html code for select box
340      */

341     private StringBuffer JavaDoc getSelectBox(String JavaDoc type) {
342         if (type.equalsIgnoreCase(TYPE)) {
343             return getMailTypeSelectBox();
344         }
345         else if (type.equalsIgnoreCase(TEMPLATE)) {
346             return getTemplateSelectBox();
347         }
348         else {
349             return new StringBuffer JavaDoc();
350         }
351
352     }
353
354     private StringBuffer JavaDoc getMailTypeSelectBox() {
355         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
356         buffer.append("<select name=\"" + TYPE + "\">");
357         addOption(MailConstants.MAIL_TEMPLATE_TEXT, buffer);
358         addOption(MailConstants.MAIL_TEMPLATE_HTML, buffer);
359         addOption(MailConstants.MAIL_TEMPLATE_VELOCITY, buffer);
360         buffer.append("</select>");
361         return buffer;
362     }
363
364     private void addOption(String JavaDoc option, StringBuffer JavaDoc buffer) {
365         buffer.append("<option value=\"").append(option).append("\">").append(option).append("");
366     }
367
368     private StringBuffer JavaDoc getTemplateSelectBox() {
369         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
370         buffer.append("<select width=\"80%\"");
371         try {
372             List JavaDoc list = MgnlMailFactory.getInstance().listTemplates();
373
374             // if no template, disable
375
if (list.size() == 0) {
376                 buffer.append(" disabled ");
377             }
378             buffer.append(" name=\"" + TEMPLATE + "\">");
379
380             addOption(NONE, buffer);
381             for (int i = 0; i < list.size(); i++) {
382                 String JavaDoc item = (String JavaDoc) list.get(i);
383                 addOption(item, buffer);
384             }
385         }
386         catch (Exception JavaDoc e) {
387             log.error("Error while getting the templates");
388         }
389         buffer.append("</select>");
390         return buffer;
391
392     }
393
394 }
395
Popular Tags