Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow customization of email receiver #41

Merged
merged 7 commits into from
Dec 4, 2023
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
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@ It will ask you to run in sudo mode in order to execute the sql.

## How to run it

- `./gradlew bootRun`
- IDE: Most recent IDEs can run gradle, use its capabilities.

- Command line: `./gradlew bootRun`

## Tests

Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
package org.worldcubeassociation.dbsanitycheck.model;

import lombok.Data;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import lombok.Data;

@Data
@Entity
@Table(name = "sanity_check_categories")
public class Category {
@Id
private Integer id;
@Id
private Integer id;

private String name;

private String name;
@Column(name = "email_to")
private String emailTo;
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
package org.worldcubeassociation.dbsanitycheck.service;

import java.util.List;

import javax.mail.MessagingException;

import org.worldcubeassociation.dbsanitycheck.bean.AnalysisBean;
import org.worldcubeassociation.dbsanitycheck.bean.SanityCheckWithErrorBean;

import java.util.List;
import javax.mail.MessagingException;

@FunctionalInterface
public interface EmailService {
void sendEmail(List<AnalysisBean> analysisResult, List<SanityCheckWithErrorBean> queriesWithError)
throws MessagingException;
void sendEmail(String emailTo, List<AnalysisBean> analysisResult, List<SanityCheckWithErrorBean> queriesWithError)
throws MessagingException;
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
Expand All @@ -15,7 +14,6 @@
import org.worldcubeassociation.dbsanitycheck.service.EmailService;
import org.worldcubeassociation.dbsanitycheck.service.ExclusionService;

import java.io.File;
import java.time.LocalDate;
import java.util.List;
import javax.mail.MessagingException;
Expand All @@ -29,18 +27,12 @@ public class EmailServiceImpl implements EmailService {
@Value("${service.mail.send}")
private boolean sendMail;

@Value("${service.mail.to}")
private String mailTo;

@Value("${service.mail.from}")
private String mailFrom;

@Value("${service.mail.subject}")
private String subject;

@Value("${service.mail.logfilepath}")
private String logFilePath;

@Autowired
private JavaMailSender emailSender;

Expand All @@ -50,32 +42,29 @@ public class EmailServiceImpl implements EmailService {
private static final boolean MULTIPART = true;

@Override
public void sendEmail(List<AnalysisBean> analysisResult, List<SanityCheckWithErrorBean> queriesWithError)
public void sendEmail(String emailTo, List<AnalysisBean> analysisResult,
List<SanityCheckWithErrorBean> queriesWithError)
throws MessagingException {
if (sendMail) {
if (sendMail && emailTo.length() > 0) {
log.info("Sending email with the analysis");

MimeMessage message = emailSender.createMimeMessage();

MimeMessageHelper helper = new MimeMessageHelper(message, MULTIPART);

helper.setFrom(mailFrom);
handleRecipients(helper);
handleRecipients(emailTo, helper);
LocalDate currentDate = LocalDate.now();
String formattedSubject = subject + " - " + currentDate.getMonth() + " " + currentDate.getYear();
helper.setSubject(formattedSubject);

log.info("Mail from: " + mailFrom);
log.info("Mail to: " + mailTo);
log.info("Mail to: " + emailTo);
log.info("Subject: " + formattedSubject);

boolean html = true;
helper.setText(getText(analysisResult, queriesWithError), html);

log.info("Attach log file");
FileSystemResource file = new FileSystemResource(new File(logFilePath));
helper.addAttachment("db-sanity-check.txt", file);

ByteArrayResource exclusionSuggestion =
exclusionService.buildExclusionSuggestionFile(analysisResult);
if (exclusionSuggestion != null) {
Expand All @@ -92,7 +81,7 @@ public void sendEmail(List<AnalysisBean> analysisResult, List<SanityCheckWithErr

}

private void handleRecipients(MimeMessageHelper helper) throws MessagingException {
private void handleRecipients(String mailTo, MimeMessageHelper helper) throws MessagingException {
var mailSplit = List.of(mailTo.split(","));
helper.setTo(InternetAddress.parse(mailTo));
helper.setReplyTo(mailSplit.get(0));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.mail.MessagingException;

Expand All @@ -34,10 +36,6 @@ public class WrtSanityCheckServiceImpl implements WrtSanityCheckService {
@Autowired
private SanityCheckRepository sanityCheckRepository;

// Hold inconsistencies
private List<AnalysisBean> analysisResult = new ArrayList<>();

private List<SanityCheckWithErrorBean> queriesWithError = new ArrayList<>();

@Override
public void execute() throws MessagingException {
Expand All @@ -49,17 +47,34 @@ public void execute() throws MessagingException {
.findAll(Sort.by(Sort.Direction.ASC, "sanityCheckCategoryId", "topic"));
log.info("Found {} queries", sanityChecks.size());

executeSanityChecks(sanityChecks);
showResults();
Map<String, List<SanityCheck>> sanityChecksByEmail = sanityChecks.stream()
.collect(Collectors.groupingBy(s -> Optional.ofNullable(s.getCategory().getEmailTo()).orElse("")));
log.info("Found {} emails", sanityChecksByEmail.size());

for (Map.Entry<String, List<SanityCheck>> entry : sanityChecksByEmail.entrySet()) {
sendSanityChecksToEmail(entry.getKey(), entry.getValue());
}
}

private void sendSanityChecksToEmail(String email, List<SanityCheck> sanityChecks) throws MessagingException {

// Hold inconsistencies
List<AnalysisBean> analysisResult = new ArrayList<>();

List<SanityCheckWithErrorBean> queriesWithError = new ArrayList<>();

executeSanityChecks(sanityChecks, analysisResult, queriesWithError);
showResults(analysisResult, queriesWithError);

log.info("All queries executed");

emailService.sendEmail(analysisResult, queriesWithError);
emailService.sendEmail(email, analysisResult, queriesWithError);

log.info("Sanity check finished");
}

private void executeSanityChecks(List<SanityCheck> sanityChecks) {
private void executeSanityChecks(List<SanityCheck> sanityChecks, List<AnalysisBean> analysisResult,
List<SanityCheckWithErrorBean> queriesWithError) {
log.info("Execute queries");

String prevCategory = null;
Expand All @@ -72,14 +87,15 @@ private void executeSanityChecks(List<SanityCheck> sanityChecks) {
prevCategory = category;
}

generalAnalysis(sanityCheck);
generalAnalysis(sanityCheck, analysisResult, queriesWithError);
}
}

/**
* A general purpose analysis. If the query returns any value, it will be added to the result
*/
private void generalAnalysis(SanityCheck sanityCheck) {
private void generalAnalysis(SanityCheck sanityCheck, List<AnalysisBean> analysisResult,
List<SanityCheckWithErrorBean> queriesWithError) {
String topic = sanityCheck.getTopic();
String query = sanityCheck.getQuery();

Expand Down Expand Up @@ -194,7 +210,7 @@ private boolean partiallyEquals(JSONObject exclusion, JSONObject sanityCheckResu
}


private void showResults() {
private void showResults(List<AnalysisBean> analysisResult, List<SanityCheckWithErrorBean> queriesWithError) {
analysisResult.forEach(item -> {
log.warn(" ** Inconsistency at [{}] {}", item.getSanityCheck().getCategory().getName(),
item.getSanityCheck().getTopic());
Expand Down
2 changes: 0 additions & 2 deletions src/main/resources/application-local.properties
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,8 @@ spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect

service.mail.send=false
service.mail.to[email protected]@
service.mail.from[email protected]@
service.mail.subject=Sanity Check
service.mail.logfilepath=log/db-sanity-check.log

spring.mail.host[email protected]@
spring.mail.port=587
Expand Down
2 changes: 0 additions & 2 deletions src/main/resources/application-prod.properties
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,8 @@ [email protected]@
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect

service.mail.send=true
service.mail.to[email protected]@
service.mail.from[email protected]@
service.mail.subject=Sanity Check
service.mail.logfilepath=log/db-sanity-check.log

spring.mail.host[email protected]@
spring.mail.port=587
Expand Down
2 changes: 0 additions & 2 deletions src/main/resources/application-test.properties
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,5 @@ spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect

service.mail.send=true
service.mail.to[email protected]
service.mail.from[email protected]
service.mail.subject=Sanity Check
service.mail.logfilepath=log/db-sanity-check.log
Loading
Loading