Skip to content

Commit

Permalink
Add email to be sent to devs when error arrise
Browse files Browse the repository at this point in the history
  • Loading branch information
pankajjangid05 committed Apr 4, 2023
1 parent d9ca06d commit 0832454
Show file tree
Hide file tree
Showing 6 changed files with 167 additions and 15 deletions.
6 changes: 5 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,11 @@
<version>4.9.3</version>
</dependency>
<!-- Minio CDN Dependencies - End -->
</dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
</dependencies>

<build>
<plugins>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,24 @@
import com.uci.adapter.provider.factory.ProviderFactory;
import com.uci.dao.models.XMessageDAO;
import com.uci.dao.repository.XMessageRepository;
import com.uci.dao.utils.XMessageDAOUtils;
import com.uci.outbound.entity.EmailDetails;
import com.uci.outbound.service.EmailServiceImpl;
import com.uci.utils.cache.service.RedisCacheService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import messagerosa.core.model.XMessage;
import com.uci.dao.utils.XMessageDAOUtils;
import com.uci.utils.cache.service.RedisCacheService;

import io.fusionauth.client.FusionAuthClient;
import io.fusionauth.domain.api.LoginRequest;
import messagerosa.xml.XMessageParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.kafka.receiver.ReceiverRecord;
import javax.xml.bind.JAXBException;

import javax.xml.bind.JAXBException;
import java.io.ByteArrayInputStream;
import java.util.function.Consumer;

Expand All @@ -38,27 +37,33 @@ public class OutboundKafkaController {

@Autowired
private XMessageRepository xMessageRepo;

@Autowired
private RedisCacheService redisCacheService;

private HashOperations hashOperations; //to access Redis cache

@Autowired
private EmailServiceImpl emailService;

@Value("${spring.mail.recipient}")
private String recipient;

@EventListener(ApplicationStartedEvent.class)
public void onMessage() {

reactiveKafkaReceiver
.doOnNext(new Consumer<ReceiverRecord<String, String>>() {
@Override
public void accept(ReceiverRecord<String, String> msg) {
log.info("kafka message receieved!");
log.info("kafka message receieved!");
XMessage currentXmsg = null;
try {
currentXmsg = XMessageParser.parse(new ByteArrayInputStream(msg.value().getBytes()));
sendOutboundMessage(currentXmsg);
} catch (Exception e) {
e.printStackTrace();
}
}

}
})
Expand All @@ -85,6 +90,7 @@ public void sendOutboundMessage(XMessage currentXmsg) throws Exception {
.doOnError(new Consumer<Throwable>() {
@Override
public void accept(Throwable e) {
sentEmail(currentXmsg, "Error in Outbound", "PFA", recipient, "XMessage.txt");
log.error("Exception in processOutBoundMessageF:"+e.getMessage());
}
}).subscribe(new Consumer<XMessage>() {
Expand All @@ -110,7 +116,9 @@ public void accept(XMessageDAO xMessageDAO) {
}
});
}catch(Exception e){
sentEmail(xMessage, "Error in Outbound", "PFA", recipient, "XMessage.txt");
log.error("Exception in convertXMessageToDAO:" + e.getMessage());
e.printStackTrace();
try{
log.error("The current XMessage was " + xMessage.toXML());
}catch(JAXBException j) {
Expand All @@ -126,8 +134,21 @@ public void accept(XMessageDAO xMessageDAO) {
}
});
}

private String redisKeyWithPrefix(String key) {
return System.getenv("ENV")+"-"+key;
return System.getenv("ENV")+"-"+key;
}

private void sentEmail(XMessage xMessage, String subject, String body, String recipient, String attachmentFileName){
log.info("Email Sending....");
EmailDetails emailDetails = new EmailDetails().builder()
.subject(subject)
.msgBody(body)
.recipient(recipient)
.attachment(xMessage.toString())
.attachmentFileName(attachmentFileName)
.build();
log.info("EmailDetails :" + emailDetails);
emailService.sendMailWithAttachment(emailDetails);
}
}
16 changes: 16 additions & 0 deletions src/main/java/com/uci/outbound/entity/EmailDetails.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.uci.outbound.entity;

import lombok.*;

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Builder
public class EmailDetails {
private String recipient;
private String msgBody;
private String subject;
private String attachment;
private String attachmentFileName;
}
9 changes: 9 additions & 0 deletions src/main/java/com/uci/outbound/service/EmailService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.uci.outbound.service;

import com.uci.outbound.entity.EmailDetails;

public interface EmailService {
public void sendSimpleMail(EmailDetails details);

public void sendMailWithAttachment(EmailDetails details);
}
92 changes: 92 additions & 0 deletions src/main/java/com/uci/outbound/service/EmailServiceImpl.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package com.uci.outbound.service;


import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.mail.internet.MimeMessage;

import com.uci.outbound.entity.EmailDetails;
import lombok.extern.slf4j.Slf4j;
import messagerosa.core.model.XMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class EmailServiceImpl implements EmailService {
@Autowired
private JavaMailSender javaMailSender;

@Value("${spring.mail.username}")
private String sender;

public void sendSimpleMail(EmailDetails details) {
try {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setFrom(sender);
mailMessage.setTo(details.getRecipient());
mailMessage.setText(details.getMsgBody());
mailMessage.setSubject(details.getSubject());
javaMailSender.send(mailMessage);
log.info("Mail Sent Successfully...");
} catch (Exception e) {
log.error("Error while Sending Mail" + e.getMessage());
}
}

public void sendMailWithAttachment(EmailDetails details) {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper;
String tempPath = "/tmp/" + details.getAttachmentFileName();
File file = new File(tempPath);
try {
mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
mimeMessageHelper.setFrom(sender);
if (details.getRecipient().contains(",")) {
String recipients[] = details.getRecipient().split(",");
mimeMessageHelper.setTo(recipients);
} else {
mimeMessageHelper.setTo(details.getRecipient());
}
mimeMessageHelper.setText(details.getMsgBody());
mimeMessageHelper.setSubject(details.getSubject());
createTempFile(details.getAttachment(), tempPath);
FileSystemResource fileSystemResource = new FileSystemResource(file);
mimeMessageHelper.addAttachment(fileSystemResource.getFilename(), file);
javaMailSender.send(mimeMessage);
log.info("Mail sent Successfully...");
} catch (Exception e) {
log.error("Error while sending mail!!! " + e.getMessage());
} finally {
if (file.exists() && file.delete()) {
log.info("file deleted : " + file.getPath());
}
}
}

// public void sendMailWithAttachment(String subject, String body, String recipient, XMessage xMessage, String attachmentFileName) {
// EmailDetails emailDetails = new EmailDetails();
// emailDetails.setSubject(subject);
// emailDetails.setMsgBody(body);
// emailDetails.setRecipient(recipient);
// emailDetails.setAttachment(xMessage.toString());
// emailDetails.setAttachmentFileName(attachmentFileName);
// log.info("EmailDetails :" + emailDetails);
// sendMailWithAttachment(emailDetails);
// }

private void createTempFile(String fileData, String filePath) throws IOException {
Path path = Paths.get(filePath);
Files.writeString(path, fileData, StandardCharsets.UTF_8);
log.info("Email attachment temp file is created : " + filePath);
}
}
10 changes: 10 additions & 0 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -118,3 +118,13 @@ file.cdn.selected=${SELECTED_FILE_CDN:#{"azure"}}

#for notification key enable/disable when notification triggered
fcm.notificationKeyEnable=${NOTIFICATION_KEY_ENABLE:#{"true"}}

#Email Config SMTP
spring.mail.host=${EMAIL_HOST:#{""}}
spring.mail.port=${EMAIL_PORT:#{""}}
spring.mail.username=${EMAIL_USERNAME:#{""}}
spring.mail.password=${EMAIL_PASSWORD:#{""}}
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.recipient=${RECIPIENT_EMAILS:#{""}}

0 comments on commit 0832454

Please sign in to comment.