parent
be9d328eee
commit
c0a0544923
@ -0,0 +1,70 @@
|
|||||||
|
package com.example.sbcamel.service;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
import javax.mail.Message;
|
||||||
|
import javax.mail.Session;
|
||||||
|
import javax.mail.Transport;
|
||||||
|
import javax.mail.internet.InternetAddress;
|
||||||
|
import javax.mail.internet.MimeMessage;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class EmailService {
|
||||||
|
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(EmailService.class);
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private Properties javaMailProperties;
|
||||||
|
|
||||||
|
public boolean sendEmail(String fromAddress, String smtpPassword, String[] toAddresses, String subject,
|
||||||
|
String content) {
|
||||||
|
try {
|
||||||
|
logger.debug("[sendEmail] fromAddress: {}, toAddresses: {}", fromAddress, toAddresses);
|
||||||
|
if (StringUtils.isEmpty(subject) || StringUtils.isEmpty(smtpPassword) || StringUtils.isEmpty(fromAddress)
|
||||||
|
|| toAddresses.length == 0) {
|
||||||
|
logger.warn("[sendEmail] subject, smtp-password, source-address or target-address is not set");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
String emailHost = javaMailProperties.getProperty("mail.smtp.host");
|
||||||
|
logger.debug("[sendEmail] {} -> {}, mail.smtp.host: {}", fromAddress, List.of(toAddresses), emailHost);
|
||||||
|
if (StringUtils.isNotBlank(emailHost) && StringUtils.isNotBlank(fromAddress) && toAddresses.length > 0) {
|
||||||
|
logger.debug("[sendEmail] starting to send message from: {}", fromAddress);
|
||||||
|
Session session = Session.getInstance(javaMailProperties);
|
||||||
|
|
||||||
|
MimeMessage message = new MimeMessage(session);
|
||||||
|
message.setContent(content, "text/html; charset=utf-8");
|
||||||
|
message.setFrom(new InternetAddress(fromAddress));
|
||||||
|
|
||||||
|
Arrays.asList(toAddresses).forEach(toAddress -> {
|
||||||
|
try {
|
||||||
|
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error("sendEmail error!", e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
message.setSubject(subject);
|
||||||
|
|
||||||
|
Transport transport = session.getTransport("smtp");
|
||||||
|
transport.connect(emailHost, fromAddress, smtpPassword);
|
||||||
|
transport.sendMessage(message, message.getAllRecipients());
|
||||||
|
transport.close();
|
||||||
|
logger.debug("sendEmail to: {}", Arrays.asList(toAddresses));
|
||||||
|
|
||||||
|
return true;
|
||||||
|
} else {
|
||||||
|
logger.warn("[sendEmail] missing either from-field, to-field or host address!");
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error("sendEmail error!", e);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,161 @@
|
|||||||
|
package com.example.sbcamel.service;
|
||||||
|
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.apache.commons.io.FileUtils;
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
import org.apache.commons.lang3.tuple.Pair;
|
||||||
|
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
|
||||||
|
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
|
||||||
|
import org.apache.hc.core5.http.ClassicHttpResponse;
|
||||||
|
import org.apache.hc.core5.http.HttpException;
|
||||||
|
import org.apache.hc.core5.http.io.HttpClientResponseHandler;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.type.TypeReference;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.google.common.collect.MapDifference;
|
||||||
|
import com.google.common.collect.MapDifference.ValueDifference;
|
||||||
|
import com.google.common.collect.Maps;
|
||||||
|
|
||||||
|
public class InspectionClient {
|
||||||
|
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(InspectionClient.class);
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private CloseableHttpClient httpClient;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private EmailService emailService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
@Value("${app.inspection-client.email-password:}")
|
||||||
|
private String smtpPassword;
|
||||||
|
|
||||||
|
@Value("${app.inspection-client.email-sender:}")
|
||||||
|
private String fromAddress;
|
||||||
|
|
||||||
|
@Value("${app.inspection-client.email-recipient:}")
|
||||||
|
private String[] toAddresses;
|
||||||
|
|
||||||
|
@Value("${app.inspection-client.http-url}")
|
||||||
|
private String url;
|
||||||
|
|
||||||
|
@Value("${app.inspection-client.http-method}")
|
||||||
|
private String httpMethod;
|
||||||
|
|
||||||
|
@Value("${app.inspection-client.expected-result-file-path}")
|
||||||
|
private String expectedResultFilePath;
|
||||||
|
|
||||||
|
@Value("${app.inspection-client.alert-subject}")
|
||||||
|
private String alertSubject;
|
||||||
|
|
||||||
|
@Value("${app.inspection-client.http-username}")
|
||||||
|
private String username;
|
||||||
|
|
||||||
|
@Value("${app.inspection-client.http-password}")
|
||||||
|
private String password;
|
||||||
|
|
||||||
|
private static final String getBasicAuthenticationHeader(String username, String password) {
|
||||||
|
String valueToEncode = username + ":" + password;
|
||||||
|
return "Basic " + Base64.getEncoder().encodeToString(valueToEncode.getBytes());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void sendMessage() {
|
||||||
|
try {
|
||||||
|
File jsonFile = new File(expectedResultFilePath);
|
||||||
|
if (!jsonFile.exists()) {
|
||||||
|
logger.info("file does not exist: {}", expectedResultFilePath);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
String jsonString = FileUtils.readFileToString(jsonFile, StandardCharsets.UTF_8);
|
||||||
|
logger.info("expected result: {}", jsonString);
|
||||||
|
HashMap<String, Object> expectedMap = convertStringToMap(jsonString);
|
||||||
|
logger.info("calling {} {}", httpMethod, url);
|
||||||
|
|
||||||
|
HttpUriRequestBase req = new HttpUriRequestBase(httpMethod, URI.create(url));
|
||||||
|
req.addHeader("Authorization", getBasicAuthenticationHeader(username, password));
|
||||||
|
Pair<Boolean, Boolean> sendEmailResult = httpClient.execute(req,
|
||||||
|
new HttpClientResponseHandler<Pair<Boolean, Boolean>>() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Pair<Boolean, Boolean> handleResponse(ClassicHttpResponse result)
|
||||||
|
throws HttpException, IOException {
|
||||||
|
|
||||||
|
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||||
|
result.getEntity().writeTo(baos);
|
||||||
|
String responseText = new String(baos.toByteArray(), StandardCharsets.UTF_8);
|
||||||
|
logger.info("actual result: {}", responseText);
|
||||||
|
|
||||||
|
if (StringUtils.isEmpty(responseText)) {
|
||||||
|
logger.error("actual result is empty!");
|
||||||
|
return Pair.of(Boolean.FALSE, Boolean.FALSE);
|
||||||
|
}
|
||||||
|
baos.close();
|
||||||
|
try {
|
||||||
|
HashMap<String, Object> resultMap = convertStringToMap(responseText);
|
||||||
|
MapDifference<String, Object> diff = Maps.difference(expectedMap, resultMap);
|
||||||
|
logger.info("diff.areEqual: {}", diff.areEqual());
|
||||||
|
StringBuilder contentBuilder = new StringBuilder();
|
||||||
|
if (!diff.areEqual()) {
|
||||||
|
Map<String, ValueDifference<Object>> entriesDiffering = diff.entriesDiffering();
|
||||||
|
entriesDiffering.entrySet().stream().forEach(entry -> {
|
||||||
|
logger.info("entriesDiffering key: {}", entry.getKey());
|
||||||
|
logger.info("entriesDiffering expected: {}", entry.getValue().leftValue());
|
||||||
|
logger.info("entriesDiffering actual: {}", entry.getValue().rightValue());
|
||||||
|
contentBuilder.append(entry.getKey() + "\n");
|
||||||
|
contentBuilder.append("EXPECTED: " + entry.getValue().leftValue() + "\n");
|
||||||
|
contentBuilder.append("ACTUAL: " + entry.getValue().rightValue() + "\n");
|
||||||
|
contentBuilder.append("\n");
|
||||||
|
});
|
||||||
|
return Pair.of(Boolean.TRUE, emailService.sendEmail(fromAddress, smtpPassword,
|
||||||
|
toAddresses, alertSubject, contentBuilder.toString()));
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
logger.error("Error occurred while parsing message", e);
|
||||||
|
}
|
||||||
|
return Pair.of(Boolean.FALSE, Boolean.FALSE);
|
||||||
|
}
|
||||||
|
|
||||||
|
});
|
||||||
|
logger.info("send email result: {}", sendEmailResult);
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error("Error occurred while preparing to send message", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public HashMap<String, Object> convertStringToMap(String jsonString) throws IOException {
|
||||||
|
TypeReference<java.util.HashMap<String, Object>> ref = new TypeReference<>() {
|
||||||
|
};
|
||||||
|
return new HashMap<>(objectMapper.readValue(jsonString, ref));
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getUrl() {
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setUrl(String url) {
|
||||||
|
this.url = url;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getHttpMethod() {
|
||||||
|
return httpMethod;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setHttpMethod(String httpMethod) {
|
||||||
|
this.httpMethod = httpMethod;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,19 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xmlns:task="http://www.springframework.org/schema/task"
|
||||||
|
xsi:schemaLocation="http://www.springframework.org/schema/task https://www.springframework.org/schema/task/spring-task.xsd
|
||||||
|
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
|
||||||
|
|
||||||
|
<task:scheduler id="inspectionScheduler" pool-size="2" />
|
||||||
|
|
||||||
|
<bean id="inspectionClient"
|
||||||
|
class="com.example.sbcamel.service.InspectionClient">
|
||||||
|
</bean>
|
||||||
|
|
||||||
|
<task:scheduled-tasks scheduler="inspectionScheduler">
|
||||||
|
<task:scheduled ref="inspectionClient"
|
||||||
|
method="sendMessage" cron="0 * * * * ?" />
|
||||||
|
</task:scheduled-tasks>
|
||||||
|
|
||||||
|
</beans>
|
||||||
Loading…
Reference in new issue