Merge pull request 'exceptions added' (#4) from develop into master

Reviewed-on: #4
pull/7/head
commit 1524337587

@ -3,6 +3,7 @@ package entgra.mailsender.Controller;
import entgra.mailsender.DTO.MailModel; import entgra.mailsender.DTO.MailModel;
import entgra.mailsender.Service.MailService; import entgra.mailsender.Service.MailService;
import entgra.mailsender.exception.MailException;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@ -27,7 +28,7 @@ public class MailController {
mailService.sendEmail(emailModel); mailService.sendEmail(emailModel);
msg = "Email sent successfully"; msg = "Email sent successfully";
return ResponseEntity.ok(msg); return ResponseEntity.ok(msg);
} catch (RuntimeException e) { } catch (MailException e) {
msg = "Invalid email address"; msg = "Invalid email address";
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(msg); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(msg);
} catch (MessagingException | IOException exception) { } catch (MessagingException | IOException exception) {

@ -4,29 +4,19 @@ import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import entgra.mailsender.DAO.MailDAO; import entgra.mailsender.DAO.MailDAO;
import entgra.mailsender.DTO.MailModel; import entgra.mailsender.DTO.MailModel;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Component;
import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.sql.Connection; import java.sql.*;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.ResultSet;
import java.sql.Blob;
import java.sql.Date;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.function.Supplier;
import java.util.logging.Logger; import java.util.logging.Logger;
@Component
@Service
public class MailDAOImpl implements MailDAO { public class MailDAOImpl implements MailDAO {
Logger logger = Logger.getLogger(String.valueOf(MailDAOImpl.class)); Logger logger = Logger.getLogger(String.valueOf(MailDAOImpl.class));
@ -36,13 +26,14 @@ private Connection getConnection() throws SQLException {
} }
@Override @Override
public void addMail(MailModel mailModel){ public int addMail(MailModel mailModel){
logger.info("Add mail work successfully"); logger.info("Add mail work successfully");
PreparedStatement stmt; PreparedStatement stmt;
int generatedId = -1;
try { try {
Connection conn = this.getConnection(); Connection conn = this.getConnection();
stmt = conn.prepareStatement("INSERT INTO email (EMAIL_ADDRESS, MSG_TEMPLATE, PRIORITY, ATTACHMENT, PARAMETERS, TIME, FILENAME, EXPIRY_AT) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"); stmt = conn.prepareStatement("INSERT INTO email (EMAIL_ADDRESS, MSG_TEMPLATE, PRIORITY, ATTACHMENT, PARAMETERS, TIME, FILENAME, EXPIRY_AT) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", PreparedStatement.RETURN_GENERATED_KEYS);
Timestamp current_time = new Timestamp(System.currentTimeMillis()); Timestamp current_time = new Timestamp(System.currentTimeMillis());
String parametersJson = new ObjectMapper().writeValueAsString(mailModel.getParameters()); String parametersJson = new ObjectMapper().writeValueAsString(mailModel.getParameters());
stmt.setString(1,mailModel.getEmailAddress()); stmt.setString(1,mailModel.getEmailAddress());
@ -54,7 +45,11 @@ public void addMail(MailModel mailModel){
String filename = mailModel.getAttachment().getOriginalFilename(); String filename = mailModel.getAttachment().getOriginalFilename();
stmt.setString(7,filename); stmt.setString(7,filename);
stmt.setDate(8,mailModel.getExpiry_at()); stmt.setDate(8,mailModel.getExpiry_at());
stmt.execute(); stmt.executeUpdate();
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()) {
generatedId = rs.getInt(1);
}
logger.info("Stored successfully"); logger.info("Stored successfully");
} catch (SQLException e) { } catch (SQLException e) {
logger.info(e.getMessage()); logger.info(e.getMessage());
@ -62,6 +57,7 @@ public void addMail(MailModel mailModel){
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
return generatedId;
} }
@ -100,8 +96,6 @@ public MailModel getMailDetails(Integer mail_id){
stmt.setInt(1,mail_id); stmt.setInt(1,mail_id);
try(ResultSet rs = stmt.executeQuery()) { try(ResultSet rs = stmt.executeQuery()) {
while (rs.next()){ while (rs.next()){
logger.info(rs.getString("email_address"));
mailModel.setEmailId(rs.getInt("email_id")); mailModel.setEmailId(rs.getInt("email_id"));
mailModel.setEmailAddress(rs.getString("email_address")); mailModel.setEmailAddress(rs.getString("email_address"));
mailModel.setMsgTemplate(rs.getString("msg_template")); mailModel.setMsgTemplate(rs.getString("msg_template"));
@ -115,7 +109,6 @@ public MailModel getMailDetails(Integer mail_id){
mailModel.setFilename(filename); mailModel.setFilename(filename);
Blob blob = rs.getBlob("attachment"); Blob blob = rs.getBlob("attachment");
logger.info(blob.toString());
File file = convertBlobToFile(blob,filename); File file = convertBlobToFile(blob,filename);
mailModel.setFile(file); mailModel.setFile(file);

@ -6,7 +6,7 @@ import java.util.List;
public interface MailDAO { public interface MailDAO {
void addMail(MailModel mailModel); int addMail(MailModel mailModel);
MailModel getMailDetails(Integer mail_id); MailModel getMailDetails(Integer mail_id);

@ -27,7 +27,6 @@ public class MailQueueServiceImpl implements MailQueueService {
@Override @Override
public void enqueMails(List<MailModel> mailModelList){ public void enqueMails(List<MailModel> mailModelList){
logger.info("came here");
BlockingQueue<MailModel> priorityQueue = PriorityQueueHolder.getInstance().getPriorityQueue(); BlockingQueue<MailModel> priorityQueue = PriorityQueueHolder.getInstance().getPriorityQueue();
AtomicLong insertionOrderCounter = PriorityQueueHolder.getInstance().getInsertionOrderCounter(); AtomicLong insertionOrderCounter = PriorityQueueHolder.getInstance().getInsertionOrderCounter();
Set<MailModel> uniqueMails = PriorityQueueHolder.getInstance().getUniqueMails(); Set<MailModel> uniqueMails = PriorityQueueHolder.getInstance().getUniqueMails();

@ -4,6 +4,8 @@ import entgra.mailsender.DAO.MailDAO;
import entgra.mailsender.DTO.MailModel; import entgra.mailsender.DTO.MailModel;
import entgra.mailsender.Service.MailQueueService; import entgra.mailsender.Service.MailQueueService;
import entgra.mailsender.Service.MailService; import entgra.mailsender.Service.MailService;
import entgra.mailsender.exception.BadRequestException;
import entgra.mailsender.exception.MailException;
import entgra.mailsender.util.PriorityQueueHolder; import entgra.mailsender.util.PriorityQueueHolder;
import jakarta.annotation.PreDestroy; import jakarta.annotation.PreDestroy;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -11,6 +13,7 @@ import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.logging.Logger; import java.util.logging.Logger;
@ -38,15 +41,66 @@ public class MailServiceImpl implements MailService {
public void sendEmail(MailModel emailModel){ public void sendEmail(MailModel emailModel) throws MailException {
if (shutdownRequested) {
String msg = "Server is shutting down. SMS requests will not be accepted.";
logger.warning(msg);
throw new BadRequestException(msg);
}
logger.warning("email address : "+emailModel.getEmailAddress());
if (isValidEmailAddress(emailModel.getEmailAddress())){ if (isValidEmailAddress(emailModel.getEmailAddress())){
throw new RuntimeException("Invalid Email address"); String msg = "Invalid Email address";
logger.warning(msg);
throw new BadRequestException(msg);
} }
mailDAO.addMail(emailModel); // save the mail details in the database int emailid = mailDAO.addMail(emailModel); // save the mail details in the database and get the auto generated id
syncMailWithDB(); //here we need to check the unsent mail details
emailModel.setEmailId(emailid);
emailModel.setFilename(emailModel.getAttachment().getOriginalFilename());
//add to the priority queue
List<MailModel> mailModels = new ArrayList<>();
mailModels.add(emailModel);
try {
mailQueueService.enqueMails(mailModels);
} catch (Exception e){
throw new RuntimeException(e);
}
//send the high priority mail
while (PriorityQueueHolder.getInstance().getPriorityQueue().peek() != null){
MailModel prioritizedMail =mailQueueService.getHighPriorityMail();
javaMailSender.send(mimeMessage -> {
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
mimeMessageHelper.setTo(prioritizedMail.getEmailAddress());
mimeMessageHelper.setSubject("Bill details for March ");
StringBuilder emailBody = new StringBuilder();
emailBody.append(prioritizedMail.getMsgTemplate()).append("\n");
// Append parameters to email body
List<MailModel.Parameter> parameters = prioritizedMail.getParameters();
for (MailModel.Parameter parameter : parameters) {
emailBody.append("\n").append(parameter.getKey()).append(": ").append(parameter.getValue());
}
// Append text to email body
mimeMessageHelper.setText(emailBody.toString(), false);
// Append attachments to email body
mimeMessageHelper.addAttachment(prioritizedMail.getFilename(), prioritizedMail.getAttachment());
//Store the sent mail to the table
mailDAO.addToSentMail(prioritizedMail.getEmailId());
});
}
} }
@ -66,22 +120,19 @@ public class MailServiceImpl implements MailService {
} }
while(PriorityQueueHolder.getInstance().getPriorityQueue().peek() != null) { while(PriorityQueueHolder.getInstance().getPriorityQueue().peek() != null) {
MailModel prioritizedMail = mailQueueService.getHighPriorityMail(); MailModel prioritizedMail = mailDAO.getMailDetails(mailQueueService.getHighPriorityMail().getEmailId());
MailModel updatedModel = mailDAO.getMailDetails(prioritizedMail.getEmailId());
logger.info("High priority mail : " + updatedModel.getEmailAddress());
javaMailSender.send(mimeMessage -> { javaMailSender.send(mimeMessage -> {
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
mimeMessageHelper.setTo(updatedModel.getEmailAddress()); mimeMessageHelper.setTo(prioritizedMail.getEmailAddress());
logger.info(updatedModel.getEmailAddress());
mimeMessageHelper.setSubject("Bill details for March "); mimeMessageHelper.setSubject("Bill details for March ");
StringBuilder emailBody = new StringBuilder(); StringBuilder emailBody = new StringBuilder();
emailBody.append(updatedModel.getMsgTemplate()).append("\n"); emailBody.append(prioritizedMail.getMsgTemplate()).append("\n");
// Append parameters to email body // Append parameters to email body
List<MailModel.Parameter> parameters = updatedModel.getParameters(); List<MailModel.Parameter> parameters = prioritizedMail.getParameters();
for (MailModel.Parameter parameter : parameters) { for (MailModel.Parameter parameter : parameters) {
System.out.println("Parameter name: " + parameter.getKey()); System.out.println("Parameter name: " + parameter.getKey());
System.out.println("Parameter value: " + parameter.getValue()); System.out.println("Parameter value: " + parameter.getValue());
@ -95,12 +146,10 @@ public class MailServiceImpl implements MailService {
mimeMessageHelper.setText(emailBody.toString(), false); mimeMessageHelper.setText(emailBody.toString(), false);
// Append attachments to email body // Append attachments to email body
mimeMessageHelper.addAttachment(updatedModel.getFilename(), updatedModel.getFile()); mimeMessageHelper.addAttachment(prioritizedMail.getFilename(), prioritizedMail.getFile());
logger.info("Mail sent successfully");
//Store the sent mail to the table //Store the sent mail to the table
mailDAO.addToSentMail(updatedModel.getEmailId()); mailDAO.addToSentMail(prioritizedMail.getEmailId());
} }

@ -1,13 +1,15 @@
package entgra.mailsender.Service; package entgra.mailsender.Service;
import entgra.mailsender.DTO.MailModel; import entgra.mailsender.DTO.MailModel;
import entgra.mailsender.exception.BadRequestException;
import entgra.mailsender.exception.MailException;
import javax.mail.MessagingException; import javax.mail.MessagingException;
import java.io.IOException; import java.io.IOException;
public interface MailService { public interface MailService {
void sendEmail(MailModel emailModel) throws MessagingException, IOException; void sendEmail(MailModel emailModel) throws MessagingException, IOException, BadRequestException, MailException;
boolean isValidEmailAddress(String email); boolean isValidEmailAddress(String email);

@ -0,0 +1,10 @@
package entgra.mailsender.exception;
public class BadRequestException extends MailException{
public BadRequestException(String message, Throwable ex){ super(message, ex);}
public BadRequestException(String message) {
super(message);
}
}

@ -0,0 +1,30 @@
package entgra.mailsender.exception;
import lombok.Data;
@Data
public class MailException extends Exception{
private String errorMessage;
public MailException(){super();}
public MailException(Throwable cause) {
super(cause);
}
public MailException(String msg, Exception nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
}
public MailException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
public MailException(String msg) {
super(msg);
setErrorMessage(msg);
}
}
Loading…
Cancel
Save