KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > info > magnolia > cms > mail > MgnlMailFactory


1 package info.magnolia.cms.mail;
2
3 import info.magnolia.cms.beans.config.ContentRepository;
4 import info.magnolia.cms.beans.config.ObservedManager;
5 import info.magnolia.cms.core.Content;
6 import info.magnolia.cms.core.HierarchyManager;
7 import info.magnolia.cms.core.NodeData;
8 import info.magnolia.cms.mail.handlers.MgnlMailHandler;
9 import info.magnolia.cms.mail.templates.MailAttachment;
10 import info.magnolia.cms.mail.templates.MgnlEmail;
11 import info.magnolia.cms.mail.templates.impl.FreemarkerEmail;
12 import info.magnolia.cms.mail.templates.impl.HtmlEmail;
13 import info.magnolia.cms.mail.templates.impl.MagnoliaEmail;
14 import info.magnolia.cms.mail.templates.impl.SimpleEmail;
15 import info.magnolia.cms.mail.templates.impl.VelocityEmail;
16 import info.magnolia.cms.util.FactoryUtil;
17
18 import java.net.URL JavaDoc;
19 import java.util.ArrayList JavaDoc;
20 import java.util.Collection JavaDoc;
21 import java.util.Hashtable JavaDoc;
22 import java.util.Iterator JavaDoc;
23 import java.util.List JavaDoc;
24 import java.util.Map JavaDoc;
25 import java.util.Properties JavaDoc;
26
27 import javax.mail.Authenticator JavaDoc;
28 import javax.mail.PasswordAuthentication JavaDoc;
29 import javax.mail.Session JavaDoc;
30
31 import org.apache.commons.lang.StringUtils;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34
35
36 /**
37  * This reads the repository to know what kind of email to instanciate
38  * @author <a HREF="mailto:niko@macnica.com">Nicolas Modrzyk</a>
39  */

40 public class MgnlMailFactory extends ObservedManager {
41
42     protected static final String JavaDoc MAIL_FROM = "from";
43
44     protected static final String JavaDoc MAIL_SUBJECT = "subject";
45
46     protected static final String JavaDoc MAIL_BODY = "body";
47
48     protected static final String JavaDoc EMAIL = "email";
49
50     protected static final String JavaDoc SMTP_SERVER = "smtpServer";
51
52     protected static final String JavaDoc SMTP_PORT = "smtpPort";
53
54     protected static final String JavaDoc SMTP_USER = "smtpUser";
55
56     protected static final String JavaDoc SMTP_PASSWORD = "smtpPassword";
57
58     protected static final String JavaDoc SMTP_AUTH = "smtpAuth";
59
60     protected static final String JavaDoc SMTP_DEFAULT_HOST = "127.0.0.1";
61
62     protected static final String JavaDoc SMTP_DEFAULT_PORT = "25";
63
64     protected static final String JavaDoc SMTP_SEND_PARTIAL = "smtpSendPartial";
65
66     protected static final String JavaDoc MAIL_TYPE = "type";
67
68     protected static final String JavaDoc MAIL_ATTACHMENT = "attachment";
69
70     private static Logger log = LoggerFactory.getLogger(MgnlMailFactory.class);
71
72     private static MgnlMailFactory factory = new MgnlMailFactory();
73
74     protected Map JavaDoc mailParameters;
75
76     private List JavaDoc templates;
77
78     private static Class JavaDoc mailHandlerClass;
79
80     private String JavaDoc templatePath;
81
82     private MgnlMailFactory() {
83         mailHandlerClass = info.magnolia.cms.mail.handlers.MgnlMailHandler.class;
84         this.mailParameters = new Hashtable JavaDoc();
85         this.templates = new ArrayList JavaDoc();
86     }
87
88     public static MgnlMailFactory getInstance() {
89         return factory;
90     }
91
92     public MgnlMailHandler getEmailHandler() {
93         return (MgnlMailHandler) FactoryUtil.getSingleton(mailHandlerClass);
94     }
95
96     /**
97      * Data is fetch into the repository to get the different parameters of the email
98      * @param id the id to find under the template section of the repository
99      * @return a new <code>MgnlMail</code> instance, with the template set
100      * @throws Exception if fails
101      */

102     public MgnlEmail getEmailFromTemplate(String JavaDoc id, Map JavaDoc map) throws Exception JavaDoc {
103         if (id == null) {
104             return new SimpleEmail(getSession());
105         }
106         HierarchyManager hm = ContentRepository.getHierarchyManager(ContentRepository.CONFIG);
107         String JavaDoc nodeTemplatePath = templatePath + "/" + id;
108         if (!hm.isExist(nodeTemplatePath)) {
109             throw new MailException("Template:[" + id + "] configuration was not found in repository");
110         }
111
112         Content node = hm.getContent(nodeTemplatePath);
113
114         // type
115
NodeData typeNode = node.getNodeData(MAIL_TYPE);
116         String JavaDoc type = typeNode.getValue().getString();
117
118         MgnlEmail mail = getEmailFromType(type);
119
120         // body
121
NodeData bodyNode = node.getNodeData(MAIL_BODY);
122         String JavaDoc body = bodyNode.getValue().getString();
123         mail.setBodyFromResourceFile(body, map);
124
125         // from
126
NodeData fromNode = node.getNodeData(MAIL_FROM);
127         String JavaDoc from = fromNode.getValue().getString();
128         mail.setFrom(from);
129
130         // subject
131
NodeData subjectNode = node.getNodeData(MAIL_SUBJECT);
132         String JavaDoc subject = subjectNode.getValue().getString();
133         mail.setSubject(subject);
134
135         String JavaDoc attachNodePath = node.getHandle() + "/" + MAIL_ATTACHMENT;
136         if (hm.isExist(attachNodePath)) {
137             Content attachments = hm.getContent(attachNodePath);
138             Collection JavaDoc atts = attachments.getChildren();
139             Iterator JavaDoc iter = atts.iterator();
140             while (iter.hasNext()) {
141                 Content att = (Content) iter.next();
142                 String JavaDoc cid = att.getNodeData("cid").getString();
143                 String JavaDoc url = att.getNodeData("url").getString();
144                 MailAttachment a = new MailAttachment(new URL JavaDoc(url), cid);
145                 mail.addAttachment(a);
146             }
147         }
148
149         // parameters
150
mail.setParameters(map);
151
152         return mail;
153     }
154
155     protected void onRegister(Content node) {
156         if (node.getHandle().endsWith("templates")) {
157             log.info("Loading mail templates from node:" + node.getHandle());
158             templates = listTemplatesFromRepository(node);
159         }
160         else if (node.getHandle().endsWith("smtp")) {
161             log.info("Loading mail smptp settings from node:" + node.getHandle());
162             initMailParameter(node);
163         }
164
165     }
166
167     protected void onClear() {
168         log.info("Clearing mail parameters");
169         this.templates.clear();
170         this.mailParameters.clear();
171     }
172
173     /**
174      * Return an instance of the mail type, given a string description.
175      * @param type the type of the email as defined in <code>MailConstants</code>
176      * @return a new <code>MgnlEmail</code> instance, template is not set.
177      * @throws Exception if fails
178      */

179     public MgnlEmail getEmailFromType(String JavaDoc type) throws Exception JavaDoc {
180         if (type.equalsIgnoreCase(MailConstants.MAIL_TEMPLATE_VELOCITY)) {
181             return new VelocityEmail(getSession());
182         }
183         else if (type.equalsIgnoreCase(MailConstants.MAIL_TEMPLATE_HTML)) {
184             return new HtmlEmail(getSession());
185         }
186         else if (type.equalsIgnoreCase(MailConstants.MAIL_TEMPLATE_FREEMARKER)) {
187             return new FreemarkerEmail(getSession());
188         }
189         else if (type.equalsIgnoreCase(MailConstants.MAIL_TEMPLATE_MAGNOLIA)) {
190             return new MagnoliaEmail(getSession());
191         }
192         else {
193             return new SimpleEmail(getSession());
194         }
195     }
196
197     public List JavaDoc listTemplates() {
198         return this.templates;
199     }
200
201     /**
202      * List the templates stored in the repository
203      * @return <code>ArrayList</code> of <code>String</code> containing the template name
204      */

205     private ArrayList JavaDoc listTemplatesFromRepository(Content templatesNode) {
206         ArrayList JavaDoc list = new ArrayList JavaDoc();
207         this.templatePath = templatesNode.getHandle();
208         try {
209             Iterator JavaDoc iter = templatesNode.getChildren().iterator();
210             while (iter.hasNext()) {
211                 Content temp = (Content) iter.next();
212                 String JavaDoc templateName = temp.getName();
213                 log.info("Loading template:" + templateName);
214                 list.add(templateName);
215             }
216         }
217         catch (Exception JavaDoc e) {
218             log.error("Error while listing templates", e);
219         }
220
221         return list;
222     }
223
224     public void setMailParameters(Map JavaDoc _mailParameters) {
225         this.mailParameters = _mailParameters;
226     }
227
228     public Map JavaDoc getMailParameters() {
229         return this.mailParameters;
230     }
231
232     public Session JavaDoc getSession() {
233         Properties JavaDoc props = new Properties JavaDoc(); // System.getProperties(); should I try to use the system properties ?
234
props.put("mail.smtp.host", this.mailParameters.get(SMTP_SERVER));
235         props.put("mail.smtp.port", this.mailParameters.get(SMTP_PORT));
236         Authenticator JavaDoc auth = null;
237         if (Boolean.valueOf((String JavaDoc) this.mailParameters.get(SMTP_AUTH)).booleanValue()) {
238             props.put("mail.smtp.auth", "true");
239             props.put("mail.smtp.user", this.mailParameters.get(SMTP_USER));
240             auth = new Authenticator JavaDoc() {
241
242                 protected PasswordAuthentication JavaDoc getPasswordAuthentication() {
243                     return new PasswordAuthentication JavaDoc(
244                         (String JavaDoc) MgnlMailFactory.this.mailParameters.get(SMTP_USER),
245                         (String JavaDoc) MgnlMailFactory.this.mailParameters.get(SMTP_PASSWORD));
246                 }
247             };
248         }
249         props.put("mail.smtp.sendpartial", StringUtils.defaultString((String JavaDoc) this.mailParameters
250             .get(SMTP_SEND_PARTIAL)));
251         return Session.getInstance(props, auth);
252     }
253
254     protected void initMailParameter(Content node) {
255         initParam(node, SMTP_SERVER, SMTP_DEFAULT_HOST);
256         initParam(node, SMTP_PORT, SMTP_DEFAULT_PORT);
257         initParam(node, SMTP_USER, StringUtils.EMPTY);
258         initParam(node, SMTP_PASSWORD, StringUtils.EMPTY);
259         initParam(node, SMTP_AUTH, StringUtils.EMPTY);
260         initParam(node, SMTP_SEND_PARTIAL, StringUtils.EMPTY);
261     }
262
263     /**
264      * Method to init a stmp parameter
265      */

266     protected void initParam(Content configNode, String JavaDoc paramName, String JavaDoc defaultValue) {
267         String JavaDoc value = configNode.getNodeData(paramName).getString();
268         if (!StringUtils.isEmpty(value)) {
269             log.info("Init param[{}] with value:[{}]", paramName, value);
270             initParam(paramName, value);
271         }
272         else {
273             log.info("Init param[{}] with value:[{}] (default)", paramName, defaultValue);
274             initParam(paramName, defaultValue);
275         }
276     }
277
278     protected void initParam(String JavaDoc paramName, String JavaDoc paramValue) {
279         this.mailParameters.put(paramName, paramValue);
280     }
281
282     /**
283      * convert email address mapping<br>
284      * <code>user-</code> will be replace by the email address of the user as stored in the user repository
285      * <code>group-</code> will
286      */

287     public String JavaDoc convertEmailList(String JavaDoc mailTo) {
288         StringBuffer JavaDoc ret = new StringBuffer JavaDoc();
289         if(StringUtils.isEmpty(mailTo)){
290             return "";
291         }
292         
293         String JavaDoc[] list = mailTo.split(";");
294         if (list == null) {
295             return "";
296         }
297         for (int i = 0; i < list.length; i++) { // for each item
298
String JavaDoc userName = list[i];
299             if (i != 0) {
300                 ret.append("\n");
301             }
302             if (userName.startsWith(MailConstants.PREFIX_USER)) {
303                 userName = StringUtils.removeStart(userName, MailConstants.PREFIX_USER);
304                 if (log.isDebugEnabled()) {
305                     log.debug("username =" + userName);
306                 }
307                 ret.append(getUserMail(userName));
308             }
309             else if (userName.startsWith(MailConstants.PREFIX_GROUP)) {
310
311             }
312             else if (userName.startsWith(MailConstants.PREFIX_ROLE)) {
313
314             }
315             else {
316                 // none of the above, just add the mail to the list
317
ret.append(userName);
318             }
319
320         }
321         return ret.toString();
322     }
323
324     /**
325      * retrieve email address fo user
326      * @param userName
327      * @return the email of the user as stored in the repository, if not found returns the parameter userName
328      */

329     public String JavaDoc getUserMail(String JavaDoc userName) {
330         try {
331             HierarchyManager hm = ContentRepository.getHierarchyManager(ContentRepository.USERS);
332             Content user = hm.getContent(userName);
333             if (user != null) {
334                 return user.getNodeData(EMAIL).getValue().getString();
335             }
336         }
337         catch (Exception JavaDoc e) {
338             log.error("can not get user email info.");
339         }
340         return userName;
341     }
342 }
343
Popular Tags