Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@
/sma-server/target/
db/
sma-server.conf
sma-server.log
sma-server*.log
.flattened-pom.xml
.idea
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@
public final class Constants {

// in millis
public static int MAX_WAIT_SPAM = 15000;
public static final int MAX_WAIT_SPAM_SEC = 15;
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
import com.icegreen.greenmail.util.GreenMail;
import com.icegreen.greenmail.util.ServerSetupTest;

import fr.insalyon.creatis.sma.server.Configuration;
import fr.insalyon.creatis.sma.server.SmaServer;
import fr.insalyon.creatis.sma.server.utils.Configuration;
import jakarta.mail.internet.MimeMessage;

public class SMAClientAndServerTest {
Expand All @@ -42,16 +42,16 @@ private void mockConfig(SmtpServer server) {
when(configuration.getMailProtocol()).thenReturn(server.getProtocol());
when(configuration.getMailHost()).thenReturn(server.getBindTo());
when(configuration.getMailPort()).thenReturn(server.getPort());
when(configuration.getMailSslTrust()).thenReturn(server.getBindTo());
when(configuration.isMailSslTrust()).thenReturn(false);

when(configuration.isMailAuth()).thenReturn(false);
when(configuration.getMailUsername()).thenReturn("");
when(configuration.getMailPassword()).thenReturn("");

when(configuration.getMailFrom()).thenReturn("test@test.com");
when(configuration.getMailFromName()).thenReturn("test");
when(configuration.getMailMaxRuns()).thenReturn(5);

when(configuration.getMailMaxRuns()).thenReturn(10);
when(configuration.getMailPort()).thenReturn(server.getPort());

Configuration.getInstance().setConfiguration(configuration);
}
Expand Down Expand Up @@ -79,22 +79,23 @@ public void spamMailClient() throws Exception {
final String message = "je suis vraiment trop fort";
final String subject = "wow ce titre est incroyable";
final String username = "bliblou";
final int nmails = 1000;
String[] randomAddress;
client = new SMAClient(InetAddress.getLocalHost(), configuration.getPort());

for (int i = 0; i < 1000; i++) {
for (int i = 0; i < nmails; i++) {
randomAddress = generateRandomAddress();
client.sendEmail(subject, message, randomAddress, true, username);
System.err.println("Sending mail to : " + randomAddress[0]);
}

before = Instant.now();
System.err.println("Waiting for mails to reach de server !");
while (mailServer.getReceivedMessages().length != 1000) {
System.err.println("Waiting !");
while (mailServer.getReceivedMessages().length != nmails) {
System.err.println("Waiting ! (" + mailServer.getReceivedMessages().length + " mails arrived)");
Thread.sleep(1000);
after = Instant.now();
assertFalse(Duration.between(before, after).toMillis() > Constants.MAX_WAIT_SPAM);
assertFalse(Duration.between(before, after).toSeconds() > Constants.MAX_WAIT_SPAM_SEC);
}
System.err.println("All mails sended !");

Expand Down
9 changes: 0 additions & 9 deletions sma-common/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,4 @@
<artifactId>sma-common</artifactId>
<packaging>jar</packaging>
<name>SMA-Common</name>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
2 changes: 1 addition & 1 deletion sma-server/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.177</version>
<version>2.3.232</version>
</dependency>

<dependency>
Expand Down
4 changes: 2 additions & 2 deletions sma-server/sma-conf.example
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ mail.transport.protocol = smtps
mail.host = smtp.creatis.insa-lyon.fr
mail.port = 1

# if an host is trusted, then SSL certificate won't be checked!
mail.smtp.ssl.trust = localhost
# if true, then only mail.host will be trusted, SSL certificate won't be checked!
mail.smtp.ssl.trust = True

mail.auth = True
mail.username = b
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,6 @@
*/
package fr.insalyon.creatis.sma.server;

/**
*
* @author Rafael Ferreira da Silva
*/
public class Main {

public static void main(String[] args) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,51 +4,80 @@
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import fr.insalyon.creatis.sma.common.Communication;
import fr.insalyon.creatis.sma.server.execution.Executor;
import fr.insalyon.creatis.sma.server.execution.MessageCleanerPool;
import fr.insalyon.creatis.sma.server.business.MessagePoolBusiness;
import fr.insalyon.creatis.sma.server.dao.MessagePoolDAO;
import fr.insalyon.creatis.sma.server.dao.h2.MessagePoolData;
import fr.insalyon.creatis.sma.server.execution.ScheduledTasksCreator;
import fr.insalyon.creatis.sma.server.execution.executors.CommunicationExecutor;
import fr.insalyon.creatis.sma.server.utils.Configuration;
import fr.insalyon.creatis.sma.server.utils.Constants;

/**
* SmaServer
*/
public class SmaServer extends Thread {

private static final Logger logger = Logger.getLogger(Main.class);
private static final Logger LOG = Logger.getLogger(Main.class);

private final ScheduledExecutorService tasksExecutor;
private final ExecutorService socketExecutor;
private final ExecutorService sendMessageExecutor;
private final Configuration config;

private final MessagePoolDAO messagePoolDAO;
private final MessagePoolBusiness messagePoolBusiness;
private boolean started = false;

public SmaServer() {
PropertyConfigurator.configure(Main.class.getClassLoader().getResource("smaLog4j.properties"));

config = Configuration.getInstance();
tasksExecutor = Executors.newSingleThreadScheduledExecutor();
socketExecutor = Executors.newCachedThreadPool();
sendMessageExecutor = Executors.newFixedThreadPool(config.getMailMaxRuns());

messagePoolDAO = new MessagePoolData();
messagePoolBusiness = new MessagePoolBusiness(messagePoolDAO);

schedule();
}

public synchronized void waitToBeReady() throws InterruptedException {
while (started == false) {
Thread.sleep(1000);
}
}

public final void schedule() {
ScheduledTasksCreator creator = new ScheduledTasksCreator();

tasksExecutor.scheduleWithFixedDelay(
creator.getPoolCleanerTask(messagePoolDAO), 0, Constants.CLEANER_POOL_SLEEP_HOURS, TimeUnit.HOURS);
tasksExecutor.scheduleWithFixedDelay(
creator.getMessagePoolTask(sendMessageExecutor, messagePoolDAO, messagePoolBusiness), 0, Constants.MESSAGE_POOL_SLEEP_SECONDS, TimeUnit.SECONDS);
}

@Override
public void run() {
PropertyConfigurator.configure(Main.class.getClassLoader().getResource("smaLog4j.properties"));
Configuration.getInstance();
LOG.info("Starting SMA Server on port " + config.getPort());

logger.info("Starting SMA Server on port " + Configuration.getInstance().getPort());

// Pools
MessageCleanerPool.getInstance();

// Socket
try (ServerSocket serverSocket = new ServerSocket(
Configuration.getInstance().getPort(), 50, InetAddress.getByName("0.0.0.0"))) {

try (ServerSocket serverSocket = new ServerSocket(config.getPort(), 50, InetAddress.getByName("0.0.0.0"))) {
started = true;

while (true) {
Socket socket = serverSocket.accept();
Communication communication = new Communication(socket);
new Executor(communication).start();
}

socketExecutor.submit(new CommunicationExecutor(communication, messagePoolBusiness));
}
} catch (IOException ex) {
logger.error("Error processing a request ", ex);
LOG.error("Error processing a request ", ex);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,104 +35,38 @@
package fr.insalyon.creatis.sma.server.business;

import fr.insalyon.creatis.sma.common.bean.MessageOperation;
import fr.insalyon.creatis.sma.server.Configuration;
import fr.insalyon.creatis.sma.common.bean.OperationStatus;
import fr.insalyon.creatis.sma.server.dao.DAOException;
import fr.insalyon.creatis.sma.server.dao.DAOFactory;
import fr.insalyon.creatis.sma.server.execution.MessagePool;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import jakarta.mail.Message;
import jakarta.mail.MessagingException;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import org.apache.log4j.Logger;
import fr.insalyon.creatis.sma.server.dao.MessagePoolDAO;

/**
*
* @author Rafael Ferreira da Silva
*/
public class MessagePoolBusiness {

private final static Logger logger = Logger.getLogger(MessagePoolBusiness.class);
private final MessagePoolDAO messagePoolDAO;

/**
*
* @param operation
* @throws BusinessException
*/
public void addOperation(MessageOperation operation) throws BusinessException {
public MessagePoolBusiness(MessagePoolDAO messagePoolDAO) {
this.messagePoolDAO = messagePoolDAO;
}

public void addOperation(MessageOperation operation) throws BusinessException {
try {
DAOFactory.getDAOFactory().getMessagePoolDAO().add(operation);
MessagePool.getInstance();
messagePoolDAO.add(operation);

} catch (DAOException ex) {
throw new BusinessException(ex);
} catch (DAOException e) {
throw new BusinessException(e);
}
}

public void sendEmail(String ownerEmail, String owner, String subject,
String content, String[] recipients, boolean direct) throws BusinessException {
// see https://javaee.github.io/javamail/docs/api/com/sun/mail/smtp/package-summary.html
public void updateStatus(MessageOperation operation, OperationStatus status) throws BusinessException {
try {
logger.info("Sending email to: " + String.join(" ", recipients));
Configuration conf = Configuration.getInstance();
Properties props = new Properties();
props.setProperty("mail.transport.protocol", conf.getMailProtocol());
props.setProperty("mail.smtp.host", conf.getMailHost());
props.setProperty("mail.smtp.port", String.valueOf(conf.getMailPort()));
props.setProperty("mail.smtp.auth", String.valueOf(conf.isMailAuth()));
props.setProperty("mail.smtp.starttls.enable", String.valueOf(conf.isMailAuth()));
props.setProperty("mail.smtp.ssl.trust", conf.getMailSslTrust());

Session session = Session.getDefaultInstance(props);
session.setDebug(false);

MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setContent(content, "text/html");
mimeMessage.addHeader("Content-Type", "text/html");

InternetAddress from = new InternetAddress(ownerEmail, owner);
mimeMessage.setReplyTo(new InternetAddress[]{from});
mimeMessage.setFrom(from);
mimeMessage.setSentDate(new Date());
mimeMessage.setSubject(subject);

Transport transport = session.getTransport();

if (conf.isMailAuth()) {
transport.connect(
conf.getMailHost(), conf.getMailPort(),
conf.getMailUsername(), conf.getMailPassword());
} else {
transport.connect();
}

InternetAddress[] addressTo = null;

if (recipients != null && recipients.length > 0) {
addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}
if (direct) {
mimeMessage.setRecipients(Message.RecipientType.TO, addressTo);
} else {
mimeMessage.setRecipients(Message.RecipientType.BCC, addressTo);
}

transport.sendMessage(mimeMessage, addressTo);
transport.close();
operation.setStatus(status);
messagePoolDAO.update(operation);

} else {
logger.warn("There's no recipients to send the email.");
}
} catch (UnsupportedEncodingException | MessagingException ex) {
logger.error(ex);
throw new BusinessException(ex);
} catch (DAOException e){
throw new BusinessException(e);
}
}
}
Loading
Loading