KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > mx4j > tools > mail > SMTP


1 /*
2  * Copyright (C) The MX4J Contributors.
3  * All rights reserved.
4  *
5  * This software is distributed under the terms of the MX4J License version 1.0.
6  * See the terms of the MX4J License in the documentation provided with this software.
7  */

8
9 package mx4j.tools.mail;
10
11 import java.text.DateFormat JavaDoc;
12 import java.util.Date JavaDoc;
13 import java.util.Properties JavaDoc;
14 import javax.mail.Address JavaDoc;
15 import javax.mail.Message JavaDoc;
16 import javax.mail.Session JavaDoc;
17 import javax.mail.Transport JavaDoc;
18 import javax.mail.internet.InternetAddress JavaDoc;
19 import javax.mail.internet.MimeMessage JavaDoc;
20 import javax.management.InstanceNotFoundException JavaDoc;
21 import javax.management.ListenerNotFoundException JavaDoc;
22 import javax.management.MBeanRegistration JavaDoc;
23 import javax.management.MBeanServer JavaDoc;
24 import javax.management.Notification JavaDoc;
25 import javax.management.NotificationFilter JavaDoc;
26 import javax.management.NotificationListener JavaDoc;
27 import javax.management.ObjectName JavaDoc;
28
29 import mx4j.log.Log;
30 import mx4j.log.Logger;
31
32 /**
33  * This MBean is meant to send a mail given certain situation. It may be used to listen to a monitor
34  * or timer and send a mail.
35  * <p/>
36  * To use it you need to add to your classpath the mail.jar from the JavaMail API and the activation.jar
37  * from the Java Activation Framework.
38  * <p/>
39  * Besides you need to configure all the required fields, at least the serverHost and To fields and if your server
40  * requires login also the serverUsername and serverPassword fields
41  * <p/>
42  * The subject and content fields are subject to keyword expansions, i.e. some keyworks put between $ signs will
43  * be exapnded this can be used to give a more informative message. The current available expansions are
44  * <p/>
45  * $date$ -> Current date formatted with locale format
46  * $time$ -> Current tim formatted with locale format
47  * $datetime$ -> Current date and time formatted with locale format
48  * $notification$ -> Notification type
49  * $observed$ -> ObjectName of the observed object
50  * $objectname$ -> This MBean's objectname
51  *
52  * @version $Revision: 1.7 $
53  */

54 public class SMTP implements SMTPMBean, NotificationListener JavaDoc, MBeanRegistration JavaDoc
55 {
56    private MBeanServer JavaDoc server = null;
57    private ObjectName JavaDoc targetMBeanName, objectName;
58    private String JavaDoc notificationName;
59    private Properties JavaDoc sessionProperties = new Properties JavaDoc();
60    private Session JavaDoc session;
61    private String JavaDoc content = "Empty default mail";
62    private String JavaDoc mimeType = "text/plain";
63    private String JavaDoc subject = "Empty Subject";
64    private String JavaDoc fromAddress = "noreply";
65    private String JavaDoc fromName = "MX4J default";
66    private String JavaDoc toAddresses = null;
67    private String JavaDoc ccAddresses = null;
68    private String JavaDoc bccAddresses = null;
69    private String JavaDoc serverHost;
70    private String JavaDoc serverPassword;
71    private String JavaDoc serverUserName;
72    private int serverPort = 25;
73    private int timeout = 10000;
74    private boolean doLogin;
75    private Object JavaDoc sessionLock = new Object JavaDoc();
76
77    public void handleNotification(Notification JavaDoc notification, Object JavaDoc handback)
78    {
79       if (notificationName != null && !notification.getType().equals(notificationName)) return;
80
81       Logger log = getLogger();
82       log.debug("Notification " + notification + " hit, sending message");
83       sendMail();
84    }
85
86    private Logger getLogger()
87    {
88       return Log.getLogger(getClass().getName());
89    }
90
91    public void sendMail()
92    {
93       // send the message in an independet thread not to stop the MBeanServer execution flow
94
new Thread JavaDoc(new Runnable JavaDoc()
95       {
96          public void run()
97          {
98             if (validState())
99             {
100                Logger logger = getLogger();
101
102                synchronized (sessionLock)
103                {
104                   createSession();
105                   try
106                   {
107                      MimeMessage JavaDoc message = new MimeMessage JavaDoc(session);
108                      message.setContent(doKeywordExpansion(content), mimeType);
109                      message.setSubject(doKeywordExpansion(subject));
110
111                      Address JavaDoc from = new InternetAddress JavaDoc(fromAddress, fromName);
112                      message.setFrom(from);
113                      message.setReplyTo(new Address JavaDoc[]{from});
114
115                      if (toAddresses != null)
116                      {
117                         message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddresses));
118                      }
119
120                      if (ccAddresses != null)
121                      {
122                         message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(ccAddresses));
123                      }
124
125                      if (bccAddresses != null)
126                      {
127                         message.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(bccAddresses));
128                      }
129                      Transport JavaDoc transport = session.getTransport("smtp");
130                      if (doLogin)
131                      {
132                         transport.connect(serverHost, serverPort, serverUserName, serverPassword);
133                      }
134                      else
135                      {
136                         transport.connect();
137                      }
138                      message.saveChanges();
139
140                      if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Sending message");
141                      transport.sendMessage(message, message.getAllRecipients());
142                      transport.close();
143                      if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Message sent");
144                   }
145                   catch (Exception JavaDoc e)
146                   {
147                      logger.error("Exception during message sending ", e);
148                   }
149                }
150             }
151          }
152       }).start();
153    }
154
155    private String JavaDoc doKeywordExpansion(String JavaDoc source)
156    {
157       StringBuffer JavaDoc sourceCopy = new StringBuffer JavaDoc();
158       int index = -1;
159       int lastIndex = 0;
160       int length = source.length();
161       while ((index = source.indexOf("$", lastIndex)) > 0)
162       {
163          sourceCopy.append(source.substring(lastIndex, index));
164          if (index >= (length - 1))
165          {
166             break;
167          }
168          lastIndex = ++index;
169          if (source.charAt(index) == '$')
170          {
171             sourceCopy.append('$');
172             lastIndex++;
173          }
174          if (source.startsWith("date$", index))
175          {
176             sourceCopy.append(DateFormat.getDateInstance().format(new Date JavaDoc()));
177             lastIndex += 5;
178          }
179          if (source.startsWith("time$", index))
180          {
181             sourceCopy.append(DateFormat.getTimeInstance().format(new Date JavaDoc()));
182             lastIndex += 5;
183          }
184          if (source.startsWith("datetime$", index))
185          {
186             sourceCopy.append(DateFormat.getDateTimeInstance().format(new Date JavaDoc()));
187             lastIndex += 9;
188          }
189          if (source.startsWith("observed$", index))
190          {
191             if (targetMBeanName != null)
192             {
193                sourceCopy.append(targetMBeanName);
194                lastIndex += 9;
195             }
196          }
197          if (source.startsWith("objectname$", index))
198          {
199             if (objectName != null)
200             {
201                sourceCopy.append(objectName);
202                lastIndex += 11;
203             }
204          }
205          if (source.startsWith("notification$", index))
206          {
207             if (notificationName != null)
208             {
209                sourceCopy.append(notificationName);
210                lastIndex += 13;
211             }
212          }
213       }
214       sourceCopy.append(source.substring(lastIndex, length));
215       return sourceCopy.toString();
216    }
217
218    /**
219     * Sanity check
220     */

221    private boolean validState()
222    {
223       return serverHost != null && toAddresses != null && (!doLogin || (serverUserName != null || serverPassword != null));
224    }
225
226    private void createSession()
227    {
228       synchronized (sessionLock)
229       {
230          if (session == null)
231          {
232             sessionProperties.setProperty("mail.smtp.host", serverHost);
233             sessionProperties.setProperty("mail.smtp.port", Integer.toString(serverPort));
234             sessionProperties.setProperty("mail.smtp.timeout", Integer.toString(timeout));
235             sessionProperties.setProperty("mail.smtp.connectiontimeout", Integer.toString(timeout));
236             sessionProperties.setProperty("mail.smtp.sendpartial", "true");
237             session = Session.getInstance(sessionProperties, null);
238          }
239       }
240    }
241
242    public String JavaDoc getBCC()
243    {
244       return bccAddresses;
245    }
246
247    public void setBCC(String JavaDoc bccAddresses)
248    {
249       this.bccAddresses = bccAddresses;
250    }
251
252    public void setCC(String JavaDoc ccAddresses)
253    {
254       this.ccAddresses = ccAddresses;
255    }
256
257    public String JavaDoc getCC()
258    {
259       return ccAddresses;
260    }
261
262    public String JavaDoc getFromAddress()
263    {
264       return fromAddress;
265    }
266
267    public void setFromAddress(String JavaDoc fromAddress)
268    {
269       this.fromAddress = fromAddress;
270    }
271
272    public void setServerHost(String JavaDoc host)
273    {
274       synchronized (sessionLock)
275       {
276          this.serverHost = host;
277          session = null;
278       }
279    }
280
281    public String JavaDoc getServerHost()
282    {
283       return this.serverHost;
284    }
285
286    public void setServerPort(int port)
287    {
288       synchronized (sessionLock)
289       {
290          this.serverPort = port;
291          session = null;
292       }
293    }
294
295    public int getServerPort()
296    {
297       return this.serverPort;
298    }
299
300    public void setServerUsername(String JavaDoc username)
301    {
302       this.serverUserName = username;
303    }
304
305    public String JavaDoc getServerUsername()
306    {
307       return this.serverUserName;
308    }
309
310    public void setServerPassword(String JavaDoc password)
311    {
312       this.serverPassword = password;
313    }
314
315    public void setLoginToServer(boolean login)
316    {
317       this.doLogin = login;
318    }
319
320    public boolean isLoginToServer()
321    {
322       return this.doLogin;
323    }
324
325    public String JavaDoc getFromName()
326    {
327       return fromName;
328    }
329
330    public void setFromName(String JavaDoc fromName)
331    {
332       this.fromName = fromName;
333    }
334
335    public String JavaDoc getMimeType()
336    {
337       return mimeType;
338    }
339
340    public void setMimeType(String JavaDoc mimeType)
341    {
342       this.mimeType = mimeType;
343    }
344
345    public String JavaDoc getNotificationName()
346    {
347       return notificationName;
348    }
349
350    public void setNotificationName(String JavaDoc notificationName)
351    {
352       this.notificationName = notificationName;
353    }
354
355    public String JavaDoc getSubject()
356    {
357       return subject;
358    }
359
360    public void setSubject(String JavaDoc subject)
361    {
362       this.subject = subject;
363    }
364
365    public String JavaDoc getContent()
366    {
367       return content;
368    }
369
370    public void setContent(String JavaDoc content)
371    {
372       this.content = content;
373    }
374
375    public void setTimeout(int timeout)
376    {
377       synchronized (sessionLock)
378       {
379          this.timeout = timeout;
380          session = null;
381       }
382    }
383
384    public int getTimeout()
385    {
386       return timeout;
387    }
388
389    public void setObservedObject(ObjectName JavaDoc targetMBeanName)
390    {
391       this.targetMBeanName = targetMBeanName;
392       registerListener();
393    }
394
395
396    public ObjectName JavaDoc getObservedObject()
397    {
398       return targetMBeanName;
399    }
400
401    public String JavaDoc getTo()
402    {
403       return toAddresses;
404    }
405
406    public void setTo(String JavaDoc toAddresses)
407    {
408       this.toAddresses = toAddresses;
409    }
410
411    /**
412     * Gathers some basic data
413     */

414    public ObjectName JavaDoc preRegister(MBeanServer JavaDoc server, ObjectName JavaDoc name)
415            throws java.lang.Exception JavaDoc
416    {
417       this.server = server;
418       this.objectName = name;
419       return name;
420    }
421
422
423    public void postRegister(Boolean JavaDoc registrationDone)
424    {
425    }
426
427
428    public void preDeregister() throws java.lang.Exception JavaDoc
429    {
430       unregisterListener();
431    }
432
433
434    public void postDeregister()
435    {
436    }
437
438    protected void registerListener()
439    {
440       try
441       {
442          if (targetMBeanName != null && server.isInstanceOf(targetMBeanName, "javax.management.NotificationBroadcaster"))
443          {
444             server.addNotificationListener(targetMBeanName, this, new MessageFilter(), null);
445          }
446       }
447       catch (InstanceNotFoundException JavaDoc e)
448       {
449          Logger log = getLogger();
450          log.error("Exception during notification registration", e);
451       }
452    }
453
454    protected void unregisterListener()
455    {
456       try
457       {
458          if (targetMBeanName != null && server.isInstanceOf(targetMBeanName, "javax.management.NotificationBroadcaster"))
459          {
460             server.removeNotificationListener(targetMBeanName, this);
461          }
462       }
463       catch (InstanceNotFoundException JavaDoc e)
464       {
465          Logger log = getLogger();
466          log.error("Exception during notification unregistration", e);
467       }
468       catch (ListenerNotFoundException JavaDoc e)
469       {
470       }
471    }
472
473    private class MessageFilter implements NotificationFilter JavaDoc
474    {
475       public boolean isNotificationEnabled(Notification JavaDoc notification)
476       {
477          return notificationName == null || (notification.getType() != null && notification.getType().equals(notificationName));
478       }
479    }
480 }
481
Popular Tags