Commit 99d97b79 by Johannes Edmeier

fix deprecations

parent 74c1089d
...@@ -15,9 +15,18 @@ ...@@ -15,9 +15,18 @@
*/ */
package de.codecentric.boot.admin.config; package de.codecentric.boot.admin.config;
import de.codecentric.boot.admin.event.ClientApplicationDeregisteredEvent;
import de.codecentric.boot.admin.event.ClientApplicationRegisteredEvent;
import de.codecentric.boot.admin.event.RoutesOutdatedEvent;
import de.codecentric.boot.admin.journal.ApplicationEventJournal;
import de.codecentric.boot.admin.journal.web.JournalController;
import de.codecentric.boot.admin.registry.ApplicationRegistry;
import de.codecentric.boot.admin.registry.web.RegistryController;
import de.codecentric.boot.admin.web.AdminController;
import de.codecentric.boot.admin.web.PrefixHandlerMapping;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationContextAware;
...@@ -28,87 +37,75 @@ import org.springframework.context.event.EventListener; ...@@ -28,87 +37,75 @@ import org.springframework.context.event.EventListener;
import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import de.codecentric.boot.admin.event.ClientApplicationDeregisteredEvent;
import de.codecentric.boot.admin.event.ClientApplicationRegisteredEvent;
import de.codecentric.boot.admin.event.RoutesOutdatedEvent;
import de.codecentric.boot.admin.journal.ApplicationEventJournal;
import de.codecentric.boot.admin.journal.web.JournalController;
import de.codecentric.boot.admin.registry.ApplicationRegistry;
import de.codecentric.boot.admin.registry.web.RegistryController;
import de.codecentric.boot.admin.web.AdminController;
import de.codecentric.boot.admin.web.PrefixHandlerMapping;
@Configuration @Configuration
public class AdminServerWebConfiguration extends WebMvcConfigurerAdapter public class AdminServerWebConfiguration implements WebMvcConfigurer, ApplicationContextAware {
implements ApplicationContextAware { private final ApplicationEventPublisher publisher;
private final ApplicationEventPublisher publisher; private final AdminServerProperties adminServerProperties;
private final AdminServerProperties adminServerProperties; private ApplicationContext applicationContext;
private ApplicationContext applicationContext;
public AdminServerWebConfiguration(ApplicationEventPublisher publisher, public AdminServerWebConfiguration(ApplicationEventPublisher publisher,
AdminServerProperties adminServerProperties) { AdminServerProperties adminServerProperties) {
this.publisher = publisher; this.publisher = publisher;
this.adminServerProperties = adminServerProperties; this.adminServerProperties = adminServerProperties;
} }
@Override @Override
public void setApplicationContext(ApplicationContext applicationContext) { public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext; this.applicationContext = applicationContext;
} }
@Override @Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) { public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
if (!hasConverter(converters, MappingJackson2HttpMessageConverter.class)) { if (!hasConverter(converters, MappingJackson2HttpMessageConverter.class)) {
ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json() ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json()
.applicationContext(this.applicationContext).build(); .applicationContext(this.applicationContext)
converters.add(new MappingJackson2HttpMessageConverter(objectMapper)); .build();
} converters.add(new MappingJackson2HttpMessageConverter(objectMapper));
} }
}
private boolean hasConverter(List<HttpMessageConverter<?>> converters, private boolean hasConverter(List<HttpMessageConverter<?>> converters,
Class<? extends HttpMessageConverter<?>> clazz) { Class<? extends HttpMessageConverter<?>> clazz) {
for (HttpMessageConverter<?> converter : converters) { for (HttpMessageConverter<?> converter : converters) {
if (clazz.isInstance(converter)) { if (clazz.isInstance(converter)) {
return true; return true;
} }
} }
return false; return false;
} }
@Bean @Bean
public PrefixHandlerMapping prefixHandlerMapping() { public PrefixHandlerMapping prefixHandlerMapping() {
Map<String, Object> beans = applicationContext Map<String, Object> beans = applicationContext.getBeansWithAnnotation(AdminController.class);
.getBeansWithAnnotation(AdminController.class); PrefixHandlerMapping prefixHandlerMapping = new PrefixHandlerMapping(
PrefixHandlerMapping prefixHandlerMapping = new PrefixHandlerMapping( beans.values().toArray(new Object[beans.size()]));
beans.values().toArray(new Object[beans.size()])); prefixHandlerMapping.setPrefix(adminServerProperties.getContextPath());
prefixHandlerMapping.setPrefix(adminServerProperties.getContextPath()); return prefixHandlerMapping;
return prefixHandlerMapping; }
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public RegistryController registryController(ApplicationRegistry applicationRegistry) { public RegistryController registryController(ApplicationRegistry applicationRegistry) {
return new RegistryController(applicationRegistry); return new RegistryController(applicationRegistry);
} }
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public JournalController journalController(ApplicationEventJournal applicationEventJournal) { public JournalController journalController(ApplicationEventJournal applicationEventJournal) {
return new JournalController(applicationEventJournal); return new JournalController(applicationEventJournal);
} }
@EventListener @EventListener
public void onClientApplicationRegistered(ClientApplicationRegisteredEvent event) { public void onClientApplicationRegistered(ClientApplicationRegisteredEvent event) {
publisher.publishEvent(new RoutesOutdatedEvent()); publisher.publishEvent(new RoutesOutdatedEvent());
} }
@EventListener @EventListener
public void onClientApplicationDeregistered(ClientApplicationDeregisteredEvent event) { public void onClientApplicationDeregistered(ClientApplicationDeregisteredEvent event) {
publisher.publishEvent(new RoutesOutdatedEvent()); publisher.publishEvent(new RoutesOutdatedEvent());
} }
} }
...@@ -32,6 +32,7 @@ import org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfigu ...@@ -32,6 +32,7 @@ import org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfigu
import org.springframework.boot.test.util.EnvironmentTestUtils; import org.springframework.boot.test.util.EnvironmentTestUtils;
import org.springframework.cloud.client.discovery.simple.SimpleDiscoveryClientAutoConfiguration; import org.springframework.cloud.client.discovery.simple.SimpleDiscoveryClientAutoConfiguration;
import org.springframework.cloud.commons.util.UtilAutoConfiguration; import org.springframework.cloud.commons.util.UtilAutoConfiguration;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter;
...@@ -126,7 +127,7 @@ public class AdminServerWebConfigurationTest { ...@@ -126,7 +127,7 @@ public class AdminServerWebConfigurationTest {
applicationContext.register(AdminServerCoreConfiguration.class); applicationContext.register(AdminServerCoreConfiguration.class);
applicationContext.register(AdminServerWebConfiguration.class); applicationContext.register(AdminServerWebConfiguration.class);
EnvironmentTestUtils.addEnvironment(applicationContext, environment); TestPropertyValues.of(environment).applyTo(applicationContext);
applicationContext.refresh(); applicationContext.refresh();
this.context = applicationContext; this.context = applicationContext;
} }
......
...@@ -31,7 +31,7 @@ import java.util.List; ...@@ -31,7 +31,7 @@ import java.util.List;
import org.junit.After; import org.junit.After;
import org.junit.Test; import org.junit.Test;
import org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration; import org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration;
import org.springframework.boot.test.util.EnvironmentTestUtils; import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Primary;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
...@@ -108,7 +108,7 @@ public class NotifierConfigurationTest { ...@@ -108,7 +108,7 @@ public class NotifierConfigurationTest {
context.register(MailSenderAutoConfiguration.class); context.register(MailSenderAutoConfiguration.class);
context.register(NotifierConfiguration.class); context.register(NotifierConfiguration.class);
EnvironmentTestUtils.addEnvironment(context, environment); TestPropertyValues.of(environment).applyTo(context);
context.refresh(); context.refresh();
} }
......
package de.codecentric.boot.admin.notify; package de.codecentric.boot.admin.notify;
import static java.util.Arrays.asList; import de.codecentric.boot.admin.event.ClientApplicationStatusChangedEvent;
import static org.assertj.core.api.Assertions.assertThat; import de.codecentric.boot.admin.model.Application;
import static org.mockito.Matchers.eq; import de.codecentric.boot.admin.model.StatusInfo;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.net.URI; import java.net.URI;
import java.util.Map; import java.util.Map;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
...@@ -17,80 +13,75 @@ import org.springframework.http.HttpEntity; ...@@ -17,80 +13,75 @@ import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import de.codecentric.boot.admin.event.ClientApplicationStatusChangedEvent; import static java.util.Arrays.asList;
import de.codecentric.boot.admin.model.Application; import static org.assertj.core.api.Assertions.assertThat;
import de.codecentric.boot.admin.model.StatusInfo; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/** /**
* @author Jamie Brown * @author Jamie Brown
*/ */
public class HipchatNotifierTest { public class HipchatNotifierTest {
private HipchatNotifier notifier; private HipchatNotifier notifier;
private RestTemplate restTemplate; private RestTemplate restTemplate;
@Before @Before
public void setUp() { public void setUp() {
restTemplate = mock(RestTemplate.class); restTemplate = mock(RestTemplate.class);
notifier = new HipchatNotifier(); notifier = new HipchatNotifier();
notifier.setNotify(true); notifier.setNotify(true);
notifier.setAuthToken("--token-"); notifier.setAuthToken("--token-");
notifier.setRoomId("-room-"); notifier.setRoomId("-room-");
notifier.setUrl(URI.create("http://localhost/v2")); notifier.setUrl(URI.create("http://localhost/v2"));
notifier.setRestTemplate(restTemplate); notifier.setRestTemplate(restTemplate);
} }
@Test @Test
public void test_onApplicationEvent_resolve() { public void test_onApplicationEvent_resolve() {
StatusInfo infoDown = StatusInfo.ofDown(); StatusInfo infoDown = StatusInfo.ofDown();
StatusInfo infoUp = StatusInfo.ofUp(); StatusInfo infoUp = StatusInfo.ofUp();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked") ArgumentCaptor<HttpEntity<Map<String, Object>>> httpRequest = ArgumentCaptor.forClass(
ArgumentCaptor<HttpEntity<Map<String, Object>>> httpRequest = ArgumentCaptor (Class<HttpEntity<Map<String, Object>>>) (Class<?>) HttpEntity.class);
.forClass((Class<HttpEntity<Map<String, Object>>>) (Class<?>) HttpEntity.class);
when(restTemplate.postForEntity(isA(String.class), httpRequest.capture(), eq(Void.class))).thenReturn(
when(restTemplate.postForEntity(isA(String.class), httpRequest.capture(), eq(Void.class))) ResponseEntity.ok((Void) null));
.thenReturn(ResponseEntity.ok((Void) null));
notifier.notify(new ClientApplicationStatusChangedEvent(
notifier.notify(new ClientApplicationStatusChangedEvent( Application.create("App").withId("-id-").withHealthUrl("http://health").build(), infoDown, infoUp));
Application.create("App").withId("-id-").withHealthUrl("http://health").build(),
infoDown, infoUp)); assertThat(httpRequest.getValue().getHeaders()).containsEntry("Content-Type", asList("application/json"));
assertThat(httpRequest.getValue().getHeaders()).containsEntry("Content-Type", Map<String, Object> body = httpRequest.getValue().getBody();
asList("application/json")); assertThat(body).containsEntry("color", "green");
assertThat(body).containsEntry("message", "<strong>App</strong>/-id- is <strong>UP</strong>");
Map<String, Object> body = httpRequest.getValue().getBody(); assertThat(body).containsEntry("notify", Boolean.TRUE);
assertThat(body).containsEntry("color", "green"); assertThat(body).containsEntry("message_format", "html");
assertThat(body).containsEntry("message",
"<strong>App</strong>/-id- is <strong>UP</strong>"); }
assertThat(body).containsEntry("notify", Boolean.TRUE);
assertThat(body).containsEntry("message_format", "html"); @Test
public void test_onApplicationEvent_trigger() {
} StatusInfo infoDown = StatusInfo.ofDown();
StatusInfo infoUp = StatusInfo.ofUp();
@Test
public void test_onApplicationEvent_trigger() { @SuppressWarnings("unchecked") ArgumentCaptor<HttpEntity<Map<String, Object>>> httpRequest = ArgumentCaptor.forClass(
StatusInfo infoDown = StatusInfo.ofDown(); (Class<HttpEntity<Map<String, Object>>>) (Class<?>) HttpEntity.class);
StatusInfo infoUp = StatusInfo.ofUp();
when(restTemplate.postForEntity(isA(String.class), httpRequest.capture(), eq(Void.class))).thenReturn(
@SuppressWarnings("unchecked") ResponseEntity.ok((Void) null));
ArgumentCaptor<HttpEntity<Map<String, Object>>> httpRequest = ArgumentCaptor
.forClass((Class<HttpEntity<Map<String, Object>>>) (Class<?>) HttpEntity.class); notifier.notify(new ClientApplicationStatusChangedEvent(
Application.create("App").withId("-id-").withHealthUrl("http://health").build(), infoUp, infoDown));
when(restTemplate.postForEntity(isA(String.class), httpRequest.capture(), eq(Void.class)))
.thenReturn(ResponseEntity.ok((Void) null)); assertThat(httpRequest.getValue().getHeaders()).containsEntry("Content-Type", asList("application/json"));
notifier.notify(new ClientApplicationStatusChangedEvent( Map<String, Object> body = httpRequest.getValue().getBody();
Application.create("App").withId("-id-").withHealthUrl("http://health").build(), assertThat(body).containsEntry("color", "red");
infoUp, infoDown)); assertThat(body).containsEntry("message", "<strong>App</strong>/-id- is <strong>DOWN</strong>");
assertThat(body).containsEntry("notify", Boolean.TRUE);
assertThat(httpRequest.getValue().getHeaders()).containsEntry("Content-Type", assertThat(body).containsEntry("message_format", "html");
asList("application/json")); }
Map<String, Object> body = httpRequest.getValue().getBody();
assertThat(body).containsEntry("color", "red");
assertThat(body).containsEntry("message",
"<strong>App</strong>/-id- is <strong>DOWN</strong>");
assertThat(body).containsEntry("notify", Boolean.TRUE);
assertThat(body).containsEntry("message_format", "html");
}
} }
package de.codecentric.boot.admin.notify; package de.codecentric.boot.admin.notify;
import static org.mockito.Matchers.eq; import de.codecentric.boot.admin.event.ClientApplicationStatusChangedEvent;
import static org.mockito.Mockito.mock; import de.codecentric.boot.admin.model.Application;
import static org.mockito.Mockito.verify; import de.codecentric.boot.admin.model.StatusInfo;
import java.net.URI; import java.net.URI;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.springframework.http.HttpEntity; import org.springframework.http.HttpEntity;
...@@ -17,73 +16,74 @@ import org.springframework.http.MediaType; ...@@ -17,73 +16,74 @@ import org.springframework.http.MediaType;
import org.springframework.util.Base64Utils; import org.springframework.util.Base64Utils;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import de.codecentric.boot.admin.event.ClientApplicationStatusChangedEvent; import static org.mockito.ArgumentMatchers.eq;
import de.codecentric.boot.admin.model.Application; import static org.mockito.Mockito.mock;
import de.codecentric.boot.admin.model.StatusInfo; import static org.mockito.Mockito.verify;
public class LetsChatNotifierTest { public class LetsChatNotifierTest {
private static final String room = "text_room"; private static final String room = "text_room";
private static final String token = "text_token"; private static final String token = "text_token";
private static final String user = "api_user"; private static final String user = "api_user";
private static final String appName = "App"; private static final String appName = "App";
private static final String id = "-id-"; private static final String id = "-id-";
private static final String host = "http://localhost"; private static final String host = "http://localhost";
private LetsChatNotifier notifier; private LetsChatNotifier notifier;
private RestTemplate restTemplate; private RestTemplate restTemplate;
@Before @Before
public void setUp() { public void setUp() {
restTemplate = mock(RestTemplate.class); restTemplate = mock(RestTemplate.class);
notifier = new LetsChatNotifier(); notifier = new LetsChatNotifier();
notifier.setUsername(user); notifier.setUsername(user);
notifier.setUrl(URI.create(host)); notifier.setUrl(URI.create(host));
notifier.setRoom(room); notifier.setRoom(room);
notifier.setToken(token); notifier.setToken(token);
notifier.setRestTemplate(restTemplate); notifier.setRestTemplate(restTemplate);
} }
@Test @Test
public void test_onApplicationEvent_resolve() { public void test_onApplicationEvent_resolve() {
StatusInfo infoDown = StatusInfo.ofDown(); StatusInfo infoDown = StatusInfo.ofDown();
StatusInfo infoUp = StatusInfo.ofUp(); StatusInfo infoUp = StatusInfo.ofUp();
notifier.notify(getEvent(infoDown, infoUp)); notifier.notify(getEvent(infoDown, infoUp));
HttpEntity<?> expected = expectedMessage(standardMessage(infoUp.getStatus(), appName, id)); HttpEntity<?> expected = expectedMessage(standardMessage(infoUp.getStatus(), appName, id));
verify(restTemplate).exchange(eq(URI.create(String.format("%s/rooms/%s/messages", host, room))), eq(HttpMethod.POST), eq(expected), eq(Void.class)); verify(restTemplate).exchange(eq(URI.create(String.format("%s/rooms/%s/messages", host, room))),
} eq(HttpMethod.POST), eq(expected), eq(Void.class));
}
@Test
public void test_onApplicationEvent_resolve_with_custom_message() { @Test
StatusInfo infoDown = StatusInfo.ofDown(); public void test_onApplicationEvent_resolve_with_custom_message() {
StatusInfo infoUp = StatusInfo.ofUp(); StatusInfo infoDown = StatusInfo.ofDown();
StatusInfo infoUp = StatusInfo.ofUp();
notifier.setMessage("TEST");
notifier.notify(getEvent(infoDown, infoUp)); notifier.setMessage("TEST");
notifier.notify(getEvent(infoDown, infoUp));
HttpEntity<?> expected = expectedMessage("TEST");
verify(restTemplate).exchange(eq(URI.create(String.format("%s/rooms/%s/messages", host, room))), eq(HttpMethod.POST), eq(expected), eq(Void.class)); HttpEntity<?> expected = expectedMessage("TEST");
} verify(restTemplate).exchange(eq(URI.create(String.format("%s/rooms/%s/messages", host, room))),
eq(HttpMethod.POST), eq(expected), eq(Void.class));
private ClientApplicationStatusChangedEvent getEvent(StatusInfo infoDown, StatusInfo infoUp) { }
return new ClientApplicationStatusChangedEvent(
Application.create(appName).withId(id).withHealthUrl("http://health").build(), private ClientApplicationStatusChangedEvent getEvent(StatusInfo infoDown, StatusInfo infoUp) {
infoDown, infoUp); return new ClientApplicationStatusChangedEvent(
} Application.create(appName).withId(id).withHealthUrl("http://health").build(), infoDown, infoUp);
}
private HttpEntity<?> expectedMessage(String message) {
HttpHeaders httpHeaders = new HttpHeaders(); private HttpEntity<?> expectedMessage(String message) {
httpHeaders.setContentType(MediaType.APPLICATION_JSON); HttpHeaders httpHeaders = new HttpHeaders();
String auth = Base64Utils.encodeToString(String.format("%s:%s", token, user).getBytes()); httpHeaders.setContentType(MediaType.APPLICATION_JSON);
httpHeaders.add(HttpHeaders.AUTHORIZATION, String.format("Basic %s", auth)); String auth = Base64Utils.encodeToString(String.format("%s:%s", token, user).getBytes());
Map<String, Object> messageJson = new HashMap<>(); httpHeaders.add(HttpHeaders.AUTHORIZATION, String.format("Basic %s", auth));
messageJson.put("text", message); Map<String, Object> messageJson = new HashMap<>();
return new HttpEntity<>(messageJson, httpHeaders); messageJson.put("text", message);
} return new HttpEntity<>(messageJson, httpHeaders);
}
private String standardMessage(String status, String appName, String id) {
return "*" + appName + "* (" + id + ") is *" + status + "*"; private String standardMessage(String status, String appName, String id) {
} return "*" + appName + "* (" + id + ") is *" + status + "*";
}
} }
...@@ -15,94 +15,94 @@ ...@@ -15,94 +15,94 @@
*/ */
package de.codecentric.boot.admin.notify; package de.codecentric.boot.admin.notify;
import static org.mockito.Matchers.eq; import de.codecentric.boot.admin.event.ClientApplicationEvent;
import static org.mockito.Mockito.mock; import de.codecentric.boot.admin.event.ClientApplicationStatusChangedEvent;
import static org.mockito.Mockito.verify; import de.codecentric.boot.admin.model.Application;
import static org.mockito.Mockito.verifyNoMoreInteractions; import de.codecentric.boot.admin.model.StatusInfo;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.springframework.mail.MailSender; import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.SimpleMailMessage;
import de.codecentric.boot.admin.event.ClientApplicationEvent; import static org.mockito.ArgumentMatchers.eq;
import de.codecentric.boot.admin.event.ClientApplicationStatusChangedEvent; import static org.mockito.Mockito.mock;
import de.codecentric.boot.admin.model.Application; import static org.mockito.Mockito.verify;
import de.codecentric.boot.admin.model.StatusInfo; import static org.mockito.Mockito.verifyNoMoreInteractions;
public class MailNotifierTest { public class MailNotifierTest {
private MailSender sender; private MailSender sender;
private MailNotifier notifier; private MailNotifier notifier;
@Before @Before
public void setup() { public void setup() {
sender = mock(MailSender.class); sender = mock(MailSender.class);
notifier = new MailNotifier(sender); notifier = new MailNotifier(sender);
notifier.setTo(new String[] { "foo@bar.com" }); notifier.setTo(new String[]{"foo@bar.com"});
notifier.setCc(new String[] { "bar@foo.com" }); notifier.setCc(new String[]{"bar@foo.com"});
notifier.setFrom("SBA <no-reply@example.com>"); notifier.setFrom("SBA <no-reply@example.com>");
notifier.setSubject("#{application.id} is #{to.status}"); notifier.setSubject("#{application.id} is #{to.status}");
} }
@Test @Test
public void test_onApplicationEvent() { public void test_onApplicationEvent() {
notifier.notify(new ClientApplicationStatusChangedEvent( notifier.notify(new ClientApplicationStatusChangedEvent(
Application.create("App").withId("-id-").withHealthUrl("http://health").build(), Application.create("App").withId("-id-").withHealthUrl("http://health").build(), StatusInfo.ofDown(),
StatusInfo.ofDown(), StatusInfo.ofUp())); StatusInfo.ofUp()));
SimpleMailMessage expected = new SimpleMailMessage(); SimpleMailMessage expected = new SimpleMailMessage();
expected.setTo(new String[] { "foo@bar.com" }); expected.setTo(new String[]{"foo@bar.com"});
expected.setCc(new String[] { "bar@foo.com" }); expected.setCc(new String[]{"bar@foo.com"});
expected.setFrom("SBA <no-reply@example.com>"); expected.setFrom("SBA <no-reply@example.com>");
expected.setText("App (-id-)\nstatus changed from DOWN to UP\n\nhttp://health"); expected.setText("App (-id-)\nstatus changed from DOWN to UP\n\nhttp://health");
expected.setSubject("-id- is UP"); expected.setSubject("-id- is UP");
verify(sender).send(eq(expected)); verify(sender).send(eq(expected));
} }
// The following tests are rather for AbstractNotifier // The following tests are rather for AbstractNotifier
@Test @Test
public void test_onApplicationEvent_disbaled() { public void test_onApplicationEvent_disbaled() {
notifier.setEnabled(false); notifier.setEnabled(false);
notifier.notify(new ClientApplicationStatusChangedEvent( notifier.notify(new ClientApplicationStatusChangedEvent(
Application.create("App").withId("-id-").withHealthUrl("http://health").build(), Application.create("App").withId("-id-").withHealthUrl("http://health").build(), StatusInfo.ofDown(),
StatusInfo.ofDown(), StatusInfo.ofUp())); StatusInfo.ofUp()));
verifyNoMoreInteractions(sender); verifyNoMoreInteractions(sender);
} }
@Test @Test
public void test_onApplicationEvent_noSend() { public void test_onApplicationEvent_noSend() {
notifier.notify(new ClientApplicationStatusChangedEvent( notifier.notify(new ClientApplicationStatusChangedEvent(
Application.create("App").withId("-id-").withHealthUrl("http://health").build(), Application.create("App").withId("-id-").withHealthUrl("http://health").build(), StatusInfo.ofUnknown(),
StatusInfo.ofUnknown(), StatusInfo.ofUp())); StatusInfo.ofUp()));
verifyNoMoreInteractions(sender); verifyNoMoreInteractions(sender);
} }
@Test @Test
public void test_onApplicationEvent_noSend_wildcard() { public void test_onApplicationEvent_noSend_wildcard() {
notifier.setIgnoreChanges(new String[] { "*:UP" }); notifier.setIgnoreChanges(new String[]{"*:UP"});
notifier.notify(new ClientApplicationStatusChangedEvent( notifier.notify(new ClientApplicationStatusChangedEvent(
Application.create("App").withId("-id-").withHealthUrl("http://health").build(), Application.create("App").withId("-id-").withHealthUrl("http://health").build(), StatusInfo.ofOffline(),
StatusInfo.ofOffline(), StatusInfo.ofUp())); StatusInfo.ofUp()));
verifyNoMoreInteractions(sender); verifyNoMoreInteractions(sender);
} }
@Test @Test
public void test_onApplicationEvent_throw_doesnt_propagate() { public void test_onApplicationEvent_throw_doesnt_propagate() {
Notifier notifier = new AbstractStatusChangeNotifier() { Notifier notifier = new AbstractStatusChangeNotifier() {
@Override @Override
protected void doNotify(ClientApplicationEvent event) throws Exception { protected void doNotify(ClientApplicationEvent event) throws Exception {
throw new IllegalStateException("test"); throw new IllegalStateException("test");
} }
}; };
notifier.notify(new ClientApplicationStatusChangedEvent( notifier.notify(new ClientApplicationStatusChangedEvent(
Application.create("App").withId("-id-").withHealthUrl("http://health").build(), Application.create("App").withId("-id-").withHealthUrl("http://health").build(), StatusInfo.ofOffline(),
StatusInfo.ofOffline(), StatusInfo.ofUp())); StatusInfo.ofUp()));
} }
} }
...@@ -15,8 +15,8 @@ import org.springframework.http.HttpHeaders; ...@@ -15,8 +15,8 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import static org.mockito.Matchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Matchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
......
package de.codecentric.boot.admin.registry; package de.codecentric.boot.admin.registry;
import static org.mockito.Matchers.any; import de.codecentric.boot.admin.event.ClientApplicationRegisteredEvent;
import static org.mockito.Matchers.eq; import de.codecentric.boot.admin.model.Application;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.concurrent.Future; import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
import org.junit.Test; import org.junit.Test;
import org.mockito.stubbing.Answer; import org.mockito.stubbing.Answer;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
...@@ -18,52 +13,53 @@ import org.springframework.context.event.ContextClosedEvent; ...@@ -18,52 +13,53 @@ import org.springframework.context.event.ContextClosedEvent;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.util.concurrent.SettableListenableFuture; import org.springframework.util.concurrent.SettableListenableFuture;
import org.springframework.web.context.ConfigurableWebApplicationContext; import org.springframework.web.context.ConfigurableWebApplicationContext;
import de.codecentric.boot.admin.event.ClientApplicationRegisteredEvent;
import de.codecentric.boot.admin.model.Application;
import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.WebApplicationContext;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class StatusUpdateApplicationListenerTest { public class StatusUpdateApplicationListenerTest {
@SuppressWarnings({ "unchecked", "rawtypes" }) @SuppressWarnings({"unchecked", "rawtypes"})
@Test @Test
public void test_start_stop() throws Exception { public void test_start_stop() throws Exception {
StatusUpdater statusUpdater = mock(StatusUpdater.class); StatusUpdater statusUpdater = mock(StatusUpdater.class);
ThreadPoolTaskScheduler scheduler = mock(ThreadPoolTaskScheduler.class); ThreadPoolTaskScheduler scheduler = mock(ThreadPoolTaskScheduler.class);
StatusUpdateApplicationListener listener = new StatusUpdateApplicationListener( StatusUpdateApplicationListener listener = new StatusUpdateApplicationListener(statusUpdater, scheduler);
statusUpdater, scheduler);
ScheduledFuture task = mock(ScheduledFuture.class); ScheduledFuture task = mock(ScheduledFuture.class);
when(scheduler.scheduleAtFixedRate(isA(Runnable.class), eq(10_000L))).thenReturn(task); when(scheduler.scheduleAtFixedRate(isA(Runnable.class), eq(10_000L))).thenReturn(task);
listener.onApplicationReady(new ApplicationReadyEvent(mock(SpringApplication.class), null, listener.onApplicationReady(new ApplicationReadyEvent(mock(SpringApplication.class), null,
mock(ConfigurableWebApplicationContext.class))); mock(ConfigurableWebApplicationContext.class)));
verify(scheduler).scheduleAtFixedRate(isA(Runnable.class), eq(10_000L)); verify(scheduler).scheduleAtFixedRate(isA(Runnable.class), eq(10_000L));
listener.onContextClosed(new ContextClosedEvent(mock(WebApplicationContext.class))); listener.onContextClosed(new ContextClosedEvent(mock(WebApplicationContext.class)));
verify(task).cancel(true); verify(task).cancel(true);
} }
@Test @Test
public void test_newApplication() throws Exception { public void test_newApplication() throws Exception {
StatusUpdater statusUpdater = mock(StatusUpdater.class); StatusUpdater statusUpdater = mock(StatusUpdater.class);
ThreadPoolTaskScheduler scheduler = mock(ThreadPoolTaskScheduler.class); ThreadPoolTaskScheduler scheduler = mock(ThreadPoolTaskScheduler.class);
when(scheduler.submit(any(Runnable.class))).then((Answer<Future<?>>) invocation -> { when(scheduler.submit(any(Runnable.class))).then((Answer<Future<?>>) invocation -> {
invocation.<Runnable>getArgument(0).run(); invocation.<Runnable>getArgument(0).run();
SettableListenableFuture<?> future = new SettableListenableFuture<Void>(); SettableListenableFuture<?> future = new SettableListenableFuture<Void>();
future.set(null); future.set(null);
return future; return future;
}); });
StatusUpdateApplicationListener listener = new StatusUpdateApplicationListener( StatusUpdateApplicationListener listener = new StatusUpdateApplicationListener(statusUpdater, scheduler);
statusUpdater, scheduler);
Application application = Application.create("test").withHealthUrl("http://example.com") Application application = Application.create("test").withHealthUrl("http://example.com").build();
.build();
listener.onClientApplicationRegistered(new ClientApplicationRegisteredEvent(application)); listener.onClientApplicationRegistered(new ClientApplicationRegisteredEvent(application));
verify(statusUpdater).updateStatus(eq(application)); verify(statusUpdater).updateStatus(eq(application));
} }
} }
package de.codecentric.boot.admin.web.client; package de.codecentric.boot.admin.web.client;
import static java.util.Arrays.asList; import de.codecentric.boot.admin.model.Application;
import static java.util.Collections.singletonMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.Serializable; import java.io.Serializable;
import java.net.URI; import java.net.URI;
import java.util.Map; import java.util.Map;
import org.junit.Test; import org.junit.Test;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.springframework.http.HttpEntity; import org.springframework.http.HttpEntity;
...@@ -19,7 +13,12 @@ import org.springframework.http.HttpMethod; ...@@ -19,7 +13,12 @@ import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import de.codecentric.boot.admin.model.Application; import static java.util.Arrays.asList;
import static java.util.Collections.singletonMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ApplicationOperationsTest { public class ApplicationOperationsTest {
...@@ -30,17 +29,18 @@ public class ApplicationOperationsTest { ...@@ -30,17 +29,18 @@ public class ApplicationOperationsTest {
@Test @Test
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public void test_getInfo() { public void test_getInfo() {
Application app = Application.create("test").withHealthUrl("http://health") Application app = Application.create("test")
.withManagementUrl("http://mgmt").build(); .withHealthUrl("http://health")
.withManagementUrl("http://mgmt")
.build();
ArgumentCaptor<HttpEntity> requestEntity = ArgumentCaptor.forClass(HttpEntity.class); ArgumentCaptor<HttpEntity> requestEntity = ArgumentCaptor.forClass(HttpEntity.class);
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.add("auth", "foo:bar"); headers.add("auth", "foo:bar");
when(headersProvider.getHeaders(eq(app))).thenReturn(headers); when(headersProvider.getHeaders(eq(app))).thenReturn(headers);
when(restTemplate.exchange(eq(URI.create("http://mgmt/info")), eq(HttpMethod.GET), when(restTemplate.exchange(eq(URI.create("http://mgmt/info")), eq(HttpMethod.GET), requestEntity.capture(),
requestEntity.capture(), eq(Map.class))) eq(Map.class))).thenReturn(ResponseEntity.ok().body((Map) singletonMap("foo", "bar")));
.thenReturn(ResponseEntity.ok().body((Map) singletonMap("foo", "bar")));
ResponseEntity<Map<String, Serializable>> response = ops.getInfo(app); ResponseEntity<Map<String, Serializable>> response = ops.getInfo(app);
...@@ -51,17 +51,18 @@ public class ApplicationOperationsTest { ...@@ -51,17 +51,18 @@ public class ApplicationOperationsTest {
@Test @Test
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public void test_getHealth() { public void test_getHealth() {
Application app = Application.create("test").withHealthUrl("http://health") Application app = Application.create("test")
.withManagementUrl("http://mgmt").build(); .withHealthUrl("http://health")
.withManagementUrl("http://mgmt")
.build();
ArgumentCaptor<HttpEntity> requestEntity = ArgumentCaptor.forClass(HttpEntity.class); ArgumentCaptor<HttpEntity> requestEntity = ArgumentCaptor.forClass(HttpEntity.class);
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.add("auth", "foo:bar"); headers.add("auth", "foo:bar");
when(headersProvider.getHeaders(eq(app))).thenReturn(headers); when(headersProvider.getHeaders(eq(app))).thenReturn(headers);
when(restTemplate.exchange(eq(URI.create("http://health")), eq(HttpMethod.GET), when(restTemplate.exchange(eq(URI.create("http://health")), eq(HttpMethod.GET), requestEntity.capture(),
requestEntity.capture(), eq(Map.class))) eq(Map.class))).thenReturn(ResponseEntity.ok().body((Map) singletonMap("foo", "bar")));
.thenReturn(ResponseEntity.ok().body((Map) singletonMap("foo", "bar")));
ResponseEntity<Map<String, Serializable>> response = ops.getHealth(app); ResponseEntity<Map<String, Serializable>> response = ops.getHealth(app);
......
...@@ -51,5 +51,4 @@ public class SpringBootAdminClientAutoConfigurationTest { ...@@ -51,5 +51,4 @@ public class SpringBootAdminClientAutoConfigurationTest {
@EnableAutoConfiguration @EnableAutoConfiguration
static class TestClientApplication { static class TestClientApplication {
} }
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment