KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > tools > ant > listener > MailLogger


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */

18 package org.apache.tools.ant.listener;
19
20 import java.io.FileInputStream JavaDoc;
21 import java.io.IOException JavaDoc;
22 import java.io.InputStream JavaDoc;
23 import java.io.PrintStream JavaDoc;
24 import java.util.Hashtable JavaDoc;
25 import java.util.Vector JavaDoc;
26 import java.util.Properties JavaDoc;
27 import java.util.Enumeration JavaDoc;
28 import java.util.StringTokenizer JavaDoc;
29
30 import org.apache.tools.ant.BuildEvent;
31 import org.apache.tools.ant.BuildException;
32 import org.apache.tools.ant.DefaultLogger;
33 import org.apache.tools.ant.Project;
34 import org.apache.tools.ant.taskdefs.email.EmailAddress;
35 import org.apache.tools.ant.taskdefs.email.Message;
36 import org.apache.tools.ant.taskdefs.email.Mailer;
37 import org.apache.tools.ant.util.ClasspathUtils;
38 import org.apache.tools.ant.util.DateUtils;
39 import org.apache.tools.ant.util.StringUtils;
40 import org.apache.tools.mail.MailMessage;
41
42 /**
43  * Buffers log messages from DefaultLogger, and sends an e-mail with the
44  * results. The following Project properties are used to send the mail.
45  * <ul>
46  * <li> MailLogger.mailhost [default: localhost] - Mail server to use</li>
47  * <li> MailLogger.port [default: 25] - Default port for SMTP </li>
48  * <li> MailLogger.from [required] - Mail "from" address</li>
49  * <li> MailLogger.failure.notify [default: true] - Send build failure
50  * e-mails?</li>
51  * <li> MailLogger.success.notify [default: true] - Send build success
52  * e-mails?</li>
53  * <li> MailLogger.failure.to [required if failure mail to be sent] - Address
54  * to send failure messages to</li>
55  * <li> MailLogger.success.to [required if success mail to be sent] - Address
56  * to send success messages to</li>
57  * <li> MailLogger.failure.subject [default: "Build Failure"] - Subject of
58  * failed build</li>
59  * <li> MailLogger.success.subject [default: "Build Success"] - Subject of
60  * successful build</li>
61  * </ul>
62  * These properties are set using standard Ant property setting mechanisms
63  * (&lt;property&gt;, command-line -D, etc). Ant properties can be overridden
64  * by specifying the filename of a properties file in the <i>
65  * MailLogger.properties.file property</i> . Any properties defined in that
66  * file will override Ant properties.
67  *
68  */

69 public class MailLogger extends DefaultLogger {
70     /** Buffer in which the message is constructed prior to sending */
71     private StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
72
73     /**
74      * Sends an e-mail with the log results.
75      *
76      * @param event the build finished event
77      */

78     public void buildFinished(BuildEvent event) {
79         super.buildFinished(event);
80
81         Project project = event.getProject();
82         Hashtable JavaDoc properties = project.getProperties();
83
84         // overlay specified properties file (if any), which overrides project
85
// settings
86
Properties JavaDoc fileProperties = new Properties JavaDoc();
87         String JavaDoc filename = (String JavaDoc) properties.get("MailLogger.properties.file");
88         if (filename != null) {
89             InputStream JavaDoc is = null;
90             try {
91                 is = new FileInputStream JavaDoc(filename);
92                 fileProperties.load(is);
93             } catch (IOException JavaDoc ioe) {
94                 // ignore because properties file is not required
95
} finally {
96                 if (is != null) {
97                     try {
98                         is.close();
99                     } catch (IOException JavaDoc e) {
100                         // ignore
101
}
102                 }
103             }
104         }
105
106         for (Enumeration JavaDoc e = fileProperties.keys(); e.hasMoreElements();) {
107             String JavaDoc key = (String JavaDoc) e.nextElement();
108             String JavaDoc value = fileProperties.getProperty(key);
109             properties.put(key, project.replaceProperties(value));
110         }
111
112         boolean success = (event.getException() == null);
113         String JavaDoc prefix = success ? "success" : "failure";
114
115         try {
116             boolean notify = Project.toBoolean(getValue(properties,
117                     prefix + ".notify", "on"));
118
119             if (!notify) {
120                 return;
121             }
122
123             String JavaDoc mailhost = getValue(properties, "mailhost", "localhost");
124             int port = Integer.parseInt(getValue(properties, "port",
125                                         String.valueOf(MailMessage.DEFAULT_PORT)));
126             String JavaDoc user = getValue(properties, "user", "");
127             String JavaDoc password = getValue(properties, "password", "");
128             boolean ssl = Project.toBoolean(getValue(properties,
129                      "ssl", "off"));
130             String JavaDoc from = getValue(properties, "from", null);
131             String JavaDoc replytoList = getValue(properties, "replyto", "");
132             String JavaDoc toList = getValue(properties, prefix + ".to", null);
133             String JavaDoc subject = getValue(properties, prefix + ".subject",
134                     (success) ? "Build Success" : "Build Failure");
135             if (user.equals("") && password.equals("") && !ssl) {
136                 sendMail(mailhost, port, from, replytoList, toList,
137                          subject, buffer.substring(0));
138             } else {
139                 sendMimeMail(event.getProject(), mailhost, port, user,
140                              password, ssl, from, replytoList, toList,
141                              subject, buffer.substring(0));
142             }
143         } catch (Exception JavaDoc e) {
144             System.out.println("MailLogger failed to send e-mail!");
145             e.printStackTrace(System.err);
146         }
147     }
148
149
150     /**
151      * Receives and buffers log messages.
152      *
153      * @param message the message being logger
154      */

155     protected void log(String JavaDoc message) {
156         buffer.append(message).append(StringUtils.LINE_SEP);
157     }
158
159
160     /**
161      * Gets the value of a property.
162      *
163      * @param properties Properties to obtain value from
164      * @param name suffix of property name. "MailLogger." will be
165      * prepended internally.
166      * @param defaultValue value returned if not present in the properties.
167      * Set to null to make required.
168      * @return The value of the property, or default value.
169      * @exception Exception thrown if no default value is specified and the
170      * property is not present in properties.
171      */

172     private String JavaDoc getValue(Hashtable JavaDoc properties, String JavaDoc name,
173                             String JavaDoc defaultValue) throws Exception JavaDoc {
174         String JavaDoc propertyName = "MailLogger." + name;
175         String JavaDoc value = (String JavaDoc) properties.get(propertyName);
176
177         if (value == null) {
178             value = defaultValue;
179         }
180
181         if (value == null) {
182             throw new Exception JavaDoc("Missing required parameter: " + propertyName);
183         }
184
185         return value;
186     }
187
188
189     /**
190      * Send the mail
191      * @param mailhost mail server
192      * @param port mail server port number
193      * @param from from address
194      * @param replyToList comma-separated replyto list
195      * @param toList comma-separated recipient list
196      * @param subject mail subject
197      * @param message mail body
198      * @exception IOException thrown if sending message fails
199      */

200     private void sendMail(String JavaDoc mailhost, int port, String JavaDoc from, String JavaDoc replyToList, String JavaDoc toList,
201                           String JavaDoc subject, String JavaDoc message) throws IOException JavaDoc {
202         MailMessage mailMessage = new MailMessage(mailhost, port);
203         mailMessage.setHeader("Date", DateUtils.getDateForHeader());
204
205         mailMessage.from(from);
206         if (!replyToList.equals("")) {
207             StringTokenizer JavaDoc t = new StringTokenizer JavaDoc(replyToList, ", ", false);
208             while (t.hasMoreTokens()) {
209                 mailMessage.replyto(t.nextToken());
210             }
211         }
212         StringTokenizer JavaDoc t = new StringTokenizer JavaDoc(toList, ", ", false);
213         while (t.hasMoreTokens()) {
214             mailMessage.to(t.nextToken());
215         }
216
217         mailMessage.setSubject(subject);
218
219         PrintStream JavaDoc ps = mailMessage.getPrintStream();
220         ps.println(message);
221
222         mailMessage.sendAndClose();
223     }
224     /**
225      * Send the mail (MimeMail)
226      * @param project current ant project
227      * @param host mail server
228      * @param port mail server port number
229      * @param user user name for SMTP auth
230      * @param password password for SMTP auth
231      * @param ssl if true send message over SSL
232      * @param from from address
233      * @param replyToString comma-separated replyto list
234      * @param toString comma-separated recipient list
235      * @param subject mail subject
236      * @param message mail body
237      */

238     private void sendMimeMail(Project project, String JavaDoc host, int port,
239                               String JavaDoc user, String JavaDoc password, boolean ssl,
240                               String JavaDoc from, String JavaDoc replyToString,
241                               String JavaDoc toString, String JavaDoc subject,
242                               String JavaDoc message) {
243         // convert the replyTo string into a vector of emailaddresses
244
Mailer mailer = null;
245         try {
246             mailer = (Mailer) ClasspathUtils.newInstance(
247                     "org.apache.tools.ant.taskdefs.email.MimeMailer",
248                     MailLogger.class.getClassLoader(), Mailer.class);
249         } catch (BuildException e) {
250             Throwable JavaDoc t = e.getCause() == null ? e : e.getCause();
251             log("Failed to initialise MIME mail: " + t.getMessage());
252             return;
253         }
254         Vector JavaDoc replyToList = vectorizeEmailAddresses(replyToString);
255         mailer.setHost(host);
256         mailer.setPort(port);
257         mailer.setUser(user);
258         mailer.setPassword(password);
259         mailer.setSSL(ssl);
260         Message mymessage = new Message(message);
261         mymessage.setProject(project);
262         mailer.setMessage(mymessage);
263         mailer.setFrom(new EmailAddress(from));
264         mailer.setReplyToList(replyToList);
265         Vector JavaDoc toList = vectorizeEmailAddresses(toString);
266         mailer.setToList(toList);
267         mailer.setCcList(new Vector JavaDoc());
268         mailer.setBccList(new Vector JavaDoc());
269         mailer.setFiles(new Vector JavaDoc());
270         mailer.setSubject(subject);
271         mailer.send();
272     }
273     private Vector JavaDoc vectorizeEmailAddresses(String JavaDoc listString) {
274         Vector JavaDoc emailList = new Vector JavaDoc();
275         StringTokenizer JavaDoc tokens = new StringTokenizer JavaDoc(listString, ",");
276         while (tokens.hasMoreTokens()) {
277             emailList.addElement(new EmailAddress(tokens.nextToken()));
278         }
279         return emailList;
280     }
281 }
282
283
284
Popular Tags