001: package dalma.endpoints.email;
002:
003: import javax.mail.MessagingException;
004: import javax.mail.Session;
005: import javax.mail.Transport;
006: import javax.mail.internet.MimeMessage;
007: import java.util.ArrayList;
008: import java.util.List;
009: import java.util.logging.Level;
010: import java.util.logging.Logger;
011:
012: /**
013: * {@link Thread} that send e-mails via SMTP.
014: *
015: * <p>
016: * This mechanism allows multiple e-mails to be sent through one connection,
017: * and thereby improve the performance.
018: *
019: * @author Kohsuke Kawaguchi
020: */
021: final class SenderThread extends Thread {
022:
023: private final List<MimeMessage> msgs = new ArrayList<MimeMessage>();
024:
025: private final Session session;
026:
027: private boolean isShuttingDown = false;
028:
029: private static final Logger logger = Logger
030: .getLogger(SenderThread.class.getName());
031:
032: public SenderThread(Session session) {
033: super ("SMTP sender thread");
034: this .session = session;
035: }
036:
037: public synchronized void queue(MimeMessage msg) {
038: if (isShuttingDown)
039: throw new IllegalStateException(
040: "the sender thread is shutting down");
041:
042: msgs.add(msg);
043: notify();
044: }
045:
046: private synchronized void waitForMessage()
047: throws InterruptedException {
048: while (msgs.isEmpty())
049: this .wait();
050: }
051:
052: public synchronized void shutDown() {
053: if (!isShuttingDown) {
054: isShuttingDown = true;
055: interrupt();
056: }
057: try {
058: join();
059: } catch (InterruptedException e) {
060: // process an interrupt later
061: Thread.currentThread().interrupt();
062: }
063: }
064:
065: private synchronized boolean hasMessage() {
066: return !msgs.isEmpty();
067: }
068:
069: private synchronized MimeMessage getNext() {
070: return msgs.remove(0);
071: }
072:
073: public void run() {
074: while (!isShuttingDown) {
075: try {
076: waitForMessage();
077: } catch (InterruptedException e) {
078: // going to shutdown
079: assert isShuttingDown;
080: if (!hasMessage())
081: return;
082: }
083:
084: // send all the messages in the queue
085: try {
086: logger.fine(toString() + " : waking up");
087: Transport t = session.getTransport("smtp");
088: t.connect();
089: do {
090: MimeMessage msg = getNext();
091: logger.fine(toString() + " : sending "
092: + msg.getSubject());
093: t.sendMessage(msg, msg.getAllRecipients());
094: } while (hasMessage());
095: t.close();
096: logger.fine(toString() + " : going back to sleep");
097: } catch (MessagingException e) {
098: logger.log(Level.WARNING,
099: "Failed to send an e-mail via SMTP", e);
100: }
101: }
102: }
103: }
|