View Javadoc
1   package com.nilhcem.fakesmtp.server;
2   
3   import java.net.InetAddress;
4   
5   import org.slf4j.Logger;
6   import org.slf4j.LoggerFactory;
7   import org.subethamail.smtp.helper.SimpleMessageListenerAdapter;
8   import org.subethamail.smtp.server.SMTPServer;
9   import com.nilhcem.fakesmtp.core.exception.BindPortException;
10  import com.nilhcem.fakesmtp.core.exception.OutOfRangePortException;
11  
12  /**
13   * Starts and stops the SMTP server.
14   *
15   * @author Nilhcem
16   * @since 1.0
17   */
18  public enum SMTPServerHandler {
19  	INSTANCE;
20  
21  	private static final Logger LOGGER = LoggerFactory.getLogger(SMTPServerHandler.class);
22  	private final MailSaver mailSaver = new MailSaver();
23  	private final MailListener myListener = new MailListener(mailSaver);
24  	private final SMTPServer smtpServer = new SMTPServer(new SimpleMessageListenerAdapter(myListener), new SMTPAuthHandlerFactory());
25  
26  	SMTPServerHandler() {
27  	}
28  
29  	/**
30  	 * Starts the server on the port and address specified in parameters.
31  	 *
32  	 * @param port the SMTP port to be opened.
33  	 * @param bindAddress the address to bind to. null means bind to all.
34  	 * @throws BindPortException when the port can't be opened.
35  	 * @throws OutOfRangePortException when port is out of range.
36  	 * @throws IllegalArgumentException when port is out of range.
37  	 */
38  	public void startServer(int port, InetAddress bindAddress) throws BindPortException, OutOfRangePortException {
39  		LOGGER.debug("Starting server on port {}", port);
40  		try {
41  			smtpServer.setBindAddress(bindAddress);
42  			smtpServer.setPort(port);
43  			smtpServer.start();
44  		} catch (RuntimeException exception) {
45  			if (exception.getMessage().contains("BindException")) { // Can't open port
46  				LOGGER.error("{}. Port {}", exception.getMessage(), port);
47  				throw new BindPortException(exception, port);
48  			} else if (exception.getMessage().contains("out of range")) { // Port out of range
49  				LOGGER.error("Port {} out of range.", port);
50  				throw new OutOfRangePortException(exception, port);
51  			} else { // Unknown error
52  				LOGGER.error("", exception);
53  				throw exception;
54  			}
55  		}
56  	}
57  
58  	/**
59  	 * Stops the server.
60  	 * <p>
61  	 * If the server is not started, does nothing special.
62  	 * </p>
63  	 */
64  	public void stopServer() {
65  		if (smtpServer.isRunning()) {
66  			LOGGER.debug("Stopping server");
67  			smtpServer.stop();
68  		}
69  	}
70  
71  	/**
72  	 * Returns the {@code MailSaver} object.
73  	 *
74  	 * @return the {@code MailSaver} object.
75  	 */
76  	public MailSaver getMailSaver() {
77  		return mailSaver;
78  	}
79  
80  	/**
81  	 * Returns the {@code SMTPServer} object.
82       *
83       * @return the {@code SMTPServer} object.
84  	 */
85  	public SMTPServer getSmtpServer() {
86  		return smtpServer;
87  	}
88  }