aslsocial/src/main/java/org/gcube/applicationsupportlayer/social/mailing/EmailNotificationsConsumer....

91 lines
2.4 KiB
Java

package org.gcube.applicationsupportlayer.social.mailing;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author Massimiliano Assante ISTI-CNR
*
*/
public class EmailNotificationsConsumer extends Thread {
private static Logger _log = LoggerFactory.getLogger(EmailNotificationsConsumer.class);
public EmailNotificationsConsumer() {
super();
_log.info("EmailNotificationsConsumer thread started at " + new Date());
}
@Override
public void run() {
Properties props = System.getProperties();
String mailServiceHost = "localhost";
props.put("mail.smtp.host", mailServiceHost);
String mailServicePort = "25";
props.put("mail.smtp.port", mailServicePort);
Session session = Session.getDefaultInstance(props);
session.setDebug(true);
for (;;) {
try {
Thread.sleep(1000*EmailPlugin.SECONDS2WAIT);
} catch (InterruptedException e) {
e.printStackTrace();
}
//_log.debug("Checking Emails Buffer ... ");
if (EmailPlugin.BUFFER_EMAILS != null && EmailPlugin.BUFFER_EMAILS.size() > 0) {
_log.debug("Emails Buffer not empty, sending emails ");
Transport t = null;
try {
t = session.getTransport();
t.connect();
//sync method to ensure the producer do not put new emails in the meantime
synchronized(EmailPlugin.BUFFER_EMAILS){
for (NotificationMail mail : EmailPlugin.BUFFER_EMAILS) {
Message m = EmailPlugin.getMessageNotification(session, mail.getNotification2Send(), mail.getVreName(), mail.getPortalName(), mail.getSenderEmail());
if (m != null) {
m.saveChanges();
Address[] addresses = m.getAllRecipients();
t.sendMessage(m, addresses);
_log.debug("Message sent to " + mail.getSenderEmail());
}
else {
_log.warn("Message not sent to " + mail.getNotification2Send().getUserid());
}
}
//close session and empty the buffer
_log.info("Emails sent emptying the buffer");
EmailPlugin.BUFFER_EMAILS = new ArrayList<NotificationMail>();
t.close();
}
}
catch (Exception e) {
e.printStackTrace();
try {
t.close();
} catch (MessagingException e1) {
e1.printStackTrace();
}
}
}
}
}
}