You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@shardingsphere.apache.org by zh...@apache.org on 2020/09/29 03:29:42 UTC
[shardingsphere-elasticjob] branch master updated: Code style for
elasticjob-error-handler-email (#1511)
This is an automated email from the ASF dual-hosted git repository.
zhangliang pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/shardingsphere-elasticjob.git
The following commit(s) were added to refs/heads/master by this push:
new e6e3d5c Code style for elasticjob-error-handler-email (#1511)
e6e3d5c is described below
commit e6e3d5c6f5837a203f881c7721699deb558317be
Author: Liang Zhang <te...@163.com>
AuthorDate: Tue Sep 29 11:29:33 2020 +0800
Code style for elasticjob-error-handler-email (#1511)
* For code style
* Rename EmailConfigurationLoader
* Add dependency management for java mail
* Add try with resource for inputStream
---
.../elasticjob-error-handler-email/pom.xml | 1 -
...onLoader.java => EmailConfigurationLoader.java} | 57 +++++++-------
.../error/handler/email/EmailJobErrorHandler.java | 86 +++++++++++-----------
.../handler/email/EmailJobErrorHandlerTest.java | 27 ++++---
pom.xml | 10 ++-
5 files changed, 95 insertions(+), 86 deletions(-)
diff --git a/elasticjob-error-handler/elasticjob-error-handler-email/pom.xml b/elasticjob-error-handler/elasticjob-error-handler-email/pom.xml
index 4ec9157..7651db4 100644
--- a/elasticjob-error-handler/elasticjob-error-handler-email/pom.xml
+++ b/elasticjob-error-handler/elasticjob-error-handler-email/pom.xml
@@ -43,7 +43,6 @@
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
- <version>1.6.0</version>
</dependency>
<dependency>
diff --git a/elasticjob-error-handler/elasticjob-error-handler-email/src/main/java/org/apache/shardingsphere/elasticjob/error/handler/email/ConfigurationLoader.java b/elasticjob-error-handler/elasticjob-error-handler-email/src/main/java/org/apache/shardingsphere/elasticjob/error/handler/email/EmailConfigurationLoader.java
similarity index 51%
rename from elasticjob-error-handler/elasticjob-error-handler-email/src/main/java/org/apache/shardingsphere/elasticjob/error/handler/email/ConfigurationLoader.java
rename to elasticjob-error-handler/elasticjob-error-handler-email/src/main/java/org/apache/shardingsphere/elasticjob/error/handler/email/EmailConfigurationLoader.java
index 521e5ca..b4f79c0 100644
--- a/elasticjob-error-handler/elasticjob-error-handler-email/src/main/java/org/apache/shardingsphere/elasticjob/error/handler/email/ConfigurationLoader.java
+++ b/elasticjob-error-handler/elasticjob-error-handler-email/src/main/java/org/apache/shardingsphere/elasticjob/error/handler/email/EmailConfigurationLoader.java
@@ -22,65 +22,70 @@ import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.shardingsphere.elasticjob.infra.yaml.YamlEngine;
+import java.io.IOException;
import java.io.InputStream;
/**
* Job error configuration loader.
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
-public class ConfigurationLoader {
+public final class EmailConfigurationLoader {
- private static final String ERROR_HANDLER_CONFIG = "conf/error-handler-email.yaml";
+ private static final String CONFIG_FILE = "conf/error-handler-email.yaml";
/**
- * Unmarshal YAML.
+ * Unmarshal configuration from YAML.
*
- * @param prefix config prefix
+ * @param configPrefix configuration prefix
* @return object from YAML
*/
- public static EmailConfiguration buildConfigByYaml(final String prefix) {
- InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(ERROR_HANDLER_CONFIG);
- return YamlEngine.unmarshal(prefix, inputStream, EmailConfiguration.class);
+ public static EmailConfiguration unmarshal(final String configPrefix) {
+ try (InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(CONFIG_FILE)) {
+ return YamlEngine.unmarshal(configPrefix, inputStream, EmailConfiguration.class);
+ } catch (final IOException ex) {
+ // TODO throw config file load failure exception
+ throw new RuntimeException(ex);
+ }
}
/**
- * read system properties.
+ * Unmarshal configuration from system properties.
*
* @return object from system properties
*/
- public static EmailConfiguration buildConfigBySystemProperties() {
+ public static EmailConfiguration unmarshalFromSystemProperties() {
String isBySystemProperties = System.getProperty("error-handler-email.use-system-properties");
- if (!Boolean.valueOf(isBySystemProperties)) {
+ if (!Boolean.parseBoolean(isBySystemProperties)) {
return null;
}
- EmailConfiguration emailConfiguration = new EmailConfiguration();
- emailConfiguration.setHost(System.getProperty("error-handler-email.host"));
- emailConfiguration.setUsername(System.getProperty("error-handler-email.username"));
- emailConfiguration.setPassword(System.getProperty("error-handler-email.password"));
- emailConfiguration.setFrom(System.getProperty("error-handler-email.from"));
- emailConfiguration.setTo(System.getProperty("error-handler-email.to"));
- emailConfiguration.setCc(System.getProperty("error-handler-email.cc"));
- emailConfiguration.setBcc(System.getProperty("error-handler-email.bcc"));
+ EmailConfiguration result = new EmailConfiguration();
+ result.setHost(System.getProperty("error-handler-email.host"));
+ result.setUsername(System.getProperty("error-handler-email.username"));
+ result.setPassword(System.getProperty("error-handler-email.password"));
+ result.setFrom(System.getProperty("error-handler-email.from"));
+ result.setTo(System.getProperty("error-handler-email.to"));
+ result.setCc(System.getProperty("error-handler-email.cc"));
+ result.setBcc(System.getProperty("error-handler-email.bcc"));
String protocol = System.getProperty("error-handler-email.protocol");
if (StringUtils.isNotBlank(protocol)) {
- emailConfiguration.setProtocol(System.getProperty("error-handler-email.protocol"));
+ result.setProtocol(System.getProperty("error-handler-email.protocol"));
}
- String useSsl = System.getProperty("error-handler-email.use-ssl");
- if (StringUtils.isNotBlank(useSsl)) {
- emailConfiguration.setUseSsl(Boolean.parseBoolean(useSsl));
+ String useSSL = System.getProperty("error-handler-email.use-ssl");
+ if (StringUtils.isNotBlank(useSSL)) {
+ result.setUseSsl(Boolean.parseBoolean(useSSL));
}
String subject = System.getProperty("error-handler-email.subject");
if (StringUtils.isNotBlank(subject)) {
- emailConfiguration.setSubject(subject);
+ result.setSubject(subject);
}
String port = System.getProperty("error-handler-email.port");
if (StringUtils.isNotBlank(port)) {
- emailConfiguration.setPort(Integer.valueOf(port));
+ result.setPort(Integer.valueOf(port));
}
String debug = System.getProperty("error-handler-email.debug");
if (StringUtils.isNotBlank(debug)) {
- emailConfiguration.setDebug(Boolean.parseBoolean(debug));
+ result.setDebug(Boolean.parseBoolean(debug));
}
- return emailConfiguration;
+ return result;
}
}
diff --git a/elasticjob-error-handler/elasticjob-error-handler-email/src/main/java/org/apache/shardingsphere/elasticjob/error/handler/email/EmailJobErrorHandler.java b/elasticjob-error-handler/elasticjob-error-handler-email/src/main/java/org/apache/shardingsphere/elasticjob/error/handler/email/EmailJobErrorHandler.java
index abaafd4..2ae34d5 100644
--- a/elasticjob-error-handler/elasticjob-error-handler-email/src/main/java/org/apache/shardingsphere/elasticjob/error/handler/email/EmailJobErrorHandler.java
+++ b/elasticjob-error-handler/elasticjob-error-handler-email/src/main/java/org/apache/shardingsphere/elasticjob/error/handler/email/EmailJobErrorHandler.java
@@ -48,7 +48,7 @@ public final class EmailJobErrorHandler implements JobErrorHandler {
public static final String CONFIG_PREFIX = "email";
- private EmailConfiguration emailConfiguration;
+ private EmailConfiguration config;
private Session session;
@@ -56,10 +56,17 @@ public final class EmailJobErrorHandler implements JobErrorHandler {
loadConfiguration();
}
+ private void loadConfiguration() {
+ config = EmailConfigurationLoader.unmarshalFromSystemProperties();
+ if (null == config) {
+ config = EmailConfigurationLoader.unmarshal(CONFIG_PREFIX);
+ }
+ }
+
@Override
public void handleException(final String jobName, final Throwable cause) {
try {
- Preconditions.checkNotNull(emailConfiguration);
+ Preconditions.checkNotNull(config);
String content = buildContent(jobName, cause);
Message message = buildMessage(content);
sendMessage(message);
@@ -68,68 +75,61 @@ public final class EmailJobErrorHandler implements JobErrorHandler {
}
}
- private void loadConfiguration() {
- emailConfiguration = ConfigurationLoader.buildConfigBySystemProperties();
- if (null == emailConfiguration) {
- emailConfiguration = ConfigurationLoader.buildConfigByYaml(CONFIG_PREFIX);
- }
+ private String buildContent(final String jobName, final Throwable cause) {
+ StringWriter sw = new StringWriter();
+ cause.printStackTrace(new PrintWriter(sw, true));
+ String causeString = sw.toString();
+ return String.format("Job '%s' exception occur in job processing, caused by %s", jobName, causeString);
}
- @Override
- public String getType() {
- return "EMAIL";
+ private Message buildMessage(final String content) throws MessagingException {
+ MimeMessage message = new MimeMessage(Optional.ofNullable(session).orElseGet(this::buildSession));
+ message.setFrom(new InternetAddress(config.getFrom()));
+ message.setSubject(config.getSubject());
+ message.setSentDate(new Date());
+ Multipart multipart = new MimeMultipart();
+ BodyPart mailBody = new MimeBodyPart();
+ mailBody.setContent(content, "text/html; charset=utf-8");
+ multipart.addBodyPart(mailBody);
+ message.setContent(multipart);
+ if (StringUtils.isNotBlank(config.getTo())) {
+ message.addRecipient(Message.RecipientType.TO, new InternetAddress(config.getTo()));
+ }
+ if (StringUtils.isNotBlank(config.getCc())) {
+ message.addRecipient(Message.RecipientType.CC, new InternetAddress(config.getCc()));
+ }
+ message.saveChanges();
+ return message;
}
private synchronized Session buildSession() {
if (null == session) {
Properties props = new Properties();
- props.put("mail.smtp.host", emailConfiguration.getHost());
- props.put("mail.smtp.port", emailConfiguration.getPort());
+ props.put("mail.smtp.host", config.getHost());
+ props.put("mail.smtp.port", config.getPort());
props.put("mail.smtp.auth", "true");
- props.put("mail.transport.protocol", emailConfiguration.getProtocol());
- props.setProperty("mail.debug", Boolean.toString(emailConfiguration.isDebug()));
- if (emailConfiguration.isUseSsl()) {
+ props.put("mail.transport.protocol", config.getProtocol());
+ props.setProperty("mail.debug", Boolean.toString(config.isDebug()));
+ if (config.isUseSsl()) {
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
}
session = Session.getDefaultInstance(props, new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(emailConfiguration.getUsername(), emailConfiguration.getPassword());
+ return new PasswordAuthentication(config.getUsername(), config.getPassword());
}
});
}
return session;
}
- private Message buildMessage(final String content) throws MessagingException {
- MimeMessage message = new MimeMessage(Optional.ofNullable(session).orElseGet(this::buildSession));
- message.setFrom(new InternetAddress(emailConfiguration.getFrom()));
- message.setSubject(emailConfiguration.getSubject());
- message.setSentDate(new Date());
- Multipart multipart = new MimeMultipart();
- BodyPart mailBody = new MimeBodyPart();
- mailBody.setContent(content, "text/html; charset=utf-8");
- multipart.addBodyPart(mailBody);
- message.setContent(multipart);
- if (StringUtils.isNotBlank(emailConfiguration.getTo())) {
- message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailConfiguration.getTo()));
- }
- if (StringUtils.isNotBlank(emailConfiguration.getCc())) {
- message.addRecipient(Message.RecipientType.CC, new InternetAddress(emailConfiguration.getCc()));
- }
- message.saveChanges();
- return message;
- }
-
- private String buildContent(final String jobName, final Throwable cause) {
- StringWriter sw = new StringWriter();
- cause.printStackTrace(new PrintWriter(sw, true));
- String causeString = sw.toString();
- return String.format("Job '%s' exception occur in job processing, caused by %s", jobName, causeString);
- }
-
private void sendMessage(final Message message) throws MessagingException {
Transport.send(message);
}
+
+ @Override
+ public String getType() {
+ return "EMAIL";
+ }
}
diff --git a/elasticjob-error-handler/elasticjob-error-handler-email/src/test/java/org/apache/shardingsphere/elasticjob/error/handler/email/EmailJobErrorHandlerTest.java b/elasticjob-error-handler/elasticjob-error-handler-email/src/test/java/org/apache/shardingsphere/elasticjob/error/handler/email/EmailJobErrorHandlerTest.java
index 9674751..b84aa18 100644
--- a/elasticjob-error-handler/elasticjob-error-handler-email/src/test/java/org/apache/shardingsphere/elasticjob/error/handler/email/EmailJobErrorHandlerTest.java
+++ b/elasticjob-error-handler/elasticjob-error-handler-email/src/test/java/org/apache/shardingsphere/elasticjob/error/handler/email/EmailJobErrorHandlerTest.java
@@ -24,8 +24,10 @@ import org.mockito.ArgumentMatchers;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.slf4j.Logger;
+
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
+
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
@@ -34,17 +36,16 @@ import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class)
public final class EmailJobErrorHandlerTest {
-
+
@Mock
private Logger log;
-
+
@Test
- @SneakyThrows
- public void assertHandleExceptionWithYAMLConfiguration() {
+ public void assertHandleExceptionWithYAMLConfiguration() throws ReflectiveOperationException {
resetSystemProperties();
EmailJobErrorHandler emailJobErrorHandler = new EmailJobErrorHandler();
emailJobErrorHandler.handleException("test job name", new RuntimeException("test exception"));
- Field field = emailJobErrorHandler.getClass().getDeclaredField("emailConfiguration");
+ Field field = emailJobErrorHandler.getClass().getDeclaredField("config");
field.setAccessible(true);
EmailConfiguration emailConfiguration = (EmailConfiguration) field.get(emailJobErrorHandler);
assertNotNull(emailConfiguration);
@@ -61,12 +62,11 @@ public final class EmailJobErrorHandlerTest {
}
@Test
- @SneakyThrows
- public void assertHandleExceptionWithSystemPropertiesConfiguration() {
+ public void assertHandleExceptionWithSystemPropertiesConfiguration() throws ReflectiveOperationException {
initSystemProperties();
EmailJobErrorHandler emailJobErrorHandler = new EmailJobErrorHandler();
emailJobErrorHandler.handleException("test job name", new RuntimeException("test exception"));
- Field field = emailJobErrorHandler.getClass().getDeclaredField("emailConfiguration");
+ Field field = emailJobErrorHandler.getClass().getDeclaredField("config");
field.setAccessible(true);
EmailConfiguration emailConfiguration = (EmailConfiguration) field.get(emailJobErrorHandler);
assertNotNull(emailConfiguration);
@@ -80,12 +80,11 @@ public final class EmailJobErrorHandlerTest {
assertTrue(emailConfiguration.isUseSsl());
assertTrue(emailConfiguration.isDebug());
}
-
+
@Test
- @SneakyThrows
- public void assertHandleExceptionForNullConfiguration() {
+ public void assertHandleExceptionForNullConfiguration() throws ReflectiveOperationException {
EmailJobErrorHandler emailJobErrorHandler = new EmailJobErrorHandler();
- Field emailConfigurationField = EmailJobErrorHandler.class.getDeclaredField("emailConfiguration");
+ Field emailConfigurationField = EmailJobErrorHandler.class.getDeclaredField("config");
emailConfigurationField.setAccessible(true);
emailConfigurationField.set(emailJobErrorHandler, null);
setStaticFieldValue(emailJobErrorHandler);
@@ -93,7 +92,7 @@ public final class EmailJobErrorHandlerTest {
emailJobErrorHandler.handleException("test job name", cause);
verify(log).error(ArgumentMatchers.any(String.class), ArgumentMatchers.any(NullPointerException.class));
}
-
+
@SneakyThrows
private void setStaticFieldValue(final EmailJobErrorHandler emailJobErrorHandler) {
Field field = emailJobErrorHandler.getClass().getDeclaredField("log");
@@ -103,7 +102,7 @@ public final class EmailJobErrorHandlerTest {
modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(emailJobErrorHandler, log);
}
-
+
@Test
public void assertType() {
EmailJobErrorHandler emailJobErrorHandler = new EmailJobErrorHandler();
diff --git a/pom.xml b/pom.xml
index 63a88f7..c525742 100644
--- a/pom.xml
+++ b/pom.xml
@@ -62,6 +62,8 @@
<fenzo.version>0.11.1</fenzo.version>
<commons-dbcp.version>1.4</commons-dbcp.version>
+ <mail.version>1.6.0</mail.version>
+
<mysql-connector-java.version>8.0.16</mysql-connector-java.version>
<h2.version>1.4.184</h2.version>
<junit.version>4.12</junit.version>
@@ -197,7 +199,7 @@
<artifactId>netty-codec-http</artifactId>
<version>${netty.version}</version>
</dependency>
-
+
<dependency>
<groupId>org.apache.mesos</groupId>
<artifactId>mesos</artifactId>
@@ -208,12 +210,16 @@
<artifactId>fenzo-core</artifactId>
<version>${fenzo.version}</version>
</dependency>
-
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>${commons-dbcp.version}</version>
</dependency>
+ <dependency>
+ <groupId>com.sun.mail</groupId>
+ <artifactId>javax.mail</artifactId>
+ <version>${mail.version}</version>
+ </dependency>
<dependency>
<groupId>org.projectlombok</groupId>