Formatting

This commit is contained in:
spencergibb
2020-09-16 17:18:55 -04:00
parent 8eea033ded
commit e4ba406415
31 changed files with 314 additions and 444 deletions

View File

@@ -30,8 +30,7 @@ import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest(
properties = { "spring.jmx.enabled=true", "endpoints.default.jmx.enabled=true" })
@SpringBootTest(properties = { "spring.jmx.enabled=true", "endpoints.default.jmx.enabled=true" })
public class BusJmxEndpointTests {
@Autowired(required = false)

View File

@@ -51,8 +51,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
@RunWith(SpringRunner.class)
@SpringBootTest(
properties = "spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS:true",
@SpringBootTest(properties = "spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS:true",
webEnvironment = RANDOM_PORT)
@DirtiesContext
public class BusJacksonIntegrationTests {
@@ -75,16 +74,14 @@ public class BusJacksonIntegrationTests {
assertThat(this.converter.getMapper().getSerializationConfig()
.isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)).isTrue();
Map map = this.rest.getForObject("http://localhost:" + this.port + "/date",
Map.class);
Map map = this.rest.getForObject("http://localhost:" + this.port + "/date", Map.class);
assertThat(map).containsOnlyKeys("date");
assertThat(map.get("date")).isInstanceOf(Long.class);
this.rest.put("http://localhost:" + this.port + "/names" + "/foo", null);
this.rest.put("http://localhost:" + this.port + "/names" + "/bar", null);
ResponseEntity<List> response = this.rest
.getForEntity("http://localhost:" + this.port + "/names", List.class);
ResponseEntity<List> response = this.rest.getForEntity("http://localhost:" + this.port + "/names", List.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody()).contains("foo", "bar");
}
@@ -133,8 +130,7 @@ public class BusJacksonIntegrationTests {
@PutMapping("/names/{name}")
public void sayName(@PathVariable String name) {
this.names.add(name);
this.publisher.publishEvent(
new NameEvent(this, this.busServiceMatcher.getServiceId(), name));
this.publisher.publishEvent(new NameEvent(this, this.busServiceMatcher.getServiceId(), name));
}
@GetMapping("/date")

View File

@@ -65,8 +65,7 @@ import org.springframework.messaging.support.MessageBuilder;
@EnableConfigurationProperties(BusProperties.class)
@AutoConfigureBefore(BindingServiceConfiguration.class)
// so stream bindings work properly
@AutoConfigureAfter({ LifecycleMvcEndpointAutoConfiguration.class,
ServiceMatcherAutoConfiguration.class })
@AutoConfigureAfter({ LifecycleMvcEndpointAutoConfiguration.class, ServiceMatcherAutoConfiguration.class })
// so actuator endpoints have needed dependencies
public class BusAutoConfiguration implements ApplicationEventPublisherAware {
@@ -92,8 +91,7 @@ public class BusAutoConfiguration implements ApplicationEventPublisherAware {
private ApplicationEventPublisher applicationEventPublisher;
public BusAutoConfiguration(ServiceMatcher serviceMatcher,
BindingServiceProperties bindings, BusProperties bus) {
public BusAutoConfiguration(ServiceMatcher serviceMatcher, BindingServiceProperties bindings, BusProperties bus) {
this.serviceMatcher = serviceMatcher;
this.bindings = bindings;
this.bus = bus;
@@ -101,35 +99,26 @@ public class BusAutoConfiguration implements ApplicationEventPublisherAware {
@PostConstruct
public void init() {
BindingProperties inputBinding = this.bindings.getBindings()
.get(SpringCloudBusClient.INPUT);
BindingProperties inputBinding = this.bindings.getBindings().get(SpringCloudBusClient.INPUT);
if (inputBinding == null) {
this.bindings.getBindings().put(SpringCloudBusClient.INPUT,
new BindingProperties());
this.bindings.getBindings().put(SpringCloudBusClient.INPUT, new BindingProperties());
}
BindingProperties input = this.bindings.getBindings()
.get(SpringCloudBusClient.INPUT);
if (input.getDestination() == null
|| input.getDestination().equals(SpringCloudBusClient.INPUT)) {
BindingProperties input = this.bindings.getBindings().get(SpringCloudBusClient.INPUT);
if (input.getDestination() == null || input.getDestination().equals(SpringCloudBusClient.INPUT)) {
input.setDestination(this.bus.getDestination());
}
BindingProperties outputBinding = this.bindings.getBindings()
.get(SpringCloudBusClient.OUTPUT);
BindingProperties outputBinding = this.bindings.getBindings().get(SpringCloudBusClient.OUTPUT);
if (outputBinding == null) {
this.bindings.getBindings().put(SpringCloudBusClient.OUTPUT,
new BindingProperties());
this.bindings.getBindings().put(SpringCloudBusClient.OUTPUT, new BindingProperties());
}
BindingProperties output = this.bindings.getBindings()
.get(SpringCloudBusClient.OUTPUT);
if (output.getDestination() == null
|| output.getDestination().equals(SpringCloudBusClient.OUTPUT)) {
BindingProperties output = this.bindings.getBindings().get(SpringCloudBusClient.OUTPUT);
if (output.getDestination() == null || output.getDestination().equals(SpringCloudBusClient.OUTPUT)) {
output.setDestination(this.bus.getDestination());
}
}
@Override
public void setApplicationEventPublisher(
ApplicationEventPublisher applicationEventPublisher) {
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
@@ -141,8 +130,7 @@ public class BusAutoConfiguration implements ApplicationEventPublisherAware {
@EventListener(classes = RemoteApplicationEvent.class)
public void acceptLocal(RemoteApplicationEvent event) {
if (this.serviceMatcher.isFromSelf(event)
&& !(event instanceof AckRemoteApplicationEvent)) {
if (this.serviceMatcher.isFromSelf(event) && !(event instanceof AckRemoteApplicationEvent)) {
if (log.isDebugEnabled()) {
log.debug("Sending remote event on bus: " + event);
}
@@ -165,35 +153,30 @@ public class BusAutoConfiguration implements ApplicationEventPublisherAware {
log.debug("Received remote event from bus: " + event);
}
if (this.serviceMatcher.isForSelf(event)
&& this.applicationEventPublisher != null) {
if (this.serviceMatcher.isForSelf(event) && this.applicationEventPublisher != null) {
if (!this.serviceMatcher.isFromSelf(event)) {
this.applicationEventPublisher.publishEvent(event);
}
if (this.bus.getAck().isEnabled()) {
AckRemoteApplicationEvent ack = new AckRemoteApplicationEvent(this,
this.serviceMatcher.getServiceId(),
this.bus.getAck().getDestinationService(),
event.getDestinationService(), event.getId(), event.getClass());
this.cloudBusOutboundChannel
.send(MessageBuilder.withPayload(ack).build());
AckRemoteApplicationEvent ack = new AckRemoteApplicationEvent(this, this.serviceMatcher.getServiceId(),
this.bus.getAck().getDestinationService(), event.getDestinationService(), event.getId(),
event.getClass());
this.cloudBusOutboundChannel.send(MessageBuilder.withPayload(ack).build());
this.applicationEventPublisher.publishEvent(ack);
}
}
if (this.bus.getTrace().isEnabled() && this.applicationEventPublisher != null) {
// We are set to register sent events so publish it for local consumption,
// irrespective of the origin
this.applicationEventPublisher.publishEvent(new SentApplicationEvent(this,
event.getOriginService(), event.getDestinationService(),
event.getId(), event.getClass()));
this.applicationEventPublisher.publishEvent(new SentApplicationEvent(this, event.getOriginService(),
event.getDestinationService(), event.getId(), event.getClass()));
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ Endpoint.class })
@ConditionalOnBean(HttpTraceRepository.class)
@ConditionalOnProperty(value = "spring.cloud.bus.trace.enabled",
matchIfMissing = false)
@ConditionalOnProperty(value = "spring.cloud.bus.trace.enabled", matchIfMissing = false)
protected static class BusAckTraceConfiguration {
@Bean
@@ -210,8 +193,7 @@ public class BusAutoConfiguration implements ApplicationEventPublisherAware {
protected static class BusEnvironmentConfiguration {
@Bean
@ConditionalOnProperty(value = "spring.cloud.bus.env.enabled",
matchIfMissing = true)
@ConditionalOnProperty(value = "spring.cloud.bus.env.enabled", matchIfMissing = true)
public EnvironmentChangeListener environmentChangeListener() {
return new EnvironmentChangeListener();
}
@@ -222,8 +204,7 @@ public class BusAutoConfiguration implements ApplicationEventPublisherAware {
@Bean
@ConditionalOnAvailableEndpoint
public EnvironmentBusEndpoint environmentBusEndpoint(
ApplicationContext context, BusProperties bus) {
public EnvironmentBusEndpoint environmentBusEndpoint(ApplicationContext context, BusProperties bus) {
return new EnvironmentBusEndpoint(context, bus.getId());
}

View File

@@ -38,19 +38,15 @@ public class BusEnvironmentPostProcessor implements EnvironmentPostProcessor {
private static final String PROPERTY_SOURCE_NAME = "defaultProperties";
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment,
SpringApplication application) {
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("spring.cloud.stream.bindings." + SpringCloudBusClient.OUTPUT
+ ".content-type",
environment.getProperty("spring.cloud.bus.content-type",
"application/json"));
map.put("spring.cloud.stream.bindings." + SpringCloudBusClient.OUTPUT + ".content-type",
environment.getProperty("spring.cloud.bus.content-type", "application/json"));
map.put("spring.cloud.bus.id", IdUtils.getUnresolvedServiceId());
addOrReplace(environment.getPropertySources(), map);
}
private void addOrReplace(MutablePropertySources propertySources,
Map<String, Object> map) {
private void addOrReplace(MutablePropertySources propertySources, Map<String, Object> map) {
MapPropertySource target = null;
if (propertySources.contains(PROPERTY_SOURCE_NAME)) {
PropertySource<?> source = propertySources.get(PROPERTY_SOURCE_NAME);

View File

@@ -32,8 +32,7 @@ import org.springframework.beans.factory.annotation.Qualifier;
*
*/
@Qualifier
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE,
ElementType.PARAMETER })
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented

View File

@@ -33,29 +33,24 @@ import org.springframework.context.annotation.Configuration;
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnBusEnabled
@AutoConfigureAfter(
name = { "org.springframework.cloud.autoconfigure.RefreshAutoConfiguration" })
@AutoConfigureAfter(name = { "org.springframework.cloud.autoconfigure.RefreshAutoConfiguration" })
public class BusRefreshAutoConfiguration {
@Bean
@ConditionalOnProperty(value = "spring.cloud.bus.refresh.enabled",
matchIfMissing = true)
@ConditionalOnProperty(value = "spring.cloud.bus.refresh.enabled", matchIfMissing = true)
@ConditionalOnBean(ContextRefresher.class)
public RefreshListener refreshListener(ContextRefresher contextRefresher,
ServiceMatcher serviceMatcher) {
public RefreshListener refreshListener(ContextRefresher contextRefresher, ServiceMatcher serviceMatcher) {
return new RefreshListener(contextRefresher, serviceMatcher);
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(
name = { "org.springframework.boot.actuate.endpoint.annotation.Endpoint",
"org.springframework.cloud.context.scope.refresh.RefreshScope" })
@ConditionalOnClass(name = { "org.springframework.boot.actuate.endpoint.annotation.Endpoint",
"org.springframework.cloud.context.scope.refresh.RefreshScope" })
protected static class BusRefreshEndpointConfiguration {
@Bean
@ConditionalOnAvailableEndpoint
public RefreshBusEndpoint refreshBusEndpoint(ApplicationContext context,
BusProperties bus) {
public RefreshBusEndpoint refreshBusEndpoint(ApplicationContext context, BusProperties bus) {
return new RefreshBusEndpoint(context, bus.getId());
}

View File

@@ -26,8 +26,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
/**
* @author Spencer Gibb
*/
@ConditionalOnProperty(value = ConditionalOnBusEnabled.SPRING_CLOUD_BUS_ENABLED,
matchIfMissing = true)
@ConditionalOnProperty(value = ConditionalOnBusEnabled.SPRING_CLOUD_BUS_ENABLED, matchIfMissing = true)
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
public @interface ConditionalOnBusEnabled {

View File

@@ -43,12 +43,10 @@ public class ServiceMatcherAutoConfiguration {
}
@Bean
public ServiceMatcher serviceMatcher(@BusPathMatcher PathMatcher pathMatcher,
BusProperties properties, Environment environment) {
String[] configNames = environment.getProperty(CLOUD_CONFIG_NAME_PROPERTY,
String[].class, new String[] {});
ServiceMatcher serviceMatcher = new ServiceMatcher(pathMatcher,
properties.getId(), configNames);
public ServiceMatcher serviceMatcher(@BusPathMatcher PathMatcher pathMatcher, BusProperties properties,
Environment environment) {
String[] configNames = environment.getProperty(CLOUD_CONFIG_NAME_PROPERTY, String[].class, new String[] {});
ServiceMatcher serviceMatcher = new ServiceMatcher(pathMatcher, properties.getId(), configNames);
return serviceMatcher;
}

View File

@@ -36,18 +36,16 @@ public class EnvironmentBusEndpoint extends AbstractBusEndpoint {
}
@WriteOperation
public void busEnvWithDestination(String name, String value,
@Selector String destination) { // TODO: document params
// TODO: document params
public void busEnvWithDestination(String name, String value, @Selector String destination) {
Map<String, String> params = Collections.singletonMap(name, value);
publish(new EnvironmentChangeRemoteApplicationEvent(this, getInstanceId(),
destination, params));
publish(new EnvironmentChangeRemoteApplicationEvent(this, getInstanceId(), destination, params));
}
@WriteOperation
public void busEnv(String name, String value) { // TODO: document params
Map<String, String> params = Collections.singletonMap(name, value);
publish(new EnvironmentChangeRemoteApplicationEvent(this, getInstanceId(), null,
params));
publish(new EnvironmentChangeRemoteApplicationEvent(this, getInstanceId(), null, params));
}
}

View File

@@ -44,9 +44,8 @@ public class AckRemoteApplicationEvent extends RemoteApplicationEvent {
this.event = null;
}
public AckRemoteApplicationEvent(Object source, String originService,
String destinationService, String ackDestinationService, String ackId,
Class<? extends RemoteApplicationEvent> type) {
public AckRemoteApplicationEvent(Object source, String originService, String destinationService,
String ackDestinationService, String ackId, Class<? extends RemoteApplicationEvent> type) {
super(source, originService, destinationService);
this.ackDestinationService = ackDestinationService;
this.ackId = ackId;
@@ -74,8 +73,7 @@ public class AckRemoteApplicationEvent extends RemoteApplicationEvent {
@JsonProperty("event")
public void setEventName(String eventName) {
try {
this.event = (Class<? extends RemoteApplicationEvent>) Class
.forName(eventName);
this.event = (Class<? extends RemoteApplicationEvent>) Class.forName(eventName);
}
catch (ClassNotFoundException e) {
this.event = UnknownRemoteApplicationEvent.class;
@@ -86,8 +84,7 @@ public class AckRemoteApplicationEvent extends RemoteApplicationEvent {
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((this.ackDestinationService == null) ? 0
: this.ackDestinationService.hashCode());
result = prime * result + ((this.ackDestinationService == null) ? 0 : this.ackDestinationService.hashCode());
result = prime * result + ((this.ackId == null) ? 0 : this.ackId.hashCode());
result = prime * result + ((this.event == null) ? 0 : this.event.hashCode());
return result;

View File

@@ -28,8 +28,7 @@ import org.springframework.context.ApplicationListener;
/**
* @author Spencer Gibb
*/
public class EnvironmentChangeListener
implements ApplicationListener<EnvironmentChangeRemoteApplicationEvent> {
public class EnvironmentChangeListener implements ApplicationListener<EnvironmentChangeRemoteApplicationEvent> {
private static Log log = LogFactory.getLog(EnvironmentChangeListener.class);
@@ -39,8 +38,7 @@ public class EnvironmentChangeListener
@Override
public void onApplicationEvent(EnvironmentChangeRemoteApplicationEvent event) {
Map<String, String> values = event.getValues();
log.info("Received remote environment change request. Keys/values to update "
+ values);
log.info("Received remote environment change request. Keys/values to update " + values);
for (Map.Entry<String, String> entry : values.entrySet()) {
this.env.setProperty(entry.getKey(), entry.getValue());
}

View File

@@ -34,8 +34,8 @@ public class EnvironmentChangeRemoteApplicationEvent extends RemoteApplicationEv
this.values = null;
}
public EnvironmentChangeRemoteApplicationEvent(Object source, String originService,
String destinationService, Map<String, String> values) {
public EnvironmentChangeRemoteApplicationEvent(Object source, String originService, String destinationService,
Map<String, String> values) {
super(source, originService, destinationService);
this.values = values;
}
@@ -77,10 +77,8 @@ public class EnvironmentChangeRemoteApplicationEvent extends RemoteApplicationEv
@Override
public String toString() {
return new ToStringCreator(this).append("id", getId())
.append("originService", getOriginService())
.append("destinationService", getDestinationService())
.append("values", values).toString();
return new ToStringCreator(this).append("id", getId()).append("originService", getOriginService())
.append("destinationService", getDestinationService()).append("values", values).toString();
}

View File

@@ -29,8 +29,7 @@ import org.springframework.context.ApplicationListener;
* @author Spencer Gibb
* @author Ryan Baxter
*/
public class RefreshListener
implements ApplicationListener<RefreshRemoteApplicationEvent> {
public class RefreshListener implements ApplicationListener<RefreshRemoteApplicationEvent> {
private static Log log = LogFactory.getLog(RefreshListener.class);
@@ -38,8 +37,7 @@ public class RefreshListener
private ServiceMatcher serviceMatcher;
public RefreshListener(ContextRefresher contextRefresher,
ServiceMatcher serviceMatcher) {
public RefreshListener(ContextRefresher contextRefresher, ServiceMatcher serviceMatcher) {
this.contextRefresher = contextRefresher;
this.serviceMatcher = serviceMatcher;
}
@@ -52,8 +50,7 @@ public class RefreshListener
log.info("Keys refreshed " + keys);
}
else {
log.info("Refresh not performed, the event was targetting "
+ event.getDestinationService());
log.info("Refresh not performed, the event was targetting " + event.getDestinationService());
}
}

View File

@@ -27,8 +27,7 @@ public class RefreshRemoteApplicationEvent extends RemoteApplicationEvent {
// for serializers
}
public RefreshRemoteApplicationEvent(Object source, String originService,
String destinationService) {
public RefreshRemoteApplicationEvent(Object source, String originService, String destinationService) {
super(source, originService, destinationService);
}

View File

@@ -46,8 +46,7 @@ public abstract class RemoteApplicationEvent extends ApplicationEvent {
this(TRANSIENT_SOURCE, null, null);
}
protected RemoteApplicationEvent(Object source, String originService,
String destinationService) {
protected RemoteApplicationEvent(Object source, String originService, String destinationService) {
super(source);
this.originService = originService;
if (destinationService == null) {
@@ -88,11 +87,9 @@ public abstract class RemoteApplicationEvent extends ApplicationEvent {
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.destinationService == null) ? 0
: this.destinationService.hashCode());
result = prime * result + ((this.destinationService == null) ? 0 : this.destinationService.hashCode());
result = prime * result + ((this.id == null) ? 0 : this.id.hashCode());
result = prime * result
+ ((this.originService == null) ? 0 : this.originService.hashCode());
result = prime * result + ((this.originService == null) ? 0 : this.originService.hashCode());
return result;
}
@@ -137,8 +134,7 @@ public abstract class RemoteApplicationEvent extends ApplicationEvent {
@Override
public String toString() {
return new ToStringCreator(this).append("id", id)
.append("originService", originService)
return new ToStringCreator(this).append("id", id).append("originService", originService)
.append("destinationService", destinationService).toString();
}

View File

@@ -51,8 +51,7 @@ public class SentApplicationEvent extends ApplicationEvent {
this(TRANSIENT_SOURCE, null, null, null, RemoteApplicationEvent.class);
}
public SentApplicationEvent(Object source, String originService,
String destinationService, String id,
public SentApplicationEvent(Object source, String originService, String destinationService, String id,
Class<? extends RemoteApplicationEvent> type) {
super(source);
this.originService = originService;
@@ -92,11 +91,9 @@ public class SentApplicationEvent extends ApplicationEvent {
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.destinationService == null) ? 0
: this.destinationService.hashCode());
result = prime * result + ((this.destinationService == null) ? 0 : this.destinationService.hashCode());
result = prime * result + ((this.id == null) ? 0 : this.id.hashCode());
result = prime * result
+ ((this.originService == null) ? 0 : this.originService.hashCode());
result = prime * result + ((this.originService == null) ? 0 : this.originService.hashCode());
result = prime * result + ((this.type == null) ? 0 : this.type.hashCode());
return result;
}

View File

@@ -59,11 +59,9 @@ public class UnknownRemoteApplicationEvent extends RemoteApplicationEvent {
@Override
public String toString() {
return new ToStringCreator(this).append("id", getId())
.append("originService", getOriginService())
.append("destinationService", getDestinationService())
.append("typeInfo", typeInfo).append("payload", getPayloadAsString())
.toString();
return new ToStringCreator(this).append("id", getId()).append("originService", getOriginService())
.append("destinationService", getDestinationService()).append("typeInfo", typeInfo)
.append("payload", getPayloadAsString()).toString();
}

View File

@@ -66,20 +66,17 @@ public class BusJacksonAutoConfiguration {
@Bean
@ConditionalOnMissingBean(name = "busJsonConverter")
@StreamMessageConverter
public AbstractMessageConverter busJsonConverter(
@Autowired(required = false) ObjectMapper objectMapper) {
public AbstractMessageConverter busJsonConverter(@Autowired(required = false) ObjectMapper objectMapper) {
return new BusJacksonMessageConverter(objectMapper);
}
}
class BusJacksonMessageConverter extends AbstractMessageConverter
implements InitializingBean {
class BusJacksonMessageConverter extends AbstractMessageConverter implements InitializingBean {
private static final Log log = LogFactory.getLog(BusJacksonMessageConverter.class);
private static final String DEFAULT_PACKAGE = ClassUtils
.getPackageName(RemoteApplicationEvent.class);
private static final String DEFAULT_PACKAGE = ClassUtils.getPackageName(RemoteApplicationEvent.class);
private final ObjectMapper mapper;
@@ -127,8 +124,7 @@ class BusJacksonMessageConverter extends AbstractMessageConverter
for (String pkg : this.packagesToScan) {
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
false);
provider.addIncludeFilter(
new AssignableTypeFilter(RemoteApplicationEvent.class));
provider.addIncludeFilter(new AssignableTypeFilter(RemoteApplicationEvent.class));
Set<BeanDefinition> components = provider.findCandidateComponents(pkg);
for (BeanDefinition component : components) {
@@ -136,8 +132,7 @@ class BusJacksonMessageConverter extends AbstractMessageConverter
types.add(Class.forName(component.getBeanClassName()));
}
catch (ClassNotFoundException e) {
throw new IllegalStateException(
"Failed to scan classpath for remote event classes", e);
throw new IllegalStateException("Failed to scan classpath for remote event classes", e);
}
}
}
@@ -155,8 +150,7 @@ class BusJacksonMessageConverter extends AbstractMessageConverter
}
@Override
public Object convertFromInternal(Message<?> message, Class<?> targetClass,
Object conversionHint) {
public Object convertFromInternal(Message<?> message, Class<?> targetClass, Object conversionHint) {
Object result = null;
try {
Object payload = message.getPayload();
@@ -166,8 +160,7 @@ class BusJacksonMessageConverter extends AbstractMessageConverter
result = this.mapper.readValue((byte[]) payload, targetClass);
}
catch (InvalidTypeIdException e) {
return new UnknownRemoteApplicationEvent(new Object(), e.getTypeId(),
(byte[]) payload);
return new UnknownRemoteApplicationEvent(new Object(), e.getTypeId(), (byte[]) payload);
}
}
else if (payload instanceof String) {

View File

@@ -47,8 +47,7 @@ public class RemoteApplicationEventRegistrar implements ImportBeanDefinitionRegi
final BeanDefinitionRegistry registry) {
Map<String, Object> componentScan = importingClassMetadata
.getAnnotationAttributes(RemoteApplicationEventScan.class.getName(),
false);
.getAnnotationAttributes(RemoteApplicationEventScan.class.getName(), false);
Set<String> basePackages = new HashSet<>();
for (String pkg : (String[]) componentScan.get("value")) {
@@ -66,8 +65,7 @@ public class RemoteApplicationEventRegistrar implements ImportBeanDefinitionRegi
}
if (basePackages.isEmpty()) {
basePackages.add(
ClassUtils.getPackageName(importingClassMetadata.getClassName()));
basePackages.add(ClassUtils.getPackageName(importingClassMetadata.getClassName()));
}
if (!registry.containsBeanDefinition(BUS_JSON_CONVERTER)) {
@@ -75,27 +73,22 @@ public class RemoteApplicationEventRegistrar implements ImportBeanDefinitionRegi
.genericBeanDefinition(BusJacksonMessageConverter.class);
beanDefinitionBuilder.addPropertyValue(PACKAGES_TO_SCAN,
basePackages.toArray(new String[basePackages.size()]));
AbstractBeanDefinition beanDefinition = beanDefinitionBuilder
.getBeanDefinition();
AbstractBeanDefinition beanDefinition = beanDefinitionBuilder.getBeanDefinition();
BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition,
BUS_JSON_CONVERTER);
BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, BUS_JSON_CONVERTER);
BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);
}
else {
basePackages.addAll(getEarlierPackagesToScan(registry));
registry.getBeanDefinition(BUS_JSON_CONVERTER).getPropertyValues()
.addPropertyValue(PACKAGES_TO_SCAN,
basePackages.toArray(new String[basePackages.size()]));
registry.getBeanDefinition(BUS_JSON_CONVERTER).getPropertyValues().addPropertyValue(PACKAGES_TO_SCAN,
basePackages.toArray(new String[basePackages.size()]));
}
}
private Set<String> getEarlierPackagesToScan(final BeanDefinitionRegistry registry) {
if (registry.containsBeanDefinition(BUS_JSON_CONVERTER)
&& registry.getBeanDefinition(BUS_JSON_CONVERTER).getPropertyValues()
.get(PACKAGES_TO_SCAN) != null) {
String[] earlierValues = (String[]) registry
.getBeanDefinition(BUS_JSON_CONVERTER).getPropertyValues()
&& registry.getBeanDefinition(BUS_JSON_CONVERTER).getPropertyValues().get(PACKAGES_TO_SCAN) != null) {
String[] earlierValues = (String[]) registry.getBeanDefinition(BUS_JSON_CONVERTER).getPropertyValues()
.get(PACKAGES_TO_SCAN);
return new HashSet<>(Arrays.asList(earlierValues));
}

View File

@@ -30,16 +30,14 @@ import org.springframework.cloud.test.ModifiedClassPathRunner;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(ModifiedClassPathRunner.class)
@ClassPathExclusions({ "spring-boot-actuator-*.jar",
"spring-boot-starter-actuator-*.jar" })
@ClassPathExclusions({ "spring-boot-actuator-*.jar", "spring-boot-starter-actuator-*.jar" })
public class BusAutoConfigurationClassPathTests {
@Test
public void refreshListenerCreatedWithoutActuator() {
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(RefreshAutoConfiguration.class,
ServiceMatcherAutoConfiguration.class,
BusRefreshAutoConfiguration.class))
ServiceMatcherAutoConfiguration.class, BusRefreshAutoConfiguration.class))
.run(context -> assertThat(context).hasSingleBean(RefreshListener.class)
.doesNotHaveBean(RefreshBusEndpoint.class));
}

View File

@@ -69,84 +69,66 @@ public class BusAutoConfigurationTests {
@Test
public void defaultId() {
this.context = SpringApplication.run(InboundMessageHandlerConfiguration.class,
"--server.port=0");
assertThat(this.context.getBean(BusProperties.class).getId()
.startsWith("application:0:")).as(
"Wrong ID: " + this.context.getBean(BusProperties.class).getId())
.isTrue();
this.context = SpringApplication.run(InboundMessageHandlerConfiguration.class, "--server.port=0");
assertThat(this.context.getBean(BusProperties.class).getId().startsWith("application:0:"))
.as("Wrong ID: " + this.context.getBean(BusProperties.class).getId()).isTrue();
}
@Test
public void inboundNotForSelf() {
this.context = SpringApplication.run(InboundMessageHandlerConfiguration.class,
"--spring.cloud.bus.id=foo", "--server.port=0");
this.context = SpringApplication.run(InboundMessageHandlerConfiguration.class, "--spring.cloud.bus.id=foo",
"--server.port=0");
this.context.getBean(SpringCloudBusClient.INPUT, MessageChannel.class)
.send(new GenericMessage<>(
new RefreshRemoteApplicationEvent(this, "bar", "bar")));
assertThat(this.context.getBean(InboundMessageHandlerConfiguration.class).refresh)
.isNull();
.send(new GenericMessage<>(new RefreshRemoteApplicationEvent(this, "bar", "bar")));
assertThat(this.context.getBean(InboundMessageHandlerConfiguration.class).refresh).isNull();
}
@Test
public void inboundFromSelf() {
this.context = SpringApplication.run(InboundMessageHandlerConfiguration.class,
"--spring.cloud.bus.id=foo", "--server.port=0");
this.context = SpringApplication.run(InboundMessageHandlerConfiguration.class, "--spring.cloud.bus.id=foo",
"--server.port=0");
this.context.getBean(SpringCloudBusClient.INPUT, MessageChannel.class)
.send(new GenericMessage<>(
new RefreshRemoteApplicationEvent(this, "foo", null)));
assertThat(this.context.getBean(InboundMessageHandlerConfiguration.class).refresh)
.isNull();
.send(new GenericMessage<>(new RefreshRemoteApplicationEvent(this, "foo", null)));
assertThat(this.context.getBean(InboundMessageHandlerConfiguration.class).refresh).isNull();
}
@Test
public void inboundNotFromSelf() {
this.context = SpringApplication.run(InboundMessageHandlerConfiguration.class,
"--spring.cloud.bus.id=bar", "--server.port=0");
this.context = SpringApplication.run(InboundMessageHandlerConfiguration.class, "--spring.cloud.bus.id=bar",
"--server.port=0");
this.context.getBean(SpringCloudBusClient.INPUT, MessageChannel.class)
.send(new GenericMessage<>(
new RefreshRemoteApplicationEvent(this, "foo", null)));
assertThat(this.context.getBean(InboundMessageHandlerConfiguration.class).refresh)
.isNotNull();
.send(new GenericMessage<>(new RefreshRemoteApplicationEvent(this, "foo", null)));
assertThat(this.context.getBean(InboundMessageHandlerConfiguration.class).refresh).isNotNull();
}
@Test
public void inboundNotFromSelfWithAck() throws Exception {
this.context = SpringApplication.run(
new Class[] { InboundMessageHandlerConfiguration.class,
OutboundMessageHandlerConfiguration.class,
new Class[] { InboundMessageHandlerConfiguration.class, OutboundMessageHandlerConfiguration.class,
SentMessageConfiguration.class },
new String[] { "--spring.cloud.bus.id=bar", "--server.port=0" });
this.context.getBean(SpringCloudBusClient.INPUT, MessageChannel.class)
.send(new GenericMessage<>(
new RefreshRemoteApplicationEvent(this, "foo", null)));
RefreshRemoteApplicationEvent refresh = this.context
.getBean(InboundMessageHandlerConfiguration.class).refresh;
.send(new GenericMessage<>(new RefreshRemoteApplicationEvent(this, "foo", null)));
RefreshRemoteApplicationEvent refresh = this.context.getBean(InboundMessageHandlerConfiguration.class).refresh;
assertThat(refresh).isNotNull();
OutboundMessageHandlerConfiguration outbound = this.context
.getBean(OutboundMessageHandlerConfiguration.class);
OutboundMessageHandlerConfiguration outbound = this.context.getBean(OutboundMessageHandlerConfiguration.class);
outbound.latch.await(2000L, TimeUnit.MILLISECONDS);
String message = (String) outbound.message.getPayload();
assertThat(message.contains("\"ackId\":\"" + refresh.getId()))
.as("Wrong ackId: " + message).isTrue();
assertThat(message.contains("\"ackId\":\"" + refresh.getId())).as("Wrong ackId: " + message).isTrue();
}
@Test
public void inboundNotFromSelfWithTrace() throws Exception {
this.context = SpringApplication.run(
new Class[] { InboundMessageHandlerConfiguration.class,
OutboundMessageHandlerConfiguration.class,
new Class[] { InboundMessageHandlerConfiguration.class, OutboundMessageHandlerConfiguration.class,
SentMessageConfiguration.class },
new String[] { "--spring.cloud.bus.trace.enabled=true",
"--spring.cloud.bus.id=bar", "--server.port=0" });
new String[] { "--spring.cloud.bus.trace.enabled=true", "--spring.cloud.bus.id=bar",
"--server.port=0" });
this.context.getBean(SpringCloudBusClient.INPUT, MessageChannel.class)
.send(new GenericMessage<>(
new RefreshRemoteApplicationEvent(this, "foo", null)));
RefreshRemoteApplicationEvent refresh = this.context
.getBean(InboundMessageHandlerConfiguration.class).refresh;
.send(new GenericMessage<>(new RefreshRemoteApplicationEvent(this, "foo", null)));
RefreshRemoteApplicationEvent refresh = this.context.getBean(InboundMessageHandlerConfiguration.class).refresh;
assertThat(refresh).isNotNull();
SentMessageConfiguration sent = this.context
.getBean(SentMessageConfiguration.class);
SentMessageConfiguration sent = this.context.getBean(SentMessageConfiguration.class);
assertThat(sent.event).isNotNull();
assertThat(sent.count).isEqualTo(1);
}
@@ -154,51 +136,43 @@ public class BusAutoConfigurationTests {
@Test
public void inboundAckWithTrace() throws Exception {
this.context = SpringApplication.run(
new Class[] { InboundMessageHandlerConfiguration.class,
OutboundMessageHandlerConfiguration.class,
new Class[] { InboundMessageHandlerConfiguration.class, OutboundMessageHandlerConfiguration.class,
AckMessageConfiguration.class },
new String[] { "--spring.cloud.bus.trace.enabled=true",
"--spring.cloud.bus.id=bar", "--server.port=0" });
new String[] { "--spring.cloud.bus.trace.enabled=true", "--spring.cloud.bus.id=bar",
"--server.port=0" });
this.context.getBean(BusProperties.class).setId("bar");
this.context.getBean(SpringCloudBusClient.INPUT, MessageChannel.class)
.send(new GenericMessage<>(new AckRemoteApplicationEvent(this, "foo",
null, "ID", "bar", RefreshRemoteApplicationEvent.class)));
AckMessageConfiguration sent = this.context
.getBean(AckMessageConfiguration.class);
this.context.getBean(SpringCloudBusClient.INPUT, MessageChannel.class).send(new GenericMessage<>(
new AckRemoteApplicationEvent(this, "foo", null, "ID", "bar", RefreshRemoteApplicationEvent.class)));
AckMessageConfiguration sent = this.context.getBean(AckMessageConfiguration.class);
assertThat(sent.event).isNotNull();
assertThat(sent.count).isEqualTo(1);
}
@Test
public void outboundFromSelf() throws Exception {
this.context = SpringApplication.run(OutboundMessageHandlerConfiguration.class,
"--debug=true", "--spring.cloud.bus.id=foo", "--server.port=0");
this.context = SpringApplication.run(OutboundMessageHandlerConfiguration.class, "--debug=true",
"--spring.cloud.bus.id=foo", "--server.port=0");
this.context.publishEvent(new RefreshRemoteApplicationEvent(this, "foo", null));
OutboundMessageHandlerConfiguration outbound = this.context
.getBean(OutboundMessageHandlerConfiguration.class);
OutboundMessageHandlerConfiguration outbound = this.context.getBean(OutboundMessageHandlerConfiguration.class);
outbound.latch.await(2000L, TimeUnit.MILLISECONDS);
assertThat(outbound.message).as("message was null").isNotNull();
}
@Test
public void outboundNotFromSelf() {
this.context = SpringApplication.run(OutboundMessageHandlerConfiguration.class,
"--spring.cloud.bus.id=bar", "--server.port=0");
this.context = SpringApplication.run(OutboundMessageHandlerConfiguration.class, "--spring.cloud.bus.id=bar",
"--server.port=0");
this.context.publishEvent(new RefreshRemoteApplicationEvent(this, "foo", null));
assertThat(
this.context.getBean(OutboundMessageHandlerConfiguration.class).message)
.isNull();
assertThat(this.context.getBean(OutboundMessageHandlerConfiguration.class).message).isNull();
}
@Test
public void inboundNotFromSelfPathPattern() {
this.context = SpringApplication.run(InboundMessageHandlerConfiguration.class,
"--spring.cloud.bus.id=bar:1000", "--server.port=0");
this.context = SpringApplication.run(InboundMessageHandlerConfiguration.class, "--spring.cloud.bus.id=bar:1000",
"--server.port=0");
this.context.getBean(SpringCloudBusClient.INPUT, MessageChannel.class)
.send(new GenericMessage<>(
new RefreshRemoteApplicationEvent(this, "foo", "bar:*")));
assertThat(this.context.getBean(InboundMessageHandlerConfiguration.class).refresh)
.isNotNull();
.send(new GenericMessage<>(new RefreshRemoteApplicationEvent(this, "foo", "bar:*")));
assertThat(this.context.getBean(InboundMessageHandlerConfiguration.class).refresh).isNotNull();
}
@Test
@@ -206,31 +180,26 @@ public class BusAutoConfigurationTests {
this.context = SpringApplication.run(InboundMessageHandlerConfiguration.class,
"--spring.cloud.bus.id=bar:test:1000", "--server.port=0");
this.context.getBean(SpringCloudBusClient.INPUT, MessageChannel.class)
.send(new GenericMessage<>(
new RefreshRemoteApplicationEvent(this, "foo", "bar:**")));
assertThat(this.context.getBean(InboundMessageHandlerConfiguration.class).refresh)
.isNotNull();
.send(new GenericMessage<>(new RefreshRemoteApplicationEvent(this, "foo", "bar:**")));
assertThat(this.context.getBean(InboundMessageHandlerConfiguration.class).refresh).isNotNull();
}
@Test
public void inboundNotFromSelfFlatPattern() {
this.context = SpringApplication.run(InboundMessageHandlerConfiguration.class,
"--spring.cloud.bus.id=bar", "--server.port=0");
this.context = SpringApplication.run(InboundMessageHandlerConfiguration.class, "--spring.cloud.bus.id=bar",
"--server.port=0");
this.context.getBean(SpringCloudBusClient.INPUT, MessageChannel.class)
.send(new GenericMessage<>(
new RefreshRemoteApplicationEvent(this, "foo", "bar*")));
assertThat(this.context.getBean(InboundMessageHandlerConfiguration.class).refresh)
.isNotNull();
.send(new GenericMessage<>(new RefreshRemoteApplicationEvent(this, "foo", "bar*")));
assertThat(this.context.getBean(InboundMessageHandlerConfiguration.class).refresh).isNotNull();
}
// see https://github.com/spring-cloud/spring-cloud-bus/issues/74
@Test
public void inboundNotFromSelfUnknown() {
this.context = SpringApplication.run(InboundMessageHandlerConfiguration.class,
"--spring.cloud.bus.id=bar", "--server.port=0");
this.context = SpringApplication.run(InboundMessageHandlerConfiguration.class, "--spring.cloud.bus.id=bar",
"--server.port=0");
this.context.getBean(SpringCloudBusClient.INPUT, MessageChannel.class)
.send(new GenericMessage<>(new UnknownRemoteApplicationEvent(this,
"UnknownEvent", "yada".getBytes())));
.send(new GenericMessage<>(new UnknownRemoteApplicationEvent(this, "UnknownEvent", "yada".getBytes())));
// No Exception expected
}
@@ -285,14 +254,13 @@ public class BusAutoConfigurationTests {
assertThat(output.getDestination()).isEqualTo(bus.getDestination());
}
private BusProperties setupBusAutoConfig(
HashMap<String, BindingProperties> properties) {
private BusProperties setupBusAutoConfig(HashMap<String, BindingProperties> properties) {
BindingServiceProperties serviceProperties = mock(BindingServiceProperties.class);
when(serviceProperties.getBindings()).thenReturn(properties);
BusProperties bus = new BusProperties();
BusAutoConfiguration configuration = new BusAutoConfiguration(
mock(ServiceMatcher.class), serviceProperties, bus);
BusAutoConfiguration configuration = new BusAutoConfiguration(mock(ServiceMatcher.class), serviceProperties,
bus);
configuration.init();
return bus;
}
@@ -303,8 +271,7 @@ public class BusAutoConfigurationTests {
public void serviceMatcherIdIsConstantAfterRefresh() {
this.context = SpringApplication.run(new Class[] { RefreshConfig.class, },
new String[] { "--spring.main.allow-bean-definition-overriding=true" });
String originalServiceId = this.context.getBean(ServiceMatcher.class)
.getServiceId();
String originalServiceId = this.context.getBean(ServiceMatcher.class).getServiceId();
this.context.getBean(ContextRefresher.class).refresh();
String newServiceId = this.context.getBean(ServiceMatcher.class).getServiceId();
assertThat(newServiceId).isEqualTo(originalServiceId);
@@ -318,8 +285,7 @@ public class BusAutoConfigurationTests {
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@Import({ MessageConsumer.class, BusAutoConfiguration.class,
TestSupportBinderAutoConfiguration.class,
@Import({ MessageConsumer.class, BusAutoConfiguration.class, TestSupportBinderAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class })
protected static class OutboundMessageHandlerConfiguration {
@@ -339,8 +305,7 @@ public class BusAutoConfigurationTests {
private ChannelInterceptor interceptor() {
return new ChannelInterceptorAdapter() {
@Override
public void postSend(Message<?> message, MessageChannel channel,
boolean sent) {
public void postSend(Message<?> message, MessageChannel channel, boolean sent) {
OutboundMessageHandlerConfiguration.this.message = message;
OutboundMessageHandlerConfiguration.this.latch.countDown();
}
@@ -361,8 +326,7 @@ public class BusAutoConfigurationTests {
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@Import({ MessageConsumer.class, BusAutoConfiguration.class,
TestSupportBinderAutoConfiguration.class,
@Import({ MessageConsumer.class, BusAutoConfiguration.class, TestSupportBinderAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class })
protected static class InboundMessageHandlerConfiguration
implements ApplicationListener<RefreshRemoteApplicationEvent> {
@@ -377,8 +341,7 @@ public class BusAutoConfigurationTests {
}
@Configuration(proxyBeanMethods = false)
protected static class SentMessageConfiguration
implements ApplicationListener<SentApplicationEvent> {
protected static class SentMessageConfiguration implements ApplicationListener<SentApplicationEvent> {
private SentApplicationEvent event;
@@ -393,8 +356,7 @@ public class BusAutoConfigurationTests {
}
@Configuration(proxyBeanMethods = false)
protected static class AckMessageConfiguration
implements ApplicationListener<AckRemoteApplicationEvent> {
protected static class AckMessageConfiguration implements ApplicationListener<AckRemoteApplicationEvent> {
private AckRemoteApplicationEvent event;

View File

@@ -47,25 +47,20 @@ public class ConditionalOnBusEnabledTests {
@Test
public void busEnabledTrue() {
load(MyBusEnabledConfig.class,
ConditionalOnBusEnabled.SPRING_CLOUD_BUS_ENABLED + ":true");
assertThat(this.context.containsBean("foo"))
.as("missing bean from @ConditionalOnBusEnabled config").isTrue();
load(MyBusEnabledConfig.class, ConditionalOnBusEnabled.SPRING_CLOUD_BUS_ENABLED + ":true");
assertThat(this.context.containsBean("foo")).as("missing bean from @ConditionalOnBusEnabled config").isTrue();
}
@Test
public void busEnabledMissing() {
load(MyBusEnabledConfig.class);
assertThat(this.context.containsBean("foo"))
.as("missing bean from @ConditionalOnBusEnabled config").isTrue();
assertThat(this.context.containsBean("foo")).as("missing bean from @ConditionalOnBusEnabled config").isTrue();
}
@Test
public void busDisabled() {
load(MyBusEnabledConfig.class,
ConditionalOnBusEnabled.SPRING_CLOUD_BUS_ENABLED + ":false");
assertThat(this.context.containsBean("foo"))
.as("bean exists from disabled @ConditionalOnBusEnabled config")
load(MyBusEnabledConfig.class, ConditionalOnBusEnabled.SPRING_CLOUD_BUS_ENABLED + ":false");
assertThat(this.context.containsBean("foo")).as("bean exists from disabled @ConditionalOnBusEnabled config")
.isFalse();
}

View File

@@ -41,8 +41,7 @@ import static org.mockito.Mockito.verify;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = RefreshListenerIntegrationTests.MyApp.class,
properties = { "management.endpoints.web.exposure.include=*",
"spring.application.name=foobar" })
properties = { "management.endpoints.web.exposure.include=*", "spring.application.name=foobar" })
public class RefreshListenerIntegrationTests {
@Autowired
@@ -57,10 +56,10 @@ public class RefreshListenerIntegrationTests {
@Test
public void testEndpoint() {
System.out.println(rest.getForObject("/actuator", String.class));
assertThat(rest.postForEntity("/actuator/bus-refresh/demoapp", new HashMap<>(),
String.class).getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
assertThat(rest.postForEntity("/actuator/bus-refresh/foobar", new HashMap<>(),
String.class).getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
assertThat(rest.postForEntity("/actuator/bus-refresh/demoapp", new HashMap<>(), String.class).getStatusCode())
.isEqualTo(HttpStatus.NO_CONTENT);
assertThat(rest.postForEntity("/actuator/bus-refresh/foobar", new HashMap<>(), String.class).getStatusCode())
.isEqualTo(HttpStatus.NO_CONTENT);
verify(contextRefresher, times(1)).refresh();
}

View File

@@ -45,87 +45,97 @@ public class ServiceMatcherTests {
private void initMatcher(String id) {
BusProperties properties = new BusProperties();
properties.setId(id);
DefaultBusPathMatcher pathMatcher = new DefaultBusPathMatcher(
new AntPathMatcher(":"));
DefaultBusPathMatcher pathMatcher = new DefaultBusPathMatcher(new AntPathMatcher(":"));
this.matcher = new ServiceMatcher(pathMatcher, properties.getId());
}
@Test
public void fromSelf() {
assertThat(this.matcher.isFromSelf(new EnvironmentChangeRemoteApplicationEvent(
this, "one:two:8888", "foo:bar:spam", EMPTY_MAP))).isTrue();
assertThat(this.matcher.isFromSelf(
new EnvironmentChangeRemoteApplicationEvent(this, "one:two:8888", "foo:bar:spam", EMPTY_MAP))).isTrue();
}
@Test
public void forSelf() {
assertThat(this.matcher.isForSelf(new EnvironmentChangeRemoteApplicationEvent(
this, "foo:bar:spam", "one:two:8888", EMPTY_MAP))).isTrue();
assertThat(this.matcher.isForSelf(
new EnvironmentChangeRemoteApplicationEvent(this, "foo:bar:spam", "one:two:8888", EMPTY_MAP))).isTrue();
}
@Test
public void forSelfWithWildcard() {
assertThat(this.matcher.isForSelf(new EnvironmentChangeRemoteApplicationEvent(
this, "foo:bar:spam", "one:two:*", EMPTY_MAP))).isTrue();
assertThat(this.matcher
.isForSelf(new EnvironmentChangeRemoteApplicationEvent(this, "foo:bar:spam", "one:two:*", EMPTY_MAP)))
.isTrue();
}
@Test
public void forSelfWithGlobalWildcard() {
assertThat(this.matcher.isForSelf(new EnvironmentChangeRemoteApplicationEvent(
this, "foo:bar:spam", "**", EMPTY_MAP))).isTrue();
assertThat(this.matcher
.isForSelf(new EnvironmentChangeRemoteApplicationEvent(this, "foo:bar:spam", "**", EMPTY_MAP)))
.isTrue();
}
@Test
public void forSelfWithWildcardName() {
assertThat(this.matcher.isForSelf(new EnvironmentChangeRemoteApplicationEvent(
this, "foo:bar:spam", "o*", EMPTY_MAP))).isTrue();
assertThat(this.matcher
.isForSelf(new EnvironmentChangeRemoteApplicationEvent(this, "foo:bar:spam", "o*", EMPTY_MAP)))
.isTrue();
}
@Test
public void forSelfWithWildcardNameAndProfile() {
assertThat(this.matcher.isForSelf(new EnvironmentChangeRemoteApplicationEvent(
this, "foo:bar:spam", "o*:t*", EMPTY_MAP))).isTrue();
assertThat(this.matcher
.isForSelf(new EnvironmentChangeRemoteApplicationEvent(this, "foo:bar:spam", "o*:t*", EMPTY_MAP)))
.isTrue();
}
@Test
public void forSelfWithWildcardString() {
assertThat(this.matcher.isForSelf(new EnvironmentChangeRemoteApplicationEvent(
this, "foo:bar:spam", "o*", EMPTY_MAP))).isTrue();
assertThat(this.matcher
.isForSelf(new EnvironmentChangeRemoteApplicationEvent(this, "foo:bar:spam", "o*", EMPTY_MAP)))
.isTrue();
}
@Test
public void notForSelfWithWildCardNameAndMismatchingProfile() {
assertThat(this.matcher.isForSelf(new EnvironmentChangeRemoteApplicationEvent(
this, "foo:bar:spam", "o*:f*", EMPTY_MAP))).isFalse();
assertThat(this.matcher
.isForSelf(new EnvironmentChangeRemoteApplicationEvent(this, "foo:bar:spam", "o*:f*", EMPTY_MAP)))
.isFalse();
}
@Test
public void forSelfWithDoubleWildcard() {
assertThat(this.matcher.isForSelf(new EnvironmentChangeRemoteApplicationEvent(
this, "foo:bar:spam", "one:**", EMPTY_MAP))).isTrue();
assertThat(this.matcher
.isForSelf(new EnvironmentChangeRemoteApplicationEvent(this, "foo:bar:spam", "one:**", EMPTY_MAP)))
.isTrue();
}
@Test
public void forSelfWithNoWildcard() {
assertThat(this.matcher.isForSelf(new EnvironmentChangeRemoteApplicationEvent(
this, "foo:bar:spam", "one", EMPTY_MAP))).isTrue();
assertThat(this.matcher
.isForSelf(new EnvironmentChangeRemoteApplicationEvent(this, "foo:bar:spam", "one", EMPTY_MAP)))
.isTrue();
}
@Test
public void forSelfWithProfileNoWildcard() {
assertThat(this.matcher.isForSelf(new EnvironmentChangeRemoteApplicationEvent(
this, "foo:bar:spam", "one:two", EMPTY_MAP))).isTrue();
assertThat(this.matcher
.isForSelf(new EnvironmentChangeRemoteApplicationEvent(this, "foo:bar:spam", "one:two", EMPTY_MAP)))
.isTrue();
}
@Test
public void notForSelf() {
assertThat(this.matcher.isForSelf(new EnvironmentChangeRemoteApplicationEvent(
this, "foo:bar:spam", "one:two:9999", EMPTY_MAP))).isFalse();
assertThat(this.matcher.isForSelf(
new EnvironmentChangeRemoteApplicationEvent(this, "foo:bar:spam", "one:two:9999", EMPTY_MAP)))
.isFalse();
}
@Test
public void notFromSelf() {
assertThat(this.matcher.isFromSelf(new EnvironmentChangeRemoteApplicationEvent(
this, "one:two:9999", "foo:bar:spam", EMPTY_MAP))).isFalse();
assertThat(this.matcher.isFromSelf(
new EnvironmentChangeRemoteApplicationEvent(this, "one:two:9999", "foo:bar:spam", EMPTY_MAP)))
.isFalse();
}
/**
@@ -134,8 +144,9 @@ public class ServiceMatcherTests {
@Test
public void forSelfWithMultipleProfiles() {
initMatcher("customerportal:dev,cloud:80");
assertThat(this.matcher.isForSelf(new EnvironmentChangeRemoteApplicationEvent(
this, "foo:bar:spam", "customerportal:cloud:*", EMPTY_MAP))).isTrue();
assertThat(this.matcher.isForSelf(
new EnvironmentChangeRemoteApplicationEvent(this, "foo:bar:spam", "customerportal:cloud:*", EMPTY_MAP)))
.isTrue();
}
/**
@@ -144,8 +155,9 @@ public class ServiceMatcherTests {
@Test
public void notForSelfWithMultipleProfiles() {
initMatcher("customerportal:dev,cloud:80");
assertThat(this.matcher.isForSelf(new EnvironmentChangeRemoteApplicationEvent(
this, "foo:bar:spam", "bar:cloud:*", EMPTY_MAP))).isFalse();
assertThat(this.matcher
.isForSelf(new EnvironmentChangeRemoteApplicationEvent(this, "foo:bar:spam", "bar:cloud:*", EMPTY_MAP)))
.isFalse();
}
/**
@@ -154,8 +166,8 @@ public class ServiceMatcherTests {
@Test
public void notForSelfWithMultipleProfilesDifferentPort() {
initMatcher("customerportal:dev,cloud:80");
assertThat(this.matcher.isForSelf(new EnvironmentChangeRemoteApplicationEvent(
this, "foo:bar:spam", "customerportal:cloud:8008", EMPTY_MAP))).isFalse();
assertThat(this.matcher.isForSelf(new EnvironmentChangeRemoteApplicationEvent(this, "foo:bar:spam",
"customerportal:cloud:8008", EMPTY_MAP))).isFalse();
}
}

View File

@@ -45,96 +45,108 @@ public class ServiceMatcherWithConfigNamesTests {
private void initMatcher(String id, String[] configNames) {
BusProperties properties = new BusProperties();
properties.setId(id);
DefaultBusPathMatcher pathMatcher = new DefaultBusPathMatcher(
new AntPathMatcher(":"));
DefaultBusPathMatcher pathMatcher = new DefaultBusPathMatcher(new AntPathMatcher(":"));
this.matcher = new ServiceMatcher(pathMatcher, properties.getId(), configNames);
}
@Test
public void forSelfWithWildcard() {
assertThat(this.matcher.isForSelf(new EnvironmentChangeRemoteApplicationEvent(
this, "foo:bar:spam", "one:two:*", EMPTY_MAP))).isTrue();
assertThat(this.matcher
.isForSelf(new EnvironmentChangeRemoteApplicationEvent(this, "foo:bar:spam", "one:two:*", EMPTY_MAP)))
.isTrue();
}
@Test
public void forSelfWithWildcardAndOtherConfigName() {
assertThat(this.matcher.isForSelf(new EnvironmentChangeRemoteApplicationEvent(
this, "foo:bar:spam", "three:two:*", EMPTY_MAP))).isTrue();
assertThat(this.matcher
.isForSelf(new EnvironmentChangeRemoteApplicationEvent(this, "foo:bar:spam", "three:two:*", EMPTY_MAP)))
.isTrue();
}
@Test
public void forSelfWithGlobalWildcard() {
assertThat(this.matcher.isForSelf(new EnvironmentChangeRemoteApplicationEvent(
this, "foo:bar:spam", "**", EMPTY_MAP))).isTrue();
assertThat(this.matcher
.isForSelf(new EnvironmentChangeRemoteApplicationEvent(this, "foo:bar:spam", "**", EMPTY_MAP)))
.isTrue();
}
@Test
public void forSelfWithWildcardName() {
assertThat(this.matcher.isForSelf(new EnvironmentChangeRemoteApplicationEvent(
this, "foo:bar:spam", "o*", EMPTY_MAP))).isTrue();
assertThat(this.matcher
.isForSelf(new EnvironmentChangeRemoteApplicationEvent(this, "foo:bar:spam", "o*", EMPTY_MAP)))
.isTrue();
}
@Test
public void forSelfWithWildcardNameAndProfile() {
assertThat(this.matcher.isForSelf(new EnvironmentChangeRemoteApplicationEvent(
this, "foo:bar:spam", "o*:t*", EMPTY_MAP))).isTrue();
assertThat(this.matcher
.isForSelf(new EnvironmentChangeRemoteApplicationEvent(this, "foo:bar:spam", "o*:t*", EMPTY_MAP)))
.isTrue();
}
@Test
public void forSelfWithWildcardString() {
assertThat(this.matcher.isForSelf(new EnvironmentChangeRemoteApplicationEvent(
this, "foo:bar:spam", "o*", EMPTY_MAP))).isTrue();
assertThat(this.matcher
.isForSelf(new EnvironmentChangeRemoteApplicationEvent(this, "foo:bar:spam", "o*", EMPTY_MAP)))
.isTrue();
}
@Test
public void notForSelfWithWildCardNameAndMismatchingProfile() {
assertThat(this.matcher.isForSelf(new EnvironmentChangeRemoteApplicationEvent(
this, "foo:bar:spam", "o*:f*", EMPTY_MAP))).isFalse();
assertThat(this.matcher
.isForSelf(new EnvironmentChangeRemoteApplicationEvent(this, "foo:bar:spam", "o*:f*", EMPTY_MAP)))
.isFalse();
}
@Test
public void forSelfWithDoubleWildcard() {
assertThat(this.matcher.isForSelf(new EnvironmentChangeRemoteApplicationEvent(
this, "foo:bar:spam", "one:**", EMPTY_MAP))).isTrue();
assertThat(this.matcher
.isForSelf(new EnvironmentChangeRemoteApplicationEvent(this, "foo:bar:spam", "one:**", EMPTY_MAP)))
.isTrue();
}
@Test
public void forSelfWithNoWildcard() {
assertThat(this.matcher.isForSelf(new EnvironmentChangeRemoteApplicationEvent(
this, "foo:bar:spam", "one", EMPTY_MAP))).isTrue();
assertThat(this.matcher
.isForSelf(new EnvironmentChangeRemoteApplicationEvent(this, "foo:bar:spam", "one", EMPTY_MAP)))
.isTrue();
}
@Test
public void forSelfWithProfileNoWildcard() {
assertThat(this.matcher.isForSelf(new EnvironmentChangeRemoteApplicationEvent(
this, "foo:bar:spam", "one:two", EMPTY_MAP))).isTrue();
assertThat(this.matcher
.isForSelf(new EnvironmentChangeRemoteApplicationEvent(this, "foo:bar:spam", "one:two", EMPTY_MAP)))
.isTrue();
}
@Test
public void notForSelf() {
assertThat(this.matcher.isForSelf(new EnvironmentChangeRemoteApplicationEvent(
this, "foo:bar:spam", "one:two:9999", EMPTY_MAP))).isFalse();
assertThat(this.matcher.isForSelf(
new EnvironmentChangeRemoteApplicationEvent(this, "foo:bar:spam", "one:two:9999", EMPTY_MAP)))
.isFalse();
}
@Test
public void forSelfWithMultipleProfiles() {
initMatcher("customerportal:dev,cloud:80", new String[] { "one", "three" });
assertThat(this.matcher.isForSelf(new EnvironmentChangeRemoteApplicationEvent(
this, "foo:bar:spam", "one:cloud:*", EMPTY_MAP))).isTrue();
assertThat(this.matcher
.isForSelf(new EnvironmentChangeRemoteApplicationEvent(this, "foo:bar:spam", "one:cloud:*", EMPTY_MAP)))
.isTrue();
}
@Test
public void notForSelfWithMultipleProfiles() {
initMatcher("customerportal:dev,cloud:80", new String[] { "one", "three" });
assertThat(this.matcher.isForSelf(new EnvironmentChangeRemoteApplicationEvent(
this, "foo:bar:spam", "bar:cloud:*", EMPTY_MAP))).isFalse();
assertThat(this.matcher
.isForSelf(new EnvironmentChangeRemoteApplicationEvent(this, "foo:bar:spam", "bar:cloud:*", EMPTY_MAP)))
.isFalse();
}
@Test
public void notForSelfWithMultipleProfilesDifferentPort() {
initMatcher("customerportal:dev,cloud:80", new String[] { "one", "three" });
assertThat(this.matcher.isForSelf(new EnvironmentChangeRemoteApplicationEvent(
this, "foo:bar:spam", "customerportal:cloud:8008", EMPTY_MAP))).isFalse();
assertThat(this.matcher.isForSelf(new EnvironmentChangeRemoteApplicationEvent(this, "foo:bar:spam",
"customerportal:cloud:8008", EMPTY_MAP))).isFalse();
}
}

View File

@@ -25,8 +25,7 @@ public class TestRemoteApplicationEvent extends RemoteApplicationEvent {
private TestRemoteApplicationEvent() {
}
protected TestRemoteApplicationEvent(Object source, String originService,
String destinationService) {
protected TestRemoteApplicationEvent(Object source, String originService, String destinationService) {
super(source, originService, destinationService);
}

View File

@@ -28,8 +28,7 @@ public class TypedRemoteApplicationEvent extends RemoteApplicationEvent {
private TypedRemoteApplicationEvent() {
}
protected TypedRemoteApplicationEvent(Object source, String originService,
String destinationService) {
protected TypedRemoteApplicationEvent(Object source, String originService, String destinationService) {
super(source, originService, destinationService);
}

View File

@@ -50,87 +50,72 @@ public class RemoteApplicationEventScanTests {
@Test
public void importingClassMetadataPackageRegistered() {
this.converter = createTestContext(DefaultConfig.class)
.getBean(BusJacksonMessageConverter.class);
this.converter = createTestContext(DefaultConfig.class).getBean(BusJacksonMessageConverter.class);
assertConverterBeanAfterPropertiesSet(
new String[] { "org.springframework.cloud.bus.jackson",
"org.springframework.cloud.bus.event" },
AnotherRemoteApplicationEvent.class, MyRemoteApplicationEvent.class,
TestRemoteApplicationEvent.class, TypedRemoteApplicationEvent.class);
new String[] { "org.springframework.cloud.bus.jackson", "org.springframework.cloud.bus.event" },
AnotherRemoteApplicationEvent.class, MyRemoteApplicationEvent.class, TestRemoteApplicationEvent.class,
TypedRemoteApplicationEvent.class);
}
@Test
public void annotationValuePackagesRegistered() {
this.converter = createTestContext(ValueConfig.class)
.getBean(BusJacksonMessageConverter.class);
this.converter = createTestContext(ValueConfig.class).getBean(BusJacksonMessageConverter.class);
assertConverterBeanAfterPropertiesSet(
new String[] { "test.foo.bar", "com.acme",
"org.springframework.cloud.bus.event" },
new String[] { "test.foo.bar", "com.acme", "org.springframework.cloud.bus.event" },
FooBarTestRemoteApplicationEvent.class, TestRemoteApplicationEvent.class,
TypedRemoteApplicationEvent.class);
}
@Test
public void annotationValueBasePackagesRegistered() {
this.converter = createTestContext(BasePackagesConfig.class)
.getBean(BusJacksonMessageConverter.class);
this.converter = createTestContext(BasePackagesConfig.class).getBean(BusJacksonMessageConverter.class);
assertConverterBeanAfterPropertiesSet(
new String[] { "test.foo.bar", "fizz.buzz", "com.acme",
"org.springframework.cloud.bus.event" },
new String[] { "test.foo.bar", "fizz.buzz", "com.acme", "org.springframework.cloud.bus.event" },
FooBarTestRemoteApplicationEvent.class, TestRemoteApplicationEvent.class,
TypedRemoteApplicationEvent.class);
}
@Test
public void annotationBasePackagesRegistered() {
this.converter = createTestContext(BasePackageClassesConfig.class)
.getBean(BusJacksonMessageConverter.class);
this.converter = createTestContext(BasePackageClassesConfig.class).getBean(BusJacksonMessageConverter.class);
assertConverterBeanAfterPropertiesSet(
new String[] { "org.springframework.cloud.bus.event.test",
"org.springframework.cloud.bus.event" },
new String[] { "org.springframework.cloud.bus.event.test", "org.springframework.cloud.bus.event" },
TestRemoteApplicationEvent.class, TypedRemoteApplicationEvent.class);
}
private ConfigurableApplicationContext createTestContext(Class<?> configuration) {
return new SpringApplicationBuilder(configuration).web(WebApplicationType.NONE)
.bannerMode(Banner.Mode.OFF).run();
return new SpringApplicationBuilder(configuration).web(WebApplicationType.NONE).bannerMode(Banner.Mode.OFF)
.run();
}
private void assertConverterBeanAfterPropertiesSet(
final String[] expectedPackageToScan,
private void assertConverterBeanAfterPropertiesSet(final String[] expectedPackageToScan,
final Class<?>... expectedRegisterdClasses) {
final ObjectMapper mapper = (ObjectMapper) ReflectionTestUtils
.getField(this.converter, "mapper");
final ObjectMapper mapper = (ObjectMapper) ReflectionTestUtils.getField(this.converter, "mapper");
@SuppressWarnings("unchecked")
final LinkedHashSet<NamedType> registeredSubtypes = (LinkedHashSet<NamedType>) ReflectionTestUtils
.getField(mapper.getSubtypeResolver(), "_registeredSubtypes");
final List<Class<?>> expectedRegisterdClassesAsList = new ArrayList<>(
Arrays.asList(expectedRegisterdClasses));
final List<Class<?>> expectedRegisterdClassesAsList = new ArrayList<>(Arrays.asList(expectedRegisterdClasses));
addStandardSpringCloudEventBusEvents(expectedRegisterdClassesAsList);
assertThat(expectedRegisterdClassesAsList.size() == registeredSubtypes.size())
.as("Wrong RemoteApplicationEvent classes are registerd in object mapper")
.isTrue();
.as("Wrong RemoteApplicationEvent classes are registerd in object mapper").isTrue();
for (final NamedType namedType : registeredSubtypes) {
assertThat(expectedRegisterdClassesAsList.contains(namedType.getType()))
.isTrue();
assertThat(expectedRegisterdClassesAsList.contains(namedType.getType())).isTrue();
}
assertThat(Arrays.asList((String[]) ReflectionTestUtils.getField(this.converter,
"packagesToScan"))).as("RemoteApplicationEvent packages not registered")
.contains(expectedPackageToScan);
assertThat(Arrays.asList((String[]) ReflectionTestUtils.getField(this.converter, "packagesToScan")))
.as("RemoteApplicationEvent packages not registered").contains(expectedPackageToScan);
}
private void addStandardSpringCloudEventBusEvents(
final List<Class<?>> expectedRegisterdClassesAsList) {
private void addStandardSpringCloudEventBusEvents(final List<Class<?>> expectedRegisterdClassesAsList) {
expectedRegisterdClassesAsList.add(AckRemoteApplicationEvent.class);
expectedRegisterdClassesAsList.add(EnvironmentChangeRemoteApplicationEvent.class);
expectedRegisterdClassesAsList.add(RefreshRemoteApplicationEvent.class);

View File

@@ -37,13 +37,12 @@ public class SerializationTests {
@Test
public void vanillaDeserialize() throws Exception {
this.mapper.registerModule(new SubtypeModule(RefreshRemoteApplicationEvent.class,
EnvironmentChangeRemoteApplicationEvent.class));
EnvironmentChangeRemoteApplicationEvent source = new EnvironmentChangeRemoteApplicationEvent(
this, "foo", "bar", Collections.<String, String>emptyMap());
this.mapper.registerModule(
new SubtypeModule(RefreshRemoteApplicationEvent.class, EnvironmentChangeRemoteApplicationEvent.class));
EnvironmentChangeRemoteApplicationEvent source = new EnvironmentChangeRemoteApplicationEvent(this, "foo", "bar",
Collections.<String, String>emptyMap());
String value = this.mapper.writeValueAsString(source);
RemoteApplicationEvent event = this.mapper.readValue(value,
RemoteApplicationEvent.class);
RemoteApplicationEvent event = this.mapper.readValue(value, RemoteApplicationEvent.class);
assertThat(event instanceof EnvironmentChangeRemoteApplicationEvent).isTrue();
assertThat(event.getId()).isNotNull();
assertThat(event.getId().equals(source.getId())).isTrue();
@@ -51,14 +50,13 @@ public class SerializationTests {
@Test
public void deserializeOldValueWithNoId() throws Exception {
this.mapper.registerModule(new SubtypeModule(RefreshRemoteApplicationEvent.class,
EnvironmentChangeRemoteApplicationEvent.class));
EnvironmentChangeRemoteApplicationEvent source = new EnvironmentChangeRemoteApplicationEvent(
this, "foo", "bar", Collections.<String, String>emptyMap());
this.mapper.registerModule(
new SubtypeModule(RefreshRemoteApplicationEvent.class, EnvironmentChangeRemoteApplicationEvent.class));
EnvironmentChangeRemoteApplicationEvent source = new EnvironmentChangeRemoteApplicationEvent(this, "foo", "bar",
Collections.<String, String>emptyMap());
String value = this.mapper.writeValueAsString(source);
value = value.replaceAll(",\"id\":\"[a-f0-9-]*\"", "");
RemoteApplicationEvent event = this.mapper.readValue(value,
RemoteApplicationEvent.class);
RemoteApplicationEvent event = this.mapper.readValue(value, RemoteApplicationEvent.class);
assertThat(event instanceof EnvironmentChangeRemoteApplicationEvent).isTrue();
assertThat(event.getId()).isNotNull();
assertThat(event.getId().equals(source.getId())).isFalse();

View File

@@ -44,23 +44,18 @@ public class SubtypeModuleTests {
RemoteApplicationEvent event = mapper.readValue(
"{\"type\":\"my\", \"destinationService\":\"myservice\", \"originService\":\"myorigin\"}",
RemoteApplicationEvent.class);
assertThat(event instanceof MyRemoteApplicationEvent).as("event is wrong type")
.isTrue();
assertThat(event instanceof MyRemoteApplicationEvent).as("event is wrong type").isTrue();
MyRemoteApplicationEvent myEvent = MyRemoteApplicationEvent.class.cast(event);
assertThat(myEvent.getOriginService()).as("originService was wrong")
.isEqualTo("myorigin");
assertThat(myEvent.getDestinationService()).as("destinationService was wrong")
.isEqualTo("myservice");
assertThat(myEvent.getOriginService()).as("originService was wrong").isEqualTo("myorigin");
assertThat(myEvent.getDestinationService()).as("destinationService was wrong").isEqualTo("myservice");
}
@Test
public void testDeserializeWhenTypeIsKnown() throws Exception {
ObjectMapper mapper = new ObjectMapper();
RemoteApplicationEvent event = mapper.readValue("{\"type\":\"another\"}",
AnotherRemoteApplicationEvent.class);
assertThat(event instanceof AnotherRemoteApplicationEvent)
.as("event is wrong type").isTrue();
RemoteApplicationEvent event = mapper.readValue("{\"type\":\"another\"}", AnotherRemoteApplicationEvent.class);
assertThat(event instanceof AnotherRemoteApplicationEvent).as("event is wrong type").isTrue();
}
@Test
@@ -70,39 +65,34 @@ public class SubtypeModuleTests {
BusJacksonMessageConverter converter = new BusJacksonMessageConverter(mapper);
converter.afterPropertiesSet();
Object event = converter.fromMessage(MessageBuilder.withPayload(
"{\"type\":\"TestRemoteApplicationEvent\", \"origin_service\":\"myorigin\"}")
.build(), RemoteApplicationEvent.class);
Object event = converter.fromMessage(MessageBuilder
.withPayload("{\"type\":\"TestRemoteApplicationEvent\", \"origin_service\":\"myorigin\"}").build(),
RemoteApplicationEvent.class);
assertThat(event).isNotNull().isInstanceOf(TestRemoteApplicationEvent.class);
assertThat(TestRemoteApplicationEvent.class.cast(event).getOriginService())
.isEqualTo("myorigin");
assertThat(TestRemoteApplicationEvent.class.cast(event).getOriginService()).isEqualTo("myorigin");
}
@Test
public void testDeserializeWithMessageConverter() throws Exception {
BusJacksonMessageConverter converter = new BusJacksonMessageConverter(null);
converter.afterPropertiesSet();
Object event = converter.fromMessage(MessageBuilder
.withPayload("{\"type\":\"TestRemoteApplicationEvent\"}").build(),
Object event = converter.fromMessage(
MessageBuilder.withPayload("{\"type\":\"TestRemoteApplicationEvent\"}").build(),
RemoteApplicationEvent.class);
assertThat(event instanceof TestRemoteApplicationEvent).as("event is wrong type")
.isTrue();
assertThat(event instanceof TestRemoteApplicationEvent).as("event is wrong type").isTrue();
}
@Test
public void testDeserializeUnknownTypeWithMessageConverter() throws Exception {
BusJacksonMessageConverter converter = new BusJacksonMessageConverter(null);
converter.afterPropertiesSet();
Object event = converter.fromMessage(MessageBuilder
.withPayload("{\"type\":\"NotDefinedTestRemoteApplicationEvent\"}")
.build(), RemoteApplicationEvent.class);
assertThat(event instanceof UnknownRemoteApplicationEvent)
.as("event is wrong type").isTrue();
assertThat(((UnknownRemoteApplicationEvent) event).getTypeInfo())
.as("type information is wrong")
Object event = converter.fromMessage(
MessageBuilder.withPayload("{\"type\":\"NotDefinedTestRemoteApplicationEvent\"}").build(),
RemoteApplicationEvent.class);
assertThat(event instanceof UnknownRemoteApplicationEvent).as("event is wrong type").isTrue();
assertThat(((UnknownRemoteApplicationEvent) event).getTypeInfo()).as("type information is wrong")
.isEqualTo("NotDefinedTestRemoteApplicationEvent");
assertThat(((UnknownRemoteApplicationEvent) event).getPayloadAsString())
.as("payload is wrong")
assertThat(((UnknownRemoteApplicationEvent) event).getPayloadAsString()).as("payload is wrong")
.isEqualTo("{\"type\":\"NotDefinedTestRemoteApplicationEvent\"}");
}
@@ -110,11 +100,9 @@ public class SubtypeModuleTests {
public void testDeserializeJsonTypeWithMessageConverter() throws Exception {
BusJacksonMessageConverter converter = new BusJacksonMessageConverter(null);
converter.afterPropertiesSet();
Object event = converter.fromMessage(
MessageBuilder.withPayload("{\"type\":\"typed\"}").build(),
Object event = converter.fromMessage(MessageBuilder.withPayload("{\"type\":\"typed\"}").build(),
RemoteApplicationEvent.class);
assertThat(event instanceof TypedRemoteApplicationEvent).as("event is wrong type")
.isTrue();
assertThat(event instanceof TypedRemoteApplicationEvent).as("event is wrong type").isTrue();
}
/**
@@ -124,12 +112,12 @@ public class SubtypeModuleTests {
public void testDeserializeAckRemoteApplicationEventWithKnownType() throws Exception {
BusJacksonMessageConverter converter = new BusJacksonMessageConverter(null);
converter.afterPropertiesSet();
Object event = converter.fromMessage(MessageBuilder
.withPayload("{\"type\":\"AckRemoteApplicationEvent\", "
+ "\"event\":\"org.springframework.cloud.bus.event.test.TestRemoteApplicationEvent\"}")
.build(), RemoteApplicationEvent.class);
assertThat(event instanceof AckRemoteApplicationEvent).as("event is no ack")
.isTrue();
Object event = converter
.fromMessage(MessageBuilder
.withPayload("{\"type\":\"AckRemoteApplicationEvent\", "
+ "\"event\":\"org.springframework.cloud.bus.event.test.TestRemoteApplicationEvent\"}")
.build(), RemoteApplicationEvent.class);
assertThat(event instanceof AckRemoteApplicationEvent).as("event is no ack").isTrue();
AckRemoteApplicationEvent ackEvent = AckRemoteApplicationEvent.class.cast(event);
assertThat(ackEvent.getEvent()).as("inner ack event has wrong type")
.isEqualTo(TestRemoteApplicationEvent.class);
@@ -139,15 +127,14 @@ public class SubtypeModuleTests {
* see https://github.com/spring-cloud/spring-cloud-bus/issues/74
*/
@Test
public void testDeserializeAckRemoteApplicationEventWithUnknownType()
throws Exception {
public void testDeserializeAckRemoteApplicationEventWithUnknownType() throws Exception {
BusJacksonMessageConverter converter = new BusJacksonMessageConverter(null);
converter.afterPropertiesSet();
Object event = converter.fromMessage(MessageBuilder.withPayload(
"{\"type\":\"AckRemoteApplicationEvent\", \"event\":\"foo.bar.TestRemoteApplicationEvent\"}")
Object event = converter.fromMessage(MessageBuilder
.withPayload(
"{\"type\":\"AckRemoteApplicationEvent\", \"event\":\"foo.bar.TestRemoteApplicationEvent\"}")
.build(), RemoteApplicationEvent.class);
assertThat(event instanceof AckRemoteApplicationEvent).as("event is no ack")
.isTrue();
assertThat(event instanceof AckRemoteApplicationEvent).as("event is no ack").isTrue();
AckRemoteApplicationEvent ackEvent = AckRemoteApplicationEvent.class.cast(event);
assertThat(ackEvent.getEvent()).as("inner ack event has wrong type")
.isEqualTo(UnknownRemoteApplicationEvent.class);
@@ -161,8 +148,7 @@ public class SubtypeModuleTests {
private MyRemoteApplicationEvent() {
}
protected MyRemoteApplicationEvent(Object source, String originService,
String destinationService) {
protected MyRemoteApplicationEvent(Object source, String originService, String destinationService) {
super(source, originService, destinationService);
}
@@ -180,8 +166,7 @@ public class SubtypeModuleTests {
private AnotherRemoteApplicationEvent() {
}
protected AnotherRemoteApplicationEvent(Object source, String originService,
String destinationService) {
protected AnotherRemoteApplicationEvent(Object source, String originService, String destinationService) {
super(source, originService, destinationService);
}

View File

@@ -25,13 +25,12 @@ public class FooBarTestRemoteApplicationEvent extends RemoteApplicationEvent {
private FooBarTestRemoteApplicationEvent() {
}
protected FooBarTestRemoteApplicationEvent(final Object source,
final String originService, final String destinationService) {
protected FooBarTestRemoteApplicationEvent(final Object source, final String originService,
final String destinationService) {
super(source, originService, destinationService);
}
protected FooBarTestRemoteApplicationEvent(final Object source,
final String originService) {
protected FooBarTestRemoteApplicationEvent(final Object source, final String originService) {
super(source, originService);
}