Project

General

Profile

1
package eu.dnetlib.msro.notification;
2

    
3
import java.util.Arrays;
4
import java.util.Date;
5
import java.util.Map;
6
import java.util.Properties;
7
import java.util.Set;
8
import java.util.concurrent.BlockingQueue;
9
import java.util.concurrent.LinkedBlockingQueue;
10

    
11
import javax.mail.Authenticator;
12
import javax.mail.Message;
13
import javax.mail.MessagingException;
14
import javax.mail.PasswordAuthentication;
15
import javax.mail.Session;
16
import javax.mail.Transport;
17
import javax.mail.internet.InternetAddress;
18
import javax.mail.internet.MimeMessage;
19

    
20
import org.antlr.stringtemplate.StringTemplate;
21
import org.apache.commons.io.IOUtils;
22
import org.apache.commons.logging.Log;
23
import org.apache.commons.logging.LogFactory;
24
import org.springframework.beans.factory.annotation.Required;
25

    
26
import com.google.common.base.Splitter;
27
import com.google.common.collect.Maps;
28

    
29
public class EmailDispatcher {
30

    
31
	private String from;
32
	private String fromName;
33
	private String cc;
34
	private String smtpHost;
35
	private int smtpPort = 587;
36
	private String smtpUser;
37
	private String smtpPassword;
38
	private String baseUrl;
39

    
40
	private static final Log log = LogFactory.getLog(EmailDispatcher.class);
41

    
42
	private final BlockingQueue<Message> queue = new LinkedBlockingQueue<Message>();
43

    
44
	public void sendMail(final Set<String> to, final String subject, final String template, final Map<String, Object> tmplParams) {
45
		try {
46
			final StringTemplate st = new StringTemplate(template);
47
			st.setAttributes(tmplParams);
48
			st.setAttribute("baseUrl", baseUrl);
49

    
50
			final Session session = Session.getInstance(obtainProperties(), obtainAuthenticator());
51

    
52
			final MimeMessage message = new MimeMessage(session);
53
			message.setFrom(new InternetAddress(from, fromName));
54
			message.setSubject(subject);
55
			message.setContent(st.toString(), "text/html; charset=utf-8");
56
			message.setSentDate(new Date());
57

    
58
			for (String s : to) {
59
				message.addRecipient(Message.RecipientType.TO, new InternetAddress(s));
60
			}
61
			if ((cc != null) && !cc.isEmpty()) {
62
				for (String aCC : Splitter.on(",").omitEmptyStrings().trimResults().split(getCc())) {
63
					message.addRecipient(Message.RecipientType.CC, new InternetAddress(aCC));
64
				}
65
			}
66

    
67
			queue.add(message);
68

    
69
			log.info("Mail to " + Arrays.toString(to.toArray()) + " in queue");
70
		} catch (Exception e) {
71
			log.error("Error sending mail", e);
72
		}
73
	}
74

    
75
	public void processMailQueue() {
76
		while (true) {
77
			final Message message = queue.poll();
78
			if (message == null) {
79
				return;
80
			} else {
81
				try {
82
					log.info("Sending mail...");
83
					Transport.send(message);
84
					log.info("...sent");
85
				} catch (MessagingException e) {
86
					log.error("Error sending email", e);
87
					queue.add(message);
88
					return;
89
				}
90
			}
91
		}
92
	}
93

    
94
	private void sendWfStatusMail(final boolean success,
95
			final Set<String> to,
96
			final String wfId,
97
			final String procId,
98
			final String wfName,
99
			final Map<String, String> pendingWfs,
100
			final Map<String, String> responses,
101
			final String error) {
102
		try {
103
			final Map<String, Object> map = Maps.newHashMap();
104
			map.put("wfId", wfId);
105
			map.put("wfName", wfName);
106
			map.put("procId", procId);
107
			if ((pendingWfs != null) && !pendingWfs.isEmpty()) {
108
				map.put("pendingWfs", pendingWfs);
109
			}
110
			if ((responses != null) && !responses.isEmpty()) {
111
				map.put("responses", responses);
112
			}
113
			if ((error != null) && !error.isEmpty()) {
114
				map.put("error", error);
115
			}
116

    
117
			final String subject = success ? "Workflow '" + wfName + "' has been completed successfully" : "Workflow '" + wfName + "' is failed";
118
			final String tmplName = success ? "wf_success.mail.st" : "wf_failed.mail.st";
119
			final String template = IOUtils.toString(getClass().getResourceAsStream("/eu/dnetlib/msro/mail/" + tmplName));
120

    
121
			sendMail(to, subject, template, map);
122
		} catch (Exception e) {
123
			log.error("Error generating success-mail", e);
124
		}
125
	}
126

    
127
	public void sendSuccessMail(final Set<String> to,
128
			final String wfId,
129
			final String procId,
130
			final String wfName,
131
			final Map<String, String> pendingWfs,
132
			final Map<String, String> responses) {
133
		sendWfStatusMail(true, to, wfId, procId, wfName, pendingWfs, responses, "");
134
	}
135

    
136
	public void sendFailedMail(final Set<String> to,
137
			final String wfId,
138
			final String procId,
139
			final String wfName,
140
			final Map<String, String> pendingWfs,
141
			final Map<String, String> responses,
142
			final String error) {
143
		sendWfStatusMail(false, to, wfId, procId, wfName, pendingWfs, responses, error);
144
	}
145

    
146
	private Properties obtainProperties() {
147
		final Properties props = new Properties();
148
		props.put("mail.transport.protocol", "smtp");
149
		props.put("mail.smtp.host", smtpHost);
150
		props.put("mail.smtp.port", smtpPort);
151
		props.put("mail.smtp.auth", Boolean.toString((smtpUser != null) && !smtpUser.isEmpty()));
152
		return props;
153
	}
154

    
155
	private Authenticator obtainAuthenticator() {
156
		if ((smtpUser == null) || smtpUser.isEmpty()) { return null; }
157

    
158
		return new Authenticator() {
159

    
160
			private final PasswordAuthentication authentication = new PasswordAuthentication(smtpUser, smtpPassword);
161

    
162
			@Override
163
			protected PasswordAuthentication getPasswordAuthentication() {
164
				return authentication;
165
			}
166

    
167
		};
168
	}
169

    
170
	public String getFrom() {
171
		return from;
172
	}
173

    
174
	@Required
175
	public void setFrom(final String from) {
176
		this.from = from;
177
	}
178

    
179
	public String getFromName() {
180
		return fromName;
181
	}
182

    
183
	@Required
184
	public void setFromName(final String fromName) {
185
		this.fromName = fromName;
186
	}
187

    
188
	public String getCc() {
189
		return cc;
190
	}
191

    
192
	@Required
193
	public void setCc(final String cc) {
194
		this.cc = cc;
195
	}
196

    
197
	public String getSmtpHost() {
198
		return smtpHost;
199
	}
200

    
201
	@Required
202
	public void setSmtpHost(final String smtpHost) {
203
		this.smtpHost = smtpHost;
204
	}
205

    
206
	public int getSmtpPort() {
207
		return smtpPort;
208
	}
209

    
210
	public void setSmtpPort(final int smtpPort) {
211
		this.smtpPort = smtpPort;
212
	}
213

    
214
	public String getSmtpUser() {
215
		return smtpUser;
216
	}
217

    
218
	public void setSmtpUser(final String smtpUser) {
219
		this.smtpUser = smtpUser;
220
	}
221

    
222
	public String getSmtpPassword() {
223
		return smtpPassword;
224
	}
225

    
226
	public void setSmtpPassword(final String smtpPassword) {
227
		this.smtpPassword = smtpPassword;
228
	}
229

    
230
	public String getBaseUrl() {
231
		return baseUrl;
232
	}
233

    
234
	@Required
235
	public void setBaseUrl(final String baseUrl) {
236
		this.baseUrl = baseUrl;
237
	}
238

    
239
}
(1-1/2)