KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > mycompany > listeners > MailLogger


1 package com.mycompany.listeners;
2
3 import java.io.ByteArrayOutputStream JavaDoc;
4 import java.io.FileInputStream JavaDoc;
5 import java.io.IOException JavaDoc;
6 import java.io.InputStream JavaDoc;
7 import java.util.Enumeration JavaDoc;
8 import java.util.Properties JavaDoc;
9 import java.util.StringTokenizer JavaDoc;
10
11 import javax.mail.Session JavaDoc;
12 import javax.mail.Transport JavaDoc;
13 import javax.mail.internet.InternetAddress JavaDoc;
14 import javax.mail.internet.MimeMessage JavaDoc;
15
16 import com.puppycrawl.tools.checkstyle.DefaultLogger;
17 import com.puppycrawl.tools.checkstyle.api.AuditEvent;
18 import com.puppycrawl.tools.checkstyle.api.AuditListener;
19 import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
20 import com.puppycrawl.tools.checkstyle.api.SeverityLevel;
21
22 /**
23  * Buffers log messages from DefaultLogger, and sends an e-mail with the
24  * results. The following Project properties are used to send the mail.
25  * <ul>
26  * <li> MailLogger.mailhost [default: localhost] - Mail server to use</li>
27  *
28  * <li> MailLogger.from [required] - Mail "from" address</li>
29  * <li> MailLlistener.failure.notify [default: true] - Send build failure
30  * e-mails?</li>
31  * <li> MailLogger.success.notify [default: true] - Send build success
32  * e-mails?</li>
33  * <li> MailLogger.failure.to [required if failure mail to be sent] - Address
34  * to send failure messages to</li>
35  * <li> MailLogger.success.to [required if success mail to be sent] - Address
36  * to send success messages to</li>
37  * <li> MailLogger.failure.subject [default: "Build Failure"] - Subject of
38  * failed build</li>
39  * <li> MailLlistener.success.subject [default: "Build Success"] - Subject of
40  * successful build</li>
41  * </ul>
42  * These properties are set using standard property setting mechanisms
43  * (command-line -D, ant &lt;property&gt;, etc).Properties can be overridden
44  * by specifying the filename of a properties file in the <i>
45  * MailLogger.properties.file property</i> . Any properties defined in that
46  * file will override properties.
47  * Based on
48  * <a HREF="http://ant.apache.org/index.html">org.apache.tools.ant.listener.MailLogger>org.apache.tools.ant.listener.MailLogger</a>
49  * @author Erik Hatcher
50  * <a HREF="mailto:ehatcher@apache.org">ehatcher@apache.org</a>
51  * @author Rick Giles
52  */

53 public class MailLogger
54     implements AuditListener
55 {
56     /** output stream for logger */
57     private ByteArrayOutputStream JavaDoc mOutputStream;
58
59     /** adapted listener */
60     private DefaultLogger mLogger;
61
62     /** count of the number of errors and exceptions */
63     private int mErrors;
64
65     /**
66      * Constructs a <code>MailLogger</code>
67      */

68     public MailLogger()
69     {
70         mOutputStream = new ByteArrayOutputStream JavaDoc();
71         mLogger = new DefaultLogger(mOutputStream, false);
72         mErrors = 0;
73     }
74
75     /** @see com.puppycrawl.tools.checkstyle.api.AuditListener */
76     public void auditStarted(AuditEvent aEvt)
77     {
78         mLogger.auditStarted(aEvt);
79     }
80
81     /**
82      * Sends an e-mail with the log results.
83      * @see com.puppycrawl.tools.checkstyle.api.AuditListener
84      */

85     public void auditFinished(AuditEvent aEvt)
86     {
87         mLogger.auditFinished(aEvt);
88
89         final Properties JavaDoc properties = System.getProperties();
90
91         // overlay specified properties file (if any), which overrides project
92
// settings
93
final Properties JavaDoc fileProperties = new Properties JavaDoc();
94         final String JavaDoc filename =
95             (String JavaDoc) properties.get("MailLogger.properties.file");
96         if (filename != null) {
97             InputStream JavaDoc is = null;
98             try {
99                 is = new FileInputStream JavaDoc(filename);
100                 fileProperties.load(is);
101             }
102             catch (IOException JavaDoc ioe) {
103                 // ignore because properties file is not required
104
;
105             }
106             finally {
107                 if (is != null) {
108                     try {
109                         is.close();
110                     }
111                     catch (IOException JavaDoc e) {
112                         ;
113                     }
114                 }
115             }
116         }
117
118         for (Enumeration JavaDoc e = fileProperties.keys(); e.hasMoreElements();) {
119             final String JavaDoc key = (String JavaDoc) e.nextElement();
120             final String JavaDoc value = fileProperties.getProperty(key);
121             properties.put(key, value);
122         }
123
124         final boolean success = (mErrors == 0);
125         final String JavaDoc prefix = success ? "success" : "failure";
126
127         try {
128             final String JavaDoc mailhost =
129                 getValue(properties, "mailhost", "localhost");
130             final String JavaDoc from = getValue(properties, "from", null);
131
132             final String JavaDoc toList = getValue(properties, prefix + ".to", null);
133             final String JavaDoc subject = getValue(properties, prefix + ".subject",
134                     (success)
135                         ? "Checkstyle Audit Success"
136                         : "Checkstyle Audit Failure");
137
138             sendMail(mailhost, from, toList, subject, mOutputStream.toString());
139         }
140         catch (Exception JavaDoc e) {
141             System.out.println("MailLogger failed to send e-mail!");
142             e.printStackTrace(System.err);
143         }
144     }
145
146     /** @see com.puppycrawl.tools.checkstyle.api.AuditListener */
147     public void fileStarted(AuditEvent aEvt)
148     {
149         mLogger.fileStarted(aEvt);
150     }
151
152     /** @see com.puppycrawl.tools.checkstyle.api.AuditListener */
153     public void fileFinished(AuditEvent aEvt)
154     {
155         mLogger.fileFinished(aEvt);
156     }
157
158     /** @see com.puppycrawl.tools.checkstyle.api.AuditListener */
159     public void addError(AuditEvent aEvt)
160     {
161         if (SeverityLevel.ERROR.equals(aEvt.getSeverityLevel())) {
162             mLogger.addError(aEvt);
163             mErrors++;
164         }
165     }
166
167     /** @see com.puppycrawl.tools.checkstyle.api.AuditListener */
168     public void addException(AuditEvent aEvt, Throwable JavaDoc aThrowable)
169     {
170         mLogger.addException(aEvt, aThrowable);
171         mErrors++;
172     }
173
174     /**
175      * Gets the value of a property.
176      *
177      * @param aProperties Properties to obtain value from.
178      * @param aName suffix of property name. "MailLogger." will be
179      * prepended internally.
180      * @param aDefaultValue value returned if not present in the properties.
181      * Set to null to make required.
182      * @return The value of the property, or default value.
183      * @throws CheckstyleException if no default value is specified and the
184      * property is not present in properties.
185      */

186     private String JavaDoc getValue(Properties JavaDoc aProperties, String JavaDoc aName,
187                             String JavaDoc aDefaultValue) throws CheckstyleException
188     {
189         final String JavaDoc propertyName = "MailLogger." + aName;
190         String JavaDoc value = (String JavaDoc) aProperties.get(propertyName);
191
192         if (value == null) {
193             value = aDefaultValue;
194         }
195
196         if (value == null) {
197             throw new CheckstyleException(
198                 "Missing required parameter: " + propertyName);
199         }
200
201         return value;
202     }
203     /**
204      * Send the mail
205      *
206      * @param aMailhost mail server
207      * @param aFrom from address
208      * @param aToList comma-separated recipient list
209      * @param aSubject mail subject
210      * @param aText mail body
211      * @throws Exception if sending message fails
212      */

213     private void sendMail(String JavaDoc aMailhost, String JavaDoc aFrom, String JavaDoc aToList,
214             String JavaDoc aSubject, String JavaDoc aText)
215         throws Exception JavaDoc
216     {
217         // Get system properties
218
final Properties JavaDoc props = System.getProperties();
219
220         // Setup mail server
221
props.put("mail.smtp.host", aMailhost);
222
223         // Get session
224
final Session JavaDoc session = Session.getDefaultInstance(props, null);
225
226         // Define message
227
final MimeMessage JavaDoc message = new MimeMessage JavaDoc(session);
228
229         message.setFrom(new InternetAddress JavaDoc(aFrom));
230         final StringTokenizer JavaDoc t = new StringTokenizer JavaDoc(aToList, ", ", false);
231         while (t.hasMoreTokens()) {
232             message.addRecipient(
233                 MimeMessage.RecipientType.TO,
234                 new InternetAddress JavaDoc(t.nextToken()));
235         }
236         message.setSubject(aSubject);
237         message.setText(aText);
238
239         Transport.send(message);
240     }
241 }
242
Popular Tags