| 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 | |
|
| 14 | |
|
| 15 | |
|
| 16 | |
|
| 17 | |
|
| 18 | 1 | public enum SMTPServerHandler { |
| 19 | 1 | INSTANCE; |
| 20 | |
|
| 21 | 1 | private static final Logger LOGGER = LoggerFactory.getLogger(SMTPServerHandler.class); |
| 22 | 1 | private final MailSaver mailSaver = new MailSaver(); |
| 23 | 1 | private final MailListener myListener = new MailListener(mailSaver); |
| 24 | 1 | private final SMTPServer smtpServer = new SMTPServer(new SimpleMessageListenerAdapter(myListener), new SMTPAuthHandlerFactory()); |
| 25 | |
|
| 26 | 1 | SMTPServerHandler() { |
| 27 | 1 | } |
| 28 | |
|
| 29 | |
|
| 30 | |
|
| 31 | |
|
| 32 | |
|
| 33 | |
|
| 34 | |
|
| 35 | |
|
| 36 | |
|
| 37 | |
|
| 38 | |
public void startServer(int port, InetAddress bindAddress) throws BindPortException, OutOfRangePortException { |
| 39 | 2 | LOGGER.debug("Starting server on port {}", port); |
| 40 | |
try { |
| 41 | 2 | smtpServer.setBindAddress(bindAddress); |
| 42 | 2 | smtpServer.setPort(port); |
| 43 | 2 | smtpServer.start(); |
| 44 | 1 | } catch (RuntimeException exception) { |
| 45 | 1 | if (exception.getMessage().contains("BindException")) { |
| 46 | 0 | LOGGER.error("{}. Port {}", exception.getMessage(), port); |
| 47 | 0 | throw new BindPortException(exception, port); |
| 48 | 1 | } else if (exception.getMessage().contains("out of range")) { |
| 49 | 1 | LOGGER.error("Port {} out of range.", port); |
| 50 | 1 | throw new OutOfRangePortException(exception, port); |
| 51 | |
} else { |
| 52 | 0 | LOGGER.error("", exception); |
| 53 | 0 | throw exception; |
| 54 | |
} |
| 55 | 1 | } |
| 56 | 1 | } |
| 57 | |
|
| 58 | |
|
| 59 | |
|
| 60 | |
|
| 61 | |
|
| 62 | |
|
| 63 | |
|
| 64 | |
public void stopServer() { |
| 65 | 3 | if (smtpServer.isRunning()) { |
| 66 | 0 | LOGGER.debug("Stopping server"); |
| 67 | 0 | smtpServer.stop(); |
| 68 | |
} |
| 69 | 3 | } |
| 70 | |
|
| 71 | |
|
| 72 | |
|
| 73 | |
|
| 74 | |
|
| 75 | |
|
| 76 | |
public MailSaver getMailSaver() { |
| 77 | 0 | return mailSaver; |
| 78 | |
} |
| 79 | |
|
| 80 | |
|
| 81 | |
|
| 82 | |
|
| 83 | |
|
| 84 | |
|
| 85 | |
public SMTPServer getSmtpServer() { |
| 86 | 0 | return smtpServer; |
| 87 | |
} |
| 88 | |
} |