1   package org.sourceforge.vlibrary.user.workers;
2   
3   import java.util.Iterator;
4   
5   import org.apache.log4j.Logger;
6   
7   import com.dumbster.smtp.SimpleSmtpServer;
8   import com.dumbster.smtp.SmtpMessage;
9   
10  /**
11   * Wraps Dumbster's SimpleSmtpServer (http://quintanasoft.com/dumbster/)
12   * to expose the port and workaround for race condition bug in start method
13   * http://sourceforge.net/tracker/index.php?func=detail&aid=1179454&group_id=78413&atid=553186
14   *
15   */
16  public class DelegatingSimpleSmtpServer  {
17      private int port;
18      private SimpleSmtpServer delegate;
19      private static Logger logger =
20          Logger.getLogger(DelegatingSimpleSmtpServer.class.getName());
21  
22      public DelegatingSimpleSmtpServer(int port) {
23          this.port = port;
24      }
25  
26      /**
27       * Fixes (supposedly closed) Dumbster bug 179454 using patch in the
28       * bug report.
29       *
30       */
31      public synchronized void start() {
32          logger.info("Creating SimpleSmtpServer");
33          SimpleSmtpServer server = new SimpleSmtpServer(port);
34          Thread t = new Thread(server);
35  
36          // Block until the server socket is created
37          synchronized (server) {
38            try {
39              t.start();
40              server.wait();
41            } catch (InterruptedException e) {
42              // Ignore don't care.
43            }
44          }
45          logger.info("Created SimpleSmtpServer");
46          this.delegate = server;
47      }
48  
49      public synchronized int getPort() {
50          return this.port;
51      }
52  
53      public synchronized SimpleSmtpServer getDelegate() {
54          return delegate;
55      }
56  
57      @SuppressWarnings("unchecked")
58      public Iterator<SmtpMessage> getReceivedEmail() {
59          synchronized(delegate) {
60          return delegate.getReceivedEmail();
61          }
62      }
63  
64      public int getReceivedEmailSize() {
65          synchronized(delegate) {
66          return delegate.getReceivedEmailSize();
67          }
68      }
69  
70      public void stop() {
71          synchronized(delegate) {
72          delegate.stop();
73          }
74      }
75  }