001: /*
002: * Copyright 2005 Sun Microsystems, Inc. All rights reserved.
003: *
004: * Redistribution and use in source and binary forms, with or without
005: * modification, are permitted provided that the following conditions
006: * are met:
007: *
008: * - Redistributions of source code must retain the above copyright
009: * notice, this list of conditions and the following disclaimer.
010: *
011: * - Redistribution in binary form must reproduce the above copyright
012: * notice, this list of conditions and the following disclaimer in
013: * the documentation and/or other materials provided with the
014: * distribution.
015: *
016: * Neither the name of Sun Microsystems, Inc. or the names of
017: * contributors may be used to endorse or promote products derived
018: * from this software without specific prior written permission.
019: *
020: * This software is provided "AS IS," without a warranty of any
021: * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
022: * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
023: * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
024: * EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES
025: * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
026: * DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN
027: * OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR
028: * FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR
029: * PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF
030: * LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE,
031: * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
032: *
033: * You acknowledge that Software is not designed, licensed or intended
034: * any nuclear facility.
035: */
036:
037: package com.sun.portal.community.notification.impl;
038:
039: import java.util.Date;
040: import java.util.Set;
041: import java.util.HashSet;
042: import java.util.Iterator;
043: import java.util.Properties;
044: import java.util.logging.Logger;
045: import java.util.logging.LogRecord;
046: import java.util.logging.Level;
047:
048: import javax.servlet.http.HttpServletRequest;
049:
050: import javax.mail.Session;
051: import javax.mail.Message;
052: import javax.mail.Transport;
053: import javax.mail.MessagingException;
054: import javax.mail.Authenticator;
055:
056: import javax.mail.internet.MimeMessage;
057: import javax.mail.internet.InternetAddress;
058: import javax.mail.internet.AddressException;
059:
060: import com.sun.portal.log.common.PortalLogger;
061:
062: import com.sun.portal.community.CommunityUser;
063: import com.sun.portal.community.CommunityException;
064:
065: import com.sun.portal.community.impl.CommunityProperties;
066: import com.sun.portal.community.impl.CommunityUserImpl;
067:
068: import com.sun.portal.community.notification.Notification;
069: import com.sun.portal.community.notification.NotificationException;
070: import com.sun.portal.community.notification.Notifier;
071:
072: public class JavaMailNotifierImpl implements Notifier {
073:
074: private Session _session = null;
075: private InternetAddress _defaultSenderAddr = null;
076:
077: private static Logger logger = PortalLogger
078: .getLogger(JavaMailNotifierImpl.class);
079:
080: public void init() throws NotificationException {
081:
082: CommunityProperties cProps = CommunityProperties.getInstance();
083:
084: // load JavaMail authenticator class (if any)
085: Authenticator auth = null;
086: String authClassname = cProps.getJMAuthClass();
087: if (authClassname != null && authClassname.length() > 0) {
088: auth = loadAuthenticator(authClassname);
089: }
090:
091: // load JavaMail properties
092: Properties jmProps = cProps.getJMProperties();
093:
094: // get JavaMail session
095: _session = Session.getInstance(jmProps, auth);
096:
097: // set default sender addr
098: try {
099: _defaultSenderAddr = new InternetAddress(cProps
100: .getJMDefaultSenderAddr());
101: } catch (AddressException ae) {
102: throw new NotificationException(
103: "JavaMailNotifier.init(): Failed to set up default sender address",
104: ae);
105: }
106: }
107:
108: public void send(HttpServletRequest request,
109: Notification notification) throws NotificationException {
110:
111: if (logger.isLoggable(Level.INFO)) {
112: logger.log(Level.INFO, "PSCPM_CSPCNI00004", notification
113: .toString());
114: }
115:
116: //
117: // create message
118: //
119: Message msg = null;
120: try {
121: msg = getMessage(notification, request);
122: } catch (MessagingException me) {
123: throw new NotificationException(
124: "JavaMailNotification.send(): Failed while constructing message. ",
125: me);
126: }
127:
128: //
129: // send message
130: //
131: try {
132: Transport.send(msg);
133: } catch (MessagingException me) {
134: throw new NotificationException(
135: "JavaMailNotification.send(): Failed to transport message. ",
136: me);
137: }
138: }
139:
140: protected Message getMessage(Notification notification,
141: HttpServletRequest req) throws NotificationException,
142: MessagingException {
143:
144: MimeMessage msg = new MimeMessage(_session);
145:
146: // from
147: String sender = getEmailAddress(notification.getSender(), req);
148: InternetAddress senderAddr = null;
149: if (sender != null && sender.length() > 0) {
150: try {
151: senderAddr = new InternetAddress(sender);
152: } catch (AddressException ae) {
153: // failed to retrieve/parse sender email addr.
154: // use system default and log it
155: senderAddr = _defaultSenderAddr;
156: if (logger.isLoggable(Level.INFO)) {
157: logRecord(logger, Level.INFO, "PSCPM_CSPCNI00002",
158: ae, new Object[] {
159: notification.getType().toString(),
160: notification.getSender(),
161: _defaultSenderAddr });
162: }
163: }
164: } else {
165: // sender address not found.
166: // use system default and log it
167: senderAddr = _defaultSenderAddr;
168: if (logger.isLoggable(Level.INFO)) {
169: logger.log(Level.INFO, "PSCPM_CSPCNI00001",
170: new Object[] {
171: notification.getType().toString(),
172: notification.getSender(),
173: _defaultSenderAddr });
174: }
175: }
176: msg.setFrom(senderAddr);
177:
178: // to
179: Set addrSet = new HashSet();
180: for (Iterator i = notification.getRecipients().iterator(); i
181: .hasNext();) {
182: String recipient = (String) i.next();
183: String addr = getEmailAddress(recipient, req);
184: if (addr != null) {
185: addrSet.add(new InternetAddress(addr));
186: } else {
187: // recipient address not found. skip and log it
188: if (logger.isLoggable(Level.INFO)) {
189: logger.log(Level.INFO, "PSCPM_CSPCNI00003",
190: new Object[] {
191: notification.getType().toString(),
192: recipient, _defaultSenderAddr });
193: }
194: }
195: }
196: InternetAddress[] addrs = new InternetAddress[addrSet.size()];
197: addrSet.toArray(addrs);
198: msg.setRecipients(Message.RecipientType.TO, addrs);
199:
200: // subject/message
201: msg.setSubject(notification.getSubject());
202: msg.setText(notification.getMessage(), "UTF-8");
203:
204: // date
205: msg.setSentDate(new Date());
206:
207: return msg;
208: }
209:
210: protected String getEmailAddress(String userId,
211: HttpServletRequest req) throws NotificationException {
212:
213: String emailAddr = null;
214: try {
215: CommunityUser cu = new CommunityUserImpl(req, userId);
216: emailAddr = cu.getEmailAddr();
217: } catch (CommunityException ce) {
218: throw new NotificationException(
219: "JavaMailNotifierImpl.getEmailAddress(): failed to retrieve user's email addr. userId="
220: + userId, ce);
221: }
222:
223: return emailAddr;
224: }
225:
226: protected Authenticator loadAuthenticator(String authClassname)
227: throws NotificationException {
228:
229: Authenticator auth = null;
230:
231: try {
232: auth = (Authenticator) Class.forName(authClassname)
233: .newInstance();
234: } catch (ClassNotFoundException cnfe) {
235: throw new NotificationException(
236: "JavaMailNotifier.loadAuthenticator(): Failed to load Authenticator="
237: + authClassname, cnfe);
238: } catch (InstantiationException ie) {
239: throw new NotificationException(
240: "JavaMailNotifier.loadAuthenticator(): Failed to load Authenticator="
241: + authClassname, ie);
242: } catch (IllegalAccessException iae) {
243: throw new NotificationException(
244: "JavaMailNotifier.loadAuthenticator(): Failed to load Authenticator="
245: + authClassname, iae);
246: }
247:
248: return auth;
249: }
250:
251: public void logRecord(Logger logger, Level level, String msgKey,
252: Throwable th, Object[] parameters) {
253: LogRecord logRecord = new LogRecord(level, msgKey);
254: logRecord.setLoggerName(logger.getName());
255: logRecord.setThrown(th);
256: logRecord.setParameters(parameters);
257: logger.log(logRecord);
258: }
259:
260: }
|