Bumping versions
This commit is contained in:
@@ -83,8 +83,9 @@ public class FeaturesEndpoint implements ApplicationContextAware {
|
||||
|
||||
private void addFeature(Features features, NamedFeature feature) {
|
||||
Class<?> type = feature.getType();
|
||||
features.getEnabled().add(new Feature(feature.getName(), type.getCanonicalName(),
|
||||
type.getPackage().getImplementationVersion(), type.getPackage().getImplementationVendor()));
|
||||
features.getEnabled()
|
||||
.add(new Feature(feature.getName(), type.getCanonicalName(), type.getPackage().getImplementationVersion(),
|
||||
type.getPackage().getImplementationVendor()));
|
||||
}
|
||||
|
||||
static class Features {
|
||||
|
||||
@@ -36,7 +36,7 @@ public class DefaultCircuitBreakerObservationConvention implements CircuitBreake
|
||||
@Override
|
||||
public KeyValues getLowCardinalityKeyValues(CircuitBreakerObservationContext context) {
|
||||
return KeyValues.of(CircuitBreakerObservationDocumentation.LowCardinalityTags.OBJECT_TYPE
|
||||
.withValue(context.getType().name().toLowerCase(Locale.ROOT)));
|
||||
.withValue(context.getType().name().toLowerCase(Locale.ROOT)));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -37,9 +37,9 @@ class ObservedFunction<T> implements Function<Throwable, T> {
|
||||
String conextualName, ObservationRegistry observationRegistry, Function<Throwable, T> toRun) {
|
||||
this.delegate = toRun;
|
||||
this.observation = CircuitBreakerObservationDocumentation.CIRCUIT_BREAKER_SUPPLIER_OBSERVATION
|
||||
.observation(customConvention, DefaultCircuitBreakerObservationConvention.INSTANCE, () -> context,
|
||||
observationRegistry)
|
||||
.parentObservation(observationRegistry.getCurrentObservation());
|
||||
.observation(customConvention, DefaultCircuitBreakerObservationConvention.INSTANCE, () -> context,
|
||||
observationRegistry)
|
||||
.parentObservation(observationRegistry.getCurrentObservation());
|
||||
this.observation.contextualName(conextualName);
|
||||
}
|
||||
|
||||
|
||||
@@ -37,9 +37,9 @@ class ObservedSupplier<T> implements Supplier<T> {
|
||||
String contextualName, ObservationRegistry observationRegistry, Supplier<T> toRun) {
|
||||
this.delegate = toRun;
|
||||
this.observation = CircuitBreakerObservationDocumentation.CIRCUIT_BREAKER_SUPPLIER_OBSERVATION
|
||||
.observation(customConvention, DefaultCircuitBreakerObservationConvention.INSTANCE, () -> context,
|
||||
observationRegistry)
|
||||
.parentObservation(observationRegistry.getCurrentObservation());
|
||||
.observation(customConvention, DefaultCircuitBreakerObservationConvention.INSTANCE, () -> context,
|
||||
observationRegistry)
|
||||
.parentObservation(observationRegistry.getCurrentObservation());
|
||||
this.observation.contextualName(contextualName);
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ import org.springframework.context.annotation.Import;
|
||||
|
||||
/**
|
||||
* Annotation to enable a DiscoveryClient implementation.
|
||||
*
|
||||
* @author Spencer Gibb
|
||||
*/
|
||||
@Target(ElementType.TYPE)
|
||||
|
||||
@@ -41,7 +41,7 @@ public class EnableDiscoveryClientImportSelector extends SpringFactoryImportSele
|
||||
String[] imports = super.selectImports(metadata);
|
||||
|
||||
AnnotationAttributes attributes = AnnotationAttributes
|
||||
.fromMap(metadata.getAnnotationAttributes(getAnnotationClass().getName(), true));
|
||||
.fromMap(metadata.getAnnotationAttributes(getAnnotationClass().getName(), true));
|
||||
|
||||
boolean autoRegister = attributes.getBoolean("autoRegister");
|
||||
|
||||
|
||||
@@ -43,7 +43,7 @@ public class DiscoveryCompositeHealthContributor implements CompositeHealthContr
|
||||
public DiscoveryCompositeHealthContributor(Collection<DiscoveryHealthIndicator> indicators) {
|
||||
Assert.notNull(indicators, "'indicators' must not be null");
|
||||
this.indicators = indicators.stream()
|
||||
.collect(Collectors.toMap(DiscoveryHealthIndicator::getName, Function.identity()));
|
||||
.collect(Collectors.toMap(DiscoveryHealthIndicator::getName, Function.identity()));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -71,8 +71,8 @@ public class ReactiveDiscoveryClientHealthIndicator
|
||||
return doHealthCheck();
|
||||
}
|
||||
else {
|
||||
return Mono.just(
|
||||
Health.status(new Status(Status.UNKNOWN.getCode(), "Discovery Client not initialized")).build());
|
||||
return Mono
|
||||
.just(Health.status(new Status(Status.UNKNOWN.getCode(), "Discovery Client not initialized")).build());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ public class ReactiveDiscoveryCompositeHealthContributor implements CompositeRea
|
||||
public ReactiveDiscoveryCompositeHealthContributor(Collection<ReactiveDiscoveryHealthIndicator> indicators) {
|
||||
Assert.notNull(indicators, "'indicators' must not be null");
|
||||
this.indicators = indicators.stream()
|
||||
.collect(Collectors.toMap(ReactiveDiscoveryHealthIndicator::getName, Function.identity()));
|
||||
.collect(Collectors.toMap(ReactiveDiscoveryHealthIndicator::getName, Function.identity()));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -48,7 +48,7 @@ public class SimpleDiscoveryClient implements DiscoveryClient {
|
||||
public List<ServiceInstance> getInstances(String serviceId) {
|
||||
List<ServiceInstance> serviceInstances = new ArrayList<>();
|
||||
List<DefaultServiceInstance> serviceInstanceForService = this.simpleDiscoveryProperties.getInstances()
|
||||
.get(serviceId);
|
||||
.get(serviceId);
|
||||
if (serviceInstanceForService != null) {
|
||||
serviceInstances.addAll(serviceInstanceForService);
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ import org.springframework.beans.factory.annotation.Qualifier;
|
||||
/**
|
||||
* Annotation to mark a RestTemplate, RestClient.Builder or WebClient.Builder bean to be
|
||||
* configured to use a LoadBalancerClient.
|
||||
*
|
||||
* @author Spencer Gibb
|
||||
*/
|
||||
@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })
|
||||
|
||||
@@ -41,9 +41,10 @@ public final class LoadBalancerLifecycleValidator {
|
||||
if (lifecycleProcessors == null) {
|
||||
return new HashSet<>();
|
||||
}
|
||||
return lifecycleProcessors.values().stream()
|
||||
.filter(lifecycle -> lifecycle.supports(requestContextClass, clientResponseClass, serverTypeClass))
|
||||
.collect(Collectors.toSet());
|
||||
return lifecycleProcessors.values()
|
||||
.stream()
|
||||
.filter(lifecycle -> lifecycle.supports(requestContextClass, clientResponseClass, serverTypeClass))
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -429,7 +429,7 @@ public class LoadBalancerProperties {
|
||||
|
||||
public void setRetryableExceptions(Set<Class<? extends Throwable>> retryableExceptions) {
|
||||
retryableExceptions
|
||||
.add(org.springframework.cloud.client.loadbalancer.reactive.RetryableStatusCodeException.class);
|
||||
.add(org.springframework.cloud.client.loadbalancer.reactive.RetryableStatusCodeException.class);
|
||||
this.retryableExceptions = retryableExceptions;
|
||||
}
|
||||
|
||||
|
||||
@@ -95,7 +95,7 @@ public final class LoadBalancerUriTools {
|
||||
private static URI doReconstructURI(ServiceInstance serviceInstance, URI original) {
|
||||
String host = serviceInstance.getHost();
|
||||
String scheme = Optional.ofNullable(serviceInstance.getScheme())
|
||||
.orElse(computeScheme(original, serviceInstance));
|
||||
.orElse(computeScheme(original, serviceInstance));
|
||||
int port = computePort(serviceInstance.getPort(), scheme);
|
||||
|
||||
if (Objects.equals(host, original.getHost()) && port == original.getPort()
|
||||
|
||||
@@ -83,7 +83,7 @@ public class RequestData {
|
||||
HttpHeaders newCookies = new HttpHeaders();
|
||||
if (cookies != null) {
|
||||
cookies.forEach((key, value) -> value
|
||||
.forEach(cookie -> newCookies.put(cookie.getName(), Collections.singletonList(cookie.getValue()))));
|
||||
.forEach(cookie -> newCookies.put(cookie.getName(), Collections.singletonList(cookie.getValue()))));
|
||||
}
|
||||
return newCookies;
|
||||
}
|
||||
|
||||
@@ -83,9 +83,9 @@ public class RetryLoadBalancerInterceptor implements BlockingLoadBalancerInterce
|
||||
}
|
||||
}
|
||||
Set<LoadBalancerLifecycle> supportedLifecycleProcessors = LoadBalancerLifecycleValidator
|
||||
.getSupportedLifecycleProcessors(
|
||||
loadBalancerFactory.getInstances(serviceName, LoadBalancerLifecycle.class),
|
||||
RetryableRequestContext.class, ResponseData.class, ServiceInstance.class);
|
||||
.getSupportedLifecycleProcessors(
|
||||
loadBalancerFactory.getInstances(serviceName, LoadBalancerLifecycle.class),
|
||||
RetryableRequestContext.class, ResponseData.class, ServiceInstance.class);
|
||||
String hint = getHint(serviceName);
|
||||
if (serviceInstance == null) {
|
||||
if (LOG.isDebugEnabled()) {
|
||||
@@ -109,11 +109,10 @@ public class RetryLoadBalancerInterceptor implements BlockingLoadBalancerInterce
|
||||
Response<ServiceInstance> lbResponse = new DefaultResponse(serviceInstance);
|
||||
if (serviceInstance == null) {
|
||||
supportedLifecycleProcessors.forEach(lifecycle -> lifecycle
|
||||
.onComplete(new CompletionContext<ResponseData, ServiceInstance, RetryableRequestContext>(
|
||||
CompletionContext.Status.DISCARD,
|
||||
new DefaultRequest<>(
|
||||
new RetryableRequestContext(null, new RequestData(request), hint)),
|
||||
lbResponse)));
|
||||
.onComplete(new CompletionContext<ResponseData, ServiceInstance, RetryableRequestContext>(
|
||||
CompletionContext.Status.DISCARD,
|
||||
new DefaultRequest<>(new RetryableRequestContext(null, new RequestData(request), hint)),
|
||||
lbResponse)));
|
||||
}
|
||||
}
|
||||
LoadBalancerRequestAdapter<ClientHttpResponse, RetryableRequestContext> lbRequest = new LoadBalancerRequestAdapter<>(
|
||||
|
||||
@@ -48,14 +48,17 @@ public final class ExchangeFilterFunctionUtils {
|
||||
List<LoadBalancerClientRequestTransformer> transformers) {
|
||||
URI originalUrl = request.url();
|
||||
ClientRequest clientRequest = ClientRequest
|
||||
.create(request.method(), LoadBalancerUriTools.reconstructURI(serviceInstance, originalUrl))
|
||||
.headers(headers -> headers.addAll(request.headers())).cookies(cookies -> {
|
||||
cookies.addAll(request.cookies());
|
||||
if (!(instanceIdCookieName == null || instanceIdCookieName.length() == 0)
|
||||
&& addServiceInstanceCookie) {
|
||||
cookies.add(instanceIdCookieName, serviceInstance.getInstanceId());
|
||||
}
|
||||
}).attributes(attributes -> attributes.putAll(request.attributes())).body(request.body()).build();
|
||||
.create(request.method(), LoadBalancerUriTools.reconstructURI(serviceInstance, originalUrl))
|
||||
.headers(headers -> headers.addAll(request.headers()))
|
||||
.cookies(cookies -> {
|
||||
cookies.addAll(request.cookies());
|
||||
if (!(instanceIdCookieName == null || instanceIdCookieName.length() == 0) && addServiceInstanceCookie) {
|
||||
cookies.add(instanceIdCookieName, serviceInstance.getInstanceId());
|
||||
}
|
||||
})
|
||||
.attributes(attributes -> attributes.putAll(request.attributes()))
|
||||
.body(request.body())
|
||||
.build();
|
||||
if (transformers != null) {
|
||||
for (LoadBalancerClientRequestTransformer transformer : transformers) {
|
||||
clientRequest = transformer.transformRequest(clientRequest, serviceInstance);
|
||||
|
||||
@@ -80,9 +80,8 @@ public class ReactorLoadBalancerExchangeFilterFunction implements LoadBalancedEx
|
||||
return Mono.just(ClientResponse.create(HttpStatus.BAD_REQUEST).body(message).build());
|
||||
}
|
||||
Set<LoadBalancerLifecycle> supportedLifecycleProcessors = LoadBalancerLifecycleValidator
|
||||
.getSupportedLifecycleProcessors(
|
||||
loadBalancerFactory.getInstances(serviceId, LoadBalancerLifecycle.class),
|
||||
RequestDataContext.class, ResponseData.class, ServiceInstance.class);
|
||||
.getSupportedLifecycleProcessors(loadBalancerFactory.getInstances(serviceId, LoadBalancerLifecycle.class),
|
||||
RequestDataContext.class, ResponseData.class, ServiceInstance.class);
|
||||
String hint = getHint(serviceId, loadBalancerFactory.getProperties(serviceId).getHint());
|
||||
RequestData requestData = new RequestData(clientRequest);
|
||||
DefaultRequest<RequestDataContext> lbRequest = new DefaultRequest<>(new RequestDataContext(requestData, hint));
|
||||
@@ -95,9 +94,10 @@ public class ReactorLoadBalancerExchangeFilterFunction implements LoadBalancedEx
|
||||
LOG.warn(message);
|
||||
}
|
||||
supportedLifecycleProcessors.forEach(lifecycle -> lifecycle
|
||||
.onComplete(new CompletionContext<>(CompletionContext.Status.DISCARD, lbRequest, lbResponse)));
|
||||
.onComplete(new CompletionContext<>(CompletionContext.Status.DISCARD, lbRequest, lbResponse)));
|
||||
return Mono.just(ClientResponse.create(HttpStatus.SERVICE_UNAVAILABLE)
|
||||
.body(serviceInstanceUnavailableMessage(serviceId)).build());
|
||||
.body(serviceInstanceUnavailableMessage(serviceId))
|
||||
.build());
|
||||
}
|
||||
|
||||
if (LOG.isDebugEnabled()) {
|
||||
@@ -105,18 +105,18 @@ public class ReactorLoadBalancerExchangeFilterFunction implements LoadBalancedEx
|
||||
instance.getUri()));
|
||||
}
|
||||
LoadBalancerProperties.StickySession stickySessionProperties = loadBalancerFactory.getProperties(serviceId)
|
||||
.getStickySession();
|
||||
.getStickySession();
|
||||
ClientRequest newRequest = buildClientRequest(clientRequest, instance,
|
||||
stickySessionProperties.getInstanceIdCookieName(),
|
||||
stickySessionProperties.isAddServiceInstanceCookie(), transformers);
|
||||
supportedLifecycleProcessors.forEach(lifecycle -> lifecycle.onStartRequest(lbRequest, lbResponse));
|
||||
return next.exchange(newRequest)
|
||||
.doOnError(throwable -> supportedLifecycleProcessors.forEach(lifecycle -> lifecycle
|
||||
.onComplete(new CompletionContext<ResponseData, ServiceInstance, RequestDataContext>(
|
||||
CompletionContext.Status.FAILED, throwable, lbRequest, lbResponse))))
|
||||
.doOnSuccess(clientResponse -> supportedLifecycleProcessors.forEach(
|
||||
lifecycle -> lifecycle.onComplete(new CompletionContext<>(CompletionContext.Status.SUCCESS,
|
||||
lbRequest, lbResponse, new ResponseData(clientResponse, requestData)))));
|
||||
.doOnError(throwable -> supportedLifecycleProcessors.forEach(lifecycle -> lifecycle
|
||||
.onComplete(new CompletionContext<ResponseData, ServiceInstance, RequestDataContext>(
|
||||
CompletionContext.Status.FAILED, throwable, lbRequest, lbResponse))))
|
||||
.doOnSuccess(clientResponse -> supportedLifecycleProcessors
|
||||
.forEach(lifecycle -> lifecycle.onComplete(new CompletionContext<>(CompletionContext.Status.SUCCESS,
|
||||
lbRequest, lbResponse, new ResponseData(clientResponse, requestData)))));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -54,9 +54,11 @@ public class RetryableExchangeFilterFunctionLoadBalancerRetryPolicy implements L
|
||||
if (properties.getRetry().isRetryOnAllExceptions()) {
|
||||
return true;
|
||||
}
|
||||
return properties.getRetry().getRetryableExceptions().stream()
|
||||
.anyMatch(exception -> exception.isInstance(throwable)
|
||||
|| throwable != null && exception.isInstance(throwable.getCause()));
|
||||
return properties.getRetry()
|
||||
.getRetryableExceptions()
|
||||
.stream()
|
||||
.anyMatch(exception -> exception.isInstance(throwable)
|
||||
|| throwable != null && exception.isInstance(throwable.getCause()));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -98,9 +98,8 @@ public class RetryableLoadBalancerExchangeFilterFunction implements LoadBalanced
|
||||
properties.getRetry(), retryPolicy);
|
||||
|
||||
Set<LoadBalancerLifecycle> supportedLifecycleProcessors = LoadBalancerLifecycleValidator
|
||||
.getSupportedLifecycleProcessors(
|
||||
loadBalancerFactory.getInstances(serviceId, LoadBalancerLifecycle.class),
|
||||
RetryableRequestContext.class, ResponseData.class, ServiceInstance.class);
|
||||
.getSupportedLifecycleProcessors(loadBalancerFactory.getInstances(serviceId, LoadBalancerLifecycle.class),
|
||||
RetryableRequestContext.class, ResponseData.class, ServiceInstance.class);
|
||||
String hint = getHint(serviceId, properties.getHint());
|
||||
RequestData requestData = new RequestData(clientRequest);
|
||||
DefaultRequest<RetryableRequestContext> lbRequest = new DefaultRequest<>(
|
||||
@@ -115,10 +114,11 @@ public class RetryableLoadBalancerExchangeFilterFunction implements LoadBalanced
|
||||
LOG.warn(message);
|
||||
}
|
||||
supportedLifecycleProcessors.forEach(lifecycle -> lifecycle
|
||||
.onComplete(new CompletionContext<ResponseData, ServiceInstance, RetryableRequestContext>(
|
||||
CompletionContext.Status.DISCARD, lbRequest, lbResponse)));
|
||||
.onComplete(new CompletionContext<ResponseData, ServiceInstance, RetryableRequestContext>(
|
||||
CompletionContext.Status.DISCARD, lbRequest, lbResponse)));
|
||||
return Mono.just(ClientResponse.create(HttpStatus.SERVICE_UNAVAILABLE)
|
||||
.body(serviceInstanceUnavailableMessage(serviceId)).build());
|
||||
.body(serviceInstanceUnavailableMessage(serviceId))
|
||||
.build());
|
||||
}
|
||||
|
||||
if (LOG.isDebugEnabled()) {
|
||||
@@ -131,24 +131,24 @@ public class RetryableLoadBalancerExchangeFilterFunction implements LoadBalanced
|
||||
stickySessionProperties.isAddServiceInstanceCookie(), transformers);
|
||||
supportedLifecycleProcessors.forEach(lifecycle -> lifecycle.onStartRequest(lbRequest, lbResponse));
|
||||
return next.exchange(newRequest)
|
||||
.doOnError(throwable -> supportedLifecycleProcessors.forEach(lifecycle -> lifecycle
|
||||
.onComplete(new CompletionContext<ResponseData, ServiceInstance, RetryableRequestContext>(
|
||||
CompletionContext.Status.FAILED, throwable, lbRequest, lbResponse))))
|
||||
.doOnSuccess(clientResponse -> supportedLifecycleProcessors.forEach(
|
||||
lifecycle -> lifecycle.onComplete(new CompletionContext<>(CompletionContext.Status.SUCCESS,
|
||||
lbRequest, lbResponse, new ResponseData(clientResponse, requestData)))))
|
||||
.map(clientResponse -> {
|
||||
loadBalancerRetryContext.setClientResponse(clientResponse);
|
||||
if (shouldRetrySameServiceInstance(retryPolicy, loadBalancerRetryContext)) {
|
||||
if (LOG.isDebugEnabled()) {
|
||||
LOG.debug(String.format("Retrying on status code: %d",
|
||||
clientResponse.statusCode().value()));
|
||||
}
|
||||
throw new RetryableStatusCodeException();
|
||||
.doOnError(throwable -> supportedLifecycleProcessors.forEach(lifecycle -> lifecycle
|
||||
.onComplete(new CompletionContext<ResponseData, ServiceInstance, RetryableRequestContext>(
|
||||
CompletionContext.Status.FAILED, throwable, lbRequest, lbResponse))))
|
||||
.doOnSuccess(clientResponse -> supportedLifecycleProcessors
|
||||
.forEach(lifecycle -> lifecycle.onComplete(new CompletionContext<>(CompletionContext.Status.SUCCESS,
|
||||
lbRequest, lbResponse, new ResponseData(clientResponse, requestData)))))
|
||||
.map(clientResponse -> {
|
||||
loadBalancerRetryContext.setClientResponse(clientResponse);
|
||||
if (shouldRetrySameServiceInstance(retryPolicy, loadBalancerRetryContext)) {
|
||||
if (LOG.isDebugEnabled()) {
|
||||
LOG.debug(
|
||||
String.format("Retrying on status code: %d", clientResponse.statusCode().value()));
|
||||
}
|
||||
return clientResponse;
|
||||
throw new RetryableStatusCodeException();
|
||||
}
|
||||
return clientResponse;
|
||||
|
||||
});
|
||||
});
|
||||
}).map(clientResponse -> {
|
||||
loadBalancerRetryContext.setClientResponse(clientResponse);
|
||||
if (shouldRetryNextServiceInstance(retryPolicy, loadBalancerRetryContext)) {
|
||||
@@ -165,18 +165,21 @@ public class RetryableLoadBalancerExchangeFilterFunction implements LoadBalanced
|
||||
private Retry buildRetrySpec(int max, boolean transientErrors, LoadBalancerProperties.Retry retry,
|
||||
LoadBalancerRetryPolicy retryPolicy) {
|
||||
if (!retry.isEnabled()) {
|
||||
return Retry.max(0).filter(throwable -> isRetryException(throwable, retryPolicy))
|
||||
.transientErrors(transientErrors);
|
||||
return Retry.max(0)
|
||||
.filter(throwable -> isRetryException(throwable, retryPolicy))
|
||||
.transientErrors(transientErrors);
|
||||
}
|
||||
LoadBalancerProperties.Retry.Backoff backoffProperties = retry.getBackoff();
|
||||
if (backoffProperties.isEnabled()) {
|
||||
return RetrySpec.backoff(max, backoffProperties.getMinBackoff())
|
||||
.filter(throwable -> isRetryException(throwable, retryPolicy))
|
||||
.maxBackoff(backoffProperties.getMaxBackoff()).jitter(backoffProperties.getJitter())
|
||||
.transientErrors(transientErrors);
|
||||
}
|
||||
return RetrySpec.max(max).filter(throwable -> isRetryException(throwable, retryPolicy))
|
||||
.filter(throwable -> isRetryException(throwable, retryPolicy))
|
||||
.maxBackoff(backoffProperties.getMaxBackoff())
|
||||
.jitter(backoffProperties.getJitter())
|
||||
.transientErrors(transientErrors);
|
||||
}
|
||||
return RetrySpec.max(max)
|
||||
.filter(throwable -> isRetryException(throwable, retryPolicy))
|
||||
.transientErrors(transientErrors);
|
||||
}
|
||||
|
||||
private boolean shouldRetrySameServiceInstance(LoadBalancerRetryPolicy retryPolicy,
|
||||
|
||||
@@ -158,12 +158,12 @@ public abstract class AbstractAutoServiceRegistration<R extends Registration>
|
||||
registrationLifecycle -> registrationLifecycle.postProcessAfterStartRegister(getRegistration()));
|
||||
if (shouldRegisterManagement()) {
|
||||
this.registrationManagementLifecycles
|
||||
.forEach(registrationManagementLifecycle -> registrationManagementLifecycle
|
||||
.postProcessBeforeStartRegisterManagement(getManagementRegistration()));
|
||||
.forEach(registrationManagementLifecycle -> registrationManagementLifecycle
|
||||
.postProcessBeforeStartRegisterManagement(getManagementRegistration()));
|
||||
this.registerManagement();
|
||||
registrationManagementLifecycles
|
||||
.forEach(registrationManagementLifecycle -> registrationManagementLifecycle
|
||||
.postProcessAfterStartRegisterManagement(getManagementRegistration()));
|
||||
.forEach(registrationManagementLifecycle -> registrationManagementLifecycle
|
||||
.postProcessAfterStartRegisterManagement(getManagementRegistration()));
|
||||
|
||||
}
|
||||
this.context.publishEvent(new InstanceRegisteredEvent<>(this, getConfiguration()));
|
||||
@@ -301,12 +301,12 @@ public abstract class AbstractAutoServiceRegistration<R extends Registration>
|
||||
registrationLifecycle -> registrationLifecycle.postProcessAfterStopRegister(getRegistration()));
|
||||
if (shouldRegisterManagement()) {
|
||||
this.registrationManagementLifecycles
|
||||
.forEach(registrationManagementLifecycle -> registrationManagementLifecycle
|
||||
.postProcessBeforeStopRegisterManagement(getManagementRegistration()));
|
||||
.forEach(registrationManagementLifecycle -> registrationManagementLifecycle
|
||||
.postProcessBeforeStopRegisterManagement(getManagementRegistration()));
|
||||
deregisterManagement();
|
||||
this.registrationManagementLifecycles
|
||||
.forEach(registrationManagementLifecycle -> registrationManagementLifecycle
|
||||
.postProcessAfterStopRegisterManagement(getManagementRegistration()));
|
||||
.forEach(registrationManagementLifecycle -> registrationManagementLifecycle
|
||||
.postProcessAfterStopRegisterManagement(getManagementRegistration()));
|
||||
}
|
||||
this.serviceRegistry.close();
|
||||
}
|
||||
|
||||
@@ -88,24 +88,27 @@ public abstract class ConfigDataMissingEnvironmentPostProcessor implements Envir
|
||||
|
||||
private List<Object> getConfigImports(ConfigurableEnvironment environment) {
|
||||
MutablePropertySources propertySources = environment.getPropertySources();
|
||||
List<Object> property = propertySources.stream().filter(this::propertySourceWithConfigImport)
|
||||
.flatMap(propertySource -> {
|
||||
List<Object> configImports = new ArrayList<>();
|
||||
if (propertySource.getProperty(CONFIG_IMPORT_PROPERTY) != null) {
|
||||
configImports.add(propertySource.getProperty(CONFIG_IMPORT_PROPERTY));
|
||||
}
|
||||
else {
|
||||
configImports.addAll(Arrays.asList(getConfigImportArray(propertySource)));
|
||||
}
|
||||
return configImports.stream();
|
||||
}).collect(Collectors.toList());
|
||||
List<Object> property = propertySources.stream()
|
||||
.filter(this::propertySourceWithConfigImport)
|
||||
.flatMap(propertySource -> {
|
||||
List<Object> configImports = new ArrayList<>();
|
||||
if (propertySource.getProperty(CONFIG_IMPORT_PROPERTY) != null) {
|
||||
configImports.add(propertySource.getProperty(CONFIG_IMPORT_PROPERTY));
|
||||
}
|
||||
else {
|
||||
configImports.addAll(Arrays.asList(getConfigImportArray(propertySource)));
|
||||
}
|
||||
return configImports.stream();
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
return property;
|
||||
}
|
||||
|
||||
private boolean propertySourceWithConfigImport(PropertySource propertySource) {
|
||||
if (propertySource instanceof CompositePropertySource) {
|
||||
return ((CompositePropertySource) propertySource).getPropertySources().stream()
|
||||
.anyMatch(this::propertySourceWithConfigImport);
|
||||
return ((CompositePropertySource) propertySource).getPropertySources()
|
||||
.stream()
|
||||
.anyMatch(this::propertySourceWithConfigImport);
|
||||
}
|
||||
return propertySource.containsProperty(CONFIG_IMPORT_PROPERTY)
|
||||
|| getConfigImportArray(propertySource).length > 0;
|
||||
|
||||
@@ -150,10 +150,10 @@ final class FluxFirstNonEmptyEmitting<T> extends Flux<T> implements Scannable, P
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
static final AtomicIntegerFieldUpdater<RaceCoordinator> WIP = AtomicIntegerFieldUpdater
|
||||
.newUpdater(RaceCoordinator.class, "wip");
|
||||
.newUpdater(RaceCoordinator.class, "wip");
|
||||
|
||||
static final AtomicIntegerFieldUpdater<RaceCoordinator> COMPETING_SUBSCRIBERS = AtomicIntegerFieldUpdater
|
||||
.newUpdater(RaceCoordinator.class, "competingSubscribers");
|
||||
.newUpdater(RaceCoordinator.class, "competingSubscribers");
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
RaceCoordinator(int n) {
|
||||
|
||||
@@ -76,7 +76,7 @@ public class InetUtils implements Closeable {
|
||||
try {
|
||||
int lowest = Integer.MAX_VALUE;
|
||||
for (Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces(); nics
|
||||
.hasMoreElements();) {
|
||||
.hasMoreElements();) {
|
||||
NetworkInterface ifc = nics.nextElement();
|
||||
if (ifc.isUp()) {
|
||||
this.log.trace("Testing interface: " + ifc.getDisplayName());
|
||||
|
||||
@@ -64,7 +64,7 @@ public abstract class SpringFactoryImportSelector<T>
|
||||
return new String[0];
|
||||
}
|
||||
AnnotationAttributes attributes = AnnotationAttributes
|
||||
.fromMap(metadata.getAnnotationAttributes(this.annotationClass.getName(), true));
|
||||
.fromMap(metadata.getAnnotationAttributes(this.annotationClass.getName(), true));
|
||||
|
||||
Assert.notNull(attributes, "No " + getSimpleName() + " attributes found. Is " + metadata.getClassName()
|
||||
+ " annotated with @" + getSimpleName() + "?");
|
||||
|
||||
@@ -123,14 +123,14 @@ class SpringBootVersionVerifier implements CompatibilityVerifier {
|
||||
}
|
||||
|
||||
private String action() {
|
||||
return String.format(
|
||||
"""
|
||||
Change Spring Boot version to one of the following versions %s .
|
||||
You can find the latest Spring Boot versions here [%s].\s
|
||||
If you want to learn more about the Spring Cloud Release train compatibility, you can visit this page [%s] and check the [Release Trains] section.
|
||||
If you want to disable this check, just set the property [spring.cloud.compatibility-verifier.enabled=false]""",
|
||||
this.acceptedVersions, "https://spring.io/projects/spring-boot#learn",
|
||||
"https://spring.io/projects/spring-cloud#overview");
|
||||
return String
|
||||
.format("""
|
||||
Change Spring Boot version to one of the following versions %s .
|
||||
You can find the latest Spring Boot versions here [%s].\s
|
||||
If you want to learn more about the Spring Cloud Release train compatibility, you can visit this page [%s] and check the [Release Trains] section.
|
||||
If you want to disable this check, just set the property [spring.cloud.compatibility-verifier.enabled=false]""",
|
||||
this.acceptedVersions, "https://spring.io/projects/spring-boot#learn",
|
||||
"https://spring.io/projects/spring-cloud#overview");
|
||||
}
|
||||
|
||||
private boolean springBootVersionMatches() {
|
||||
@@ -147,7 +147,7 @@ class SpringBootVersionVerifier implements CompatibilityVerifier {
|
||||
// otherwise this could lead to false positives for future
|
||||
// versions of boot
|
||||
CompatibilityPredicate predicate = this.ACCEPTED_VERSIONS
|
||||
.get(stripWildCardFromVersion(acceptedVersion));
|
||||
.get(stripWildCardFromVersion(acceptedVersion));
|
||||
if (predicate != null && predicate.isCompatible()) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Predicate [" + predicate + "] was matched");
|
||||
|
||||
@@ -42,92 +42,99 @@ import static org.assertj.core.api.BDDAssertions.then;
|
||||
public class CommonsClientAutoConfigurationTests {
|
||||
|
||||
ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(CommonsClientAutoConfiguration.class,
|
||||
SimpleDiscoveryClientAutoConfiguration.class, UtilAutoConfiguration.class));
|
||||
.withConfiguration(AutoConfigurations.of(CommonsClientAutoConfiguration.class,
|
||||
SimpleDiscoveryClientAutoConfiguration.class, UtilAutoConfiguration.class));
|
||||
|
||||
@Test
|
||||
public void beansCreatedNormally() {
|
||||
applicationContextRunner.withConfiguration(AutoConfigurations.of(HealthEndpointAutoConfiguration.class))
|
||||
.withPropertyValues("management.endpoints.web.exposure.include=features").run(ctxt -> {
|
||||
then(ctxt.getBean(DiscoveryClientHealthIndicator.class)).isNotNull();
|
||||
then(ctxt.getBean(DiscoveryCompositeHealthContributor.class)).isNotNull();
|
||||
then(ctxt.getBean(FeaturesEndpoint.class)).isNotNull();
|
||||
then(ctxt.getBeansOfType(HasFeatures.class).values()).isNotEmpty();
|
||||
});
|
||||
.withPropertyValues("management.endpoints.web.exposure.include=features")
|
||||
.run(ctxt -> {
|
||||
then(ctxt.getBean(DiscoveryClientHealthIndicator.class)).isNotNull();
|
||||
then(ctxt.getBean(DiscoveryCompositeHealthContributor.class)).isNotNull();
|
||||
then(ctxt.getBean(FeaturesEndpoint.class)).isNotNull();
|
||||
then(ctxt.getBeansOfType(HasFeatures.class).values()).isNotEmpty();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void disableAll() {
|
||||
applicationContextRunner.withPropertyValues("spring.cloud.discovery.enabled=false",
|
||||
"management.endpoints.web.exposure.include=features").run(ctxt -> {
|
||||
assertThat(ctxt).doesNotHaveBean(DiscoveryClientHealthIndicator.class);
|
||||
assertThat(ctxt).doesNotHaveBean(DiscoveryCompositeHealthContributor.class);
|
||||
then(ctxt.getBean(FeaturesEndpoint.class)).isNotNull();
|
||||
// features actuator is independent of discovery
|
||||
assertThat(ctxt).doesNotHaveBean(HasFeatures.class);
|
||||
});
|
||||
applicationContextRunner
|
||||
.withPropertyValues("spring.cloud.discovery.enabled=false",
|
||||
"management.endpoints.web.exposure.include=features")
|
||||
.run(ctxt -> {
|
||||
assertThat(ctxt).doesNotHaveBean(DiscoveryClientHealthIndicator.class);
|
||||
assertThat(ctxt).doesNotHaveBean(DiscoveryCompositeHealthContributor.class);
|
||||
then(ctxt.getBean(FeaturesEndpoint.class)).isNotNull();
|
||||
// features actuator is independent of discovery
|
||||
assertThat(ctxt).doesNotHaveBean(HasFeatures.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void disableBlocking() {
|
||||
applicationContextRunner.withPropertyValues("spring.cloud.discovery.blocking.enabled=false",
|
||||
"management.endpoints.web.exposure.include=features").run(ctxt -> {
|
||||
assertThat(ctxt).doesNotHaveBean(DiscoveryClientHealthIndicator.class);
|
||||
assertThat(ctxt).doesNotHaveBean(DiscoveryCompositeHealthContributor.class);
|
||||
then(ctxt.getBean(FeaturesEndpoint.class)).isNotNull();
|
||||
// features actuator is independent of discovery
|
||||
assertThat(ctxt).doesNotHaveBean(HasFeatures.class);
|
||||
});
|
||||
applicationContextRunner
|
||||
.withPropertyValues("spring.cloud.discovery.blocking.enabled=false",
|
||||
"management.endpoints.web.exposure.include=features")
|
||||
.run(ctxt -> {
|
||||
assertThat(ctxt).doesNotHaveBean(DiscoveryClientHealthIndicator.class);
|
||||
assertThat(ctxt).doesNotHaveBean(DiscoveryCompositeHealthContributor.class);
|
||||
then(ctxt.getBean(FeaturesEndpoint.class)).isNotNull();
|
||||
// features actuator is independent of discovery
|
||||
assertThat(ctxt).doesNotHaveBean(HasFeatures.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void disableAllIndividually() {
|
||||
applicationContextRunner.withPropertyValues("spring.cloud.discovery.client.health-indicator.enabled=false",
|
||||
"spring.cloud.discovery.client.composite-indicator.enabled=false",
|
||||
"spring.cloud.features.enabled=false").run(ctxt -> {
|
||||
assertThat(ctxt).doesNotHaveBean(DiscoveryClientHealthIndicator.class);
|
||||
assertThat(ctxt).doesNotHaveBean(DiscoveryCompositeHealthContributor.class);
|
||||
assertThat(ctxt).doesNotHaveBean(FeaturesEndpoint.class);
|
||||
});
|
||||
applicationContextRunner
|
||||
.withPropertyValues("spring.cloud.discovery.client.health-indicator.enabled=false",
|
||||
"spring.cloud.discovery.client.composite-indicator.enabled=false",
|
||||
"spring.cloud.features.enabled=false")
|
||||
.run(ctxt -> {
|
||||
assertThat(ctxt).doesNotHaveBean(DiscoveryClientHealthIndicator.class);
|
||||
assertThat(ctxt).doesNotHaveBean(DiscoveryCompositeHealthContributor.class);
|
||||
assertThat(ctxt).doesNotHaveBean(FeaturesEndpoint.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void disableHealthIndicator() {
|
||||
applicationContextRunner.withPropertyValues("spring.cloud.discovery.client.health-indicator.enabled=false")
|
||||
.run(ctxt -> {
|
||||
assertThat(ctxt).doesNotHaveBean(DiscoveryClientHealthIndicator.class);
|
||||
assertThat(ctxt).doesNotHaveBean(DiscoveryCompositeHealthContributor.class);
|
||||
});
|
||||
.run(ctxt -> {
|
||||
assertThat(ctxt).doesNotHaveBean(DiscoveryClientHealthIndicator.class);
|
||||
assertThat(ctxt).doesNotHaveBean(DiscoveryCompositeHealthContributor.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void worksWithoutActuator() {
|
||||
applicationContextRunner.withClassLoader(new FilteredClassLoader("org.springframework.boot.actuate"))
|
||||
.run(context -> {
|
||||
assertThat(context).doesNotHaveBean(DiscoveryClientHealthIndicator.class);
|
||||
assertThat(context).doesNotHaveBean(DiscoveryCompositeHealthContributor.class);
|
||||
then(context.getBeansOfType(HasFeatures.class).values()).isEmpty();
|
||||
});
|
||||
.run(context -> {
|
||||
assertThat(context).doesNotHaveBean(DiscoveryClientHealthIndicator.class);
|
||||
assertThat(context).doesNotHaveBean(DiscoveryCompositeHealthContributor.class);
|
||||
then(context.getBeansOfType(HasFeatures.class).values()).isEmpty();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void conditionalOnDiscoveryEnabledWorks() {
|
||||
applicationContextRunner.withUserConfiguration(DiscoveryEnabledConfig.class)
|
||||
.withPropertyValues("spring.cloud.discovery.enabled=false")
|
||||
.run(context -> assertThat(context).doesNotHaveBean(TestBean.class));
|
||||
.withPropertyValues("spring.cloud.discovery.enabled=false")
|
||||
.run(context -> assertThat(context).doesNotHaveBean(TestBean.class));
|
||||
applicationContextRunner.withUserConfiguration(DiscoveryEnabledConfig.class)
|
||||
.withPropertyValues("spring.cloud.discovery.enabled=true")
|
||||
.run(context -> assertThat(context.getBean(TestBean.class)).isNotNull());
|
||||
.withPropertyValues("spring.cloud.discovery.enabled=true")
|
||||
.run(context -> assertThat(context.getBean(TestBean.class)).isNotNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void conditionalOnBlockingDiscoveryEnabledWorks() {
|
||||
applicationContextRunner.withUserConfiguration(BlockingDiscoveryEnabledConfig.class)
|
||||
.withPropertyValues("spring.cloud.discovery.blocking.enabled=false")
|
||||
.run(context -> assertThat(context).doesNotHaveBean(TestBean.class));
|
||||
.withPropertyValues("spring.cloud.discovery.blocking.enabled=false")
|
||||
.run(context -> assertThat(context).doesNotHaveBean(TestBean.class));
|
||||
applicationContextRunner.withUserConfiguration(BlockingDiscoveryEnabledConfig.class)
|
||||
.withPropertyValues("spring.cloud.discovery.blocking.enabled=true")
|
||||
.run(context -> assertThat(context.getBean(TestBean.class)).isNotNull());
|
||||
.withPropertyValues("spring.cloud.discovery.blocking.enabled=true")
|
||||
.run(context -> assertThat(context.getBean(TestBean.class)).isNotNull());
|
||||
}
|
||||
|
||||
@TestConfiguration
|
||||
|
||||
@@ -39,93 +39,99 @@ import static org.assertj.core.api.BDDAssertions.then;
|
||||
public class ReactiveCommonsClientAutoConfigurationTests {
|
||||
|
||||
ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(CommonsClientAutoConfiguration.class,
|
||||
SimpleReactiveDiscoveryClientAutoConfiguration.class, UtilAutoConfiguration.class,
|
||||
ReactiveCommonsClientAutoConfiguration.class));
|
||||
.withConfiguration(AutoConfigurations.of(CommonsClientAutoConfiguration.class,
|
||||
SimpleReactiveDiscoveryClientAutoConfiguration.class, UtilAutoConfiguration.class,
|
||||
ReactiveCommonsClientAutoConfiguration.class));
|
||||
|
||||
@Test
|
||||
public void beansCreatedNormally() {
|
||||
applicationContextRunner.withPropertyValues("management.endpoints.web.exposure.include=features")
|
||||
.run(context -> {
|
||||
then(context.getBean(ReactiveDiscoveryClientHealthIndicator.class)).isNotNull();
|
||||
then(context.getBean(ReactiveDiscoveryCompositeHealthContributor.class)).isNotNull();
|
||||
then(context.getBean(FeaturesEndpoint.class)).isNotNull();
|
||||
then(context.getBeansOfType(HasFeatures.class).values()).isNotEmpty();
|
||||
});
|
||||
.run(context -> {
|
||||
then(context.getBean(ReactiveDiscoveryClientHealthIndicator.class)).isNotNull();
|
||||
then(context.getBean(ReactiveDiscoveryCompositeHealthContributor.class)).isNotNull();
|
||||
then(context.getBean(FeaturesEndpoint.class)).isNotNull();
|
||||
then(context.getBeansOfType(HasFeatures.class).values()).isNotEmpty();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void disableAll() {
|
||||
applicationContextRunner.withPropertyValues("spring.cloud.discovery.enabled=false",
|
||||
"management.endpoints.web.exposure.include=features").run(context -> {
|
||||
assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class);
|
||||
assertThat(context).doesNotHaveBean(ReactiveDiscoveryCompositeHealthContributor.class);
|
||||
// features actuator is independent of discovery
|
||||
then(context.getBean(FeaturesEndpoint.class)).isNotNull();
|
||||
assertThat(context).doesNotHaveBean(HasFeatures.class);
|
||||
});
|
||||
applicationContextRunner
|
||||
.withPropertyValues("spring.cloud.discovery.enabled=false",
|
||||
"management.endpoints.web.exposure.include=features")
|
||||
.run(context -> {
|
||||
assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class);
|
||||
assertThat(context).doesNotHaveBean(ReactiveDiscoveryCompositeHealthContributor.class);
|
||||
// features actuator is independent of discovery
|
||||
then(context.getBean(FeaturesEndpoint.class)).isNotNull();
|
||||
assertThat(context).doesNotHaveBean(HasFeatures.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void disableReactive() {
|
||||
applicationContextRunner.withPropertyValues("spring.cloud.discovery.reactive.enabled=false",
|
||||
"management.endpoints.web.exposure.include=features").run(context -> {
|
||||
assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class);
|
||||
assertThat(context).doesNotHaveBean(ReactiveDiscoveryCompositeHealthContributor.class);
|
||||
// features actuator is independent of discovery
|
||||
then(context.getBean(FeaturesEndpoint.class)).isNotNull();
|
||||
assertThat(context).doesNotHaveBean(HasFeatures.class);
|
||||
});
|
||||
applicationContextRunner
|
||||
.withPropertyValues("spring.cloud.discovery.reactive.enabled=false",
|
||||
"management.endpoints.web.exposure.include=features")
|
||||
.run(context -> {
|
||||
assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class);
|
||||
assertThat(context).doesNotHaveBean(ReactiveDiscoveryCompositeHealthContributor.class);
|
||||
// features actuator is independent of discovery
|
||||
then(context.getBean(FeaturesEndpoint.class)).isNotNull();
|
||||
assertThat(context).doesNotHaveBean(HasFeatures.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void disableAllIndividually() {
|
||||
applicationContextRunner.withPropertyValues("spring.cloud.discovery.client.health-indicator.enabled=false",
|
||||
"spring.cloud.discovery.client.composite-indicator.enabled=false",
|
||||
"spring.cloud.features.enabled=false").run(context -> {
|
||||
assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class);
|
||||
assertThat(context).doesNotHaveBean(ReactiveDiscoveryCompositeHealthContributor.class);
|
||||
assertThat(context).doesNotHaveBean(FeaturesEndpoint.class);
|
||||
});
|
||||
applicationContextRunner
|
||||
.withPropertyValues("spring.cloud.discovery.client.health-indicator.enabled=false",
|
||||
"spring.cloud.discovery.client.composite-indicator.enabled=false",
|
||||
"spring.cloud.features.enabled=false")
|
||||
.run(context -> {
|
||||
assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class);
|
||||
assertThat(context).doesNotHaveBean(ReactiveDiscoveryCompositeHealthContributor.class);
|
||||
assertThat(context).doesNotHaveBean(FeaturesEndpoint.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void disableHealthIndicator() {
|
||||
applicationContextRunner.withPropertyValues("spring.cloud.discovery.client.health-indicator.enabled=false")
|
||||
.run(context -> {
|
||||
assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class);
|
||||
assertThat(context).doesNotHaveBean(ReactiveDiscoveryCompositeHealthContributor.class);
|
||||
});
|
||||
.run(context -> {
|
||||
assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class);
|
||||
assertThat(context).doesNotHaveBean(ReactiveDiscoveryCompositeHealthContributor.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void worksWithoutActuator() {
|
||||
applicationContextRunner.withClassLoader(new FilteredClassLoader("org.springframework.boot.actuate"))
|
||||
.run(context -> {
|
||||
assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class);
|
||||
assertThat(context).doesNotHaveBean(ReactiveDiscoveryCompositeHealthContributor.class);
|
||||
then(context.getBeansOfType(HasFeatures.class).values()).isEmpty();
|
||||
});
|
||||
.run(context -> {
|
||||
assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class);
|
||||
assertThat(context).doesNotHaveBean(ReactiveDiscoveryCompositeHealthContributor.class);
|
||||
then(context.getBeansOfType(HasFeatures.class).values()).isEmpty();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void worksWithoutWebflux() {
|
||||
applicationContextRunner.withClassLoader(new FilteredClassLoader("org.springframework.web.reactive"))
|
||||
.run(context -> {
|
||||
assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class);
|
||||
assertThat(context).doesNotHaveBean(ReactiveDiscoveryCompositeHealthContributor.class);
|
||||
assertThat(context).doesNotHaveBean(HasFeatures.class);
|
||||
});
|
||||
.run(context -> {
|
||||
assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class);
|
||||
assertThat(context).doesNotHaveBean(ReactiveDiscoveryCompositeHealthContributor.class);
|
||||
assertThat(context).doesNotHaveBean(HasFeatures.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void conditionalOnReactiveDiscoveryEnabledWorks() {
|
||||
ApplicationContextRunner contextRunner = new ApplicationContextRunner()
|
||||
.withUserConfiguration(ReactiveDiscoveryEnabledConfig.class);
|
||||
.withUserConfiguration(ReactiveDiscoveryEnabledConfig.class);
|
||||
contextRunner.withPropertyValues("spring.cloud.discovery.reactive.enabled=false")
|
||||
.run(context -> assertThat(context).doesNotHaveBean(TestBean.class));
|
||||
.run(context -> assertThat(context).doesNotHaveBean(TestBean.class));
|
||||
contextRunner.withPropertyValues("spring.cloud.discovery.reactive.enabled=true")
|
||||
.run(context -> assertThat(context.getBean(TestBean.class)).isNotNull());
|
||||
.run(context -> assertThat(context.getBean(TestBean.class)).isNotNull());
|
||||
}
|
||||
|
||||
@TestConfiguration
|
||||
|
||||
@@ -57,8 +57,8 @@ public class FeaturesEndpointTests {
|
||||
public void invokeWorks() {
|
||||
FeaturesEndpoint.Features features = this.context.getBean(FeaturesEndpoint.class).features();
|
||||
then(features).isNotNull();
|
||||
then(features.getEnabled()).hasSize(2).contains(newFeature("foo", Foo.class),
|
||||
newFeature("Baz Feature", Baz.class));
|
||||
then(features.getEnabled()).hasSize(2)
|
||||
.contains(newFeature("foo", Foo.class), newFeature("Baz Feature", Baz.class));
|
||||
then(features.getDisabled()).hasSize(1).contains("Bar");
|
||||
}
|
||||
|
||||
|
||||
@@ -47,10 +47,11 @@ class ObservedCircuitBreakerTests {
|
||||
String result = circuitBreaker.run(() -> "hello");
|
||||
|
||||
then(result).isEqualTo("hello");
|
||||
TestObservationRegistryAssert.assertThat(registry).hasSingleObservationThat()
|
||||
.hasNameEqualTo("spring.cloud.circuitbreaker")
|
||||
.hasLowCardinalityKeyValue("spring.cloud.circuitbreaker.type", "supplier")
|
||||
.hasContextualNameEqualTo("circuit-breaker");
|
||||
TestObservationRegistryAssert.assertThat(registry)
|
||||
.hasSingleObservationThat()
|
||||
.hasNameEqualTo("spring.cloud.circuitbreaker")
|
||||
.hasLowCardinalityKeyValue("spring.cloud.circuitbreaker.type", "supplier")
|
||||
.hasContextualNameEqualTo("circuit-breaker");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -78,8 +79,11 @@ class ObservedCircuitBreakerTests {
|
||||
String result = circuitBreaker.run(() -> "hello");
|
||||
|
||||
then(result).isEqualTo("hello");
|
||||
TestObservationRegistryAssert.assertThat(registry).hasSingleObservationThat().hasNameEqualTo("foo")
|
||||
.hasLowCardinalityKeyValue("bar", "baz").hasContextualNameEqualTo("circuit-breaker");
|
||||
TestObservationRegistryAssert.assertThat(registry)
|
||||
.hasSingleObservationThat()
|
||||
.hasNameEqualTo("foo")
|
||||
.hasLowCardinalityKeyValue("bar", "baz")
|
||||
.hasContextualNameEqualTo("circuit-breaker");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -105,18 +109,21 @@ class ObservedCircuitBreakerTests {
|
||||
|
||||
then(result).isEqualTo("goodbye");
|
||||
|
||||
TestObservationRegistryAssert.then(registry).hasNumberOfObservationsEqualTo(3)
|
||||
.hasHandledContextsThatSatisfy(contexts -> {
|
||||
ObservationContextAssert.then(contexts.get(0)).hasNameEqualTo("parent");
|
||||
ObservationContextAssert.then(contexts.get(1)).hasNameEqualTo("spring.cloud.circuitbreaker")
|
||||
.hasContextualNameEqualTo("circuit-breaker")
|
||||
.hasLowCardinalityKeyValue("spring.cloud.circuitbreaker.type", "supplier")
|
||||
.hasParentObservationEqualTo(parent);
|
||||
ObservationContextAssert.then(contexts.get(2)).hasNameEqualTo("spring.cloud.circuitbreaker")
|
||||
.hasContextualNameEqualTo("circuit-breaker fallback")
|
||||
.hasLowCardinalityKeyValue("spring.cloud.circuitbreaker.type", "function")
|
||||
.hasParentObservationEqualTo(parent);
|
||||
});
|
||||
TestObservationRegistryAssert.then(registry)
|
||||
.hasNumberOfObservationsEqualTo(3)
|
||||
.hasHandledContextsThatSatisfy(contexts -> {
|
||||
ObservationContextAssert.then(contexts.get(0)).hasNameEqualTo("parent");
|
||||
ObservationContextAssert.then(contexts.get(1))
|
||||
.hasNameEqualTo("spring.cloud.circuitbreaker")
|
||||
.hasContextualNameEqualTo("circuit-breaker")
|
||||
.hasLowCardinalityKeyValue("spring.cloud.circuitbreaker.type", "supplier")
|
||||
.hasParentObservationEqualTo(parent);
|
||||
ObservationContextAssert.then(contexts.get(2))
|
||||
.hasNameEqualTo("spring.cloud.circuitbreaker")
|
||||
.hasContextualNameEqualTo("circuit-breaker fallback")
|
||||
.hasLowCardinalityKeyValue("spring.cloud.circuitbreaker.type", "function")
|
||||
.hasParentObservationEqualTo(parent);
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -55,7 +55,8 @@ public class EnableDiscoveryClientImportSelectorTests {
|
||||
configureAnnotation(true);
|
||||
String[] imports = this.importSelector.selectImports(this.annotationMetadata);
|
||||
then(this.environment.getProperty("spring.cloud.service-registry.auto-registration.enabled", Boolean.class,
|
||||
true)).isTrue();
|
||||
true))
|
||||
.isTrue();
|
||||
then(imports).hasSize(1);
|
||||
}
|
||||
|
||||
@@ -64,7 +65,7 @@ public class EnableDiscoveryClientImportSelectorTests {
|
||||
configureAnnotation(false);
|
||||
String[] imports = this.importSelector.selectImports(this.annotationMetadata);
|
||||
then(this.environment.getProperty("spring.cloud.service-registry.auto-registration.enabled", Boolean.class))
|
||||
.isFalse();
|
||||
.isFalse();
|
||||
then(imports).isEmpty();
|
||||
}
|
||||
|
||||
@@ -72,7 +73,7 @@ public class EnableDiscoveryClientImportSelectorTests {
|
||||
String annotationName = EnableDiscoveryClient.class.getName();
|
||||
given(this.annotationMetadata.isAnnotated(annotationName)).willReturn(true);
|
||||
given(this.annotationMetadata.getAnnotationAttributes(annotationName, true))
|
||||
.willReturn(this.annotationAttributes);
|
||||
.willReturn(this.annotationAttributes);
|
||||
given(this.annotationAttributes.getBoolean("autoRegister")).willReturn(autoRegistration);
|
||||
}
|
||||
|
||||
|
||||
@@ -38,7 +38,8 @@ public class EnableDiscoveryClientMissingImplTests {
|
||||
@Test
|
||||
public void testContextFails() {
|
||||
try (ConfigurableApplicationContext context = new SpringApplicationBuilder().sources(App.class)
|
||||
.web(WebApplicationType.NONE).run()) {
|
||||
.web(WebApplicationType.NONE)
|
||||
.run()) {
|
||||
// do sth
|
||||
}
|
||||
catch (NestedRuntimeException e) {
|
||||
|
||||
@@ -33,7 +33,8 @@ public class ManagementServerPortUtilsTests {
|
||||
@Test
|
||||
public void contextStarts() {
|
||||
try (ConfigurableApplicationContext context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
|
||||
.sources(TestApp.class).run()) {
|
||||
.sources(TestApp.class)
|
||||
.run()) {
|
||||
|
||||
then(ManagementServerPortUtils.hasActuator).isFalse();
|
||||
}
|
||||
|
||||
@@ -49,14 +49,14 @@ public class CompositeDiscoveryClientAutoConfigurationTests {
|
||||
CompositeDiscoveryClient compositeDiscoveryClient = (CompositeDiscoveryClient) this.discoveryClient;
|
||||
then(compositeDiscoveryClient.getDiscoveryClients()).hasSize(2);
|
||||
then(compositeDiscoveryClient.getDiscoveryClients().get(0).description())
|
||||
.isEqualTo("A custom discovery client");
|
||||
.isEqualTo("A custom discovery client");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void simpleDiscoveryClientShouldBeHaveTheLowestPrecedence() {
|
||||
CompositeDiscoveryClient compositeDiscoveryClient = (CompositeDiscoveryClient) this.discoveryClient;
|
||||
then(compositeDiscoveryClient.getDiscoveryClients().get(0).description())
|
||||
.isEqualTo("A custom discovery client");
|
||||
.isEqualTo("A custom discovery client");
|
||||
then(compositeDiscoveryClient.getDiscoveryClients().get(1)).isInstanceOf(SimpleDiscoveryClient.class);
|
||||
}
|
||||
|
||||
|
||||
@@ -48,7 +48,7 @@ public class CompositeDiscoveryClientOrderTest {
|
||||
public void shouldGetOrderedDiscoveryClients() {
|
||||
// when:
|
||||
List<DiscoveryClient> discoveryClients = ((CompositeDiscoveryClient) this.discoveryClient)
|
||||
.getDiscoveryClients();
|
||||
.getDiscoveryClients();
|
||||
|
||||
// then:
|
||||
then(discoveryClients.get(0).description()).isEqualTo(CUSTOM_DISCOVERY_CLIENT);
|
||||
|
||||
@@ -34,7 +34,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
class ReactiveCompositeDiscoveryClientAutoConfigurationTests {
|
||||
|
||||
private ApplicationContextRunner contextRunner = new ApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(ReactiveCompositeDiscoveryClientAutoConfiguration.class));
|
||||
.withConfiguration(AutoConfigurations.of(ReactiveCompositeDiscoveryClientAutoConfiguration.class));
|
||||
|
||||
@Test
|
||||
public void shouldCreateCompositeReactiveDiscoveryClientWithoutDelegates() {
|
||||
|
||||
@@ -75,8 +75,12 @@ class ReactiveCompositeDiscoveryClientTests {
|
||||
|
||||
Flux<String> services = client.getServices();
|
||||
|
||||
StepVerifier.create(services).expectNext("serviceAFromClient1").expectNext("serviceBFromClient1")
|
||||
.expectNext("serviceCFromClient2").expectComplete().verify();
|
||||
StepVerifier.create(services)
|
||||
.expectNext("serviceAFromClient1")
|
||||
.expectNext("serviceBFromClient1")
|
||||
.expectNext("serviceCFromClient2")
|
||||
.expectComplete()
|
||||
.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -110,8 +114,11 @@ class ReactiveCompositeDiscoveryClientTests {
|
||||
|
||||
Flux<ServiceInstance> instances = client.getInstances("service");
|
||||
|
||||
StepVerifier.create(instances).expectNext(serviceInstance1).expectNext(serviceInstance2).expectComplete()
|
||||
.verify();
|
||||
StepVerifier.create(instances)
|
||||
.expectNext(serviceInstance1)
|
||||
.expectNext(serviceInstance2)
|
||||
.expectComplete()
|
||||
.verify();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@ class DiscoveryClientHealthIndicatorUnitTests {
|
||||
@Test
|
||||
public void shouldReturnUnknownStatusWhenNotInitialized() {
|
||||
Health expectedHealth = Health.status(new Status(Status.UNKNOWN.getCode(), "Discovery Client not initialized"))
|
||||
.build();
|
||||
.build();
|
||||
Health health = indicator.health();
|
||||
assertThat(health).isEqualTo(expectedHealth);
|
||||
}
|
||||
@@ -99,8 +99,9 @@ class DiscoveryClientHealthIndicatorUnitTests {
|
||||
public void shouldReturnUpStatusWhenUsingServicesQueryAndNoServicesReturned() {
|
||||
when(properties.isUseServicesQuery()).thenReturn(true);
|
||||
when(discoveryClient.getServices()).thenReturn(Collections.emptyList());
|
||||
Health expectedHealth = Health.status(new Status(Status.UP.getCode(), "")).withDetail("services", emptyList())
|
||||
.build();
|
||||
Health expectedHealth = Health.status(new Status(Status.UP.getCode(), ""))
|
||||
.withDetail("services", emptyList())
|
||||
.build();
|
||||
|
||||
indicator.onApplicationEvent(new InstanceRegisteredEvent<>(this, null));
|
||||
Health health = indicator.health();
|
||||
@@ -115,7 +116,8 @@ class DiscoveryClientHealthIndicatorUnitTests {
|
||||
when(discoveryClient.description()).thenReturn("Mocked Service Discovery Client");
|
||||
when(discoveryClient.getServices()).thenReturn(singletonList("service"));
|
||||
Health expectedHealth = Health.status(new Status(Status.UP.getCode(), "Mocked Service Discovery Client"))
|
||||
.withDetail("services", singletonList("service")).build();
|
||||
.withDetail("services", singletonList("service"))
|
||||
.build();
|
||||
|
||||
indicator.onApplicationEvent(new InstanceRegisteredEvent<>(this, null));
|
||||
Health health = indicator.health();
|
||||
|
||||
@@ -40,7 +40,7 @@ public class DiscoveryCompositeHealthContributorTests {
|
||||
@Test
|
||||
public void createWhenIndicatorsAreNullThrowsException() {
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> new DiscoveryCompositeHealthContributor(null))
|
||||
.withMessage("'indicators' must not be null");
|
||||
.withMessage("'indicators' must not be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -72,7 +72,7 @@ class ReactiveDiscoveryClientHealthIndicatorTests {
|
||||
@Test
|
||||
public void shouldReturnUnknownStatusWhenNotInitialized() {
|
||||
Health expectedHealth = Health.status(new Status(Status.UNKNOWN.getCode(), "Discovery Client not initialized"))
|
||||
.build();
|
||||
.build();
|
||||
Mono<Health> health = indicator.health();
|
||||
StepVerifier.create(health).expectNext(expectedHealth).expectComplete().verify();
|
||||
}
|
||||
@@ -108,8 +108,9 @@ class ReactiveDiscoveryClientHealthIndicatorTests {
|
||||
public void shouldReturnUpStatusWhenUsingServicesQueryAndNoServicesReturned() {
|
||||
when(properties.isUseServicesQuery()).thenReturn(true);
|
||||
when(discoveryClient.getServices()).thenReturn(Flux.empty());
|
||||
Health expectedHealth = Health.status(new Status(Status.UP.getCode(), "")).withDetail("services", emptyList())
|
||||
.build();
|
||||
Health expectedHealth = Health.status(new Status(Status.UP.getCode(), ""))
|
||||
.withDetail("services", emptyList())
|
||||
.build();
|
||||
|
||||
indicator.onApplicationEvent(new InstanceRegisteredEvent<>(this, null));
|
||||
Mono<Health> health = indicator.health();
|
||||
@@ -124,7 +125,8 @@ class ReactiveDiscoveryClientHealthIndicatorTests {
|
||||
when(discoveryClient.getServices()).thenReturn(Flux.just("service"));
|
||||
when(discoveryClient.description()).thenReturn("Mocked Service Discovery Client");
|
||||
Health expectedHealth = Health.status(new Status(Status.UP.getCode(), "Mocked Service Discovery Client"))
|
||||
.withDetail("services", singletonList("service")).build();
|
||||
.withDetail("services", singletonList("service"))
|
||||
.build();
|
||||
|
||||
indicator.onApplicationEvent(new InstanceRegisteredEvent<>(this, null));
|
||||
Mono<Health> health = indicator.health();
|
||||
|
||||
@@ -56,22 +56,21 @@ class SimpleReactiveDiscoveryClientAutoConfigurationTests {
|
||||
@Test
|
||||
public void shouldUseCustomConfiguration() {
|
||||
this.contextRunner.withUserConfiguration(Configuration.class)
|
||||
.withPropertyValues("spring.application.name=my-service",
|
||||
"spring.cloud.discovery.client.simple.order=1", "server.port=8443")
|
||||
.run((context) -> {
|
||||
ReactiveDiscoveryClient client = context.getBean(ReactiveDiscoveryClient.class);
|
||||
assertThat(client).isNotNull();
|
||||
assertThat(client.getOrder()).isEqualTo(1);
|
||||
InetUtils inet = context.getBean(InetUtils.class);
|
||||
assertThat(inet).isNotNull();
|
||||
SimpleReactiveDiscoveryProperties properties = context
|
||||
.getBean(SimpleReactiveDiscoveryProperties.class);
|
||||
assertThat(properties).isNotNull();
|
||||
assertThat(properties.getLocal().getServiceId()).isEqualTo("my-service");
|
||||
assertThat(properties.getLocal().getHost())
|
||||
.isEqualTo(inet.findFirstNonLoopbackHostInfo().getHostname());
|
||||
assertThat(properties.getLocal().getPort()).isEqualTo(8443);
|
||||
});
|
||||
.withPropertyValues("spring.application.name=my-service", "spring.cloud.discovery.client.simple.order=1",
|
||||
"server.port=8443")
|
||||
.run((context) -> {
|
||||
ReactiveDiscoveryClient client = context.getBean(ReactiveDiscoveryClient.class);
|
||||
assertThat(client).isNotNull();
|
||||
assertThat(client.getOrder()).isEqualTo(1);
|
||||
InetUtils inet = context.getBean(InetUtils.class);
|
||||
assertThat(inet).isNotNull();
|
||||
SimpleReactiveDiscoveryProperties properties = context.getBean(SimpleReactiveDiscoveryProperties.class);
|
||||
assertThat(properties).isNotNull();
|
||||
assertThat(properties.getLocal().getServiceId()).isEqualTo("my-service");
|
||||
assertThat(properties.getLocal().getHost())
|
||||
.isEqualTo(inet.findFirstNonLoopbackHostInfo().getHostname());
|
||||
assertThat(properties.getLocal().getPort()).isEqualTo(8443);
|
||||
});
|
||||
}
|
||||
|
||||
@TestConfiguration
|
||||
|
||||
@@ -46,7 +46,7 @@ public class SimpleReactiveDiscoveryClientTests {
|
||||
public void setUp() {
|
||||
SimpleReactiveDiscoveryProperties simpleReactiveDiscoveryProperties = new SimpleReactiveDiscoveryProperties();
|
||||
simpleReactiveDiscoveryProperties
|
||||
.setInstances(singletonMap("service", Arrays.asList(service1Inst1, service1Inst2)));
|
||||
.setInstances(singletonMap("service", Arrays.asList(service1Inst1, service1Inst2)));
|
||||
simpleReactiveDiscoveryProperties.afterPropertiesSet();
|
||||
this.client = new SimpleReactiveDiscoveryClient(simpleReactiveDiscoveryProperties);
|
||||
}
|
||||
|
||||
@@ -77,7 +77,7 @@ public class DiscoveredResourceUnitTests {
|
||||
Link link = Link.of("target", "rel");
|
||||
|
||||
when(this.provider.getServiceInstance())
|
||||
.thenReturn(new DefaultServiceInstance("instance", "service", "localhost", 8080, false));
|
||||
.thenReturn(new DefaultServiceInstance("instance", "service", "localhost", 8080, false));
|
||||
when(this.builder.asTemplatedLink()).thenReturn(link);
|
||||
|
||||
this.resource.verifyOrDiscover();
|
||||
|
||||
@@ -48,7 +48,7 @@ import static org.springframework.cloud.client.loadbalancer.reactive.ReactiveLoa
|
||||
public abstract class AbstractLoadBalancerAutoConfigurationTests {
|
||||
|
||||
protected ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(LoadBalancerAutoConfiguration.class));
|
||||
.withConfiguration(AutoConfigurations.of(LoadBalancerAutoConfiguration.class));
|
||||
|
||||
@Test
|
||||
void restTemplateGetsLoadBalancerInterceptor() {
|
||||
@@ -87,7 +87,7 @@ public abstract class AbstractLoadBalancerAutoConfigurationTests {
|
||||
then(templates).hasSize(2);
|
||||
|
||||
TwoRestTemplatesAndTwoRestClientBuilders.Two two = context
|
||||
.getBean(TwoRestTemplatesAndTwoRestClientBuilders.Two.class);
|
||||
.getBean(TwoRestTemplatesAndTwoRestClientBuilders.Two.class);
|
||||
|
||||
then(two.loadBalanced).isNotNull();
|
||||
assertLoadBalanced(two.loadBalanced);
|
||||
@@ -106,52 +106,52 @@ public abstract class AbstractLoadBalancerAutoConfigurationTests {
|
||||
assertThat(restClientBuilders.values()).hasSize(2);
|
||||
|
||||
TwoRestTemplatesAndTwoRestClientBuilders.Two two = context
|
||||
.getBean(TwoRestTemplatesAndTwoRestClientBuilders.Two.class);
|
||||
.getBean(TwoRestTemplatesAndTwoRestClientBuilders.Two.class);
|
||||
|
||||
assertThat(two.loadBalancedRestClientBuilder).isNotNull();
|
||||
assertLoadBalanced(two.loadBalancedRestClientBuilder);
|
||||
|
||||
assertThat(two.nonLoadBalancedRestClientBuilder).isNotNull();
|
||||
two.nonLoadBalancedRestClientBuilder
|
||||
.requestInterceptors(interceptors -> assertThat(interceptors).isEmpty());
|
||||
.requestInterceptors(interceptors -> assertThat(interceptors).isEmpty());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void restTemplatesAndRestClientsFromUsersAutoConfiguration() {
|
||||
applicationContextRunner
|
||||
.withConfiguration(AutoConfigurations.of(TwoRestTemplatesAndTwoRestClientBuilders.class))
|
||||
.run(context -> {
|
||||
final Map<String, RestClient.Builder> restClientBuilders = context
|
||||
.getBeansOfType(RestClient.Builder.class);
|
||||
final Map<String, RestTemplate> restTemplates = context.getBeansOfType(RestTemplate.class);
|
||||
.withConfiguration(AutoConfigurations.of(TwoRestTemplatesAndTwoRestClientBuilders.class))
|
||||
.run(context -> {
|
||||
final Map<String, RestClient.Builder> restClientBuilders = context
|
||||
.getBeansOfType(RestClient.Builder.class);
|
||||
final Map<String, RestTemplate> restTemplates = context.getBeansOfType(RestTemplate.class);
|
||||
|
||||
assertThat(restClientBuilders).isNotNull();
|
||||
assertThat(restClientBuilders.values()).hasSize(2);
|
||||
assertThat(restClientBuilders).isNotNull();
|
||||
assertThat(restClientBuilders.values()).hasSize(2);
|
||||
|
||||
TwoRestTemplatesAndTwoRestClientBuilders.Two two = context
|
||||
.getBean(TwoRestTemplatesAndTwoRestClientBuilders.Two.class);
|
||||
TwoRestTemplatesAndTwoRestClientBuilders.Two two = context
|
||||
.getBean(TwoRestTemplatesAndTwoRestClientBuilders.Two.class);
|
||||
|
||||
assertThat(two.loadBalancedRestClientBuilder).isNotNull();
|
||||
assertLoadBalanced(two.loadBalancedRestClientBuilder);
|
||||
assertThat(two.loadBalancedRestClientBuilder).isNotNull();
|
||||
assertLoadBalanced(two.loadBalancedRestClientBuilder);
|
||||
|
||||
assertThat(two.nonLoadBalancedRestClientBuilder).isNotNull();
|
||||
two.nonLoadBalancedRestClientBuilder
|
||||
.requestInterceptors(interceptors -> assertThat(interceptors).isEmpty());
|
||||
assertThat(two.nonLoadBalancedRestClientBuilder).isNotNull();
|
||||
two.nonLoadBalancedRestClientBuilder
|
||||
.requestInterceptors(interceptors -> assertThat(interceptors).isEmpty());
|
||||
|
||||
assertThat(restTemplates).isNotNull();
|
||||
Collection<RestTemplate> templates = restTemplates.values();
|
||||
assertThat(templates).hasSize(2);
|
||||
assertThat(restTemplates).isNotNull();
|
||||
Collection<RestTemplate> templates = restTemplates.values();
|
||||
assertThat(templates).hasSize(2);
|
||||
|
||||
TwoRestTemplatesAndTwoRestClientBuilders.Two twoRestTemplate = context
|
||||
.getBean(TwoRestTemplatesAndTwoRestClientBuilders.Two.class);
|
||||
TwoRestTemplatesAndTwoRestClientBuilders.Two twoRestTemplate = context
|
||||
.getBean(TwoRestTemplatesAndTwoRestClientBuilders.Two.class);
|
||||
|
||||
assertThat(twoRestTemplate.loadBalanced).isNotNull();
|
||||
assertLoadBalanced(twoRestTemplate.loadBalanced);
|
||||
assertThat(twoRestTemplate.loadBalanced).isNotNull();
|
||||
assertLoadBalanced(twoRestTemplate.loadBalanced);
|
||||
|
||||
assertThat(twoRestTemplate.nonLoadBalanced).isNotNull();
|
||||
assertThat(twoRestTemplate.nonLoadBalanced.getInterceptors()).isEmpty();
|
||||
});
|
||||
assertThat(twoRestTemplate.nonLoadBalanced).isNotNull();
|
||||
assertThat(twoRestTemplate.nonLoadBalanced.getInterceptors()).isEmpty();
|
||||
});
|
||||
}
|
||||
|
||||
protected abstract void assertLoadBalanced(RestClient.Builder restClientBuilder);
|
||||
|
||||
@@ -152,7 +152,7 @@ public class InterceptorRetryPolicyTest {
|
||||
then(interceptorRetryPolicy.equals(new Object())).isFalse();
|
||||
then(interceptorRetryPolicy.equals(interceptorRetryPolicy)).isTrue();
|
||||
then(interceptorRetryPolicy
|
||||
.equals(new InterceptorRetryPolicy(request, policy, serviceInstanceChooser, serviceName))).isTrue();
|
||||
.equals(new InterceptorRetryPolicy(request, policy, serviceInstanceChooser, serviceName))).isTrue();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ public class LoadBalancedRestClientIntegrationTests {
|
||||
void shouldBuildLoadBalancedRestClientInConstructor() {
|
||||
// Interceptors are not visible in RestClient
|
||||
assertThatThrownBy(() -> client.get().uri("http://test-service").retrieve())
|
||||
.hasMessage("LoadBalancerInterceptor invoked.");
|
||||
.hasMessage("LoadBalancerInterceptor invoked.");
|
||||
}
|
||||
|
||||
@SpringBootConfiguration
|
||||
|
||||
@@ -48,7 +48,7 @@ public class LoadBalancerAutoConfigurationTests extends AbstractLoadBalancerAuto
|
||||
assertThat(interceptors.get(0)).isInstanceOf(DeferringLoadBalancerInterceptor.class);
|
||||
DeferringLoadBalancerInterceptor interceptor = (DeferringLoadBalancerInterceptor) interceptors.get(0);
|
||||
assertThat(interceptor.getLoadBalancerInterceptorProvider().getObject())
|
||||
.isInstanceOf(LoadBalancerInterceptor.class);
|
||||
.isInstanceOf(LoadBalancerInterceptor.class);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -73,8 +73,9 @@ public class LoadBalancerRequestFactoryConfigurationTests {
|
||||
|
||||
protected ConfigurableApplicationContext init(Class<?> config) {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
|
||||
.properties("spring.aop.proxyTargetClass=true").sources(config, LoadBalancerAutoConfiguration.class)
|
||||
.run();
|
||||
.properties("spring.aop.proxyTargetClass=true")
|
||||
.sources(config, LoadBalancerAutoConfiguration.class)
|
||||
.run();
|
||||
|
||||
LoadBalancerRequestFactory lbReqFactory = context.getBean(LoadBalancerRequestFactory.class);
|
||||
this.lbRequest = lbReqFactory.createRequest(this.request, this.body, this.execution);
|
||||
@@ -88,14 +89,14 @@ public class LoadBalancerRequestFactoryConfigurationTests {
|
||||
LoadBalancerRequestTransformer transformer = context.getBean("transformer",
|
||||
LoadBalancerRequestTransformer.class);
|
||||
when(transformer.transformRequest(any(ServiceRequestWrapper.class), eq(this.instance)))
|
||||
.thenReturn(this.transformedRequest);
|
||||
.thenReturn(this.transformedRequest);
|
||||
|
||||
this.lbRequest.apply(this.instance);
|
||||
|
||||
verify(this.execution).execute(this.httpRequestCaptor.capture(), eq(this.body));
|
||||
then(this.httpRequestCaptor.getValue())
|
||||
.as("transformer should have transformed the ServiceRequestWrapper into transformedRequest")
|
||||
.isEqualTo(this.transformedRequest);
|
||||
.as("transformer should have transformed the ServiceRequestWrapper into transformedRequest")
|
||||
.isEqualTo(this.transformedRequest);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -106,7 +107,7 @@ public class LoadBalancerRequestFactoryConfigurationTests {
|
||||
|
||||
verify(this.execution).execute(this.httpRequestCaptor.capture(), eq(this.body));
|
||||
then(this.httpRequestCaptor.getValue().getClass()).as("ServiceRequestWrapper should be executed")
|
||||
.isEqualTo(ServiceRequestWrapper.class);
|
||||
.isEqualTo(ServiceRequestWrapper.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -116,17 +117,17 @@ public class LoadBalancerRequestFactoryConfigurationTests {
|
||||
LoadBalancerRequestTransformer transformer = context.getBean("transformer",
|
||||
LoadBalancerRequestTransformer.class);
|
||||
when(transformer.transformRequest(any(ServiceRequestWrapper.class), eq(this.instance)))
|
||||
.thenReturn(this.transformedRequest);
|
||||
.thenReturn(this.transformedRequest);
|
||||
LoadBalancerRequestTransformer transformer2 = context.getBean("transformer2",
|
||||
LoadBalancerRequestTransformer.class);
|
||||
when(transformer2.transformRequest(this.transformedRequest, this.instance))
|
||||
.thenReturn(this.transformedRequest2);
|
||||
.thenReturn(this.transformedRequest2);
|
||||
|
||||
this.lbRequest.apply(this.instance);
|
||||
|
||||
verify(this.execution).execute(this.httpRequestCaptor.capture(), eq(this.body));
|
||||
then(this.httpRequestCaptor.getValue()).as("transformer2 should run after transformer")
|
||||
.isEqualTo(this.transformedRequest2);
|
||||
.isEqualTo(this.transformedRequest2);
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
|
||||
@@ -80,7 +80,7 @@ public class LoadBalancerRequestFactoryTests {
|
||||
|
||||
verify(this.execution).execute(this.httpRequestCaptor.capture(), eq(this.body));
|
||||
then(this.httpRequestCaptor.getValue().getClass()).as("request should be of type ServiceRequestWrapper")
|
||||
.isEqualTo(ServiceRequestWrapper.class);
|
||||
.isEqualTo(ServiceRequestWrapper.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -91,37 +91,37 @@ public class LoadBalancerRequestFactoryTests {
|
||||
|
||||
verify(this.execution).execute(this.httpRequestCaptor.capture(), eq(this.body));
|
||||
then(this.httpRequestCaptor.getValue().getClass()).as("request should be of type ServiceRequestWrapper")
|
||||
.isEqualTo(ServiceRequestWrapper.class);
|
||||
.isEqualTo(ServiceRequestWrapper.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOneTransformer() throws Exception {
|
||||
List<LoadBalancerRequestTransformer> transformers = List.of(this.transformer1);
|
||||
when(this.transformer1.transformRequest(any(ServiceRequestWrapper.class), eq(this.instance)))
|
||||
.thenReturn(this.transformedRequest1);
|
||||
.thenReturn(this.transformedRequest1);
|
||||
|
||||
executeLbRequest(transformers);
|
||||
|
||||
verify(this.execution).execute(this.httpRequestCaptor.capture(), eq(this.body));
|
||||
then(this.httpRequestCaptor.getValue())
|
||||
.as("transformer1 should have transformed request into transformedRequest1")
|
||||
.isEqualTo(this.transformedRequest1);
|
||||
.as("transformer1 should have transformed request into transformedRequest1")
|
||||
.isEqualTo(this.transformedRequest1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTwoTransformers() throws Exception {
|
||||
List<LoadBalancerRequestTransformer> transformers = Arrays.asList(this.transformer1, this.transformer2);
|
||||
when(this.transformer1.transformRequest(any(ServiceRequestWrapper.class), eq(this.instance)))
|
||||
.thenReturn(this.transformedRequest1);
|
||||
.thenReturn(this.transformedRequest1);
|
||||
when(this.transformer2.transformRequest(this.transformedRequest1, this.instance))
|
||||
.thenReturn(this.transformedRequest2);
|
||||
.thenReturn(this.transformedRequest2);
|
||||
|
||||
executeLbRequest(transformers);
|
||||
|
||||
verify(this.execution).execute(this.httpRequestCaptor.capture(), eq(this.body));
|
||||
then(this.httpRequestCaptor.getValue())
|
||||
.as("transformer2 should have transformed transformedRequest1 into transformedRequest2")
|
||||
.isEqualTo(this.transformedRequest2);
|
||||
.as("transformer2 should have transformed transformedRequest1 into transformedRequest2")
|
||||
.isEqualTo(this.transformedRequest2);
|
||||
}
|
||||
|
||||
private void executeLbRequest(List<LoadBalancerRequestTransformer> transformers) throws Exception {
|
||||
|
||||
@@ -147,8 +147,9 @@ class LoadBalancerUriToolsTests {
|
||||
void originalUserInfoSet() {
|
||||
TestServiceInstance serviceInstance = new TestServiceInstance();
|
||||
URI original = UriComponentsBuilder
|
||||
.fromUriString("http://testUser@testHost.example/path?query1=test1&query2=test2#fragment").build()
|
||||
.toUri();
|
||||
.fromUriString("http://testUser@testHost.example/path?query1=test1&query2=test2#fragment")
|
||||
.build()
|
||||
.toUri();
|
||||
|
||||
URI reconstructed = LoadBalancerUriTools.reconstructURI(serviceInstance, original);
|
||||
|
||||
@@ -166,7 +167,9 @@ class LoadBalancerUriToolsTests {
|
||||
void reconstructedURIEncodedCorrectly() {
|
||||
TestServiceInstance serviceInstance = new TestServiceInstance();
|
||||
URI original = UriComponentsBuilder
|
||||
.fromUriString("http://test.example/path%40%21%242?query=val%40%21%242#frag%40%21%242").build().toUri();
|
||||
.fromUriString("http://test.example/path%40%21%242?query=val%40%21%242#frag%40%21%242")
|
||||
.build()
|
||||
.toUri();
|
||||
|
||||
URI reconstructed = LoadBalancerUriTools.reconstructURI(serviceInstance, original);
|
||||
|
||||
|
||||
@@ -53,32 +53,31 @@ public class RetryLoadBalancerAutoConfigurationTests extends AbstractLoadBalance
|
||||
@Test
|
||||
void testRetryDisabled() {
|
||||
applicationContextRunner.withUserConfiguration(OneRestTemplate.class)
|
||||
.withPropertyValues("spring.aop.proxyTargetClass=true", "spring.cloud.loadbalancer.retry.enabled=false")
|
||||
.run(context -> {
|
||||
List<ClientHttpRequestInterceptor> interceptors = context.getBean(RestTemplate.class)
|
||||
.getInterceptors();
|
||||
then(interceptors).hasSize(1);
|
||||
ClientHttpRequestInterceptor interceptor = interceptors.get(0);
|
||||
then(interceptor).isInstanceOf(LoadBalancerInterceptor.class);
|
||||
});
|
||||
.withPropertyValues("spring.aop.proxyTargetClass=true", "spring.cloud.loadbalancer.retry.enabled=false")
|
||||
.run(context -> {
|
||||
List<ClientHttpRequestInterceptor> interceptors = context.getBean(RestTemplate.class).getInterceptors();
|
||||
then(interceptors).hasSize(1);
|
||||
ClientHttpRequestInterceptor interceptor = interceptors.get(0);
|
||||
then(interceptor).isInstanceOf(LoadBalancerInterceptor.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRetryDisabledWithRestClientBuilder() {
|
||||
applicationContextRunner.withUserConfiguration(OneRestClientBuilder.class)
|
||||
.withPropertyValues("spring.aop.proxyTargetClass=true", "spring.cloud.loadbalancer.retry.enabled=false")
|
||||
.run(context -> {
|
||||
RestClient.Builder restClientBuilder = context.getBean(RestClient.Builder.class);
|
||||
.withPropertyValues("spring.aop.proxyTargetClass=true", "spring.cloud.loadbalancer.retry.enabled=false")
|
||||
.run(context -> {
|
||||
RestClient.Builder restClientBuilder = context.getBean(RestClient.Builder.class);
|
||||
|
||||
restClientBuilder.requestInterceptors(interceptors -> {
|
||||
assertThat(interceptors).hasSize(1);
|
||||
assertThat(interceptors.get(0)).isInstanceOf(DeferringLoadBalancerInterceptor.class);
|
||||
DeferringLoadBalancerInterceptor interceptor = (DeferringLoadBalancerInterceptor) interceptors
|
||||
.get(0);
|
||||
assertThat(interceptor.getLoadBalancerInterceptorProvider().getObject())
|
||||
.isInstanceOf(LoadBalancerInterceptor.class);
|
||||
});
|
||||
restClientBuilder.requestInterceptors(interceptors -> {
|
||||
assertThat(interceptors).hasSize(1);
|
||||
assertThat(interceptors.get(0)).isInstanceOf(DeferringLoadBalancerInterceptor.class);
|
||||
DeferringLoadBalancerInterceptor interceptor = (DeferringLoadBalancerInterceptor) interceptors
|
||||
.get(0);
|
||||
assertThat(interceptor.getLoadBalancerInterceptorProvider().getObject())
|
||||
.isInstanceOf(LoadBalancerInterceptor.class);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -108,7 +108,7 @@ public class RetryLoadBalancerInterceptorTests {
|
||||
ServiceInstance serviceInstance = mock(ServiceInstance.class);
|
||||
when(client.choose(eq("foo"), any())).thenReturn(serviceInstance);
|
||||
when(client.execute(eq("foo"), eq(serviceInstance), any(LoadBalancerRequest.class)))
|
||||
.thenThrow(new IOException());
|
||||
.thenThrow(new IOException());
|
||||
properties.getRetry().setEnabled(false);
|
||||
RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, lbRequestFactory,
|
||||
loadBalancedRetryFactory, lbFactory);
|
||||
@@ -141,7 +141,7 @@ public class RetryLoadBalancerInterceptorTests {
|
||||
ServiceInstance serviceInstance = mock(ServiceInstance.class);
|
||||
when(client.choose(eq("foo"), any())).thenReturn(serviceInstance);
|
||||
when(client.execute(eq("foo"), eq(serviceInstance), any(LoadBalancerRequest.class)))
|
||||
.thenReturn(clientHttpResponse);
|
||||
.thenReturn(clientHttpResponse);
|
||||
when(lbRequestFactory.createRequest(any(), any(), any())).thenReturn(mock(LoadBalancerRequest.class));
|
||||
properties.getRetry().setEnabled(true);
|
||||
RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, lbRequestFactory,
|
||||
@@ -162,7 +162,7 @@ public class RetryLoadBalancerInterceptorTests {
|
||||
ServiceInstance serviceInstance = mock(ServiceInstance.class);
|
||||
when(client.choose(eq("foo"), any())).thenReturn(serviceInstance);
|
||||
when(client.execute(eq("foo"), eq(serviceInstance), any(LoadBalancerRequest.class)))
|
||||
.thenReturn(clientHttpResponse);
|
||||
.thenReturn(clientHttpResponse);
|
||||
when(lbRequestFactory.createRequest(any(), any(), any())).thenReturn(mock(LoadBalancerRequest.class));
|
||||
properties.getRetry().setEnabled(true);
|
||||
RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, lbRequestFactory,
|
||||
@@ -189,7 +189,8 @@ public class RetryLoadBalancerInterceptorTests {
|
||||
ServiceInstance serviceInstance = mock(ServiceInstance.class);
|
||||
when(client.choose(eq("foo"), any())).thenReturn(serviceInstance);
|
||||
when(client.execute(eq("foo"), eq(serviceInstance), nullable(LoadBalancerRequest.class)))
|
||||
.thenReturn(clientHttpResponseNotFound).thenReturn(clientHttpResponseOk);
|
||||
.thenReturn(clientHttpResponseNotFound)
|
||||
.thenReturn(clientHttpResponseOk);
|
||||
properties.getRetry().setEnabled(true);
|
||||
RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, lbRequestFactory,
|
||||
new MyLoadBalancedRetryFactory(policy), lbFactory);
|
||||
@@ -220,7 +221,7 @@ public class RetryLoadBalancerInterceptorTests {
|
||||
when(client.choose(eq("foo"), any())).thenReturn(serviceInstance);
|
||||
when(client.execute(eq("foo"), eq(serviceInstance),
|
||||
ArgumentMatchers.<LoadBalancerRequest<ClientHttpResponse>>any()))
|
||||
.thenReturn(clientHttpResponseNotFound);
|
||||
.thenReturn(clientHttpResponseNotFound);
|
||||
|
||||
properties.getRetry().setEnabled(true);
|
||||
byte[] body = new byte[] {};
|
||||
@@ -253,7 +254,8 @@ public class RetryLoadBalancerInterceptorTests {
|
||||
ServiceInstance serviceInstance = mock(ServiceInstance.class);
|
||||
when(client.choose(eq("foo"), any())).thenReturn(serviceInstance);
|
||||
when(client.execute(eq("foo"), eq(serviceInstance), any(LoadBalancerRequest.class)))
|
||||
.thenThrow(new IOException()).thenReturn(clientHttpResponse);
|
||||
.thenThrow(new IOException())
|
||||
.thenReturn(clientHttpResponse);
|
||||
when(lbRequestFactory.createRequest(any(), any(), any())).thenReturn(mock(LoadBalancerRequest.class));
|
||||
properties.getRetry().setEnabled(true);
|
||||
RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, lbRequestFactory,
|
||||
@@ -278,7 +280,8 @@ public class RetryLoadBalancerInterceptorTests {
|
||||
ServiceInstance serviceInstance = mock(ServiceInstance.class);
|
||||
when(client.choose(eq("foo"), any())).thenReturn(serviceInstance);
|
||||
when(client.execute(eq("foo"), eq(serviceInstance), any(LoadBalancerRequest.class)))
|
||||
.thenThrow(new IOException()).thenReturn(clientHttpResponse);
|
||||
.thenThrow(new IOException())
|
||||
.thenReturn(clientHttpResponse);
|
||||
when(lbRequestFactory.createRequest(any(), any(), any())).thenReturn(mock(LoadBalancerRequest.class));
|
||||
properties.getRetry().setEnabled(true);
|
||||
RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, lbRequestFactory,
|
||||
@@ -305,7 +308,8 @@ public class RetryLoadBalancerInterceptorTests {
|
||||
ServiceInstance serviceInstance = mock(ServiceInstance.class);
|
||||
when(client.choose(eq("listener"), any())).thenReturn(serviceInstance);
|
||||
when(client.execute(eq("listener"), eq(serviceInstance), any(LoadBalancerRequest.class)))
|
||||
.thenThrow(new IOException()).thenReturn(clientHttpResponse);
|
||||
.thenThrow(new IOException())
|
||||
.thenReturn(clientHttpResponse);
|
||||
properties.getRetry().setEnabled(true);
|
||||
MyRetryListener retryListener = new MyRetryListener();
|
||||
when(lbRequestFactory.createRequest(any(), any(), any())).thenReturn(mock(LoadBalancerRequest.class));
|
||||
@@ -333,7 +337,8 @@ public class RetryLoadBalancerInterceptorTests {
|
||||
ServiceInstance serviceInstance = mock(ServiceInstance.class);
|
||||
when(client.choose(eq("default"), any())).thenReturn(serviceInstance);
|
||||
when(client.execute(eq("default"), eq(serviceInstance), any(LoadBalancerRequest.class)))
|
||||
.thenThrow(new IOException()).thenReturn(clientHttpResponse);
|
||||
.thenThrow(new IOException())
|
||||
.thenReturn(clientHttpResponse);
|
||||
properties.getRetry().setEnabled(true);
|
||||
when(lbRequestFactory.createRequest(any(), any(), any())).thenReturn(mock(LoadBalancerRequest.class));
|
||||
when(policy.retryableException(any())).thenReturn(true);
|
||||
@@ -385,28 +390,28 @@ public class RetryLoadBalancerInterceptorTests {
|
||||
|
||||
assertThat(((TestLoadBalancerLifecycle) lifecycleProcessors.get("testLifecycle")).getStartLog()).hasSize(1);
|
||||
assertThat(((TestLoadBalancerLifecycle) lifecycleProcessors.get("testLifecycle")).getStartRequestLog())
|
||||
.hasSize(0);
|
||||
.hasSize(0);
|
||||
assertThat(((TestLoadBalancerLifecycle) lifecycleProcessors.get("testLifecycle")).getCompleteLog()).hasSize(0);
|
||||
assertThat(((TestLoadBalancerLifecycle) lifecycleProcessors.get("anotherLifecycle")).getStartLog()).hasSize(1);
|
||||
assertThat(((TestLoadBalancerLifecycle) lifecycleProcessors.get("anotherLifecycle")).getStartRequestLog())
|
||||
.hasSize(0);
|
||||
.hasSize(0);
|
||||
assertThat(((TestLoadBalancerLifecycle) lifecycleProcessors.get("anotherLifecycle")).getCompleteLog())
|
||||
.hasSize(0);
|
||||
.hasSize(0);
|
||||
assertThat(((TestLoadBalancerLifecycle) client.getLifecycleProcessors().get("testLifecycle")).getStartLog())
|
||||
.hasSize(0);
|
||||
.hasSize(0);
|
||||
assertThat(
|
||||
((TestLoadBalancerLifecycle) client.getLifecycleProcessors().get("testLifecycle")).getStartRequestLog())
|
||||
.hasSize(1);
|
||||
.hasSize(1);
|
||||
assertThat(((TestLoadBalancerLifecycle) client.getLifecycleProcessors().get("testLifecycle")).getCompleteLog())
|
||||
.hasSize(1);
|
||||
.hasSize(1);
|
||||
assertThat(((TestLoadBalancerLifecycle) client.getLifecycleProcessors().get("anotherLifecycle")).getStartLog())
|
||||
.hasSize(0);
|
||||
.hasSize(0);
|
||||
assertThat(
|
||||
((TestLoadBalancerLifecycle) client.getLifecycleProcessors().get("testLifecycle")).getStartRequestLog())
|
||||
.hasSize(1);
|
||||
.hasSize(1);
|
||||
assertThat(
|
||||
((TestLoadBalancerLifecycle) client.getLifecycleProcessors().get("anotherLifecycle")).getCompleteLog())
|
||||
.hasSize(1);
|
||||
.hasSize(1);
|
||||
}
|
||||
|
||||
static class MyLoadBalancedRetryFactory implements LoadBalancedRetryFactory {
|
||||
@@ -508,14 +513,14 @@ public class RetryLoadBalancerInterceptorTests {
|
||||
@Override
|
||||
public <T> T execute(String serviceId, ServiceInstance serviceInstance, LoadBalancerRequest<T> request) {
|
||||
Set<LoadBalancerLifecycle> supportedLoadBalancerProcessors = LoadBalancerLifecycleValidator
|
||||
.getSupportedLifecycleProcessors(lifecycleProcessors, DefaultRequestContext.class, Object.class,
|
||||
ServiceInstance.class);
|
||||
.getSupportedLifecycleProcessors(lifecycleProcessors, DefaultRequestContext.class, Object.class,
|
||||
ServiceInstance.class);
|
||||
supportedLoadBalancerProcessors.forEach(lifecycle -> lifecycle.onStartRequest(new DefaultRequest<>(),
|
||||
new DefaultResponse(serviceInstance)));
|
||||
T response = (T) new MockClientHttpResponse(new byte[] {}, HttpStatus.OK);
|
||||
supportedLoadBalancerProcessors
|
||||
.forEach(lifecycle -> lifecycle.onComplete(new CompletionContext(CompletionContext.Status.SUCCESS,
|
||||
new DefaultRequest<>(), new DefaultResponse(defaultServiceInstance()))));
|
||||
.forEach(lifecycle -> lifecycle.onComplete(new CompletionContext(CompletionContext.Status.SUCCESS,
|
||||
new DefaultRequest<>(), new DefaultResponse(defaultServiceInstance()))));
|
||||
return response;
|
||||
}
|
||||
|
||||
|
||||
@@ -43,7 +43,8 @@ final class LoadBalancerTestUtils {
|
||||
|
||||
static ConfigurableApplicationContext init(Class<?>... configClasses) {
|
||||
return new SpringApplicationBuilder().web(WebApplicationType.NONE)
|
||||
.sources(ArrayUtils.add(configClasses, WebClientAutoConfiguration.class)).run();
|
||||
.sources(ArrayUtils.add(configClasses, WebClientAutoConfiguration.class))
|
||||
.run();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@@ -56,7 +57,7 @@ final class LoadBalancerTestUtils {
|
||||
then(filters).hasSize(1);
|
||||
then(filters.get(0)).isInstanceOf(DeferringLoadBalancerExchangeFilterFunction.class);
|
||||
DeferringLoadBalancerExchangeFilterFunction interceptor = (DeferringLoadBalancerExchangeFilterFunction) filters
|
||||
.get(0);
|
||||
.get(0);
|
||||
interceptor.tryResolveDelegate();
|
||||
then(interceptor.getDelegate()).isInstanceOf(exchangeFilterFunctionClass);
|
||||
}
|
||||
|
||||
@@ -59,7 +59,7 @@ public class ReactorLoadBalancerClientAutoConfigurationTests {
|
||||
assertLoadBalanced(webClientBuilder, ReactorLoadBalancerExchangeFilterFunction.class);
|
||||
|
||||
final Map<String, OneWebClientBuilder.TestService> testServiceMap = context
|
||||
.getBeansOfType(OneWebClientBuilder.TestService.class);
|
||||
.getBeansOfType(OneWebClientBuilder.TestService.class);
|
||||
then(testServiceMap).isNotNull().hasSize(1);
|
||||
OneWebClientBuilder.TestService testService = testServiceMap.values().stream().findFirst().get();
|
||||
assertLoadBalanced(testService.webClient, ReactorLoadBalancerExchangeFilterFunction.class);
|
||||
@@ -78,7 +78,7 @@ public class ReactorLoadBalancerClientAutoConfigurationTests {
|
||||
assertLoadBalanced(webClientBuilder, RetryableLoadBalancerExchangeFilterFunction.class);
|
||||
|
||||
final Map<String, OneWebClientBuilder.TestService> testServiceMap = context
|
||||
.getBeansOfType(OneWebClientBuilder.TestService.class);
|
||||
.getBeansOfType(OneWebClientBuilder.TestService.class);
|
||||
then(testServiceMap).isNotNull().hasSize(1);
|
||||
OneWebClientBuilder.TestService testService = testServiceMap.values().stream().findFirst().get();
|
||||
assertLoadBalanced(testService.webClient, RetryableLoadBalancerExchangeFilterFunction.class);
|
||||
@@ -136,10 +136,10 @@ public class ReactorLoadBalancerClientAutoConfigurationTests {
|
||||
@Test
|
||||
void defaultPropertiesWorks() {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
|
||||
.sources(OneWebClientBuilder.class, DefaulConfig.class)
|
||||
.properties("spring.cloud.loadbalancer.health-check.initial-delay=1s",
|
||||
"spring.cloud.loadbalancer.clients.myclient.health-check.interval=30s")
|
||||
.run();
|
||||
.sources(OneWebClientBuilder.class, DefaulConfig.class)
|
||||
.properties("spring.cloud.loadbalancer.health-check.initial-delay=1s",
|
||||
"spring.cloud.loadbalancer.clients.myclient.health-check.interval=30s")
|
||||
.run();
|
||||
LoadBalancerClientsProperties properties = context.getBean(LoadBalancerClientsProperties.class);
|
||||
|
||||
then(properties.getClients()).containsKey("myclient");
|
||||
|
||||
@@ -91,66 +91,94 @@ class ReactorLoadBalancerExchangeFilterFunctionTests {
|
||||
instanceWithNoLifecycleProcessors.setServiceId("serviceWithNoLifecycleProcessors");
|
||||
instanceWithNoLifecycleProcessors.setUri(URI.create("http://localhost:" + this.port));
|
||||
properties.getInstances().put("testservice", Collections.singletonList(instance));
|
||||
properties.getInstances().put("serviceWithNoLifecycleProcessors",
|
||||
Collections.singletonList(instanceWithNoLifecycleProcessors));
|
||||
properties.getInstances()
|
||||
.put("serviceWithNoLifecycleProcessors", Collections.singletonList(instanceWithNoLifecycleProcessors));
|
||||
}
|
||||
|
||||
@Test
|
||||
void correctResponseReturnedForExistingHostAndInstancePresent() {
|
||||
ClientResponse clientResponse = WebClient.builder().baseUrl("http://testservice").filter(loadBalancerFunction)
|
||||
.build().get().uri("/hello").exchange().block();
|
||||
ClientResponse clientResponse = WebClient.builder()
|
||||
.baseUrl("http://testservice")
|
||||
.filter(loadBalancerFunction)
|
||||
.build()
|
||||
.get()
|
||||
.uri("/hello")
|
||||
.exchange()
|
||||
.block();
|
||||
then(clientResponse.statusCode()).isEqualTo(HttpStatus.OK);
|
||||
then(clientResponse.bodyToMono(String.class).block()).isEqualTo("Hello World");
|
||||
}
|
||||
|
||||
@Test
|
||||
void serviceUnavailableReturnedWhenNoInstancePresent() {
|
||||
ClientResponse clientResponse = WebClient.builder().baseUrl("http://xxx").filter(this.loadBalancerFunction)
|
||||
.build().get().exchange().block();
|
||||
ClientResponse clientResponse = WebClient.builder()
|
||||
.baseUrl("http://xxx")
|
||||
.filter(this.loadBalancerFunction)
|
||||
.build()
|
||||
.get()
|
||||
.exchange()
|
||||
.block();
|
||||
then(clientResponse.statusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Disabled // FIXME 3.0.0
|
||||
void badRequestReturnedForIncorrectHost() {
|
||||
ClientResponse clientResponse = WebClient.builder().baseUrl("http:///xxx").filter(this.loadBalancerFunction)
|
||||
.build().get().exchange().block();
|
||||
ClientResponse clientResponse = WebClient.builder()
|
||||
.baseUrl("http:///xxx")
|
||||
.filter(this.loadBalancerFunction)
|
||||
.build()
|
||||
.get()
|
||||
.exchange()
|
||||
.block();
|
||||
then(clientResponse.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
@Test
|
||||
void exceptionNotThrownWhenFactoryReturnsNullLifecycleProcessorsMap() {
|
||||
assertThatCode(() -> WebClient.builder().baseUrl("http://serviceWithNoLifecycleProcessors")
|
||||
.filter(loadBalancerFunction).build().get().uri("/hello").exchange().block())
|
||||
.doesNotThrowAnyException();
|
||||
assertThatCode(() -> WebClient.builder()
|
||||
.baseUrl("http://serviceWithNoLifecycleProcessors")
|
||||
.filter(loadBalancerFunction)
|
||||
.build()
|
||||
.get()
|
||||
.uri("/hello")
|
||||
.exchange()
|
||||
.block()).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
void loadBalancerLifecycleCallbacksExecuted() {
|
||||
final String callbackTestHint = "callbackTestHint";
|
||||
loadBalancerProperties.getHint().put("testservice", "callbackTestHint");
|
||||
ClientResponse clientResponse = WebClient.builder().baseUrl("http://testservice").filter(loadBalancerFunction)
|
||||
.build().get().uri("/callback").exchange().block();
|
||||
ClientResponse clientResponse = WebClient.builder()
|
||||
.baseUrl("http://testservice")
|
||||
.filter(loadBalancerFunction)
|
||||
.build()
|
||||
.get()
|
||||
.uri("/callback")
|
||||
.exchange()
|
||||
.block();
|
||||
|
||||
Collection<Request<Object>> lifecycleLogRequests = ((TestLoadBalancerLifecycle) factory
|
||||
.getInstances("testservice", LoadBalancerLifecycle.class).get("loadBalancerLifecycle")).getStartLog()
|
||||
.values();
|
||||
.getInstances("testservice", LoadBalancerLifecycle.class)
|
||||
.get("loadBalancerLifecycle")).getStartLog().values();
|
||||
Collection<Request<Object>> lifecycleStartedLogRequests = ((TestLoadBalancerLifecycle) factory
|
||||
.getInstances("testservice", LoadBalancerLifecycle.class).get("loadBalancerLifecycle"))
|
||||
.getStartRequestLog().values();
|
||||
.getInstances("testservice", LoadBalancerLifecycle.class)
|
||||
.get("loadBalancerLifecycle")).getStartRequestLog().values();
|
||||
Collection<CompletionContext<Object, ServiceInstance, Object>> anotherLifecycleLogRequests = ((AnotherLoadBalancerLifecycle) factory
|
||||
.getInstances("testservice", LoadBalancerLifecycle.class).get("anotherLoadBalancerLifecycle"))
|
||||
.getCompleteLog().values();
|
||||
.getInstances("testservice", LoadBalancerLifecycle.class)
|
||||
.get("anotherLoadBalancerLifecycle")).getCompleteLog().values();
|
||||
then(clientResponse.statusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(lifecycleLogRequests).extracting(request -> ((DefaultRequestContext) request.getContext()).getHint())
|
||||
.contains(callbackTestHint);
|
||||
.contains(callbackTestHint);
|
||||
assertThat(lifecycleStartedLogRequests)
|
||||
.extracting(request -> ((DefaultRequestContext) request.getContext()).getHint())
|
||||
.contains(callbackTestHint);
|
||||
.extracting(request -> ((DefaultRequestContext) request.getContext()).getHint())
|
||||
.contains(callbackTestHint);
|
||||
assertThat(anotherLifecycleLogRequests)
|
||||
.extracting(completionContext -> ((ResponseData) completionContext.getClientResponse()).getRequestData()
|
||||
.getUrl().toString())
|
||||
.contains("http://testservice/callback");
|
||||
.extracting(completionContext -> ((ResponseData) completionContext.getClientResponse()).getRequestData()
|
||||
.getUrl()
|
||||
.toString())
|
||||
.contains("http://testservice/callback");
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
|
||||
@@ -93,8 +93,8 @@ class RetryableLoadBalancerExchangeFilterFunctionIntegrationTests {
|
||||
instanceWithNoLifecycleProcessors.setServiceId("serviceWithNoLifecycleProcessors");
|
||||
instanceWithNoLifecycleProcessors.setUri(URI.create("http://localhost:" + port));
|
||||
properties.getInstances().put("testservice", Collections.singletonList(instance));
|
||||
properties.getInstances().put("serviceWithNoLifecycleProcessors",
|
||||
Collections.singletonList(instanceWithNoLifecycleProcessors));
|
||||
properties.getInstances()
|
||||
.put("serviceWithNoLifecycleProcessors", Collections.singletonList(instanceWithNoLifecycleProcessors));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -102,34 +102,46 @@ class RetryableLoadBalancerExchangeFilterFunctionIntegrationTests {
|
||||
final String callbackTestHint = "callbackTestHint";
|
||||
loadBalancerProperties.getHint().put("testservice", "callbackTestHint");
|
||||
|
||||
ClientResponse clientResponse = WebClient.builder().baseUrl("http://testservice")
|
||||
.filter(this.loadBalancerFunction).build().get().uri("/callback").exchange().block();
|
||||
ClientResponse clientResponse = WebClient.builder()
|
||||
.baseUrl("http://testservice")
|
||||
.filter(this.loadBalancerFunction)
|
||||
.build()
|
||||
.get()
|
||||
.uri("/callback")
|
||||
.exchange()
|
||||
.block();
|
||||
|
||||
Collection<Request<Object>> lifecycleLogRequests = ((TestLoadBalancerLifecycle) factory
|
||||
.getInstances("testservice", LoadBalancerLifecycle.class).get("loadBalancerLifecycle")).getStartLog()
|
||||
.values();
|
||||
.getInstances("testservice", LoadBalancerLifecycle.class)
|
||||
.get("loadBalancerLifecycle")).getStartLog().values();
|
||||
Collection<Request<Object>> lifecycleLogStartRequests = ((TestLoadBalancerLifecycle) factory
|
||||
.getInstances("testservice", LoadBalancerLifecycle.class).get("loadBalancerLifecycle"))
|
||||
.getStartRequestLog().values();
|
||||
.getInstances("testservice", LoadBalancerLifecycle.class)
|
||||
.get("loadBalancerLifecycle")).getStartRequestLog().values();
|
||||
Collection<CompletionContext<Object, ServiceInstance, Object>> anotherLifecycleLogRequests = ((AnotherLoadBalancerLifecycle) factory
|
||||
.getInstances("testservice", LoadBalancerLifecycle.class).get("anotherLoadBalancerLifecycle"))
|
||||
.getCompleteLog().values();
|
||||
.getInstances("testservice", LoadBalancerLifecycle.class)
|
||||
.get("anotherLoadBalancerLifecycle")).getCompleteLog().values();
|
||||
then(clientResponse.statusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(lifecycleLogRequests).extracting(request -> ((DefaultRequestContext) request.getContext()).getHint())
|
||||
.contains(callbackTestHint);
|
||||
.contains(callbackTestHint);
|
||||
assertThat(lifecycleLogStartRequests)
|
||||
.extracting(request -> ((DefaultRequestContext) request.getContext()).getHint())
|
||||
.contains(callbackTestHint);
|
||||
.extracting(request -> ((DefaultRequestContext) request.getContext()).getHint())
|
||||
.contains(callbackTestHint);
|
||||
assertThat(anotherLifecycleLogRequests)
|
||||
.extracting(completionContext -> ((ResponseData) completionContext.getClientResponse()).getRequestData()
|
||||
.getHttpMethod())
|
||||
.contains(HttpMethod.GET);
|
||||
.extracting(completionContext -> ((ResponseData) completionContext.getClientResponse()).getRequestData()
|
||||
.getHttpMethod())
|
||||
.contains(HttpMethod.GET);
|
||||
}
|
||||
|
||||
@Test
|
||||
void correctResponseReturnedForExistingHostAndInstancePresent() {
|
||||
ClientResponse clientResponse = WebClient.builder().baseUrl("http://testservice")
|
||||
.filter(this.loadBalancerFunction).build().get().uri("/hello").exchange().block();
|
||||
ClientResponse clientResponse = WebClient.builder()
|
||||
.baseUrl("http://testservice")
|
||||
.filter(this.loadBalancerFunction)
|
||||
.build()
|
||||
.get()
|
||||
.uri("/hello")
|
||||
.exchange()
|
||||
.block();
|
||||
|
||||
then(clientResponse.statusCode()).isEqualTo(HttpStatus.OK);
|
||||
then(clientResponse.bodyToMono(String.class).block()).isEqualTo("Hello World");
|
||||
@@ -140,8 +152,14 @@ class RetryableLoadBalancerExchangeFilterFunctionIntegrationTests {
|
||||
loadBalancerProperties.getRetry().setMaxRetriesOnSameServiceInstance(1);
|
||||
loadBalancerProperties.getRetry().getRetryableStatusCodes().add(500);
|
||||
|
||||
ClientResponse clientResponse = WebClient.builder().baseUrl("http://testservice")
|
||||
.filter(this.loadBalancerFunction).build().get().uri("/exception").exchange().block();
|
||||
ClientResponse clientResponse = WebClient.builder()
|
||||
.baseUrl("http://testservice")
|
||||
.filter(this.loadBalancerFunction)
|
||||
.build()
|
||||
.get()
|
||||
.uri("/exception")
|
||||
.exchange()
|
||||
.block();
|
||||
|
||||
then(clientResponse.statusCode()).isEqualTo(HttpStatus.OK);
|
||||
then(clientResponse.bodyToMono(String.class).block()).isEqualTo("Hello World!");
|
||||
@@ -160,14 +178,26 @@ class RetryableLoadBalancerExchangeFilterFunctionIntegrationTests {
|
||||
properties.getInstances().put("retrytest", Arrays.asList(badRetryTestInstance, goodRetryTestInstance));
|
||||
loadBalancerProperties.getRetry().getRetryableStatusCodes().add(500);
|
||||
|
||||
ClientResponse clientResponse = WebClient.builder().baseUrl("http://retrytest")
|
||||
.filter(this.loadBalancerFunction).build().get().uri("/hello").exchange().block();
|
||||
ClientResponse clientResponse = WebClient.builder()
|
||||
.baseUrl("http://retrytest")
|
||||
.filter(this.loadBalancerFunction)
|
||||
.build()
|
||||
.get()
|
||||
.uri("/hello")
|
||||
.exchange()
|
||||
.block();
|
||||
|
||||
then(clientResponse.statusCode()).isEqualTo(HttpStatus.OK);
|
||||
then(clientResponse.bodyToMono(String.class).block()).isEqualTo("Hello World");
|
||||
|
||||
ClientResponse secondClientResponse = WebClient.builder().baseUrl("http://retrytest")
|
||||
.filter(this.loadBalancerFunction).build().get().uri("/hello").exchange().block();
|
||||
ClientResponse secondClientResponse = WebClient.builder()
|
||||
.baseUrl("http://retrytest")
|
||||
.filter(this.loadBalancerFunction)
|
||||
.build()
|
||||
.get()
|
||||
.uri("/hello")
|
||||
.exchange()
|
||||
.block();
|
||||
|
||||
then(secondClientResponse.statusCode()).isEqualTo(HttpStatus.OK);
|
||||
then(secondClientResponse.bodyToMono(String.class).block()).isEqualTo("Hello World");
|
||||
@@ -175,8 +205,13 @@ class RetryableLoadBalancerExchangeFilterFunctionIntegrationTests {
|
||||
|
||||
@Test
|
||||
void serviceUnavailableReturnedWhenNoInstancePresent() {
|
||||
ClientResponse clientResponse = WebClient.builder().baseUrl("http://xxx").filter(this.loadBalancerFunction)
|
||||
.build().get().exchange().block();
|
||||
ClientResponse clientResponse = WebClient.builder()
|
||||
.baseUrl("http://xxx")
|
||||
.filter(this.loadBalancerFunction)
|
||||
.build()
|
||||
.get()
|
||||
.exchange()
|
||||
.block();
|
||||
|
||||
then(clientResponse.statusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
|
||||
}
|
||||
@@ -185,17 +220,27 @@ class RetryableLoadBalancerExchangeFilterFunctionIntegrationTests {
|
||||
@Disabled
|
||||
// FIXME 3.0.0
|
||||
void badRequestReturnedForIncorrectHost() {
|
||||
ClientResponse clientResponse = WebClient.builder().baseUrl("http:///xxx").filter(this.loadBalancerFunction)
|
||||
.build().get().exchange().block();
|
||||
ClientResponse clientResponse = WebClient.builder()
|
||||
.baseUrl("http:///xxx")
|
||||
.filter(this.loadBalancerFunction)
|
||||
.build()
|
||||
.get()
|
||||
.exchange()
|
||||
.block();
|
||||
|
||||
then(clientResponse.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
@Test
|
||||
void exceptionNotThrownWhenFactoryReturnsNullLifecycleProcessorsMap() {
|
||||
assertThatCode(() -> WebClient.builder().baseUrl("http://serviceWithNoLifecycleProcessors")
|
||||
.filter(this.loadBalancerFunction).build().get().uri("/hello").exchange().block())
|
||||
.doesNotThrowAnyException();
|
||||
assertThatCode(() -> WebClient.builder()
|
||||
.baseUrl("http://serviceWithNoLifecycleProcessors")
|
||||
.filter(this.loadBalancerFunction)
|
||||
.build()
|
||||
.get()
|
||||
.uri("/hello")
|
||||
.exchange()
|
||||
.block()).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
|
||||
@@ -65,11 +65,11 @@ public class AbstractAutoServiceRegistrationTests {
|
||||
public void portsWork() {
|
||||
then(this.autoRegistration.getPort().get()).isNotEqualTo(0).as("Lifecycle port is zero");
|
||||
then(this.managementPort).isNotEqualTo(this.autoRegistration.getPort().get())
|
||||
.as("Lifecycle port is management port");
|
||||
.as("Lifecycle port is management port");
|
||||
then(this.port).isEqualTo(this.autoRegistration.getPort().get()).as("Lifecycle port is wrong");
|
||||
then(this.autoRegistration.isRunning()).isTrue().as("Lifecycle not running");
|
||||
then(this.autoRegistration.getServiceRegistry()).isInstanceOf(TestServiceRegistry.class)
|
||||
.as("ServiceRegistry is wrong type");
|
||||
.as("ServiceRegistry is wrong type");
|
||||
TestServiceRegistry serviceRegistry = (TestServiceRegistry) this.autoRegistration.getServiceRegistry();
|
||||
then(serviceRegistry.isRegistered()).isTrue().as("Lifecycle not registered");
|
||||
then(this.autoRegistration.getAppName()).as("Lifecycle appName is wrong").isEqualTo("application");
|
||||
|
||||
@@ -36,7 +36,8 @@ public class ServiceRegistryAutoConfigurationTests {
|
||||
@Test
|
||||
public void runsWithoutActuator() {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfig.class)
|
||||
.web(WebApplicationType.NONE).run();
|
||||
.web(WebApplicationType.NONE)
|
||||
.run();
|
||||
try {
|
||||
context.getBean("serviceRegistryEndpoint");
|
||||
fail("found a bean that shouldn't be there");
|
||||
|
||||
@@ -54,7 +54,7 @@ public class ServiceRegistryEndpointNoRegistrationTests {
|
||||
@Test
|
||||
public void testPost() throws Exception {
|
||||
this.mvc.perform(post("/serviceregistry/instance-status").content("newstatus"))
|
||||
.andExpect(status().isNotFound());
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Import({ JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class,
|
||||
|
||||
@@ -68,15 +68,18 @@ public class ServiceRegistryEndpointTests {
|
||||
|
||||
@Test
|
||||
public void testGet() throws Exception {
|
||||
this.mvc.perform(get(BASE_PATH + "/serviceregistry")).andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString(MYSTATUS)));
|
||||
this.mvc.perform(get(BASE_PATH + "/serviceregistry"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString(MYSTATUS)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPost() throws Exception {
|
||||
Map<String, String> status = Collections.singletonMap("status", UPDATED_STATUS);
|
||||
this.mvc.perform(post(BASE_PATH + "/serviceregistry").content(new ObjectMapper().writeValueAsString(status))
|
||||
.contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk());
|
||||
this.mvc
|
||||
.perform(post(BASE_PATH + "/serviceregistry").content(new ObjectMapper().writeValueAsString(status))
|
||||
.contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isOk());
|
||||
then(this.serviceRegistry.getUpdatedStatus().get()).isEqualTo(UPDATED_STATUS);
|
||||
}
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ public class ConfigDataMissingEnvironmentPostProcessorTests {
|
||||
SpringApplication app = mock(SpringApplication.class);
|
||||
TestConfigDataMissingEnvironmentPostProcessor processor = new TestConfigDataMissingEnvironmentPostProcessor();
|
||||
assertThatThrownBy(() -> processor.postProcessEnvironment(environment, app))
|
||||
.isInstanceOf(ConfigDataMissingEnvironmentPostProcessor.ImportException.class);
|
||||
.isInstanceOf(ConfigDataMissingEnvironmentPostProcessor.ImportException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -51,94 +51,125 @@ public class FluxFirstNonEmptyEmittingTests {
|
||||
@Test
|
||||
public void firstWinner() {
|
||||
StepVerifier.create(CloudFlux.firstNonEmpty(Flux.range(1, 10), Flux.range(11, 10)))
|
||||
.expectNext(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).verifyComplete();
|
||||
.expectNext(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void firstWinnerSecondEmpty() {
|
||||
StepVerifier.create(CloudFlux.firstNonEmpty(Flux.range(1, 10), Flux.empty()))
|
||||
.expectNext(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).verifyComplete();
|
||||
.expectNext(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void firstWinnerBackpressured() {
|
||||
StepVerifier.create(CloudFlux.firstNonEmpty(Flux.range(1, 10), Flux.range(11, 10))).thenRequest(5)
|
||||
.expectNext(1, 2, 3, 4, 5).thenCancel().verifyThenAssertThat().hasNotDiscardedElements()
|
||||
.hasNotDroppedElements().hasNotDroppedErrors();
|
||||
StepVerifier.create(CloudFlux.firstNonEmpty(Flux.range(1, 10), Flux.range(11, 10)))
|
||||
.thenRequest(5)
|
||||
.expectNext(1, 2, 3, 4, 5)
|
||||
.thenCancel()
|
||||
.verifyThenAssertThat()
|
||||
.hasNotDiscardedElements()
|
||||
.hasNotDroppedElements()
|
||||
.hasNotDroppedErrors();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void secondWinner() {
|
||||
StepVerifier.create(CloudFlux.firstNonEmpty(Flux.never(), Flux.range(11, 10).log()))
|
||||
.expectNext(11, 12, 13, 14, 15, 16, 17, 18, 19, 20).verifyComplete();
|
||||
.expectNext(11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void secondWinnerFirstEmpty() {
|
||||
StepVerifier.create(CloudFlux.firstNonEmpty(Flux.empty(), Flux.range(11, 10).log()))
|
||||
.expectNext(11, 12, 13, 14, 15, 16, 17, 18, 19, 20).verifyComplete();
|
||||
.expectNext(11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bothEmpty() {
|
||||
StepVerifier.create(CloudFlux.firstNonEmpty(Flux.empty(), Flux.empty())).expectComplete().verifyThenAssertThat()
|
||||
.hasNotDiscardedElements().hasNotDroppedElements().hasNotDroppedErrors();
|
||||
StepVerifier.create(CloudFlux.firstNonEmpty(Flux.empty(), Flux.empty()))
|
||||
.expectComplete()
|
||||
.verifyThenAssertThat()
|
||||
.hasNotDiscardedElements()
|
||||
.hasNotDroppedElements()
|
||||
.hasNotDroppedErrors();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void neverAndEmpty() {
|
||||
StepVerifier.withVirtualTime(() -> CloudFlux.firstNonEmpty(Flux.never(), Flux.empty())).expectSubscription()
|
||||
.expectNoEvent(Duration.ofDays(1)).thenCancel().verifyThenAssertThat().hasNotDiscardedElements()
|
||||
.hasNotDroppedElements().hasNotDroppedErrors();
|
||||
StepVerifier.withVirtualTime(() -> CloudFlux.firstNonEmpty(Flux.never(), Flux.empty()))
|
||||
.expectSubscription()
|
||||
.expectNoEvent(Duration.ofDays(1))
|
||||
.thenCancel()
|
||||
.verifyThenAssertThat()
|
||||
.hasNotDiscardedElements()
|
||||
.hasNotDroppedElements()
|
||||
.hasNotDroppedErrors();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void firstEmitsError() {
|
||||
RuntimeException ex = new RuntimeException("forced failure");
|
||||
StepVerifier.create(CloudFlux.firstNonEmpty(Flux.<Integer>error(ex), Flux.empty()))
|
||||
.expectErrorMessage("forced failure").verifyThenAssertThat().hasNotDiscardedElements()
|
||||
.hasNotDroppedElements().hasNotDroppedErrors();
|
||||
.expectErrorMessage("forced failure")
|
||||
.verifyThenAssertThat()
|
||||
.hasNotDiscardedElements()
|
||||
.hasNotDroppedElements()
|
||||
.hasNotDroppedErrors();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void secondEmitsError() {
|
||||
RuntimeException ex = new RuntimeException("forced failure");
|
||||
StepVerifier.create(CloudFlux.firstNonEmpty(Flux.empty(), Flux.<Integer>error(ex)))
|
||||
.expectErrorMessage("forced failure").verifyThenAssertThat().hasNotDiscardedElements()
|
||||
.hasNotDroppedElements().hasNotDroppedErrors();
|
||||
.expectErrorMessage("forced failure")
|
||||
.verifyThenAssertThat()
|
||||
.hasNotDiscardedElements()
|
||||
.hasNotDroppedElements()
|
||||
.hasNotDroppedErrors();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void neverAndSecondEmitsError() {
|
||||
RuntimeException ex = new RuntimeException("forced failure");
|
||||
StepVerifier.create(CloudFlux.firstNonEmpty(Flux.never(), Flux.<Integer>error(ex)))
|
||||
.expectErrorMessage("forced failure").verifyThenAssertThat().hasNotDiscardedElements()
|
||||
.hasNotDroppedElements().hasNotDroppedErrors();
|
||||
.expectErrorMessage("forced failure")
|
||||
.verifyThenAssertThat()
|
||||
.hasNotDiscardedElements()
|
||||
.hasNotDroppedElements()
|
||||
.hasNotDroppedErrors();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void singleArrayNullSource() {
|
||||
StepVerifier.create(CloudFlux.firstNonEmpty((Publisher<Object>) null)).expectError(NullPointerException.class)
|
||||
.verify();
|
||||
StepVerifier.create(CloudFlux.firstNonEmpty((Publisher<Object>) null))
|
||||
.expectError(NullPointerException.class)
|
||||
.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void arrayOneIsNullSource() {
|
||||
StepVerifier.create(CloudFlux.firstNonEmpty(Flux.never(), null, Flux.never()))
|
||||
.expectError(NullPointerException.class).verify();
|
||||
.expectError(NullPointerException.class)
|
||||
.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void singleIterableNullSource() {
|
||||
StepVerifier.create(CloudFlux.firstNonEmpty(singletonList((Publisher<Object>) null)))
|
||||
.expectError(NullPointerException.class).verify();
|
||||
.expectError(NullPointerException.class)
|
||||
.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void iterableOneIsNullSource() {
|
||||
StepVerifier
|
||||
.create(CloudFlux.firstNonEmpty(Arrays.asList(Flux.never(), (Publisher<Object>) null, Flux.never())))
|
||||
.expectError(NullPointerException.class).verify();
|
||||
.create(CloudFlux.firstNonEmpty(Arrays.asList(Flux.never(), (Publisher<Object>) null, Flux.never())))
|
||||
.expectError(NullPointerException.class)
|
||||
.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -46,9 +46,9 @@ public class ResourceServerTokenRelayAutoConfigurationTests {
|
||||
@Test
|
||||
public void clientNotConfigured() {
|
||||
this.context = new SpringApplicationBuilder(NoClientConfiguration.class)
|
||||
.properties("spring.config.name=test", "server.port=0", "spring.cloud.mvc.token-relay.enabled=true",
|
||||
"security.oauth2.resource.userInfoUri:https://example.com")
|
||||
.run();
|
||||
.properties("spring.config.name=test", "server.port=0", "spring.cloud.mvc.token-relay.enabled=true",
|
||||
"security.oauth2.resource.userInfoUri:https://example.com")
|
||||
.run();
|
||||
assertThat(this.context.containsBean("loadBalancedOauth2RestTemplate")).isFalse();
|
||||
}
|
||||
|
||||
|
||||
@@ -75,8 +75,8 @@ public class ResourceServerTokenRelayTests {
|
||||
public void tokenRelayJWT() {
|
||||
|
||||
mockServerToReceiveRelay.expect(requestTo("https://example.com/test"))
|
||||
.andExpect(header("authorization", AUTH_HEADER_TO_BE_RELAYED))
|
||||
.andRespond(withSuccess(TEST_RESPONSE, MediaType.APPLICATION_JSON));
|
||||
.andExpect(header("authorization", AUTH_HEADER_TO_BE_RELAYED))
|
||||
.andRespond(withSuccess(TEST_RESPONSE, MediaType.APPLICATION_JSON));
|
||||
|
||||
HttpEntity<String> authorizationHeader = createAuthorizationHeader();
|
||||
ResponseEntity<String> exchange = testRestTemplate.exchange("/token-relay", HttpMethod.GET, authorizationHeader,
|
||||
|
||||
@@ -119,7 +119,7 @@ public class IdUtilsTests {
|
||||
@Test
|
||||
public void testUnresolvedServiceIdWithActiveProfiles() {
|
||||
then(IdUtils.DEFAULT_SERVICE_ID_WITH_ACTIVE_PROFILES_STRING)
|
||||
.isEqualTo(IdUtils.getUnresolvedServiceIdWithActiveProfiles());
|
||||
.isEqualTo(IdUtils.getUnresolvedServiceIdWithActiveProfiles());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -36,7 +36,8 @@ public class JdbcConfigurationTests {
|
||||
@Test
|
||||
public void schemaApplied() {
|
||||
new SpringApplicationBuilder(BrokenApplication.class).web(WebApplicationType.NONE)
|
||||
.run("--spring.datasource.initialization-mode=always").close();
|
||||
.run("--spring.datasource.initialization-mode=always")
|
||||
.close();
|
||||
}
|
||||
|
||||
@SpringBootConfiguration
|
||||
|
||||
@@ -151,7 +151,8 @@ public class RefreshAutoConfiguration {
|
||||
@Override
|
||||
public String toString() {
|
||||
return new ToStringCreator(this)
|
||||
.append("additionalPropertySourcesToRetain", additionalPropertySourcesToRetain).toString();
|
||||
.append("additionalPropertySourcesToRetain", additionalPropertySourcesToRetain)
|
||||
.toString();
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -146,7 +146,7 @@ public class BootstrapApplicationListener implements ApplicationListener<Applica
|
||||
MutablePropertySources bootstrapProperties = bootstrapEnvironment.getPropertySources();
|
||||
String configLocation = environment.resolvePlaceholders("${spring.cloud.bootstrap.location:}");
|
||||
String configAdditionalLocation = environment
|
||||
.resolvePlaceholders("${spring.cloud.bootstrap.additional-location:}");
|
||||
.resolvePlaceholders("${spring.cloud.bootstrap.additional-location:}");
|
||||
Map<String, Object> bootstrapMap = new HashMap<>();
|
||||
bootstrapMap.put("spring.config.name", configName);
|
||||
// if an app (or test) uses spring.main.web-application-type=reactive, bootstrap
|
||||
@@ -170,9 +170,12 @@ public class BootstrapApplicationListener implements ApplicationListener<Applica
|
||||
}
|
||||
// TODO: is it possible or sensible to share a ResourceLoader?
|
||||
SpringApplicationBuilder builder = new SpringApplicationBuilder().profiles(environment.getActiveProfiles())
|
||||
.bannerMode(Mode.OFF).environment(bootstrapEnvironment)
|
||||
// Don't use the default properties in this builder
|
||||
.registerShutdownHook(false).logStartupInfo(false).web(WebApplicationType.NONE);
|
||||
.bannerMode(Mode.OFF)
|
||||
.environment(bootstrapEnvironment)
|
||||
// Don't use the default properties in this builder
|
||||
.registerShutdownHook(false)
|
||||
.logStartupInfo(false)
|
||||
.web(WebApplicationType.NONE);
|
||||
final SpringApplication builderApplication = builder.application();
|
||||
if (builderApplication.getMainApplicationClass() == null) {
|
||||
// gh_425:
|
||||
@@ -383,7 +386,7 @@ public class BootstrapApplicationListener implements ApplicationListener<Applica
|
||||
PropertySource<?> removed = environment.getPropertySources().remove(DEFAULT_PROPERTIES);
|
||||
if (removed instanceof ExtendedDefaultPropertySource defaultProperties) {
|
||||
environment.getPropertySources()
|
||||
.addLast(new MapPropertySource(DEFAULT_PROPERTIES, defaultProperties.getSource()));
|
||||
.addLast(new MapPropertySource(DEFAULT_PROPERTIES, defaultProperties.getSource()));
|
||||
for (PropertySource<?> source : defaultProperties.getPropertySources().getPropertySources()) {
|
||||
if (!environment.getPropertySources().contains(source.getName())) {
|
||||
environment.getPropertySources().addBefore(DEFAULT_PROPERTIES, source);
|
||||
|
||||
@@ -376,14 +376,15 @@ public class BootstrapConfigFileApplicationListener
|
||||
|
||||
private String[] getDefaultProfiles(Binder binder) {
|
||||
return binder.bind(AbstractEnvironment.DEFAULT_PROFILES_PROPERTY_NAME, STRING_ARRAY)
|
||||
.orElseGet(this.environment::getDefaultProfiles);
|
||||
.orElseGet(this.environment::getDefaultProfiles);
|
||||
}
|
||||
|
||||
private List<Profile> getOtherActiveProfiles(Set<Profile> activatedViaProperty,
|
||||
Set<Profile> includedViaProperty) {
|
||||
return Arrays.stream(this.environment.getActiveProfiles()).map(Profile::new).filter(
|
||||
(profile) -> !activatedViaProperty.contains(profile) && !includedViaProperty.contains(profile))
|
||||
.collect(Collectors.toList());
|
||||
return Arrays.stream(this.environment.getActiveProfiles())
|
||||
.map(Profile::new)
|
||||
.filter((profile) -> !activatedViaProperty.contains(profile) && !includedViaProperty.contains(profile))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
void addActiveProfiles(Set<Profile> profiles) {
|
||||
@@ -474,7 +475,7 @@ public class BootstrapConfigFileApplicationListener
|
||||
|
||||
private boolean canLoadFileExtension(PropertySourceLoader loader, String name) {
|
||||
return Arrays.stream(loader.getFileExtensions())
|
||||
.anyMatch((fileExtension) -> StringUtils.endsWithIgnoreCase(name, fileExtension));
|
||||
.anyMatch((fileExtension) -> StringUtils.endsWithIgnoreCase(name, fileExtension));
|
||||
}
|
||||
|
||||
private void loadForFileExtension(PropertySourceLoader loader, String prefix, String fileExtension,
|
||||
@@ -606,9 +607,12 @@ public class BootstrapConfigFileApplicationListener
|
||||
if (files != null) {
|
||||
String fileName = locationReference.substring(locationReference.lastIndexOf("/") + 1);
|
||||
Arrays.sort(files, FILE_COMPARATOR);
|
||||
return Arrays.stream(files).map((file) -> file.listFiles((dir, name) -> name.equals(fileName)))
|
||||
.filter(Objects::nonNull).flatMap((Function<File[], Stream<File>>) Arrays::stream)
|
||||
.map(FileSystemResource::new).toArray(Resource[]::new);
|
||||
return Arrays.stream(files)
|
||||
.map((file) -> file.listFiles((dir, name) -> name.equals(fileName)))
|
||||
.filter(Objects::nonNull)
|
||||
.flatMap((Function<File[], Stream<File>>) Arrays::stream)
|
||||
.map(FileSystemResource::new)
|
||||
.toArray(Resource[]::new);
|
||||
}
|
||||
return EMPTY_RESOURCES;
|
||||
}
|
||||
@@ -793,8 +797,10 @@ public class BootstrapConfigFileApplicationListener
|
||||
activeProfiles.addAll(bindStringList(binder, "spring.profiles.active"));
|
||||
}
|
||||
}
|
||||
this.processedProfiles.stream().filter(this::isDefaultProfile).map(Profile::getName)
|
||||
.forEach(activeProfiles::add);
|
||||
this.processedProfiles.stream()
|
||||
.filter(this::isDefaultProfile)
|
||||
.map(Profile::getName)
|
||||
.forEach(activeProfiles::add);
|
||||
this.environment.setActiveProfiles(activeProfiles.toArray(new String[0]));
|
||||
}
|
||||
|
||||
|
||||
@@ -64,7 +64,7 @@ public class BootstrapImportSelector implements EnvironmentAware, DeferredImport
|
||||
List<String> names = new ArrayList<>(
|
||||
SpringFactoriesLoader.loadFactoryNames(BootstrapConfiguration.class, classLoader));
|
||||
names.addAll(Arrays.asList(StringUtils
|
||||
.commaDelimitedListToStringArray(this.environment.getProperty("spring.cloud.bootstrap.sources", ""))));
|
||||
.commaDelimitedListToStringArray(this.environment.getProperty("spring.cloud.bootstrap.sources", ""))));
|
||||
|
||||
List<OrderedAnnotatedElement> elements = new ArrayList<>();
|
||||
for (String name : names) {
|
||||
|
||||
@@ -38,7 +38,7 @@ public class TextEncryptorConfigBootstrapper implements BootstrapRegistryInitial
|
||||
* RsaSecretEncryptor present.
|
||||
*/
|
||||
public static final boolean RSA_IS_PRESENT = ClassUtils
|
||||
.isPresent("org.springframework.security.rsa.crypto.RsaSecretEncryptor", null);
|
||||
.isPresent("org.springframework.security.rsa.crypto.RsaSecretEncryptor", null);
|
||||
|
||||
@Override
|
||||
public void initialize(BootstrapRegistry registry) {
|
||||
@@ -46,11 +46,15 @@ public class TextEncryptorConfigBootstrapper implements BootstrapRegistryInitial
|
||||
return;
|
||||
}
|
||||
|
||||
registry.registerIfAbsent(KeyProperties.class, context -> context.get(Binder.class)
|
||||
.bind(KeyProperties.PREFIX, KeyProperties.class).orElseGet(KeyProperties::new));
|
||||
registry.registerIfAbsent(KeyProperties.class,
|
||||
context -> context.get(Binder.class)
|
||||
.bind(KeyProperties.PREFIX, KeyProperties.class)
|
||||
.orElseGet(KeyProperties::new));
|
||||
if (RSA_IS_PRESENT) {
|
||||
registry.registerIfAbsent(RsaProperties.class, context -> context.get(Binder.class)
|
||||
.bind(RsaProperties.PREFIX, RsaProperties.class).orElseGet(RsaProperties::new));
|
||||
registry.registerIfAbsent(RsaProperties.class,
|
||||
context -> context.get(Binder.class)
|
||||
.bind(RsaProperties.PREFIX, RsaProperties.class)
|
||||
.orElseGet(RsaProperties::new));
|
||||
}
|
||||
TextEncryptorUtils.register(registry);
|
||||
|
||||
|
||||
@@ -106,7 +106,8 @@ public class PropertySourceBootstrapConfiguration implements ApplicationListener
|
||||
@Override
|
||||
public void initialize(ConfigurableApplicationContext applicationContext) {
|
||||
if (!bootstrapProperties.isInitializeOnContextRefresh() || !applicationContext.getEnvironment()
|
||||
.getPropertySources().contains(BootstrapApplicationListener.BOOTSTRAP_PROPERTY_SOURCE_NAME)) {
|
||||
.getPropertySources()
|
||||
.contains(BootstrapApplicationListener.BOOTSTRAP_PROPERTY_SOURCE_NAME)) {
|
||||
doInitialize(applicationContext);
|
||||
}
|
||||
}
|
||||
@@ -151,8 +152,9 @@ public class PropertySourceBootstrapConfiguration implements ApplicationListener
|
||||
}
|
||||
|
||||
private void reinitializeLoggingSystem(ConfigurableEnvironment environment) {
|
||||
Map<String, Object> props = Binder.get(environment).bind("logging", Bindable.mapOf(String.class, Object.class))
|
||||
.orElseGet(Collections::emptyMap);
|
||||
Map<String, Object> props = Binder.get(environment)
|
||||
.bind("logging", Bindable.mapOf(String.class, Object.class))
|
||||
.orElseGet(Collections::emptyMap);
|
||||
if (!props.isEmpty()) {
|
||||
String logConfig = environment.resolvePlaceholders("${logging.config:}");
|
||||
LogFile logFile = LogFile.get(environment);
|
||||
@@ -240,7 +242,7 @@ public class PropertySourceBootstrapConfiguration implements ApplicationListener
|
||||
|
||||
private void handleProfiles(ConfigurableEnvironment environment) {
|
||||
if (bootstrapProperties.isInitializeOnContextRefresh() && !environment.getPropertySources()
|
||||
.contains(BootstrapApplicationListener.BOOTSTRAP_PROPERTY_SOURCE_NAME)) {
|
||||
.contains(BootstrapApplicationListener.BOOTSTRAP_PROPERTY_SOURCE_NAME)) {
|
||||
// In the case that spring.cloud.config.initialize-on-context-refresh is true
|
||||
// this method will
|
||||
// be called during the bootstrap phase and the main application startup. We
|
||||
@@ -268,7 +270,7 @@ public class PropertySourceBootstrapConfiguration implements ApplicationListener
|
||||
activeProfiles.add(0, profile);
|
||||
}
|
||||
List<String> activeProfilesFromEnvironment = Arrays.stream(environment.getActiveProfiles())
|
||||
.collect(Collectors.toList());
|
||||
.collect(Collectors.toList());
|
||||
if (!activeProfiles.containsAll(activeProfilesFromEnvironment)) {
|
||||
activeProfiles.addAll(activeProfilesFromEnvironment);
|
||||
|
||||
@@ -296,7 +298,7 @@ public class PropertySourceBootstrapConfiguration implements ApplicationListener
|
||||
String property, ConfigurableEnvironment environment) {
|
||||
if (propertySource instanceof CompositePropertySource) {
|
||||
for (PropertySource<?> nestedPropertySource : ((CompositePropertySource) propertySource)
|
||||
.getPropertySources()) {
|
||||
.getPropertySources()) {
|
||||
addProfilesTo(profiles, nestedPropertySource, property, environment);
|
||||
}
|
||||
}
|
||||
@@ -331,8 +333,9 @@ public class PropertySourceBootstrapConfiguration implements ApplicationListener
|
||||
public void onApplicationEvent(ContextRefreshedEvent event) {
|
||||
if (bootstrapProperties.isInitializeOnContextRefresh()
|
||||
&& event.getApplicationContext() instanceof ConfigurableApplicationContext) {
|
||||
if (((ConfigurableApplicationContext) event.getApplicationContext()).getEnvironment().getPropertySources()
|
||||
.contains(BootstrapApplicationListener.BOOTSTRAP_PROPERTY_SOURCE_NAME)) {
|
||||
if (((ConfigurableApplicationContext) event.getApplicationContext()).getEnvironment()
|
||||
.getPropertySources()
|
||||
.contains(BootstrapApplicationListener.BOOTSTRAP_PROPERTY_SOURCE_NAME)) {
|
||||
doInitialize((ConfigurableApplicationContext) event.getApplicationContext());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,9 +29,9 @@ class EncryptionRuntimeHints implements RuntimeHintsRegistrar {
|
||||
|
||||
@Override
|
||||
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
|
||||
hints.reflection().registerTypeIfPresent(classLoader,
|
||||
"org.springframework.security.rsa.crypto.RsaSecretEncryptor",
|
||||
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
|
||||
hints.reflection()
|
||||
.registerTypeIfPresent(classLoader, "org.springframework.security.rsa.crypto.RsaSecretEncryptor",
|
||||
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -81,7 +81,7 @@ public class EnvironmentDecryptApplicationInitializer extends AbstractEnvironmen
|
||||
if (!propertySources.contains(DECRYPTED_BOOTSTRAP_PROPERTY_SOURCE_NAME)) {
|
||||
// No reason to decrypt bootstrap twice
|
||||
PropertySource<?> bootstrap = propertySources
|
||||
.get(BootstrapApplicationListener.BOOTSTRAP_PROPERTY_SOURCE_NAME);
|
||||
.get(BootstrapApplicationListener.BOOTSTRAP_PROPERTY_SOURCE_NAME);
|
||||
if (bootstrap != null) {
|
||||
Map<String, Object> map = decrypt(bootstrap);
|
||||
if (!map.isEmpty()) {
|
||||
@@ -139,7 +139,7 @@ public class EnvironmentDecryptApplicationInitializer extends AbstractEnvironmen
|
||||
while (parent != null) {
|
||||
if (parent.getEnvironment() instanceof ConfigurableEnvironment) {
|
||||
((ConfigurableEnvironment) parent.getEnvironment()).getPropertySources()
|
||||
.remove(DECRYPTED_PROPERTY_SOURCE_NAME);
|
||||
.remove(DECRYPTED_PROPERTY_SOURCE_NAME);
|
||||
}
|
||||
parent = parent.getParent();
|
||||
}
|
||||
|
||||
@@ -55,12 +55,12 @@ public abstract class TextEncryptorUtils {
|
||||
static TextEncryptor getTextEncryptor(AbstractEnvironmentDecrypt decryptor, ConfigurableEnvironment environment) {
|
||||
Binder binder = Binder.get(environment);
|
||||
KeyProperties keyProperties = binder.bind(KeyProperties.PREFIX, KeyProperties.class)
|
||||
.orElseGet(KeyProperties::new);
|
||||
.orElseGet(KeyProperties::new);
|
||||
if (TextEncryptorUtils.keysConfigured(keyProperties)) {
|
||||
decryptor.setFailOnError(keyProperties.isFailOnError());
|
||||
if (ClassUtils.isPresent("org.springframework.security.rsa.crypto.RsaSecretEncryptor", null)) {
|
||||
RsaProperties rsaProperties = binder.bind(RsaProperties.PREFIX, RsaProperties.class)
|
||||
.orElseGet(RsaProperties::new);
|
||||
.orElseGet(RsaProperties::new);
|
||||
return TextEncryptorUtils.createTextEncryptor(keyProperties, rsaProperties);
|
||||
}
|
||||
return new EncryptorFactory(keyProperties.getSalt()).create(keyProperties.getKey());
|
||||
@@ -121,7 +121,8 @@ public abstract class TextEncryptorUtils {
|
||||
if (keyStore.getLocation().exists()) {
|
||||
return new RsaSecretEncryptor(
|
||||
new KeyStoreKeyFactory(keyStore.getLocation(), keyStore.getPassword().toCharArray(),
|
||||
keyStore.getType()).getKeyPair(keyStore.getAlias(), keyStore.getSecret().toCharArray()),
|
||||
keyStore.getType())
|
||||
.getKeyPair(keyStore.getAlias(), keyStore.getSecret().toCharArray()),
|
||||
rsaProperties.getAlgorithm(), rsaProperties.getSalt(), rsaProperties.isStrong());
|
||||
}
|
||||
|
||||
|
||||
@@ -180,8 +180,10 @@ public abstract class NamedContextFactory<C extends NamedContextFactory.Specific
|
||||
: new AnnotationConfigApplicationContext();
|
||||
}
|
||||
context.setClassLoader(classLoader);
|
||||
context.getEnvironment().getPropertySources().addFirst(
|
||||
new MapPropertySource(this.propertySourceName, Collections.singletonMap(this.propertyName, name)));
|
||||
context.getEnvironment()
|
||||
.getPropertySources()
|
||||
.addFirst(
|
||||
new MapPropertySource(this.propertySourceName, Collections.singletonMap(this.propertyName, name)));
|
||||
if (this.parent != null) {
|
||||
// Uses Environment from parent as well as beans
|
||||
context.setParent(this.parent);
|
||||
|
||||
@@ -57,7 +57,7 @@ public class ConfigurationPropertiesBeans implements BeanPostProcessor, Applicat
|
||||
this.beanFactory = (ConfigurableListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
|
||||
}
|
||||
if (applicationContext.getParent() != null && applicationContext.getParent()
|
||||
.getAutowireCapableBeanFactory() instanceof ConfigurableListableBeanFactory listable) {
|
||||
.getAutowireCapableBeanFactory() instanceof ConfigurableListableBeanFactory listable) {
|
||||
String[] names = listable.getBeanNamesForType(ConfigurationPropertiesBeans.class);
|
||||
if (names.length == 1) {
|
||||
this.parent = (ConfigurationPropertiesBeans) listable.getBean(names[0]);
|
||||
|
||||
@@ -153,7 +153,7 @@ public class ConfigurationPropertiesRebinder
|
||||
@ManagedAttribute
|
||||
public Set<String> getNeverRefreshable() {
|
||||
String neverRefresh = this.applicationContext.getEnvironment()
|
||||
.getProperty("spring.cloud.refresh.never-refreshable", "com.zaxxer.hikari.HikariDataSource");
|
||||
.getProperty("spring.cloud.refresh.never-refreshable", "com.zaxxer.hikari.HikariDataSource");
|
||||
return StringUtils.commaDelimitedListToSet(neverRefresh);
|
||||
}
|
||||
|
||||
|
||||
@@ -71,7 +71,7 @@ public class ConfigDataContextRefresher extends ContextRefresher
|
||||
}
|
||||
StandardEnvironment environment = copyEnvironment(getContext().getEnvironment());
|
||||
ConfigurableBootstrapContext bootstrapContext = getContext().getBeanProvider(ConfigurableBootstrapContext.class)
|
||||
.getIfAvailable(DefaultBootstrapContext::new);
|
||||
.getIfAvailable(DefaultBootstrapContext::new);
|
||||
|
||||
// run thru all EnvironmentPostProcessor instances. This lets things like vcap and
|
||||
// decrypt happen after refresh. The hard coded call to
|
||||
|
||||
@@ -70,11 +70,13 @@ public class LegacyContextRefresher extends ContextRefresher {
|
||||
environment.getPropertySources().addFirst(new MapPropertySource(REFRESH_ARGS_PROPERTY_SOURCE, map));
|
||||
|
||||
SpringApplicationBuilder builder = new SpringApplicationBuilder(Empty.class).bannerMode(Banner.Mode.OFF)
|
||||
.web(WebApplicationType.NONE).environment(environment);
|
||||
.web(WebApplicationType.NONE)
|
||||
.environment(environment);
|
||||
// Just the listeners that affect the environment (e.g. excluding logging
|
||||
// listener because it has side effects)
|
||||
builder.application().setListeners(
|
||||
Arrays.asList(new BootstrapApplicationListener(), new BootstrapConfigFileApplicationListener()));
|
||||
builder.application()
|
||||
.setListeners(Arrays.asList(new BootstrapApplicationListener(),
|
||||
new BootstrapConfigFileApplicationListener()));
|
||||
capture = builder.run();
|
||||
if (environment.getPropertySources().contains(REFRESH_ARGS_PROPERTY_SOURCE)) {
|
||||
environment.getPropertySources().remove(REFRESH_ARGS_PROPERTY_SOURCE);
|
||||
|
||||
@@ -92,8 +92,9 @@ public class RestartEndpoint implements ApplicationListener<ContextRefreshedWith
|
||||
this.args = this.event.getArgs();
|
||||
this.application = this.event.getSpringApplication();
|
||||
this.application.addInitializers(new PostProcessorInitializer());
|
||||
this.pauseHandlers = this.context.getBeanProvider(PauseHandler.class).orderedStream()
|
||||
.collect(Collectors.toList());
|
||||
this.pauseHandlers = this.context.getBeanProvider(PauseHandler.class)
|
||||
.orderedStream()
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -33,8 +33,9 @@ public final class EnvironmentUtils {
|
||||
}
|
||||
|
||||
public static Map<String, String> getSubProperties(Environment environment, String keyPrefix) {
|
||||
return Binder.get(environment).bind(keyPrefix, Bindable.mapOf(String.class, String.class))
|
||||
.orElseGet(Collections::emptyMap);
|
||||
return Binder.get(environment)
|
||||
.bind(keyPrefix, Bindable.mapOf(String.class, String.class))
|
||||
.orElseGet(Collections::emptyMap);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -64,8 +64,9 @@ public class LoggingRebinder implements ApplicationListener<EnvironmentChangeEve
|
||||
}
|
||||
|
||||
protected void setLogLevels(LoggingSystem system, Environment environment) {
|
||||
Map<String, String> levels = Binder.get(environment).bind("logging.level", STRING_STRING_MAP)
|
||||
.orElseGet(Collections::emptyMap);
|
||||
Map<String, String> levels = Binder.get(environment)
|
||||
.bind("logging.level", STRING_STRING_MAP)
|
||||
.orElseGet(Collections::emptyMap);
|
||||
for (Entry<String, String> entry : levels.entrySet()) {
|
||||
setLogLevel(system, environment, entry.getKey(), entry.getValue());
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ public class RefreshAutoConfigurationClassPathTests {
|
||||
public void refreshEventListenerCreated() {
|
||||
try (ConfigurableApplicationContext context = getApplicationContext(Config.class)) {
|
||||
then(context.getBeansOfType(RefreshEventListener.class)).as("RefreshEventListeners not created")
|
||||
.isNotEmpty();
|
||||
.isNotEmpty();
|
||||
then(context.containsBean("refreshEndpoint")).as("refreshEndpoint created").isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,9 +46,9 @@ public class RefreshAutoConfigurationMoreClassPathTests {
|
||||
try (ConfigurableApplicationContext context = getApplicationContext(Config.class, "debug=true")) {
|
||||
String output = outputCapture.toString();
|
||||
then(output)
|
||||
.doesNotContain("Failed to introspect annotations on "
|
||||
+ "[class org.springframework.cloud.autoconfigure.RefreshEndpointAutoConfiguration")
|
||||
.doesNotContain("TypeNotPresentExceptionProxy");
|
||||
.doesNotContain("Failed to introspect annotations on "
|
||||
+ "[class org.springframework.cloud.autoconfigure.RefreshEndpointAutoConfiguration")
|
||||
.doesNotContain("TypeNotPresentExceptionProxy");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -47,8 +47,10 @@ class RefreshAutoConfigurationTests {
|
||||
|
||||
private static ConfigurableApplicationContext getApplicationContext(WebApplicationType type, Class<?> configuration,
|
||||
String... properties) {
|
||||
return new SpringApplicationBuilder(configuration).web(type).properties(properties).properties("server.port=0")
|
||||
.run();
|
||||
return new SpringApplicationBuilder(configuration).web(type)
|
||||
.properties(properties)
|
||||
.properties("server.port=0")
|
||||
.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -100,14 +102,14 @@ class RefreshAutoConfigurationTests {
|
||||
@Test
|
||||
void refreshScopeLifecylePresentByDefault() {
|
||||
new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(RefreshAutoConfiguration.class))
|
||||
.run(context -> assertThat(context).hasBean("refreshScopeLifecycle"));
|
||||
.run(context -> assertThat(context).hasBean("refreshScopeLifecycle"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void refreshScopeLifecyleDisabledWithProp() {
|
||||
new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(RefreshAutoConfiguration.class))
|
||||
.withPropertyValues("spring.cloud.refresh.on-restart.enabled=false")
|
||||
.run(context -> assertThat(context).doesNotHaveBean("refreshScopeLifecycle"));
|
||||
.withPropertyValues("spring.cloud.refresh.on-restart.enabled=false")
|
||||
.run(context -> assertThat(context).doesNotHaveBean("refreshScopeLifecycle"));
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
|
||||
@@ -39,7 +39,7 @@ public class BootstrapOrderingAutoConfigurationIntegrationTests {
|
||||
@Test
|
||||
public void bootstrapPropertiesExist() {
|
||||
then(this.environment.getPropertySources().contains("applicationConfig: [classpath:/bootstrap.properties]"))
|
||||
.isTrue();
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -48,7 +48,7 @@ public class BootstrapOrderingCustomPropertySourceIntegrationTests {
|
||||
@Test
|
||||
public void bootstrapPropertiesExist() {
|
||||
then(this.environment.getPropertySources().contains("applicationConfig: [classpath:/custom.properties]"))
|
||||
.isTrue();
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -33,7 +33,7 @@ public class BootstrapSourcesOrderingTests {
|
||||
public void sourcesAreOrderedCorrectly() {
|
||||
Class<?> firstConstructedClass = firstToBeCreated.get();
|
||||
then(firstConstructedClass).as("bootstrap sources not ordered correctly")
|
||||
.isEqualTo(TestHigherPriorityBootstrapConfiguration.class);
|
||||
.isEqualTo(TestHigherPriorityBootstrapConfiguration.class);
|
||||
}
|
||||
|
||||
@EnableAutoConfiguration
|
||||
|
||||
@@ -62,8 +62,9 @@ public class TestBootstrapConfiguration {
|
||||
public ApplicationContextInitializer<ConfigurableApplicationContext> customInitializer() {
|
||||
return applicationContext -> {
|
||||
ConfigurableEnvironment environment = applicationContext.getEnvironment();
|
||||
environment.getPropertySources().addLast(new MapPropertySource("customProperties", Collections
|
||||
.singletonMap("custom.foo", environment.resolvePlaceholders("${spring.application.name:bar}"))));
|
||||
environment.getPropertySources()
|
||||
.addLast(new MapPropertySource("customProperties", Collections.singletonMap("custom.foo",
|
||||
environment.resolvePlaceholders("${spring.application.name:bar}"))));
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -90,13 +90,15 @@ public class BootstrapConfigurationTests {
|
||||
}
|
||||
|
||||
private void pickupOnlyExternalBootstrapProperties(String... properties) {
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE).sources(BareConfiguration.class)
|
||||
.properties(properties).run();
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
|
||||
.sources(BareConfiguration.class)
|
||||
.properties(properties)
|
||||
.run();
|
||||
then(this.context.getEnvironment().getProperty("info.name")).isEqualTo("externalPropertiesInfoName");
|
||||
then(this.context.getEnvironment().getProperty("info.desc")).isNull();
|
||||
then(this.context.getEnvironment().getPropertySources()
|
||||
.contains(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME + "-testBootstrap"))
|
||||
.isTrue();
|
||||
then(this.context.getEnvironment()
|
||||
.getPropertySources()
|
||||
.contains(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME + "-testBootstrap")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -116,13 +118,15 @@ public class BootstrapConfigurationTests {
|
||||
}
|
||||
|
||||
private void pickupAdditionalExternalBootstrapProperties(String... properties) {
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE).sources(BareConfiguration.class)
|
||||
.properties(properties).run();
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
|
||||
.sources(BareConfiguration.class)
|
||||
.properties(properties)
|
||||
.run();
|
||||
then(this.context.getEnvironment().getProperty("info.name")).isEqualTo("externalPropertiesInfoName");
|
||||
then(this.context.getEnvironment().getProperty("info.desc")).isEqualTo("defaultPropertiesInfoDesc");
|
||||
then(this.context.getEnvironment().getPropertySources()
|
||||
.contains(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME + "-testBootstrap"))
|
||||
.isTrue();
|
||||
then(this.context.getEnvironment()
|
||||
.getPropertySources()
|
||||
.contains(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME + "-testBootstrap")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -137,14 +141,17 @@ public class BootstrapConfigurationTests {
|
||||
}
|
||||
|
||||
private void bootstrapPropertiesAvailableInInitializer(String... properties) {
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE).properties(properties)
|
||||
.sources(BareConfiguration.class).initializers(applicationContext -> {
|
||||
// This property is defined in bootstrap.properties
|
||||
then(applicationContext.getEnvironment().getProperty("info.name")).isEqualTo("child");
|
||||
}).run();
|
||||
then(this.context.getEnvironment().getPropertySources()
|
||||
.contains(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME + "-testBootstrap"))
|
||||
.isTrue();
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
|
||||
.properties(properties)
|
||||
.sources(BareConfiguration.class)
|
||||
.initializers(applicationContext -> {
|
||||
// This property is defined in bootstrap.properties
|
||||
then(applicationContext.getEnvironment().getProperty("info.name")).isEqualTo("child");
|
||||
})
|
||||
.run();
|
||||
then(this.context.getEnvironment()
|
||||
.getPropertySources()
|
||||
.contains(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME + "-testBootstrap")).isTrue();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -170,12 +177,14 @@ public class BootstrapConfigurationTests {
|
||||
|
||||
private void picksUpAdditionalPropertySource(String... properties) {
|
||||
PropertySourceConfiguration.MAP.put("bootstrap.foo", "bar");
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE).properties(properties)
|
||||
.sources(BareConfiguration.class).run();
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
|
||||
.properties(properties)
|
||||
.sources(BareConfiguration.class)
|
||||
.run();
|
||||
then(this.context.getEnvironment().getProperty("bootstrap.foo")).isEqualTo("bar");
|
||||
then(this.context.getEnvironment().getPropertySources()
|
||||
.contains(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME + "-testBootstrap"))
|
||||
.isTrue();
|
||||
then(this.context.getEnvironment()
|
||||
.getPropertySources()
|
||||
.contains(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME + "-testBootstrap")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -192,8 +201,10 @@ public class BootstrapConfigurationTests {
|
||||
private void failsOnPropertySource(String... properties) {
|
||||
System.setProperty("expected.fail", "true");
|
||||
Throwable throwable = Assertions.assertThrows(RuntimeException.class, () -> {
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE).properties(properties)
|
||||
.sources(BareConfiguration.class).run();
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
|
||||
.properties(properties)
|
||||
.sources(BareConfiguration.class)
|
||||
.run();
|
||||
});
|
||||
then(throwable.getMessage().equals("Planned"));
|
||||
}
|
||||
@@ -214,8 +225,10 @@ public class BootstrapConfigurationTests {
|
||||
private void overrideSystemPropertySourceByDefault(String... properties) {
|
||||
PropertySourceConfiguration.MAP.put("bootstrap.foo", "bar");
|
||||
System.setProperty("bootstrap.foo", "system");
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE).properties(properties)
|
||||
.sources(BareConfiguration.class).run();
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
|
||||
.properties(properties)
|
||||
.sources(BareConfiguration.class)
|
||||
.run();
|
||||
then(this.context.getEnvironment().getProperty("bootstrap.foo")).isEqualTo("bar");
|
||||
}
|
||||
|
||||
@@ -234,8 +247,10 @@ public class BootstrapConfigurationTests {
|
||||
PropertySourceConfiguration.MAP.put("bootstrap.foo", "bar");
|
||||
PropertySourceConfiguration.MAP.put("spring.cloud.config.overrideSystemProperties", "false");
|
||||
System.setProperty("bootstrap.foo", "system");
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE).properties(properties)
|
||||
.sources(BareConfiguration.class).run();
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
|
||||
.properties(properties)
|
||||
.sources(BareConfiguration.class)
|
||||
.run();
|
||||
then(this.context.getEnvironment().getProperty("bootstrap.foo")).isEqualTo("system");
|
||||
}
|
||||
|
||||
@@ -258,8 +273,10 @@ public class BootstrapConfigurationTests {
|
||||
// their own remote property source.
|
||||
PropertySourceConfiguration.MAP.put("spring.cloud.config.allowOverride", "false");
|
||||
System.setProperty("bootstrap.foo", "system");
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE).properties(properties)
|
||||
.sources(BareConfiguration.class).run();
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
|
||||
.properties(properties)
|
||||
.sources(BareConfiguration.class)
|
||||
.run();
|
||||
then(this.context.getEnvironment().getProperty("bootstrap.foo")).isEqualTo("bar");
|
||||
}
|
||||
|
||||
@@ -279,8 +296,10 @@ public class BootstrapConfigurationTests {
|
||||
PropertySourceConfiguration.MAP.put("spring.cloud.config.overrideSystemProperties", "false");
|
||||
PropertySourceConfiguration.MAP.put("spring.cloud.config.allowOverride", "true");
|
||||
System.setProperty("bootstrap.foo", "system");
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE).properties(properties)
|
||||
.sources(BareConfiguration.class).run();
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
|
||||
.properties(properties)
|
||||
.sources(BareConfiguration.class)
|
||||
.run();
|
||||
then(this.context.getEnvironment().getProperty("bootstrap.foo")).isEqualTo("system");
|
||||
}
|
||||
|
||||
@@ -300,10 +319,13 @@ public class BootstrapConfigurationTests {
|
||||
PropertySourceConfiguration.MAP.put("spring.cloud.config.overrideNone", "true");
|
||||
PropertySourceConfiguration.MAP.put("spring.cloud.config.allowOverride", "true");
|
||||
ConfigurableEnvironment environment = new StandardEnvironment();
|
||||
environment.getPropertySources().addLast(
|
||||
new MapPropertySource("last", Collections.<String, Object>singletonMap("bootstrap.foo", "splat")));
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE).properties(properties)
|
||||
.environment(environment).sources(BareConfiguration.class).run();
|
||||
environment.getPropertySources()
|
||||
.addLast(new MapPropertySource("last", Collections.<String, Object>singletonMap("bootstrap.foo", "splat")));
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
|
||||
.properties(properties)
|
||||
.environment(environment)
|
||||
.sources(BareConfiguration.class)
|
||||
.run();
|
||||
then(this.context.getEnvironment().getProperty("bootstrap.foo")).isEqualTo("splat");
|
||||
}
|
||||
|
||||
@@ -322,15 +344,17 @@ public class BootstrapConfigurationTests {
|
||||
|
||||
private void applicationNameInBootstrapAndMain(String... properties) {
|
||||
System.setProperty("expected.name", "main");
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE).properties(properties)
|
||||
.sources(BareConfiguration.class).run();
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
|
||||
.properties(properties)
|
||||
.sources(BareConfiguration.class)
|
||||
.run();
|
||||
then(this.context.getEnvironment().getProperty("spring.application.name")).isEqualTo("app");
|
||||
// The parent is called "main" because spring.application.name is specified in
|
||||
// other.properties (the bootstrap properties)
|
||||
then(this.context.getParent().getEnvironment().getProperty("spring.application.name")).isEqualTo("main");
|
||||
// The bootstrap context has the same "bootstrap" property source
|
||||
then(((ConfigurableEnvironment) this.context.getParent().getEnvironment()).getPropertySources()
|
||||
.get("bootstrap")).isEqualTo(this.context.getEnvironment().getPropertySources().get("bootstrap"));
|
||||
.get("bootstrap")).isEqualTo(this.context.getEnvironment().getPropertySources().get("bootstrap"));
|
||||
then(this.context.getId()).isEqualTo("main-1");
|
||||
}
|
||||
|
||||
@@ -349,8 +373,10 @@ public class BootstrapConfigurationTests {
|
||||
|
||||
private void applicationNameNotInBootstrap(String... properties) {
|
||||
System.setProperty("expected.name", "main");
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE).properties(properties)
|
||||
.sources(BareConfiguration.class).run();
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
|
||||
.properties(properties)
|
||||
.sources(BareConfiguration.class)
|
||||
.run();
|
||||
then(this.context.getEnvironment().getProperty("spring.application.name")).isEqualTo("main");
|
||||
// The parent has no name because spring.application.name is not
|
||||
// defined in the bootstrap properties
|
||||
@@ -370,8 +396,10 @@ public class BootstrapConfigurationTests {
|
||||
|
||||
private void applicationNameOnlyInBootstrap(String... properties) {
|
||||
System.setProperty("expected.name", "main");
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE).properties(properties)
|
||||
.sources(BareConfiguration.class).run();
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
|
||||
.properties(properties)
|
||||
.sources(BareConfiguration.class)
|
||||
.run();
|
||||
// The main context is called "main" because spring.application.name is specified
|
||||
// in other.properties (and not in the main config file)
|
||||
then(this.context.getEnvironment().getProperty("spring.application.name")).isEqualTo("main");
|
||||
@@ -394,14 +422,17 @@ public class BootstrapConfigurationTests {
|
||||
|
||||
private void environmentEnrichedOnceWhenSharedWithChildContext(String... properties) {
|
||||
PropertySourceConfiguration.MAP.put("bootstrap.foo", "bar");
|
||||
this.context = new SpringApplicationBuilder().sources(BareConfiguration.class).properties(properties)
|
||||
.environment(new StandardEnvironment()).child(BareConfiguration.class).web(WebApplicationType.NONE)
|
||||
.run();
|
||||
this.context = new SpringApplicationBuilder().sources(BareConfiguration.class)
|
||||
.properties(properties)
|
||||
.environment(new StandardEnvironment())
|
||||
.child(BareConfiguration.class)
|
||||
.web(WebApplicationType.NONE)
|
||||
.run();
|
||||
then(this.context.getEnvironment().getProperty("bootstrap.foo")).isEqualTo("bar");
|
||||
then(this.context.getParent().getEnvironment()).isEqualTo(this.context.getEnvironment());
|
||||
MutablePropertySources sources = this.context.getEnvironment().getPropertySources();
|
||||
PropertySource<?> bootstrap = sources
|
||||
.get(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME + "-testBootstrap");
|
||||
.get(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME + "-testBootstrap");
|
||||
then(bootstrap).isNotNull();
|
||||
then(sources.precedenceOf(bootstrap)).isEqualTo(0);
|
||||
}
|
||||
@@ -420,8 +451,11 @@ public class BootstrapConfigurationTests {
|
||||
private void onlyOneBootstrapContext(String... properties) {
|
||||
TestHigherPriorityBootstrapConfiguration.count.set(0);
|
||||
PropertySourceConfiguration.MAP.put("bootstrap.foo", "bar");
|
||||
this.context = new SpringApplicationBuilder().sources(BareConfiguration.class).properties(properties)
|
||||
.child(BareConfiguration.class).web(WebApplicationType.NONE).run();
|
||||
this.context = new SpringApplicationBuilder().sources(BareConfiguration.class)
|
||||
.properties(properties)
|
||||
.child(BareConfiguration.class)
|
||||
.web(WebApplicationType.NONE)
|
||||
.run();
|
||||
then(TestHigherPriorityBootstrapConfiguration.count.get()).isEqualTo(1);
|
||||
then(this.context.getParent()).isNotNull();
|
||||
then(this.context.getParent().getParent().getId()).isEqualTo("bootstrap");
|
||||
@@ -441,8 +475,11 @@ public class BootstrapConfigurationTests {
|
||||
}
|
||||
|
||||
private void listOverride(String... properties) {
|
||||
this.context = new SpringApplicationBuilder().sources(BareConfiguration.class).properties(properties)
|
||||
.child(BareConfiguration.class).web(WebApplicationType.NONE).run();
|
||||
this.context = new SpringApplicationBuilder().sources(BareConfiguration.class)
|
||||
.properties(properties)
|
||||
.child(BareConfiguration.class)
|
||||
.web(WebApplicationType.NONE)
|
||||
.run();
|
||||
ListProperties listProperties = new ListProperties();
|
||||
Binder.get(this.context.getEnvironment()).bind("list", Bindable.ofInstance(listProperties));
|
||||
then(listProperties.getFoo().size()).isEqualTo(1);
|
||||
@@ -464,11 +501,15 @@ public class BootstrapConfigurationTests {
|
||||
TestHigherPriorityBootstrapConfiguration.count.set(0);
|
||||
PropertySourceConfiguration.MAP.put("bootstrap.foo", "bar");
|
||||
SpringApplicationBuilder builder = new SpringApplicationBuilder().properties(properties)
|
||||
.sources(BareConfiguration.class);
|
||||
this.sibling = builder.child(BareConfiguration.class).properties("spring.application.name=sibling")
|
||||
.web(WebApplicationType.NONE).run();
|
||||
this.context = builder.child(BareConfiguration.class).properties("spring.application.name=context")
|
||||
.web(WebApplicationType.NONE).run();
|
||||
.sources(BareConfiguration.class);
|
||||
this.sibling = builder.child(BareConfiguration.class)
|
||||
.properties("spring.application.name=sibling")
|
||||
.web(WebApplicationType.NONE)
|
||||
.run();
|
||||
this.context = builder.child(BareConfiguration.class)
|
||||
.properties("spring.application.name=context")
|
||||
.web(WebApplicationType.NONE)
|
||||
.run();
|
||||
then(TestHigherPriorityBootstrapConfiguration.count.get()).isEqualTo(1);
|
||||
then(this.context.getParent()).isNotNull();
|
||||
then(this.context.getParent().getParent().getId()).isEqualTo("bootstrap");
|
||||
@@ -495,16 +536,18 @@ public class BootstrapConfigurationTests {
|
||||
|
||||
private void environmentEnrichedInParentContext(String... properties) {
|
||||
PropertySourceConfiguration.MAP.put("bootstrap.foo", "bar");
|
||||
this.context = new SpringApplicationBuilder().sources(BareConfiguration.class).properties(properties)
|
||||
.child(BareConfiguration.class).web(WebApplicationType.NONE).run();
|
||||
this.context = new SpringApplicationBuilder().sources(BareConfiguration.class)
|
||||
.properties(properties)
|
||||
.child(BareConfiguration.class)
|
||||
.web(WebApplicationType.NONE)
|
||||
.run();
|
||||
then(this.context.getEnvironment().getProperty("bootstrap.foo")).isEqualTo("bar");
|
||||
then(this.context.getParent().getEnvironment()).isNotSameAs(this.context.getEnvironment());
|
||||
then(this.context.getEnvironment().getPropertySources()
|
||||
.contains(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME + "-testBootstrap"))
|
||||
.isTrue();
|
||||
then(this.context.getEnvironment()
|
||||
.getPropertySources()
|
||||
.contains(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME + "-testBootstrap")).isTrue();
|
||||
then(((ConfigurableEnvironment) this.context.getParent().getEnvironment()).getPropertySources()
|
||||
.contains(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME + "-testBootstrap"))
|
||||
.isTrue();
|
||||
.contains(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME + "-testBootstrap")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -513,10 +556,15 @@ public class BootstrapConfigurationTests {
|
||||
PropertySourceConfiguration.MAP.put("bootstrap.foo", "bar");
|
||||
// Profiles are always merged with the child
|
||||
ConfigurableApplicationContext parent = new SpringApplicationBuilder().sources(BareConfiguration.class)
|
||||
.profiles("parent").web(WebApplicationType.NONE).run();
|
||||
.profiles("parent")
|
||||
.web(WebApplicationType.NONE)
|
||||
.run();
|
||||
this.context = new SpringApplicationBuilder(BareConfiguration.class)
|
||||
.properties("spring.config.use-legacy-processing=true").profiles("child").parent(parent)
|
||||
.web(WebApplicationType.NONE).run();
|
||||
.properties("spring.config.use-legacy-processing=true")
|
||||
.profiles("child")
|
||||
.parent(parent)
|
||||
.web(WebApplicationType.NONE)
|
||||
.run();
|
||||
then(this.context.getParent().getEnvironment()).isNotSameAs(this.context.getEnvironment());
|
||||
// The ApplicationContext merges profiles (profiles and property sources), see
|
||||
// AbstractEnvironment.merge()
|
||||
@@ -525,8 +573,7 @@ public class BootstrapConfigurationTests {
|
||||
then(this.context.getParent().getEnvironment().acceptsProfiles("child")).isFalse();
|
||||
then(this.context.getParent().getEnvironment().acceptsProfiles("parent")).isTrue();
|
||||
then(((ConfigurableEnvironment) this.context.getParent().getEnvironment()).getPropertySources()
|
||||
.contains(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME + "-testBootstrap"))
|
||||
.isTrue();
|
||||
.contains(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME + "-testBootstrap")).isTrue();
|
||||
then(this.context.getEnvironment().getProperty("bootstrap.foo")).isEqualTo("bar");
|
||||
// The "bootstrap" property source is not shared now, but it has the same
|
||||
// properties in it because they are pulled from the PropertySourceConfiguration
|
||||
@@ -550,8 +597,11 @@ public class BootstrapConfigurationTests {
|
||||
|
||||
private void includeProfileFromBootstrapPropertySource(String... properties) {
|
||||
PropertySourceConfiguration.MAP.put("spring.profiles.include", "bar,baz");
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE).properties(properties)
|
||||
.profiles("foo").sources(BareConfiguration.class).run();
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
|
||||
.properties(properties)
|
||||
.profiles("foo")
|
||||
.sources(BareConfiguration.class)
|
||||
.run();
|
||||
then(this.context.getEnvironment().acceptsProfiles("baz")).isTrue();
|
||||
then(this.context.getEnvironment().acceptsProfiles("bar")).isTrue();
|
||||
}
|
||||
@@ -572,8 +622,11 @@ public class BootstrapConfigurationTests {
|
||||
|
||||
private void activeProfileFromBootstrapPropertySource(String... properties) {
|
||||
PropertySourceConfiguration.MAP.put("spring.profiles.active", "bar,baz");
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE).properties(properties)
|
||||
.profiles("foo").sources(BareConfiguration.class).run();
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
|
||||
.properties(properties)
|
||||
.profiles("foo")
|
||||
.sources(BareConfiguration.class)
|
||||
.run();
|
||||
then(this.context.getEnvironment().acceptsProfiles("baz", "bar", "foo")).isTrue();
|
||||
|
||||
}
|
||||
@@ -592,8 +645,11 @@ public class BootstrapConfigurationTests {
|
||||
private void activeAndIncludeProfileFromBootstrapPropertySource(String... properties) {
|
||||
PropertySourceConfiguration.MAP.put("spring.profiles.active", "bar,baz");
|
||||
PropertySourceConfiguration.MAP.put("spring.profiles.include", "bar,baz,hello");
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE).properties(properties)
|
||||
.profiles("foo").sources(BareConfiguration.class).run();
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
|
||||
.properties(properties)
|
||||
.profiles("foo")
|
||||
.sources(BareConfiguration.class)
|
||||
.run();
|
||||
then(this.context.getEnvironment().acceptsProfiles("baz", "bar", "hello", "foo")).isTrue();
|
||||
then(this.context.getEnvironment().getActiveProfiles()).contains("baz", "bar", "foo", "hello");
|
||||
}
|
||||
@@ -613,8 +669,11 @@ public class BootstrapConfigurationTests {
|
||||
private void activeAndIncludeProfileFromBootstrapPropertySourceWithReplacement(String... properties) {
|
||||
PropertySourceConfiguration.MAP.put("spring.profiles.active", "${barreplacement},baz");
|
||||
PropertySourceConfiguration.MAP.put("spring.profiles.include", "${barreplacement},baz,hello");
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE).properties(properties)
|
||||
.profiles("foo").sources(BareConfiguration.class).run();
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
|
||||
.properties(properties)
|
||||
.profiles("foo")
|
||||
.sources(BareConfiguration.class)
|
||||
.run();
|
||||
then(this.context.getEnvironment().acceptsProfiles("baz", "bar", "hello", "foo")).isTrue();
|
||||
then(this.context.getEnvironment().getActiveProfiles()).contains("baz", "bar", "foo", "hello");
|
||||
}
|
||||
@@ -632,8 +691,10 @@ public class BootstrapConfigurationTests {
|
||||
}
|
||||
|
||||
private void includeProfileFromBootstrapProperties(String... properties) {
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE).sources(BareConfiguration.class)
|
||||
.properties(properties).run();
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
|
||||
.sources(BareConfiguration.class)
|
||||
.properties(properties)
|
||||
.run();
|
||||
then(this.context.getEnvironment().acceptsProfiles("local")).isTrue();
|
||||
then(this.context.getEnvironment().getProperty("added")).isEqualTo("Hello added!");
|
||||
}
|
||||
@@ -651,16 +712,20 @@ public class BootstrapConfigurationTests {
|
||||
}
|
||||
|
||||
private void nonEnumerablePropertySourceWorks(String... properties) {
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE).sources(BareConfiguration.class)
|
||||
.properties(properties).run();
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
|
||||
.sources(BareConfiguration.class)
|
||||
.properties(properties)
|
||||
.run();
|
||||
then(this.context.getEnvironment().getProperty("foo")).isEqualTo("bar");
|
||||
}
|
||||
|
||||
@Test
|
||||
void activeAndIncludeProfileFromBootstrapPropertySource_WhenMultiplePlacesHaveActiveProfileProperties_ShouldOnlyAcceptTheTopPriority() {
|
||||
String[] properties = new String[] { "spring.config.use-legacy-processing=true" };
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE).properties(properties)
|
||||
.sources(BareConfiguration.class).run("--spring.profiles.active=prod,secure");
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
|
||||
.properties(properties)
|
||||
.sources(BareConfiguration.class)
|
||||
.run("--spring.profiles.active=prod,secure");
|
||||
then(this.context.getEnvironment().acceptsProfiles("prod", "secure")).isTrue();
|
||||
// active profile from property sources with lower priority should not be included
|
||||
then(this.context.getEnvironment().acceptsProfiles("local")).isFalse();
|
||||
@@ -668,9 +733,11 @@ public class BootstrapConfigurationTests {
|
||||
then(this.context.getEnvironment().getActiveProfiles()).doesNotContain("local");
|
||||
// check if active profile value could possibly exist in other property sources
|
||||
// with lower priority
|
||||
then(this.context.getEnvironment().getPropertySources().stream()
|
||||
.map(p -> p.getProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME)).anyMatch("local"::equals))
|
||||
.isTrue();
|
||||
then(this.context.getEnvironment()
|
||||
.getPropertySources()
|
||||
.stream()
|
||||
.map(p -> p.getProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME))
|
||||
.anyMatch("local"::equals)).isTrue();
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@@ -711,7 +778,7 @@ public class BootstrapConfigurationTests {
|
||||
public PropertySource<?> locate(Environment environment) {
|
||||
if (environment instanceof ConfigurableEnvironment) {
|
||||
if (!((ConfigurableEnvironment) environment).getPropertySources()
|
||||
.contains(BootstrapApplicationListener.BOOTSTRAP_PROPERTY_SOURCE_NAME)) {
|
||||
.contains(BootstrapApplicationListener.BOOTSTRAP_PROPERTY_SOURCE_NAME)) {
|
||||
if (MAP.containsKey(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME)) {
|
||||
// This additional profile, after, should not be added when
|
||||
// initialize-on-context-refresh=true
|
||||
|
||||
@@ -37,7 +37,10 @@ public class BootstrapListenerHierarchyIntegrationTests {
|
||||
@Test
|
||||
public void shouldAddInABootstrapContext() {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder()
|
||||
.properties("spring.cloud.bootstrap.enabled=true").sources(BasicConfiguration.class).web(NONE).run();
|
||||
.properties("spring.cloud.bootstrap.enabled=true")
|
||||
.sources(BasicConfiguration.class)
|
||||
.web(NONE)
|
||||
.run();
|
||||
|
||||
then(context.getParent()).isNotNull();
|
||||
}
|
||||
@@ -45,8 +48,12 @@ public class BootstrapListenerHierarchyIntegrationTests {
|
||||
@Test
|
||||
public void shouldAddInOneBootstrapForABasicParentChildHierarchy() {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder()
|
||||
.properties("spring.cloud.bootstrap.enabled=true").sources(RootConfiguration.class).web(NONE)
|
||||
.child(BasicConfiguration.class).web(NONE).run();
|
||||
.properties("spring.cloud.bootstrap.enabled=true")
|
||||
.sources(RootConfiguration.class)
|
||||
.web(NONE)
|
||||
.child(BasicConfiguration.class)
|
||||
.web(NONE)
|
||||
.run();
|
||||
|
||||
// Should be RootConfiguration based context
|
||||
ConfigurableApplicationContext parent = (ConfigurableApplicationContext) context.getParent();
|
||||
@@ -64,8 +71,14 @@ public class BootstrapListenerHierarchyIntegrationTests {
|
||||
@Test
|
||||
public void shouldAddInOneBootstrapForSiblingsBasedHierarchy() {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder()
|
||||
.properties("spring.cloud.bootstrap.enabled=true").sources(RootConfiguration.class).web(NONE)
|
||||
.child(BasicConfiguration.class).web(NONE).sibling(BasicConfiguration.class).web(NONE).run();
|
||||
.properties("spring.cloud.bootstrap.enabled=true")
|
||||
.sources(RootConfiguration.class)
|
||||
.web(NONE)
|
||||
.child(BasicConfiguration.class)
|
||||
.web(NONE)
|
||||
.sibling(BasicConfiguration.class)
|
||||
.web(NONE)
|
||||
.run();
|
||||
|
||||
// Should be RootConfiguration based context
|
||||
ConfigurableApplicationContext parent = (ConfigurableApplicationContext) context.getParent();
|
||||
|
||||
@@ -31,7 +31,9 @@ public class EncryptionBootstrapConfigurationTests {
|
||||
@Test
|
||||
public void symmetric() {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder(EncryptionBootstrapConfiguration.class)
|
||||
.web(WebApplicationType.NONE).properties("encrypt.key:pie").run();
|
||||
.web(WebApplicationType.NONE)
|
||||
.properties("encrypt.key:pie")
|
||||
.run();
|
||||
TextEncryptor encryptor = context.getBean(TextEncryptor.class);
|
||||
then(encryptor.decrypt(encryptor.encrypt("foo"))).isEqualTo("foo");
|
||||
context.close();
|
||||
@@ -40,10 +42,10 @@ public class EncryptionBootstrapConfigurationTests {
|
||||
@Test
|
||||
public void rsaKeyStore() {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder(EncryptionBootstrapConfiguration.class)
|
||||
.web(WebApplicationType.NONE)
|
||||
.properties("encrypt.keyStore.location:classpath:/server.jks", "encrypt.keyStore.password:letmein",
|
||||
"encrypt.keyStore.alias:mytestkey", "encrypt.keyStore.secret:changeme")
|
||||
.run();
|
||||
.web(WebApplicationType.NONE)
|
||||
.properties("encrypt.keyStore.location:classpath:/server.jks", "encrypt.keyStore.password:letmein",
|
||||
"encrypt.keyStore.alias:mytestkey", "encrypt.keyStore.secret:changeme")
|
||||
.run();
|
||||
TextEncryptor encryptor = context.getBean(TextEncryptor.class);
|
||||
then(encryptor.decrypt(encryptor.encrypt("foo"))).isEqualTo("foo");
|
||||
context.close();
|
||||
@@ -52,10 +54,10 @@ public class EncryptionBootstrapConfigurationTests {
|
||||
@Test
|
||||
public void rsaPkcs12KeyStore() {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder(EncryptionBootstrapConfiguration.class)
|
||||
.web(WebApplicationType.NONE)
|
||||
.properties("encrypt.keyStore.location:classpath:/server.p12", "encrypt.keyStore.password:letmein",
|
||||
"encrypt.keyStore.alias:mytestkey", "encrypt.keyStore.type:PKCS12")
|
||||
.run();
|
||||
.web(WebApplicationType.NONE)
|
||||
.properties("encrypt.keyStore.location:classpath:/server.p12", "encrypt.keyStore.password:letmein",
|
||||
"encrypt.keyStore.alias:mytestkey", "encrypt.keyStore.type:PKCS12")
|
||||
.run();
|
||||
TextEncryptor encryptor = context.getBean(TextEncryptor.class);
|
||||
then(encryptor.decrypt(encryptor.encrypt("foo"))).isEqualTo("foo");
|
||||
context.close();
|
||||
@@ -64,10 +66,10 @@ public class EncryptionBootstrapConfigurationTests {
|
||||
@Test
|
||||
public void rsaKeyStoreWithRelaxedProperties() {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder(EncryptionBootstrapConfiguration.class)
|
||||
.web(WebApplicationType.NONE)
|
||||
.properties("encrypt.key-store.location:classpath:/server.jks", "encrypt.key-store.password:letmein",
|
||||
"encrypt.key-store.alias:mytestkey", "encrypt.key-store.secret:changeme")
|
||||
.run();
|
||||
.web(WebApplicationType.NONE)
|
||||
.properties("encrypt.key-store.location:classpath:/server.jks", "encrypt.key-store.password:letmein",
|
||||
"encrypt.key-store.alias:mytestkey", "encrypt.key-store.secret:changeme")
|
||||
.run();
|
||||
TextEncryptor encryptor = context.getBean(TextEncryptor.class);
|
||||
then(encryptor.decrypt(encryptor.encrypt("foo"))).isEqualTo("foo");
|
||||
context.close();
|
||||
@@ -76,11 +78,11 @@ public class EncryptionBootstrapConfigurationTests {
|
||||
@Test
|
||||
public void rsaProperties() {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder(EncryptionBootstrapConfiguration.class)
|
||||
.web(WebApplicationType.NONE)
|
||||
.properties("encrypt.key-store.location:classpath:/server.jks", "encrypt.key-store.password:letmein",
|
||||
"encrypt.key-store.alias:mytestkey", "encrypt.key-store.secret:changeme",
|
||||
"encrypt.rsa.strong:true", "encrypt.rsa.salt:foobar")
|
||||
.run();
|
||||
.web(WebApplicationType.NONE)
|
||||
.properties("encrypt.key-store.location:classpath:/server.jks", "encrypt.key-store.password:letmein",
|
||||
"encrypt.key-store.alias:mytestkey", "encrypt.key-store.secret:changeme", "encrypt.rsa.strong:true",
|
||||
"encrypt.rsa.salt:foobar")
|
||||
.run();
|
||||
RsaProperties properties = context.getBean(RsaProperties.class);
|
||||
then(properties.getSalt()).isEqualTo("foobar");
|
||||
then(properties.isStrong()).isTrue();
|
||||
@@ -92,10 +94,9 @@ public class EncryptionBootstrapConfigurationTests {
|
||||
public void nonExistentKeystoreLocationShouldNotBeAllowed() {
|
||||
try {
|
||||
new SpringApplicationBuilder(EncryptionBootstrapConfiguration.class).web(WebApplicationType.NONE)
|
||||
.properties("encrypt.key-store.location:classpath:/server.jks1",
|
||||
"encrypt.key-store.password:letmein", "encrypt.key-store.alias:mytestkey",
|
||||
"encrypt.key-store.secret:changeme")
|
||||
.run();
|
||||
.properties("encrypt.key-store.location:classpath:/server.jks1", "encrypt.key-store.password:letmein",
|
||||
"encrypt.key-store.alias:mytestkey", "encrypt.key-store.secret:changeme")
|
||||
.run();
|
||||
then(false).as("Should not create an application context with invalid keystore location").isTrue();
|
||||
}
|
||||
catch (Exception e) {
|
||||
|
||||
@@ -39,36 +39,40 @@ public class EncryptionIntegrationTests {
|
||||
@Test
|
||||
public void legacySymmetricPropertyValues() {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfiguration.class)
|
||||
.web(WebApplicationType.NONE).properties("spring.cloud.bootstrap.enabled=true", "encrypt.key:pie",
|
||||
"foo.password:{cipher}bf29452295df354e6153c5b31b03ef23c70e55fba24299aa85c63438f1c43c95")
|
||||
.run();
|
||||
.web(WebApplicationType.NONE)
|
||||
.properties("spring.cloud.bootstrap.enabled=true", "encrypt.key:pie",
|
||||
"foo.password:{cipher}bf29452295df354e6153c5b31b03ef23c70e55fba24299aa85c63438f1c43c95")
|
||||
.run();
|
||||
then(context.getEnvironment().getProperty("foo.password")).isEqualTo("test");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void legacySymmetricConfigurationProperties() {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfiguration.class)
|
||||
.web(WebApplicationType.NONE).properties("spring.cloud.bootstrap.enabled=true", "encrypt.key:pie",
|
||||
"foo.password:{cipher}bf29452295df354e6153c5b31b03ef23c70e55fba24299aa85c63438f1c43c95")
|
||||
.run();
|
||||
.web(WebApplicationType.NONE)
|
||||
.properties("spring.cloud.bootstrap.enabled=true", "encrypt.key:pie",
|
||||
"foo.password:{cipher}bf29452295df354e6153c5b31b03ef23c70e55fba24299aa85c63438f1c43c95")
|
||||
.run();
|
||||
then(context.getBean(PasswordProperties.class).getPassword()).isEqualTo("test");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void propSymmetricPropertyValues() {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfiguration.class)
|
||||
.web(WebApplicationType.NONE).properties("spring.cloud.bootstrap.enabled=true", "encrypt.key:pie",
|
||||
"foo.password:{cipher}bf29452295df354e6153c5b31b03ef23c70e55fba24299aa85c63438f1c43c95")
|
||||
.run();
|
||||
.web(WebApplicationType.NONE)
|
||||
.properties("spring.cloud.bootstrap.enabled=true", "encrypt.key:pie",
|
||||
"foo.password:{cipher}bf29452295df354e6153c5b31b03ef23c70e55fba24299aa85c63438f1c43c95")
|
||||
.run();
|
||||
then(context.getEnvironment().getProperty("foo.password")).isEqualTo("test");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void propSymmetricConfigurationProperties() {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfiguration.class)
|
||||
.web(WebApplicationType.NONE).properties("spring.cloud.bootstrap.enabled=true", "encrypt.key:pie",
|
||||
"foo.password:{cipher}bf29452295df354e6153c5b31b03ef23c70e55fba24299aa85c63438f1c43c95")
|
||||
.run();
|
||||
.web(WebApplicationType.NONE)
|
||||
.properties("spring.cloud.bootstrap.enabled=true", "encrypt.key:pie",
|
||||
"foo.password:{cipher}bf29452295df354e6153c5b31b03ef23c70e55fba24299aa85c63438f1c43c95")
|
||||
.run();
|
||||
then(context.getBean(PasswordProperties.class).getPassword()).isEqualTo("test");
|
||||
}
|
||||
|
||||
@@ -76,50 +80,51 @@ public class EncryptionIntegrationTests {
|
||||
public void symmetricPropertyValuesFailOnError() {
|
||||
assertThatThrownBy(() -> {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder(TestAutoConfiguration.class)
|
||||
.web(WebApplicationType.NONE)
|
||||
.properties("spring.config.use-legacy-processing=false", "encrypt.key:pie",
|
||||
"foo.password:{cipher}ZZZbf29452295df354e6153c5b31b03ef23c70e55fba24299aa85c63438f1c43c95")
|
||||
.run();
|
||||
.web(WebApplicationType.NONE)
|
||||
.properties("spring.config.use-legacy-processing=false", "encrypt.key:pie",
|
||||
"foo.password:{cipher}ZZZbf29452295df354e6153c5b31b03ef23c70e55fba24299aa85c63438f1c43c95")
|
||||
.run();
|
||||
}).isInstanceOf(IllegalStateException.class).hasMessageContaining("Cannot decrypt");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void symmetricPropertyValuesFailOnErrorFalse() {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder(TestAutoConfiguration.class)
|
||||
.web(WebApplicationType.NONE)
|
||||
.properties("encrypt.fail-on-error=false", "spring.config.use-legacy-processing=false",
|
||||
"encrypt.key:pie",
|
||||
"foo.password:{cipher}ZZZbf29452295df354e6153c5b31b03ef23c70e55fba24299aa85c63438f1c43c95")
|
||||
.run();
|
||||
.web(WebApplicationType.NONE)
|
||||
.properties("encrypt.fail-on-error=false", "spring.config.use-legacy-processing=false", "encrypt.key:pie",
|
||||
"foo.password:{cipher}ZZZbf29452295df354e6153c5b31b03ef23c70e55fba24299aa85c63438f1c43c95")
|
||||
.run();
|
||||
then(context.getEnvironment().getProperty("foo.password")).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void symmetricPropertyValues() {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder(TestAutoConfiguration.class)
|
||||
.web(WebApplicationType.NONE).properties("spring.config.use-legacy-processing=false", "encrypt.key:pie",
|
||||
"foo.password:{cipher}bf29452295df354e6153c5b31b03ef23c70e55fba24299aa85c63438f1c43c95")
|
||||
.run();
|
||||
.web(WebApplicationType.NONE)
|
||||
.properties("spring.config.use-legacy-processing=false", "encrypt.key:pie",
|
||||
"foo.password:{cipher}bf29452295df354e6153c5b31b03ef23c70e55fba24299aa85c63438f1c43c95")
|
||||
.run();
|
||||
then(context.getEnvironment().getProperty("foo.password")).isEqualTo("test");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void decryptEnvironmentPostProcessorDisabled() {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder(TestAutoConfiguration.class)
|
||||
.web(WebApplicationType.NONE)
|
||||
.properties("spring.config.use-legacy-processing=false", "encrypt.key:pie",
|
||||
"spring.cloud.decrypt-environment-post-processor.enabled=false",
|
||||
"foo.password:{cipher}bf29452295df354e6153c5b31b03ef23c70e55fba24299aa85c63438f1c43c95")
|
||||
.run();
|
||||
.web(WebApplicationType.NONE)
|
||||
.properties("spring.config.use-legacy-processing=false", "encrypt.key:pie",
|
||||
"spring.cloud.decrypt-environment-post-processor.enabled=false",
|
||||
"foo.password:{cipher}bf29452295df354e6153c5b31b03ef23c70e55fba24299aa85c63438f1c43c95")
|
||||
.run();
|
||||
then(context.getEnvironment().getProperty("foo.password")).startsWith("{cipher}bf2945");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void symmetricConfigurationProperties() {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder(TestAutoConfiguration.class)
|
||||
.web(WebApplicationType.NONE).properties("spring.config.use-legacy-processing=false", "encrypt.key:pie",
|
||||
"foo.password:{cipher}bf29452295df354e6153c5b31b03ef23c70e55fba24299aa85c63438f1c43c95")
|
||||
.run();
|
||||
.web(WebApplicationType.NONE)
|
||||
.properties("spring.config.use-legacy-processing=false", "encrypt.key:pie",
|
||||
"foo.password:{cipher}bf29452295df354e6153c5b31b03ef23c70e55fba24299aa85c63438f1c43c95")
|
||||
.run();
|
||||
then(context.getBean(PasswordProperties.class).getPassword()).isEqualTo("test");
|
||||
}
|
||||
|
||||
@@ -128,9 +133,10 @@ public class EncryptionIntegrationTests {
|
||||
TestConfigDataLocationResolver.config.put("foo.password",
|
||||
"{cipher}bf29452295df354e6153c5b31b03ef23c70e55fba24299aa85c63438f1c43c95");
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder(TestAutoConfiguration.class)
|
||||
.web(WebApplicationType.NONE).properties("encrypt.key:pie", TestEnvPostProcessor.EPP_ENABLED + "=true",
|
||||
"spring.cloud.refresh.enabled:true")
|
||||
.run();
|
||||
.web(WebApplicationType.NONE)
|
||||
.properties("encrypt.key:pie", TestEnvPostProcessor.EPP_ENABLED + "=true",
|
||||
"spring.cloud.refresh.enabled:true")
|
||||
.run();
|
||||
TextEncryptor encryptor = context.getBean(TextEncryptor.class);
|
||||
ContextRefresher refresher = context.getBean(ContextRefresher.class);
|
||||
ConfigurableEnvironment env = context.getBean(ConfigurableEnvironment.class);
|
||||
@@ -145,7 +151,10 @@ public class EncryptionIntegrationTests {
|
||||
@Test
|
||||
public void failsafeTextEncryptor() {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder(
|
||||
EncryptionIntegrationTests.TestConfiguration.class).web(WebApplicationType.NONE).properties().run();
|
||||
EncryptionIntegrationTests.TestConfiguration.class)
|
||||
.web(WebApplicationType.NONE)
|
||||
.properties()
|
||||
.run();
|
||||
then(context.getBean(TextEncryptor.class)).isInstanceOf(TextEncryptorUtils.FailsafeTextEncryptor.class);
|
||||
}
|
||||
|
||||
@@ -154,10 +163,10 @@ public class EncryptionIntegrationTests {
|
||||
TestConfigDataLocationResolver.config.put("foo.password",
|
||||
"{cipher}bf29452295df354e6153c5b31b03ef23c70e55fba24299aa85c63438f1c43c95");
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder(TestAutoConfiguration.class)
|
||||
.web(WebApplicationType.NONE)
|
||||
.properties("spring.config.import=testdatasource:,classpath:application-failsafe.properties",
|
||||
"createfailsafedelegate=true")
|
||||
.run();
|
||||
.web(WebApplicationType.NONE)
|
||||
.properties("spring.config.import=testdatasource:,classpath:application-failsafe.properties",
|
||||
"createfailsafedelegate=true")
|
||||
.run();
|
||||
ConfigurableEnvironment env = context.getBean(ConfigurableEnvironment.class);
|
||||
then(env.getProperty("foo.password")).isEqualTo("test");
|
||||
context.close();
|
||||
|
||||
@@ -40,14 +40,16 @@ class EncryptionRuntimeHintsTests {
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
SpringFactoriesLoader.forResourceLocation("META-INF/spring/aot.factories").load(RuntimeHintsRegistrar.class)
|
||||
.forEach(registrar -> registrar.registerHints(this.hints, ClassUtils.getDefaultClassLoader()));
|
||||
SpringFactoriesLoader.forResourceLocation("META-INF/spring/aot.factories")
|
||||
.load(RuntimeHintsRegistrar.class)
|
||||
.forEach(registrar -> registrar.registerHints(this.hints, ClassUtils.getDefaultClassLoader()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rsaSecretEncryptorHasHints() {
|
||||
assertThat(RuntimeHintsPredicates.reflection().onType(RsaSecretEncryptor.class)
|
||||
.withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(this.hints);
|
||||
assertThat(RuntimeHintsPredicates.reflection()
|
||||
.onType(RsaSecretEncryptor.class)
|
||||
.withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(this.hints);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -72,7 +72,7 @@ public class EnvironmentDecryptApplicationInitializerTests {
|
||||
public void relaxedBinding() {
|
||||
ConfigurableApplicationContext context = new AnnotationConfigApplicationContext();
|
||||
TestPropertyValues.of("spring.cloud.bootstrap.enabled=true", "FOO_TEXT: {cipher}bar")
|
||||
.applyTo(context.getEnvironment(), TestPropertyValues.Type.SYSTEM_ENVIRONMENT);
|
||||
.applyTo(context.getEnvironment(), TestPropertyValues.Type.SYSTEM_ENVIRONMENT);
|
||||
this.listener.initialize(context);
|
||||
then(context.getEnvironment().getProperty("foo.text")).isEqualTo("bar");
|
||||
}
|
||||
@@ -81,8 +81,9 @@ public class EnvironmentDecryptApplicationInitializerTests {
|
||||
public void propertySourcesOrderedCorrectly() {
|
||||
ConfigurableApplicationContext context = new AnnotationConfigApplicationContext();
|
||||
TestPropertyValues.of("spring.cloud.bootstrap.enabled=true", "foo: {cipher}bar").applyTo(context);
|
||||
context.getEnvironment().getPropertySources()
|
||||
.addFirst(new MapPropertySource("test_override", Collections.singletonMap("foo", "{cipher}spam")));
|
||||
context.getEnvironment()
|
||||
.getPropertySources()
|
||||
.addFirst(new MapPropertySource("test_override", Collections.singletonMap("foo", "{cipher}spam")));
|
||||
this.listener.initialize(context);
|
||||
then(context.getEnvironment().getProperty("foo")).isEqualTo("spam");
|
||||
}
|
||||
@@ -125,14 +126,14 @@ public class EnvironmentDecryptApplicationInitializerTests {
|
||||
// tests that collections in another property source don't get copied into
|
||||
// "decrypted" property source
|
||||
TestPropertyValues
|
||||
.of("spring.cloud.bootstrap.enabled=true", "yours[0].someValue: yourFoo", "yours[1].someValue: yourBar")
|
||||
.applyTo(context);
|
||||
.of("spring.cloud.bootstrap.enabled=true", "yours[0].someValue: yourFoo", "yours[1].someValue: yourBar")
|
||||
.applyTo(context);
|
||||
|
||||
// collection with some encrypted keys and some not encrypted
|
||||
TestPropertyValues
|
||||
.of("mine[0].someValue: Foo", "mine[0].someKey: {cipher}Foo0", "mine[1].someValue: Bar",
|
||||
"mine[1].someKey: {cipher}Bar1", "nonindexed: nonindexval")
|
||||
.applyTo(context.getEnvironment(), Type.MAP, "combinedTest");
|
||||
.of("mine[0].someValue: Foo", "mine[0].someKey: {cipher}Foo0", "mine[1].someValue: Bar",
|
||||
"mine[1].someKey: {cipher}Bar1", "nonindexed: nonindexval")
|
||||
.applyTo(context.getEnvironment(), Type.MAP, "combinedTest");
|
||||
this.listener.initialize(context);
|
||||
|
||||
then(context.getEnvironment().getProperty("mine[0].someValue")).isEqualTo("Foo");
|
||||
@@ -144,7 +145,7 @@ public class EnvironmentDecryptApplicationInitializerTests {
|
||||
|
||||
MutablePropertySources propertySources = context.getEnvironment().getPropertySources();
|
||||
PropertySource<Map<?, ?>> decrypted = (PropertySource<Map<?, ?>>) propertySources
|
||||
.get(DECRYPTED_PROPERTY_SOURCE_NAME);
|
||||
.get(DECRYPTED_PROPERTY_SOURCE_NAME);
|
||||
then(decrypted.getSource().size()).as("decrypted property source had wrong size").isEqualTo(4);
|
||||
}
|
||||
|
||||
@@ -193,8 +194,9 @@ public class EnvironmentDecryptApplicationInitializerTests {
|
||||
public void propertySourcesOrderedCorrectlyWithUnencryptedOverrides() {
|
||||
ConfigurableApplicationContext context = new AnnotationConfigApplicationContext();
|
||||
TestPropertyValues.of("spring.cloud.bootstrap.enabled=true", "foo: {cipher}bar").applyTo(context);
|
||||
context.getEnvironment().getPropertySources()
|
||||
.addFirst(new MapPropertySource("test_override", Collections.singletonMap("foo", "spam")));
|
||||
context.getEnvironment()
|
||||
.getPropertySources()
|
||||
.addFirst(new MapPropertySource("test_override", Collections.singletonMap("foo", "spam")));
|
||||
this.listener.initialize(context);
|
||||
then(context.getEnvironment().getProperty("foo")).isEqualTo("spam");
|
||||
}
|
||||
@@ -212,15 +214,16 @@ public class EnvironmentDecryptApplicationInitializerTests {
|
||||
ConfigurableApplicationContext context = new AnnotationConfigApplicationContext();
|
||||
TestPropertyValues.of("spring.cloud.bootstrap.enabled=true").applyTo(context);
|
||||
CompositePropertySource bootstrap = new CompositePropertySource(BOOTSTRAP_PROPERTY_SOURCE_NAME);
|
||||
bootstrap.addPropertySource(
|
||||
new MapPropertySource("configService", Collections.singletonMap("foo", "{cipher}bar")));
|
||||
bootstrap
|
||||
.addPropertySource(new MapPropertySource("configService", Collections.singletonMap("foo", "{cipher}bar")));
|
||||
context.getEnvironment().getPropertySources().addFirst(bootstrap);
|
||||
|
||||
Map<String, Object> props = new HashMap<>();
|
||||
props.put("foo2", "{cipher}bar2");
|
||||
props.put("bar", "{cipher}baz");
|
||||
context.getEnvironment().getPropertySources().addAfter(BOOTSTRAP_PROPERTY_SOURCE_NAME,
|
||||
new MapPropertySource("remote", props));
|
||||
context.getEnvironment()
|
||||
.getPropertySources()
|
||||
.addAfter(BOOTSTRAP_PROPERTY_SOURCE_NAME, new MapPropertySource("remote", props));
|
||||
|
||||
initializer.initialize(context);
|
||||
|
||||
@@ -236,8 +239,9 @@ public class EnvironmentDecryptApplicationInitializerTests {
|
||||
verify(encryptor, times(2)).decrypt("baz");
|
||||
|
||||
// Check if all encrypted properties are still decrypted
|
||||
PropertySource<?> decryptedBootstrap = context.getEnvironment().getPropertySources()
|
||||
.get(DECRYPTED_BOOTSTRAP_PROPERTY_SOURCE_NAME);
|
||||
PropertySource<?> decryptedBootstrap = context.getEnvironment()
|
||||
.getPropertySources()
|
||||
.get(DECRYPTED_BOOTSTRAP_PROPERTY_SOURCE_NAME);
|
||||
then(decryptedBootstrap.getProperty("foo")).isEqualTo("bar");
|
||||
|
||||
PropertySource<?> decrypted = context.getEnvironment().getPropertySources().get(DECRYPTED_PROPERTY_SOURCE_NAME);
|
||||
@@ -252,9 +256,10 @@ public class EnvironmentDecryptApplicationInitializerTests {
|
||||
when(encryptor.decrypt("bar2")).thenReturn("bar2");
|
||||
EnvironmentDecryptApplicationInitializer initializer = new EnvironmentDecryptApplicationInitializer(encryptor);
|
||||
TestPropertyValues.of("spring.cloud.bootstrap.enabled=true", "foo: {cipher}bar", "foo2: {cipher}bar2")
|
||||
.applyTo(context);
|
||||
context.getEnvironment().getPropertySources()
|
||||
.addFirst(new MapPropertySource("test_override", Collections.singletonMap("foo", "spam")));
|
||||
.applyTo(context);
|
||||
context.getEnvironment()
|
||||
.getPropertySources()
|
||||
.addFirst(new MapPropertySource("test_override", Collections.singletonMap("foo", "spam")));
|
||||
initializer.initialize(context);
|
||||
then(context.getEnvironment().getProperty("foo")).isEqualTo("spam");
|
||||
then(context.getEnvironment().getProperty("foo2")).isEqualTo("bar2");
|
||||
|
||||
@@ -40,8 +40,10 @@ public class RsaDisabledTests {
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
|
||||
.sources(EncryptionBootstrapConfiguration.class).web(WebApplicationType.NONE)
|
||||
.properties("encrypt.key:mykey", "encrypt.rsa.strong:true", "encrypt.rsa.salt:foobar").run();
|
||||
.sources(EncryptionBootstrapConfiguration.class)
|
||||
.web(WebApplicationType.NONE)
|
||||
.properties("encrypt.key:mykey", "encrypt.rsa.strong:true", "encrypt.rsa.salt:foobar")
|
||||
.run();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
|
||||
@@ -72,7 +72,8 @@ public class EnvironmentManagerIntegrationTests {
|
||||
String content = property("message", "Foo");
|
||||
|
||||
this.mvc.perform(post(BASE_PATH + "/env").content(content).contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isOk()).andExpect(content().string("{\"message\":\"Foo\"}"));
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string("{\"message\":\"Foo\"}"));
|
||||
then(this.properties.getMessage()).isEqualTo("Foo");
|
||||
}
|
||||
|
||||
@@ -88,9 +89,11 @@ public class EnvironmentManagerIntegrationTests {
|
||||
@Test
|
||||
public void testRefreshFails() throws Exception {
|
||||
try {
|
||||
this.mvc.perform(
|
||||
post(BASE_PATH + "/env").content(property("delay", "foo")).contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isOk()).andExpect(status().is5xxServerError());
|
||||
this.mvc
|
||||
.perform(post(BASE_PATH + "/env").content(property("delay", "foo"))
|
||||
.contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(status().is5xxServerError());
|
||||
fail("expected ServletException");
|
||||
}
|
||||
catch (ServletException e) {
|
||||
@@ -111,10 +114,10 @@ public class EnvironmentManagerIntegrationTests {
|
||||
then(envbeans.get("writableEnvironmentEndpoint")).isInstanceOf(WritableEnvironmentEndpoint.class);
|
||||
|
||||
Map<String, EnvironmentEndpointWebExtension> extbeans = this.context
|
||||
.getBeansOfType(EnvironmentEndpointWebExtension.class);
|
||||
.getBeansOfType(EnvironmentEndpointWebExtension.class);
|
||||
then(extbeans).hasSize(1).containsKey("writableEnvironmentEndpointWebExtension");
|
||||
then(extbeans.get("writableEnvironmentEndpointWebExtension"))
|
||||
.isInstanceOf(WritableEnvironmentEndpointWebExtension.class);
|
||||
.isInstanceOf(WritableEnvironmentEndpointWebExtension.class);
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
|
||||
@@ -158,11 +158,11 @@ public class NamedContextFactoryTests {
|
||||
GenericApplicationContext barContext = factory.getContext("bar");
|
||||
|
||||
then(fooContext.getClassLoader()).as("foo context classloader does not match parent")
|
||||
.isSameAs(parent.getClassLoader());
|
||||
.isSameAs(parent.getClassLoader());
|
||||
|
||||
then(fooContext.getBeanFactory().getBeanClassLoader())
|
||||
.as("foo context bean factory classloader does not match parent")
|
||||
.isSameAs(parent.getBeanFactory().getBeanClassLoader());
|
||||
.as("foo context bean factory classloader does not match parent")
|
||||
.isSameAs(parent.getBeanFactory().getBeanClassLoader());
|
||||
|
||||
assertThat(fooContext).hasFieldOrPropertyWithValue("customClassLoader", true);
|
||||
|
||||
@@ -287,7 +287,7 @@ public class NamedContextFactoryTests {
|
||||
|
||||
}
|
||||
|
||||
record Container<T> (T item) {
|
||||
record Container<T>(T item) {
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -88,13 +88,14 @@ public class ContextRefresherTests {
|
||||
System.err.println("***** " + context.getEnvironment().getPropertySources());
|
||||
then(names).doesNotContain("bootstrapProperties");
|
||||
ContextRefresher refresher = new LegacyContextRefresher(context, this.scope);
|
||||
TestPropertyValues.of("spring.cloud.bootstrap.sources: "
|
||||
+ "org.springframework.cloud.context.refresh.ContextRefresherTests.PropertySourceConfiguration")
|
||||
.applyTo(context.getEnvironment(), Type.MAP, "defaultProperties");
|
||||
TestPropertyValues
|
||||
.of("spring.cloud.bootstrap.sources: "
|
||||
+ "org.springframework.cloud.context.refresh.ContextRefresherTests.PropertySourceConfiguration")
|
||||
.applyTo(context.getEnvironment(), Type.MAP, "defaultProperties");
|
||||
refresher.refresh();
|
||||
names = names(context.getEnvironment().getPropertySources());
|
||||
then(names).first()
|
||||
.isEqualTo(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME + "-refreshTest");
|
||||
.isEqualTo(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME + "-refreshTest");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,9 +107,10 @@ public class ContextRefresherTests {
|
||||
"--spring.main.web-application-type=none", "--spring.cloud.bootstrap.enabled=true", "--debug=false",
|
||||
"--spring.main.bannerMode=OFF", "--spring.cloud.bootstrap.name=refresh")) {
|
||||
LegacyContextRefresher refresher = new LegacyContextRefresher(context, this.scope);
|
||||
TestPropertyValues.of("spring.cloud.bootstrap.sources: "
|
||||
+ "org.springframework.cloud.context.refresh.ContextRefresherTests.PropertySourceConfiguration")
|
||||
.applyTo(context);
|
||||
TestPropertyValues
|
||||
.of("spring.cloud.bootstrap.sources: "
|
||||
+ "org.springframework.cloud.context.refresh.ContextRefresherTests.PropertySourceConfiguration")
|
||||
.applyTo(context);
|
||||
|
||||
ConfigurableApplicationContext refresherContext = refresher.addConfigFilesToEnvironment();
|
||||
then(refresherContext.getParent()).isNotNull().isInstanceOf(ConfigurableApplicationContext.class);
|
||||
@@ -152,28 +154,30 @@ public class ContextRefresherTests {
|
||||
@Test
|
||||
public void legacyContextRefresherCreatedUsingBootstrapEnabled() {
|
||||
new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(RefreshAutoConfiguration.class))
|
||||
.withPropertyValues("spring.cloud.bootstrap.enabled=true").run(context -> {
|
||||
assertThat(context).hasSingleBean(LegacyContextRefresher.class);
|
||||
assertThat(context).hasSingleBean(ContextRefresher.class);
|
||||
});
|
||||
.withPropertyValues("spring.cloud.bootstrap.enabled=true")
|
||||
.run(context -> {
|
||||
assertThat(context).hasSingleBean(LegacyContextRefresher.class);
|
||||
assertThat(context).hasSingleBean(ContextRefresher.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void legacyContextRefresherCreated() {
|
||||
new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(RefreshAutoConfiguration.class))
|
||||
.withPropertyValues("spring.cloud.bootstrap.enabled=true").run(context -> {
|
||||
assertThat(context).hasSingleBean(LegacyContextRefresher.class);
|
||||
assertThat(context).hasSingleBean(ContextRefresher.class);
|
||||
});
|
||||
.withPropertyValues("spring.cloud.bootstrap.enabled=true")
|
||||
.run(context -> {
|
||||
assertThat(context).hasSingleBean(LegacyContextRefresher.class);
|
||||
assertThat(context).hasSingleBean(ContextRefresher.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void configDataContextRefresherCreated() {
|
||||
new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(RefreshAutoConfiguration.class))
|
||||
.run(context -> {
|
||||
assertThat(context).hasSingleBean(ConfigDataContextRefresher.class);
|
||||
assertThat(context).hasSingleBean(ContextRefresher.class);
|
||||
});
|
||||
.run(context -> {
|
||||
assertThat(context).hasSingleBean(ConfigDataContextRefresher.class);
|
||||
assertThat(context).hasSingleBean(ContextRefresher.class);
|
||||
});
|
||||
}
|
||||
|
||||
private List<String> names(MutablePropertySources propertySources) {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user