KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > hudson > tasks > Mailer


1 package hudson.tasks;
2
3 import hudson.Launcher;
4 import hudson.model.Build;
5 import hudson.model.BuildListener;
6 import hudson.model.Descriptor;
7 import hudson.model.Project;
8 import hudson.model.User;
9 import hudson.model.UserPropertyDescriptor;
10 import org.apache.tools.ant.types.selectors.SelectorUtils;
11 import org.kohsuke.stapler.StaplerRequest;
12
13 import javax.mail.Authenticator JavaDoc;
14 import javax.mail.PasswordAuthentication JavaDoc;
15 import javax.mail.Session JavaDoc;
16 import java.io.File JavaDoc;
17 import java.util.Map JavaDoc;
18 import java.util.Properties JavaDoc;
19 import java.util.logging.Level JavaDoc;
20 import java.util.logging.Logger JavaDoc;
21
22 /**
23  * {@link Publisher} that sends the build result in e-mail.
24  *
25  * @author Kohsuke Kawaguchi
26  */

27 public class Mailer extends Publisher {
28     private static final Logger JavaDoc LOGGER = Logger.getLogger(Mailer.class.getName());
29
30     /**
31      * Whitespace-separated list of e-mail addresses that represent recipients.
32      */

33     public String JavaDoc recipients;
34
35     /**
36      * If true, only the first unstable build will be reported.
37      */

38     public boolean dontNotifyEveryUnstableBuild;
39
40     /**
41      * If true, individuals will receive e-mails regarding who broke the build.
42      */

43     public boolean sendToIndividuals;
44
45     // TODO: left so that XStream won't get angry. figure out how to set the error handling behavior
46
// in XStream.
47
private transient String JavaDoc from;
48     private transient String JavaDoc subject;
49     private transient boolean failureOnly;
50
51     public boolean perform(Build build, Launcher launcher, BuildListener listener) throws InterruptedException JavaDoc {
52         if(debug)
53             listener.getLogger().println("Running mailer");
54         return new MailSender<Project,Build>(recipients,dontNotifyEveryUnstableBuild,sendToIndividuals) {
55             /** Check whether a path (/-separated) will be archived. */
56             @Override JavaDoc
57             public boolean artifactMatches(String JavaDoc path, Build build) {
58                 ArtifactArchiver aa = (ArtifactArchiver) build.getProject().getPublishers().get(ArtifactArchiver.DESCRIPTOR);
59                 if (aa == null) {
60                     LOGGER.finer("No ArtifactArchiver found");
61                     return false;
62                 }
63                 String JavaDoc artifacts = aa.getArtifacts();
64                 for (String JavaDoc include : artifacts.split("[, ]+")) {
65                     String JavaDoc pattern = include.replace(File.separatorChar, '/');
66                     if (pattern.endsWith("/")) {
67                         pattern += "**";
68                     }
69                     if (SelectorUtils.matchPath(pattern, path)) {
70                         LOGGER.log(Level.FINER, "DescriptorImpl.artifactMatches true for {0} against {1}", new Object JavaDoc[] {path, pattern});
71                         return true;
72                     }
73                 }
74                 LOGGER.log(Level.FINER, "DescriptorImpl.artifactMatches for {0} matched none of {1}", new Object JavaDoc[] {path, artifacts});
75                 return false;
76             }
77         }.execute(build,listener);
78     }
79
80     public Descriptor<Publisher> getDescriptor() {
81         return DESCRIPTOR;
82     }
83
84     public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
85
86     public static final class DescriptorImpl extends Descriptor<Publisher> {
87         /**
88          * The default e-mail address suffix appended to the user name found from changelog,
89          * to send e-mails. Null if not configured.
90          */

91         private String JavaDoc defaultSuffix;
92
93         /**
94          * Hudson's own URL, to put into the e-mail.
95          */

96         private String JavaDoc hudsonUrl;
97
98         /**
99          * If non-null, use SMTP-AUTH with these information.
100          */

101         private String JavaDoc smtpAuthPassword,smtpAuthUsername;
102
103         /**
104          * The e-mail address that Hudson puts to "From:" field in outgoing e-mails.
105          * Null if not configured.
106          */

107         private String JavaDoc adminAddress;
108
109         /**
110          * The SMTP server to use for sending e-mail. Null for default to the environment,
111          * which is usually <tt>localhost</tt>.
112          */

113         private String JavaDoc smtpHost;
114
115         public DescriptorImpl() {
116             super(Mailer.class);
117             load();
118         }
119
120         /**
121          * For backward compatibility.
122          */

123         protected void convert(Map JavaDoc<String JavaDoc, Object JavaDoc> oldPropertyBag) {
124             defaultSuffix = (String JavaDoc)oldPropertyBag.get("mail.default.suffix");
125             hudsonUrl = (String JavaDoc)oldPropertyBag.get("mail.hudson.url");
126             smtpAuthUsername = (String JavaDoc)oldPropertyBag.get("mail.hudson.smtpauth.username");
127             smtpAuthPassword = (String JavaDoc)oldPropertyBag.get("mail.hudson.smtpauth.password");
128             adminAddress = (String JavaDoc)oldPropertyBag.get("mail.admin.address");
129             smtpHost = (String JavaDoc)oldPropertyBag.get("mail.smtp.host");
130         }
131
132         public String JavaDoc getDisplayName() {
133             return "E-mail Notification";
134         }
135
136         public String JavaDoc getHelpFile() {
137             return "/help/project-config/mailer.html";
138         }
139
140         public String JavaDoc getDefaultSuffix() {
141             return defaultSuffix;
142         }
143
144         /** JavaMail session. */
145         public Session JavaDoc createSession() {
146             Properties JavaDoc props = new Properties JavaDoc(System.getProperties());
147             if(smtpHost!=null)
148                 props.put("mail.smtp.host",smtpHost);
149
150             return Session.getInstance(props,getAuthenticator());
151         }
152
153         private Authenticator JavaDoc getAuthenticator() {
154             final String JavaDoc un = getSmtpAuthUserName();
155             if(un==null) return null;
156             return new Authenticator JavaDoc() {
157                 protected PasswordAuthentication JavaDoc getPasswordAuthentication() {
158                     return new PasswordAuthentication JavaDoc(getSmtpAuthUserName(),getSmtpAuthPassword());
159                 }
160             };
161         }
162
163         public boolean configure(StaplerRequest req) throws FormException {
164             // this code is brain dead
165
smtpHost = nullify(req.getParameter("mailer_smtp_server"));
166             adminAddress = req.getParameter("mailer_admin_address");
167             defaultSuffix = nullify(req.getParameter("mailer_default_suffix"));
168             String JavaDoc url = nullify(req.getParameter("mailer_hudson_url"));
169             if(url!=null && !url.endsWith("/"))
170                 url += '/';
171             hudsonUrl = url;
172
173             if(req.getParameter("mailer.useSMTPAuth")!=null) {
174                 smtpAuthUsername = nullify(req.getParameter("mailer.SMTPAuth.userName"));
175                 smtpAuthPassword = nullify(req.getParameter("mailer.SMTPAuth.password"));
176             } else {
177                 smtpAuthUsername = smtpAuthPassword = null;
178             }
179
180             save();
181             return super.configure(req);
182         }
183
184         private String JavaDoc nullify(String JavaDoc v) {
185             if(v!=null && v.length()==0) v=null;
186             return v;
187         }
188
189         public String JavaDoc getSmtpServer() {
190             return smtpHost;
191         }
192
193         public String JavaDoc getAdminAddress() {
194             String JavaDoc v = adminAddress;
195             if(v==null) v = "address not configured yet <nobody>";
196             return v;
197         }
198
199         public String JavaDoc getUrl() {
200             return hudsonUrl;
201         }
202
203         public String JavaDoc getSmtpAuthUserName() {
204             return smtpAuthUsername;
205         }
206
207         public String JavaDoc getSmtpAuthPassword() {
208             return smtpAuthPassword;
209         }
210
211         public Publisher newInstance(StaplerRequest req) {
212             Mailer m = new Mailer();
213             req.bindParameters(m,"mailer_");
214             return m;
215         }
216     }
217
218     /**
219      * Per user property that is e-mail address.
220      */

221     public static class UserProperty extends hudson.model.UserProperty {
222         public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
223
224         /**
225          * The user's e-mail address.
226          * Null to leave it to default.
227          */

228         private final String JavaDoc emailAddress;
229
230         public UserProperty(String JavaDoc emailAddress) {
231             this.emailAddress = emailAddress;
232         }
233
234         public String JavaDoc getAddress() {
235             if(emailAddress!=null)
236                 return emailAddress;
237
238             String JavaDoc ds = Mailer.DESCRIPTOR.getDefaultSuffix();
239             if(ds!=null)
240                 return user.getId()+ds;
241             else
242                 return null;
243         }
244
245         public DescriptorImpl getDescriptor() {
246             return DESCRIPTOR;
247         }
248
249         public static final class DescriptorImpl extends UserPropertyDescriptor {
250             public DescriptorImpl() {
251                 super(UserProperty.class);
252             }
253
254             public String JavaDoc getDisplayName() {
255                 return "E-mail";
256             }
257
258             public UserProperty newInstance(User user) {
259                 return new UserProperty(null);
260             }
261
262             public UserProperty newInstance(StaplerRequest req) throws FormException {
263                 return new UserProperty(req.getParameter("email.address"));
264             }
265         }
266     }
267
268     /**
269      * Debug probe point to be activated by the scripting console.
270      */

271     public static boolean debug = false;
272 }
273
Popular Tags