From a21536171ee41d166b4ecb73e70f842899465086 Mon Sep 17 00:00:00 2001 From: chandrasegar Date: Tue, 20 Feb 2024 10:18:59 +0530 Subject: [PATCH] exceptions added --- .../mailsender/Controller/MailController.java | 3 +- .../mailsender/DAO/Impl/MailDAOImpl.java | 31 +++---- .../java/entgra/mailsender/DAO/MailDAO.java | 2 +- .../Service/Impl/MailQueueServiceImpl.java | 1 - .../Service/Impl/MailServiceImpl.java | 81 +++++++++++++++---- .../mailsender/Service/MailService.java | 4 +- .../exception/BadRequestException.java | 10 +++ .../mailsender/exception/MailException.java | 30 +++++++ 8 files changed, 123 insertions(+), 39 deletions(-) create mode 100644 src/main/java/entgra/mailsender/exception/BadRequestException.java create mode 100644 src/main/java/entgra/mailsender/exception/MailException.java diff --git a/src/main/java/entgra/mailsender/Controller/MailController.java b/src/main/java/entgra/mailsender/Controller/MailController.java index 790ef4d..65b3d49 100644 --- a/src/main/java/entgra/mailsender/Controller/MailController.java +++ b/src/main/java/entgra/mailsender/Controller/MailController.java @@ -3,6 +3,7 @@ package entgra.mailsender.Controller; import entgra.mailsender.DTO.MailModel; import entgra.mailsender.Service.MailService; +import entgra.mailsender.exception.MailException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -27,7 +28,7 @@ public class MailController { mailService.sendEmail(emailModel); msg = "Email sent successfully"; return ResponseEntity.ok(msg); - } catch (RuntimeException e) { + } catch (MailException e) { msg = "Invalid email address"; return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(msg); } catch (MessagingException | IOException exception) { diff --git a/src/main/java/entgra/mailsender/DAO/Impl/MailDAOImpl.java b/src/main/java/entgra/mailsender/DAO/Impl/MailDAOImpl.java index 68ad99b..56ca734 100644 --- a/src/main/java/entgra/mailsender/DAO/Impl/MailDAOImpl.java +++ b/src/main/java/entgra/mailsender/DAO/Impl/MailDAOImpl.java @@ -4,29 +4,19 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import entgra.mailsender.DAO.MailDAO; import entgra.mailsender.DTO.MailModel; -import org.springframework.stereotype.Service; +import org.springframework.stereotype.Component; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; -import java.sql.Connection; -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.sql.*; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; -import java.util.function.Supplier; import java.util.logging.Logger; - -@Service +@Component public class MailDAOImpl implements MailDAO { Logger logger = Logger.getLogger(String.valueOf(MailDAOImpl.class)); @@ -36,13 +26,14 @@ private Connection getConnection() throws SQLException { } @Override -public void addMail(MailModel mailModel){ +public int addMail(MailModel mailModel){ logger.info("Add mail work successfully"); PreparedStatement stmt; + int generatedId = -1; try { 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()); String parametersJson = new ObjectMapper().writeValueAsString(mailModel.getParameters()); stmt.setString(1,mailModel.getEmailAddress()); @@ -54,7 +45,11 @@ public void addMail(MailModel mailModel){ String filename = mailModel.getAttachment().getOriginalFilename(); stmt.setString(7,filename); 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"); } catch (SQLException e) { logger.info(e.getMessage()); @@ -62,6 +57,7 @@ public void addMail(MailModel mailModel){ } catch (IOException e) { throw new RuntimeException(e); } + return generatedId; } @@ -100,8 +96,6 @@ public MailModel getMailDetails(Integer mail_id){ stmt.setInt(1,mail_id); try(ResultSet rs = stmt.executeQuery()) { while (rs.next()){ - logger.info(rs.getString("email_address")); - mailModel.setEmailId(rs.getInt("email_id")); mailModel.setEmailAddress(rs.getString("email_address")); mailModel.setMsgTemplate(rs.getString("msg_template")); @@ -115,7 +109,6 @@ public MailModel getMailDetails(Integer mail_id){ mailModel.setFilename(filename); Blob blob = rs.getBlob("attachment"); - logger.info(blob.toString()); File file = convertBlobToFile(blob,filename); mailModel.setFile(file); diff --git a/src/main/java/entgra/mailsender/DAO/MailDAO.java b/src/main/java/entgra/mailsender/DAO/MailDAO.java index d77b2f0..7c5fea2 100644 --- a/src/main/java/entgra/mailsender/DAO/MailDAO.java +++ b/src/main/java/entgra/mailsender/DAO/MailDAO.java @@ -6,7 +6,7 @@ import java.util.List; public interface MailDAO { - void addMail(MailModel mailModel); + int addMail(MailModel mailModel); MailModel getMailDetails(Integer mail_id); diff --git a/src/main/java/entgra/mailsender/Service/Impl/MailQueueServiceImpl.java b/src/main/java/entgra/mailsender/Service/Impl/MailQueueServiceImpl.java index 844bddb..7cf29c8 100644 --- a/src/main/java/entgra/mailsender/Service/Impl/MailQueueServiceImpl.java +++ b/src/main/java/entgra/mailsender/Service/Impl/MailQueueServiceImpl.java @@ -27,7 +27,6 @@ public class MailQueueServiceImpl implements MailQueueService { @Override public void enqueMails(List mailModelList){ - logger.info("came here"); BlockingQueue priorityQueue = PriorityQueueHolder.getInstance().getPriorityQueue(); AtomicLong insertionOrderCounter = PriorityQueueHolder.getInstance().getInsertionOrderCounter(); Set uniqueMails = PriorityQueueHolder.getInstance().getUniqueMails(); diff --git a/src/main/java/entgra/mailsender/Service/Impl/MailServiceImpl.java b/src/main/java/entgra/mailsender/Service/Impl/MailServiceImpl.java index 0ddbe6e..5ffb9be 100644 --- a/src/main/java/entgra/mailsender/Service/Impl/MailServiceImpl.java +++ b/src/main/java/entgra/mailsender/Service/Impl/MailServiceImpl.java @@ -4,6 +4,8 @@ import entgra.mailsender.DAO.MailDAO; import entgra.mailsender.DTO.MailModel; import entgra.mailsender.Service.MailQueueService; import entgra.mailsender.Service.MailService; +import entgra.mailsender.exception.BadRequestException; +import entgra.mailsender.exception.MailException; import entgra.mailsender.util.PriorityQueueHolder; import jakarta.annotation.PreDestroy; 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.stereotype.Service; +import java.util.ArrayList; import java.util.List; 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())){ - 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 - syncMailWithDB(); //here we need to check the unsent mail details + int emailid = mailDAO.addMail(emailModel); // save the mail details in the database and get the auto generated id + + emailModel.setEmailId(emailid); + emailModel.setFilename(emailModel.getAttachment().getOriginalFilename()); + //add to the priority queue + List 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 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) { - MailModel prioritizedMail = mailQueueService.getHighPriorityMail(); - MailModel updatedModel = mailDAO.getMailDetails(prioritizedMail.getEmailId()); - logger.info("High priority mail : " + updatedModel.getEmailAddress()); + MailModel prioritizedMail = mailDAO.getMailDetails(mailQueueService.getHighPriorityMail().getEmailId()); javaMailSender.send(mimeMessage -> { MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); - mimeMessageHelper.setTo(updatedModel.getEmailAddress()); - logger.info(updatedModel.getEmailAddress()); + mimeMessageHelper.setTo(prioritizedMail.getEmailAddress()); mimeMessageHelper.setSubject("Bill details for March "); StringBuilder emailBody = new StringBuilder(); - emailBody.append(updatedModel.getMsgTemplate()).append("\n"); + emailBody.append(prioritizedMail.getMsgTemplate()).append("\n"); // Append parameters to email body - List parameters = updatedModel.getParameters(); + List parameters = prioritizedMail.getParameters(); for (MailModel.Parameter parameter : parameters) { System.out.println("Parameter name: " + parameter.getKey()); System.out.println("Parameter value: " + parameter.getValue()); @@ -95,12 +146,10 @@ public class MailServiceImpl implements MailService { mimeMessageHelper.setText(emailBody.toString(), false); // Append attachments to email body - mimeMessageHelper.addAttachment(updatedModel.getFilename(), updatedModel.getFile()); - - logger.info("Mail sent successfully"); + mimeMessageHelper.addAttachment(prioritizedMail.getFilename(), prioritizedMail.getFile()); //Store the sent mail to the table - mailDAO.addToSentMail(updatedModel.getEmailId()); + mailDAO.addToSentMail(prioritizedMail.getEmailId()); } diff --git a/src/main/java/entgra/mailsender/Service/MailService.java b/src/main/java/entgra/mailsender/Service/MailService.java index 7d6e87a..c945cbd 100644 --- a/src/main/java/entgra/mailsender/Service/MailService.java +++ b/src/main/java/entgra/mailsender/Service/MailService.java @@ -1,13 +1,15 @@ package entgra.mailsender.Service; import entgra.mailsender.DTO.MailModel; +import entgra.mailsender.exception.BadRequestException; +import entgra.mailsender.exception.MailException; import javax.mail.MessagingException; import java.io.IOException; public interface MailService { - void sendEmail(MailModel emailModel) throws MessagingException, IOException; + void sendEmail(MailModel emailModel) throws MessagingException, IOException, BadRequestException, MailException; boolean isValidEmailAddress(String email); diff --git a/src/main/java/entgra/mailsender/exception/BadRequestException.java b/src/main/java/entgra/mailsender/exception/BadRequestException.java new file mode 100644 index 0000000..326874e --- /dev/null +++ b/src/main/java/entgra/mailsender/exception/BadRequestException.java @@ -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); + } +} diff --git a/src/main/java/entgra/mailsender/exception/MailException.java b/src/main/java/entgra/mailsender/exception/MailException.java new file mode 100644 index 0000000..2a210f4 --- /dev/null +++ b/src/main/java/entgra/mailsender/exception/MailException.java @@ -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); + } + +}