diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..323872eea --- /dev/null +++ b/.editorconfig @@ -0,0 +1,16 @@ +root=true + +[*.java] +indent_style = tab +indent_size = 4 +continuation_indent_size = 8 + +[*.groovy] +indent_style = tab +indent_size = 4 +continuation_indent_size = 8 + +[*.xml] +indent_style = tab +indent_size = 4 +continuation_indent_size = 8 \ No newline at end of file diff --git a/.mvn/wrapper/MavenWrapperDownloader.java b/.mvn/wrapper/MavenWrapperDownloader.java index d475a89ce..0cf25d62a 100755 --- a/.mvn/wrapper/MavenWrapperDownloader.java +++ b/.mvn/wrapper/MavenWrapperDownloader.java @@ -17,9 +17,6 @@ specific language governing permissions and limitations under the License. */ -import java.net.*; -import java.io.*; -import java.nio.channels.*; import java.util.Properties; public class MavenWrapperDownloader { diff --git a/pom.xml b/pom.xml index 2af42a69c..027d1b4e4 100644 --- a/pom.xml +++ b/pom.xml @@ -32,6 +32,10 @@ reuseReports ${project.basedir}/../target/jacoco.exec java + true + + true + @@ -61,6 +65,14 @@ 1.8 + + io.spring.javaformat + spring-javaformat-maven-plugin + + + org.apache.maven.plugins + maven-checkstyle-plugin + @@ -132,6 +144,14 @@ + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + spring-cloud-netflix-dependencies spring-cloud-netflix-archaius diff --git a/spring-cloud-netflix-archaius/src/main/java/org/springframework/cloud/netflix/archaius/ArchaiusAutoConfiguration.java b/spring-cloud-netflix-archaius/src/main/java/org/springframework/cloud/netflix/archaius/ArchaiusAutoConfiguration.java index b04a7231d..0b58a409f 100644 --- a/spring-cloud-netflix-archaius/src/main/java/org/springframework/cloud/netflix/archaius/ArchaiusAutoConfiguration.java +++ b/spring-cloud-netflix-archaius/src/main/java/org/springframework/cloud/netflix/archaius/ArchaiusAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,6 +24,13 @@ import java.util.concurrent.atomic.AtomicBoolean; import javax.annotation.PreDestroy; +import com.netflix.config.AggregatedConfiguration; +import com.netflix.config.ConcurrentCompositeConfiguration; +import com.netflix.config.ConfigurationManager; +import com.netflix.config.DeploymentContext; +import com.netflix.config.DynamicProperty; +import com.netflix.config.DynamicPropertyFactory; +import com.netflix.config.DynamicURLConfiguration; import org.apache.commons.configuration.AbstractConfiguration; import org.apache.commons.configuration.ConfigurationBuilder; import org.apache.commons.configuration.EnvironmentConfiguration; @@ -32,6 +39,7 @@ import org.apache.commons.configuration.event.ConfigurationEvent; import org.apache.commons.configuration.event.ConfigurationListener; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint; import org.springframework.boot.actuate.health.Health; @@ -48,14 +56,6 @@ import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; import org.springframework.util.ReflectionUtils; -import com.netflix.config.AggregatedConfiguration; -import com.netflix.config.ConcurrentCompositeConfiguration; -import com.netflix.config.ConfigurationManager; -import com.netflix.config.DeploymentContext; -import com.netflix.config.DynamicProperty; -import com.netflix.config.DynamicPropertyFactory; -import com.netflix.config.DynamicURLConfiguration; - import static com.netflix.config.ConfigurationManager.APPLICATION_PROPERTIES; import static com.netflix.config.ConfigurationManager.DISABLE_DEFAULT_ENV_CONFIG; import static com.netflix.config.ConfigurationManager.DISABLE_DEFAULT_SYS_CONFIG; @@ -98,52 +98,21 @@ public class ArchaiusAutoConfiguration { } @Bean - public static ConfigurableEnvironmentConfiguration configurableEnvironmentConfiguration(ConfigurableEnvironment env, - ApplicationContext context) { - Map abstractConfigurationMap = context.getBeansOfType(AbstractConfiguration.class); - List externalConfigurations = new ArrayList<>(abstractConfigurationMap.values()); - ConfigurableEnvironmentConfiguration envConfig = new ConfigurableEnvironmentConfiguration(env); + public static ConfigurableEnvironmentConfiguration configurableEnvironmentConfiguration( + ConfigurableEnvironment env, ApplicationContext context) { + Map abstractConfigurationMap = context + .getBeansOfType(AbstractConfiguration.class); + List externalConfigurations = new ArrayList<>( + abstractConfigurationMap.values()); + ConfigurableEnvironmentConfiguration envConfig = new ConfigurableEnvironmentConfiguration( + env); configureArchaius(envConfig, env, externalConfigurations); return envConfig; } - @Configuration - @ConditionalOnClass(Health.class) - protected static class ArchaiusEndpointConfiguration { - @Bean - @ConditionalOnEnabledEndpoint - protected ArchaiusEndpoint archaiusEndpoint() { - return new ArchaiusEndpoint(); - } - } - - @Configuration - @ConditionalOnProperty(value = "archaius.propagate.environmentChangedEvent", matchIfMissing = true) - @ConditionalOnClass(EnvironmentChangeEvent.class) - protected static class PropagateEventsConfiguration - implements ApplicationListener { - @Autowired - private Environment env; - - @Override - public void onApplicationEvent(EnvironmentChangeEvent event) { - AbstractConfiguration manager = ConfigurationManager.getConfigInstance(); - for (String key : event.getKeys()) { - for (ConfigurationListener listener : manager - .getConfigurationListeners()) { - Object source = event.getSource(); - // TODO: Handle add vs set vs delete? - int type = AbstractConfiguration.EVENT_SET_PROPERTY; - String value = this.env.getProperty(key); - boolean beforeUpdate = false; - listener.configurationChanged(new ConfigurationEvent(source, type, - key, value, beforeUpdate)); - } - } - } - } - - protected static void configureArchaius(ConfigurableEnvironmentConfiguration envConfig, ConfigurableEnvironment env, List externalConfigurations) { + protected static void configureArchaius( + ConfigurableEnvironmentConfiguration envConfig, ConfigurableEnvironment env, + List externalConfigurations) { if (initialized.compareAndSet(false, true)) { String appName = env.getProperty("spring.application.name"); if (appName == null) { @@ -196,7 +165,8 @@ public class ArchaiusAutoConfiguration { } } - private static void addArchaiusConfiguration(ConcurrentCompositeConfiguration config) { + private static void addArchaiusConfiguration( + ConcurrentCompositeConfiguration config) { if (ConfigurationManager.isConfigurationInstalled()) { AbstractConfiguration installedConfiguration = ConfigurationManager .getConfigInstance(); @@ -224,4 +194,44 @@ public class ArchaiusAutoConfiguration { ReflectionUtils.setField(field, null, value); } + @Configuration + @ConditionalOnClass(Health.class) + protected static class ArchaiusEndpointConfiguration { + + @Bean + @ConditionalOnEnabledEndpoint + protected ArchaiusEndpoint archaiusEndpoint() { + return new ArchaiusEndpoint(); + } + + } + + @Configuration + @ConditionalOnProperty(value = "archaius.propagate.environmentChangedEvent", matchIfMissing = true) + @ConditionalOnClass(EnvironmentChangeEvent.class) + protected static class PropagateEventsConfiguration + implements ApplicationListener { + + @Autowired + private Environment env; + + @Override + public void onApplicationEvent(EnvironmentChangeEvent event) { + AbstractConfiguration manager = ConfigurationManager.getConfigInstance(); + for (String key : event.getKeys()) { + for (ConfigurationListener listener : manager + .getConfigurationListeners()) { + Object source = event.getSource(); + // TODO: Handle add vs set vs delete? + int type = AbstractConfiguration.EVENT_SET_PROPERTY; + String value = this.env.getProperty(key); + boolean beforeUpdate = false; + listener.configurationChanged(new ConfigurationEvent(source, type, + key, value, beforeUpdate)); + } + } + } + + } + } diff --git a/spring-cloud-netflix-archaius/src/main/java/org/springframework/cloud/netflix/archaius/ArchaiusDelegatingProxyUtils.java b/spring-cloud-netflix-archaius/src/main/java/org/springframework/cloud/netflix/archaius/ArchaiusDelegatingProxyUtils.java index a28507b98..5f1733677 100644 --- a/spring-cloud-netflix-archaius/src/main/java/org/springframework/cloud/netflix/archaius/ArchaiusDelegatingProxyUtils.java +++ b/spring-cloud-netflix-archaius/src/main/java/org/springframework/cloud/netflix/archaius/ArchaiusDelegatingProxyUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,24 +16,30 @@ package org.springframework.cloud.netflix.archaius; +import com.netflix.config.ConfigurationManager; import org.apache.commons.configuration.AbstractConfiguration; + import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; -import com.netflix.config.ConfigurationManager; - /** * @author Dave Syer */ -public class ArchaiusDelegatingProxyUtils { +public final class ArchaiusDelegatingProxyUtils { + private ArchaiusDelegatingProxyUtils() { + } + + /** + * {@code ApplicationContext} class name. + */ public static String APPLICATION_CONTEXT = ApplicationContext.class.getName(); public static T getNamedInstance(Class type, String name) { ApplicationContext context = (ApplicationContext) ConfigurationManager .getConfigInstance().getProperty(APPLICATION_CONTEXT); - return context != null && context.containsBean(name) ? context - .getBean(name, type) : null; + return context != null && context.containsBean(name) ? context.getBean(name, type) + : null; } public static T getInstanceWithPrefix(Class type, String prefix) { diff --git a/spring-cloud-netflix-archaius/src/main/java/org/springframework/cloud/netflix/archaius/ArchaiusEndpoint.java b/spring-cloud-netflix-archaius/src/main/java/org/springframework/cloud/netflix/archaius/ArchaiusEndpoint.java index e77114da5..8a55a67f4 100644 --- a/spring-cloud-netflix-archaius/src/main/java/org/springframework/cloud/netflix/archaius/ArchaiusEndpoint.java +++ b/spring-cloud-netflix-archaius/src/main/java/org/springframework/cloud/netflix/archaius/ArchaiusEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,17 +20,19 @@ import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; +import com.netflix.config.ConcurrentCompositeConfiguration; +import com.netflix.config.ConfigurationManager; import org.apache.commons.configuration.AbstractConfiguration; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.EnvironmentConfiguration; import org.apache.commons.configuration.SystemConfiguration; + import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; -import com.netflix.config.ConcurrentCompositeConfiguration; -import com.netflix.config.ConfigurationManager; - /** + * An actuator endpoint that returns Archaius configuration. + * * @author Dave Syer */ @Endpoint(id = "archaius") diff --git a/spring-cloud-netflix-archaius/src/main/java/org/springframework/cloud/netflix/archaius/ConfigurableEnvironmentConfiguration.java b/spring-cloud-netflix-archaius/src/main/java/org/springframework/cloud/netflix/archaius/ConfigurableEnvironmentConfiguration.java index a2419d780..79bd1ff2c 100644 --- a/spring-cloud-netflix-archaius/src/main/java/org/springframework/cloud/netflix/archaius/ConfigurableEnvironmentConfiguration.java +++ b/spring-cloud-netflix-archaius/src/main/java/org/springframework/cloud/netflix/archaius/ConfigurableEnvironmentConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +23,7 @@ import java.util.List; import java.util.Map; import org.apache.commons.configuration.AbstractConfiguration; + import org.springframework.core.env.CompositePropertySource; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.EnumerablePropertySource; @@ -31,6 +32,8 @@ import org.springframework.core.env.PropertySource; import org.springframework.core.env.StandardEnvironment; /** + * EnvironmentConfiguration wrapper class providing further configuration possibilities. + * * @author Spencer Gibb */ public class ConfigurableEnvironmentConfiguration extends AbstractConfiguration { @@ -64,7 +67,8 @@ public class ConfigurableEnvironmentConfiguration extends AbstractConfiguration @Override public Iterator getKeys() { List result = new ArrayList<>(); - for (Map.Entry> entry : getPropertySources().entrySet()) { + for (Map.Entry> entry : getPropertySources() + .entrySet()) { PropertySource source = entry.getValue(); if (source instanceof EnumerablePropertySource) { EnumerablePropertySource enumerable = (EnumerablePropertySource) source; @@ -78,8 +82,9 @@ public class ConfigurableEnvironmentConfiguration extends AbstractConfiguration private Map> getPropertySources() { Map> map = new LinkedHashMap<>(); - MutablePropertySources sources = (this.environment != null ? this.environment - .getPropertySources() : new StandardEnvironment().getPropertySources()); + MutablePropertySources sources = (this.environment != null + ? this.environment.getPropertySources() + : new StandardEnvironment().getPropertySources()); for (PropertySource source : sources) { extract("", map, source); } diff --git a/spring-cloud-netflix-archaius/src/test/java/org/springframework/cloud/netflix/archaius/ArchaiusAutoConfigurationTests.java b/spring-cloud-netflix-archaius/src/test/java/org/springframework/cloud/netflix/archaius/ArchaiusAutoConfigurationTests.java index cf9d9ce0b..8d8d39098 100644 --- a/spring-cloud-netflix-archaius/src/test/java/org/springframework/cloud/netflix/archaius/ArchaiusAutoConfigurationTests.java +++ b/spring-cloud-netflix-archaius/src/test/java/org/springframework/cloud/netflix/archaius/ArchaiusAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,27 +12,24 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.archaius; import java.util.Collections; +import com.netflix.config.ConfigurationManager; +import com.netflix.config.DynamicPropertyFactory; +import com.netflix.config.DynamicStringProperty; import org.apache.commons.configuration.AbstractConfiguration; import org.junit.After; import org.junit.Test; + import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.cloud.context.environment.EnvironmentChangeEvent; import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import com.netflix.config.ConfigurationManager; -import com.netflix.config.DynamicPropertyFactory; -import com.netflix.config.DynamicStringProperty; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -40,6 +37,7 @@ import static org.junit.Assert.assertNull; public class ArchaiusAutoConfigurationTests { private AnnotationConfigApplicationContext context; + private Object propertyValue; @After @@ -55,24 +53,23 @@ public class ArchaiusAutoConfigurationTests { ArchaiusAutoConfiguration.class); AbstractConfiguration config = this.context .getBean(ConfigurableEnvironmentConfiguration.class); - assertNotNull(config.getString("java.io.tmpdir")); + assertThat(config.getString("java.io.tmpdir")).isNotNull(); } @Test public void environmentChangeEventPropagated() { this.context = new AnnotationConfigApplicationContext( ArchaiusAutoConfiguration.class); - ConfigurationManager.getConfigInstance().addConfigurationListener( - event -> { - if (event.getPropertyName().equals("my.prop")) { - ArchaiusAutoConfigurationTests.this.propertyValue = event - .getPropertyValue(); - } - }); + ConfigurationManager.getConfigInstance().addConfigurationListener(event -> { + if (event.getPropertyName().equals("my.prop")) { + ArchaiusAutoConfigurationTests.this.propertyValue = event + .getPropertyValue(); + } + }); TestPropertyValues.of("my.prop=my.newval").applyTo(this.context); - this.context.publishEvent(new EnvironmentChangeEvent(Collections - .singleton("my.prop"))); - assertEquals("my.newval", this.propertyValue); + this.context.publishEvent( + new EnvironmentChangeEvent(Collections.singleton("my.prop"))); + assertThat(this.propertyValue).isEqualTo("my.newval"); } @Test @@ -84,9 +81,9 @@ public class ArchaiusAutoConfigurationTests { DynamicStringProperty staticProperty = DynamicPropertyFactory.getInstance() .getStringProperty("archaius.file.property", null); - assertNull(dbProperty.getValue()); - assertNotNull(staticProperty.getValue()); - assertEquals("Static config file property", staticProperty.getValue()); + assertThat(dbProperty.getValue()).isNull(); + assertThat(staticProperty.getValue()).isNotNull(); + assertThat(staticProperty.getValue()).isEqualTo("Static config file property"); } @Test @@ -100,12 +97,12 @@ public class ArchaiusAutoConfigurationTests { DynamicStringProperty staticProperty = DynamicPropertyFactory.getInstance() .getStringProperty("archaius.file.property", null); - assertNotNull(dbProperty.getValue()); - assertNotNull(secondDbProperty.getValue()); - assertNotNull(staticProperty.getValue()); - assertEquals("this is a db property", dbProperty.getValue()); - assertEquals("this is another db property", secondDbProperty.getValue()); - assertEquals("Static config file property", staticProperty.getValue()); + assertThat(dbProperty.getValue()).isNotNull(); + assertThat(secondDbProperty.getValue()).isNotNull(); + assertThat(staticProperty.getValue()).isNotNull(); + assertThat(dbProperty.getValue()).isEqualTo("this is a db property"); + assertThat(secondDbProperty.getValue()).isEqualTo("this is another db property"); + assertThat(staticProperty.getValue()).isEqualTo("Static config file property"); } } diff --git a/spring-cloud-netflix-archaius/src/test/java/org/springframework/cloud/netflix/archaius/ArchaiusEndpointTests.java b/spring-cloud-netflix-archaius/src/test/java/org/springframework/cloud/netflix/archaius/ArchaiusEndpointTests.java index 50b883d2b..7c32a0e41 100644 --- a/spring-cloud-netflix-archaius/src/test/java/org/springframework/cloud/netflix/archaius/ArchaiusEndpointTests.java +++ b/spring-cloud-netflix-archaius/src/test/java/org/springframework/cloud/netflix/archaius/ArchaiusEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,14 +18,13 @@ package org.springframework.cloud.netflix.archaius; import java.util.Map; -import org.junit.Test; -import org.springframework.core.env.StandardEnvironment; - import com.netflix.config.ConcurrentCompositeConfiguration; import com.netflix.config.ConfigurationManager; +import org.junit.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.springframework.core.env.StandardEnvironment; + +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -37,7 +36,7 @@ public class ArchaiusEndpointTests { @Test public void detectsPropertiesWhenSet() { ConfigurationManager.getConfigInstance().setProperty("foo", "bar"); - assertTrue(this.endpoint.invoke().containsKey("foo")); + assertThat(this.endpoint.invoke().containsKey("foo")).isTrue(); } @Test @@ -46,12 +45,12 @@ public class ArchaiusEndpointTests { ConfigurationManager.getConfigInstance()); ConfigurableEnvironmentConfiguration config = new ConfigurableEnvironmentConfiguration( new StandardEnvironment()); - assertTrue(config.containsKey("user.dir")); + assertThat(config.containsKey("user.dir")).isTrue(); composite.addConfiguration(config); ConfigurationManager.getConfigInstance().setProperty("foo", "bar"); Map map = this.endpoint.invoke(); - assertTrue(map.containsKey("foo")); - assertFalse(map.containsKey("user.dir")); + assertThat(map.containsKey("foo")).isTrue(); + assertThat(map.containsKey("user.dir")).isFalse(); } } diff --git a/spring-cloud-netflix-archaius/src/test/java/org/springframework/cloud/netflix/archaius/TestArchaiusExternalConfiguration.java b/spring-cloud-netflix-archaius/src/test/java/org/springframework/cloud/netflix/archaius/TestArchaiusExternalConfiguration.java index fa871eca4..f10d8f0c3 100644 --- a/spring-cloud-netflix-archaius/src/test/java/org/springframework/cloud/netflix/archaius/TestArchaiusExternalConfiguration.java +++ b/spring-cloud-netflix-archaius/src/test/java/org/springframework/cloud/netflix/archaius/TestArchaiusExternalConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,13 +16,13 @@ package org.springframework.cloud.netflix.archaius; +import com.netflix.config.ConcurrentMapConfiguration; import org.apache.commons.configuration.AbstractConfiguration; + import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import com.netflix.config.ConcurrentMapConfiguration; - /** * @author Alexandru-George Burghelea */ @@ -33,8 +33,8 @@ public class TestArchaiusExternalConfiguration { @Qualifier("dynamicConfiguration") public AbstractConfiguration createDynamicConfiguration() { ConcurrentMapConfiguration config = new ConcurrentMapConfiguration(); - config.addProperty("db.property","this is a db property"); - config.addProperty("db.second.property","this is another db property"); + config.addProperty("db.property", "this is a db property"); + config.addProperty("db.second.property", "this is another db property"); return config; } diff --git a/spring-cloud-netflix-concurrency-limits/src/main/java/org/springframework/cloud/netflix/concurrency/limits/micrometer/MicrometerMetricRegistry.java b/spring-cloud-netflix-concurrency-limits/src/main/java/org/springframework/cloud/netflix/concurrency/limits/micrometer/MicrometerMetricRegistry.java index abff27a5c..0a29a5c87 100644 --- a/spring-cloud-netflix-concurrency-limits/src/main/java/org/springframework/cloud/netflix/concurrency/limits/micrometer/MicrometerMetricRegistry.java +++ b/spring-cloud-netflix-concurrency-limits/src/main/java/org/springframework/cloud/netflix/concurrency/limits/micrometer/MicrometerMetricRegistry.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.concurrency.limits.micrometer; @@ -24,10 +23,16 @@ import io.micrometer.core.instrument.DistributionSummary; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.Tags; +/** + * A Micrometer-specific {@link MetricRegistry} implementation. + * + * @author Spencer Gibb + */ public class MicrometerMetricRegistry implements MetricRegistry { private final MeterRegistry meterRegistry; - //TODO: baseId? + + // TODO: baseId? public MicrometerMetricRegistry(MeterRegistry meterRegistry) { this.meterRegistry = meterRegistry; @@ -40,7 +45,9 @@ public class MicrometerMetricRegistry implements MetricRegistry { } @Override - public void registerGauge(String id, Supplier supplier, String... tagNameValuePairs) { + public void registerGauge(String id, Supplier supplier, + String... tagNameValuePairs) { this.meterRegistry.gauge(id, Tags.of(tagNameValuePairs), supplier.get()); } -} \ No newline at end of file + +} diff --git a/spring-cloud-netflix-concurrency-limits/src/main/java/org/springframework/cloud/netflix/concurrency/limits/reactive/ConcurrencyLimitsWebFilter.java b/spring-cloud-netflix-concurrency-limits/src/main/java/org/springframework/cloud/netflix/concurrency/limits/reactive/ConcurrencyLimitsWebFilter.java index 9b1ea3006..f99dc8f2d 100644 --- a/spring-cloud-netflix-concurrency-limits/src/main/java/org/springframework/cloud/netflix/concurrency/limits/reactive/ConcurrencyLimitsWebFilter.java +++ b/spring-cloud-netflix-concurrency-limits/src/main/java/org/springframework/cloud/netflix/concurrency/limits/reactive/ConcurrencyLimitsWebFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.concurrency.limits.reactive; @@ -25,6 +24,12 @@ import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; +/** + * A {@link WebFilter} implementation providing the possibility to use Netflix + * {@link Limiter} to handle requests. + * + * @author Spencer Gibb + */ public class ConcurrencyLimitsWebFilter implements WebFilter { private final Limiter limiter; @@ -41,8 +46,9 @@ public class ConcurrencyLimitsWebFilter implements WebFilter { .doOnError(throwable -> listener.onIgnore())) .orElseGet(() -> { exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS); - //TODO: set body + // TODO: set body return exchange.getResponse().setComplete(); }); } + } diff --git a/spring-cloud-netflix-concurrency-limits/src/main/java/org/springframework/cloud/netflix/concurrency/limits/reactive/ReactiveConcurrencyLimitsAutoConfiguration.java b/spring-cloud-netflix-concurrency-limits/src/main/java/org/springframework/cloud/netflix/concurrency/limits/reactive/ReactiveConcurrencyLimitsAutoConfiguration.java index bc1788beb..14fd1b8fa 100644 --- a/spring-cloud-netflix-concurrency-limits/src/main/java/org/springframework/cloud/netflix/concurrency/limits/reactive/ReactiveConcurrencyLimitsAutoConfiguration.java +++ b/spring-cloud-netflix-concurrency-limits/src/main/java/org/springframework/cloud/netflix/concurrency/limits/reactive/ReactiveConcurrencyLimitsAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,33 +12,39 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ + package org.springframework.cloud.netflix.concurrency.limits.reactive; -import com.netflix.concurrency.limits.Limiter; -import org.springframework.beans.factory.ObjectProvider; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.context.annotation.Bean; -import org.springframework.web.server.ServerWebExchange; -import reactor.core.publisher.Mono; - -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; -import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.server.WebFilter; - import java.util.function.Consumer; +import com.netflix.concurrency.limits.Limiter; +import reactor.core.publisher.Mono; + +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; +import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.server.ServerWebExchange; +import org.springframework.web.server.WebFilter; + +/** + * Reactive autoconfiguration class for registering Netflix {@link Limiter} bean. + * + * @author Spencer Gibb + */ @Configuration @ConditionalOnWebApplication(type = Type.REACTIVE) -@ConditionalOnClass({WebFilter.class, Mono.class}) +@ConditionalOnClass({ WebFilter.class, Mono.class }) public class ReactiveConcurrencyLimitsAutoConfiguration { private final ObjectProvider> configurerProvider; - public ReactiveConcurrencyLimitsAutoConfiguration(ObjectProvider> configurerProvider) { + public ReactiveConcurrencyLimitsAutoConfiguration( + ObjectProvider> configurerProvider) { this.configurerProvider = configurerProvider; } @@ -53,7 +59,9 @@ public class ReactiveConcurrencyLimitsAutoConfiguration { } @Bean - public ConcurrencyLimitsWebFilter concurrencyLimitsWebFilter(Limiter limiter) { + public ConcurrencyLimitsWebFilter concurrencyLimitsWebFilter( + Limiter limiter) { return new ConcurrencyLimitsWebFilter(limiter); } -} \ No newline at end of file + +} diff --git a/spring-cloud-netflix-concurrency-limits/src/main/java/org/springframework/cloud/netflix/concurrency/limits/reactive/ServerWebExchangeLimiterBuilder.java b/spring-cloud-netflix-concurrency-limits/src/main/java/org/springframework/cloud/netflix/concurrency/limits/reactive/ServerWebExchangeLimiterBuilder.java index fb11954b7..f1d184dbf 100644 --- a/spring-cloud-netflix-concurrency-limits/src/main/java/org/springframework/cloud/netflix/concurrency/limits/reactive/ServerWebExchangeLimiterBuilder.java +++ b/spring-cloud-netflix-concurrency-limits/src/main/java/org/springframework/cloud/netflix/concurrency/limits/reactive/ServerWebExchangeLimiterBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,12 +12,10 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.concurrency.limits.reactive; -import java.security.Principal; import java.util.Optional; import java.util.function.Function; @@ -25,58 +23,73 @@ import com.netflix.concurrency.limits.limiter.AbstractPartitionedLimiter; import org.springframework.web.server.ServerWebExchange; -public class ServerWebExchangeLimiterBuilder extends AbstractPartitionedLimiter.Builder { +/** + * Builder for ServerWebExchange Limiter. + * + * @author Spencer Gibb + */ +public class ServerWebExchangeLimiterBuilder extends + AbstractPartitionedLimiter.Builder { + /** - * Partition the limit by header + * Partition the limit by header. + * @param name header name * @return Chainable builder */ public ServerWebExchangeLimiterBuilder partitionByHeader(String name) { - return partitionResolver(exchange -> exchange.getRequest().getHeaders().getFirst(name)); + return partitionResolver( + exchange -> exchange.getRequest().getHeaders().getFirst(name)); } /** - * Partition the limit by {@link Principal}. Percentages of the limit are partitioned to named - * groups. Group membership is derived from the provided mapping function. + * Partition the limit by {@link Principal}. Percentages of the limit are partitioned + * to named groups. Group membership is derived from the provided mapping function. * @param principalToGroup Mapping function from {@link Principal} to a named group. - * @param configurer Configuration function though which group percentages may be specified - * Unspecified group values may only use excess capacity. + * @param configurer Configuration function though which group percentages may be + * specified Unspecified group values may only use excess capacity. * @return Chainable builder */ - /*public ServerWebExchangeLimiterBuilder partitionByUserPrincipal(Function principalToGroup, Consumer> configurer) { - return partitionResolver( - exchange -> Optional.ofNullable(request.getUserPrincipal()).map(principalToGroup).orElse(null), - configurer); - }*/ + /* + * public ServerWebExchangeLimiterBuilder partitionByUserPrincipal(Function principalToGroup, + * Consumer> configurer) { return + * partitionResolver( exchange -> + * Optional.ofNullable(request.getUserPrincipal()).map(principalToGroup).orElse(null), + * configurer); } + */ /** - * Partition the limit by request attribute + * Partition the limit by request attribute. + * @param name attribute name * @return Chainable builder */ public ServerWebExchangeLimiterBuilder partitionByAttribute(String name) { - return partitionResolver( exchange -> exchange.getAttribute(name)); + return partitionResolver(exchange -> exchange.getAttribute(name)); } /** - * Partition the limit by request parameter + * Partition the limit by request parameter. + * @param name parameter name * @return Chainable builder */ public ServerWebExchangeLimiterBuilder partitionByParameter(String name) { - return partitionResolver(exchange -> exchange.getRequest().getQueryParams().getFirst(name)); + return partitionResolver( + exchange -> exchange.getRequest().getQueryParams().getFirst(name)); } /** - * Partition the limit by the full path. Percentages of the limit are partitioned to named - * groups. Group membership is derived from the provided mapping function. + * Partition the limit by the full path. Percentages of the limit are partitioned to + * named groups. Group membership is derived from the provided mapping function. * @param pathToGroup Mapping function from full path to a named group. * @return Chainable builder */ - public ServerWebExchangeLimiterBuilder partitionByPathInfo(Function pathToGroup) { - return partitionResolver( - exchange -> { - //TODO: pathWithinApplication? - String path = exchange.getRequest().getPath().contextPath().value(); - return Optional.ofNullable(path).map(pathToGroup).orElse(null); - }); + public ServerWebExchangeLimiterBuilder partitionByPathInfo( + Function pathToGroup) { + return partitionResolver(exchange -> { + // TODO: pathWithinApplication? + String path = exchange.getRequest().getPath().contextPath().value(); + return Optional.ofNullable(path).map(pathToGroup).orElse(null); + }); } @Override diff --git a/spring-cloud-netflix-concurrency-limits/src/main/java/org/springframework/cloud/netflix/concurrency/limits/web/ConcurrencyLimitsHandlerInterceptor.java b/spring-cloud-netflix-concurrency-limits/src/main/java/org/springframework/cloud/netflix/concurrency/limits/web/ConcurrencyLimitsHandlerInterceptor.java index c1fa1216e..d2930f017 100644 --- a/spring-cloud-netflix-concurrency-limits/src/main/java/org/springframework/cloud/netflix/concurrency/limits/web/ConcurrencyLimitsHandlerInterceptor.java +++ b/spring-cloud-netflix-concurrency-limits/src/main/java/org/springframework/cloud/netflix/concurrency/limits/web/ConcurrencyLimitsHandlerInterceptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.concurrency.limits.web; @@ -30,6 +29,12 @@ import org.springframework.http.HttpStatus; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; +/** + * A {@link HandlerInterceptor} implementation providing the possibility to use Netflix + * {@link Limiter} to handle requests. + * + * @author Spencer Gibb + */ public class ConcurrencyLimitsHandlerInterceptor implements HandlerInterceptor { private final Limiter limiter; @@ -39,7 +44,8 @@ public class ConcurrencyLimitsHandlerInterceptor implements HandlerInterceptor { } @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, + Object handler) throws Exception { Optional listener = limiter.acquire(request); if (listener.isPresent()) { request.setAttribute("concurrency_limiter_listener", listener.get()); @@ -47,29 +53,36 @@ public class ConcurrencyLimitsHandlerInterceptor implements HandlerInterceptor { } try { - //TODO: headers with information? - /*response.sendError(HttpStatus.TOO_MANY_REQUESTS.value()); - response.getWriter().print("Concurrency limit exceeded");*/ + // TODO: headers with information? + /* + * response.sendError(HttpStatus.TOO_MANY_REQUESTS.value()); + * response.getWriter().print("Concurrency limit exceeded"); + */ response.sendError(HttpStatus.TOO_MANY_REQUESTS.value(), "Concurrency limit exceeded"); - } catch (IOException e) { + } + catch (IOException e) { // ignore } return false; } @Override - public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { + public void postHandle(HttpServletRequest request, HttpServletResponse response, + Object handler, ModelAndView modelAndView) throws Exception { } @Override - public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { - Listener listener = (Listener) request.getAttribute("concurrency_limiter_listener"); + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, + Object handler, Exception ex) throws Exception { + Listener listener = (Listener) request + .getAttribute("concurrency_limiter_listener"); if (listener != null) { if (ex != null) { listener.onIgnore(); - } else { + } + else { listener.onSuccess(); } } diff --git a/spring-cloud-netflix-concurrency-limits/src/main/java/org/springframework/cloud/netflix/concurrency/limits/web/MvcConcurrencyLimitsAutoConfiguration.java b/spring-cloud-netflix-concurrency-limits/src/main/java/org/springframework/cloud/netflix/concurrency/limits/web/MvcConcurrencyLimitsAutoConfiguration.java index 5a21a1173..e6b38773a 100644 --- a/spring-cloud-netflix-concurrency-limits/src/main/java/org/springframework/cloud/netflix/concurrency/limits/web/MvcConcurrencyLimitsAutoConfiguration.java +++ b/spring-cloud-netflix-concurrency-limits/src/main/java/org/springframework/cloud/netflix/concurrency/limits/web/MvcConcurrencyLimitsAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,8 +12,8 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ + package org.springframework.cloud.netflix.concurrency.limits.web; import java.util.function.Consumer; @@ -35,14 +35,20 @@ import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +/** + * MVC autoconfiguration class for registering Netflix {@link Limiter} bean. + * + * @author Spencer Gibb + */ @Configuration @ConditionalOnWebApplication(type = Type.SERVLET) -@ConditionalOnClass({HttpServletRequest.class, HandlerInterceptor.class}) +@ConditionalOnClass({ HttpServletRequest.class, HandlerInterceptor.class }) public class MvcConcurrencyLimitsAutoConfiguration implements WebMvcConfigurer { private final ObjectProvider> configurerProvider; - public MvcConcurrencyLimitsAutoConfiguration(ObjectProvider> configurerProvider) { + public MvcConcurrencyLimitsAutoConfiguration( + ObjectProvider> configurerProvider) { this.configurerProvider = configurerProvider; } @@ -62,10 +68,11 @@ public class MvcConcurrencyLimitsAutoConfiguration implements WebMvcConfigurer { @Autowired private Limiter limiter; - @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new ConcurrencyLimitsHandlerInterceptor(limiter)); } + } -} \ No newline at end of file + +} diff --git a/spring-cloud-netflix-concurrency-limits/src/test/java/org/springframework/cloud/netflix/concurrency/limits/micrometer/MicrometerMetricRegistryTests.java b/spring-cloud-netflix-concurrency-limits/src/test/java/org/springframework/cloud/netflix/concurrency/limits/micrometer/MicrometerMetricRegistryTests.java index b209fdd45..1e702a207 100644 --- a/spring-cloud-netflix-concurrency-limits/src/test/java/org/springframework/cloud/netflix/concurrency/limits/micrometer/MicrometerMetricRegistryTests.java +++ b/spring-cloud-netflix-concurrency-limits/src/test/java/org/springframework/cloud/netflix/concurrency/limits/micrometer/MicrometerMetricRegistryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.concurrency.limits.micrometer; @@ -26,6 +25,7 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class MicrometerMetricRegistryTests { + @Test public void testGuage() { MeterRegistry registry = new SimpleMeterRegistry(); @@ -39,7 +39,7 @@ public class MicrometerMetricRegistryTests { } @Test - @Ignore //FIXME: micrometer doesn't allow recreating a gauge + @Ignore // FIXME: micrometer doesn't allow recreating a gauge public void testUnregister() { MeterRegistry registry = new SimpleMeterRegistry(); MicrometerMetricRegistry metricRegistry = new MicrometerMetricRegistry(registry); @@ -52,5 +52,5 @@ public class MicrometerMetricRegistryTests { assertThat(bar.value()).isEqualTo(20.0); } -} +} diff --git a/spring-cloud-netflix-concurrency-limits/src/test/java/org/springframework/cloud/netflix/concurrency/limits/reactive/ConcurrencyLimitsWebFilterTests.java b/spring-cloud-netflix-concurrency-limits/src/test/java/org/springframework/cloud/netflix/concurrency/limits/reactive/ConcurrencyLimitsWebFilterTests.java index 2d48fe625..11e62971a 100644 --- a/spring-cloud-netflix-concurrency-limits/src/test/java/org/springframework/cloud/netflix/concurrency/limits/reactive/ConcurrencyLimitsWebFilterTests.java +++ b/spring-cloud-netflix-concurrency-limits/src/test/java/org/springframework/cloud/netflix/concurrency/limits/reactive/ConcurrencyLimitsWebFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.concurrency.limits.reactive; @@ -37,7 +36,7 @@ import org.springframework.util.SocketUtils; import org.springframework.web.reactive.function.client.WebClient; @RunWith(ModifiedClassPathRunner.class) -@ClassPathExclusions({"spring-boot-starter-tomcat-*", "tomcat-embed-*"}) +@ClassPathExclusions({ "spring-boot-starter-tomcat-*", "tomcat-embed-*" }) public class ConcurrencyLimitsWebFilterTests extends AbstractConcurrencyLimitsTests { private int port; @@ -45,7 +44,7 @@ public class ConcurrencyLimitsWebFilterTests extends AbstractConcurrencyLimitsTe @Before public void init() { port = SocketUtils.findAvailableTcpPort(); - client = WebClient.create("http://localhost:"+port); + client = WebClient.create("http://localhost:" + port); } @Test @@ -53,7 +52,8 @@ public class ConcurrencyLimitsWebFilterTests extends AbstractConcurrencyLimitsTe public void webFilterWorks() { try (ConfigurableApplicationContext context = new SpringApplicationBuilder() - .properties("server.port="+port, "spring.main.web-application-type=reactive") + .properties("server.port=" + port, + "spring.main.web-application-type=reactive") .sources(TestConfig.class).run()) { assertLimiter(client); @@ -67,9 +67,9 @@ public class ConcurrencyLimitsWebFilterTests extends AbstractConcurrencyLimitsTe @Bean public Consumer limiterBuilderConfigurer() { - return limiterBuilder -> limiterBuilder - .limit(FixedLimit.of(1)); + return limiterBuilder -> limiterBuilder.limit(FixedLimit.of(1)); } + } } diff --git a/spring-cloud-netflix-concurrency-limits/src/test/java/org/springframework/cloud/netflix/concurrency/limits/test/AbstractConcurrencyLimitsTests.java b/spring-cloud-netflix-concurrency-limits/src/test/java/org/springframework/cloud/netflix/concurrency/limits/test/AbstractConcurrencyLimitsTests.java index 16460af0f..10758251e 100644 --- a/spring-cloud-netflix-concurrency-limits/src/test/java/org/springframework/cloud/netflix/concurrency/limits/test/AbstractConcurrencyLimitsTests.java +++ b/spring-cloud-netflix-concurrency-limits/src/test/java/org/springframework/cloud/netflix/concurrency/limits/test/AbstractConcurrencyLimitsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.concurrency.limits.test; @@ -39,26 +38,26 @@ public class AbstractConcurrencyLimitsTests { Flux> flux = Flux.range(1, 100) .flatMap(integer -> client.get().uri("/").exchange(), 4) // .log("reqs", Level.INFO) - .flatMap(response -> response.bodyToMono(String.class) - .defaultIfEmpty("") - /*.log("body2mono", Level.INFO)*/ + .flatMap(response -> response.bodyToMono(String.class).defaultIfEmpty("") + /* .log("body2mono", Level.INFO) */ .zipWith(Mono.just(response.statusCode()))); Responses responses = new Responses(); - StepVerifier.create(flux) - .thenConsumeWhile(response -> true, response -> { - HttpStatus status = response.getT2(); - if (status.equals(HttpStatus.OK)) { - responses.success.incrementAndGet(); - } else if (status.equals(HttpStatus.TOO_MANY_REQUESTS)) { - responses.tooManyReqs.incrementAndGet(); - String body = response.getT1(); - //TODO: body from handler isn't coming thru - // assertThat(body).isEqualTo("Concurrency limit exceeded"); - } else { - responses.other.incrementAndGet(); - } - }).verifyComplete(); + StepVerifier.create(flux).thenConsumeWhile(response -> true, response -> { + HttpStatus status = response.getT2(); + if (status.equals(HttpStatus.OK)) { + responses.success.incrementAndGet(); + } + else if (status.equals(HttpStatus.TOO_MANY_REQUESTS)) { + responses.tooManyReqs.incrementAndGet(); + String body = response.getT1(); + // TODO: body from handler isn't coming thru + // assertThat(body).isEqualTo("Concurrency limit exceeded"); + } + else { + responses.other.incrementAndGet(); + } + }).verifyComplete(); System.out.println("Responses: " + responses); @@ -75,5 +74,7 @@ public class AbstractConcurrencyLimitsTests { public String get() { return "Hello"; } + } + } diff --git a/spring-cloud-netflix-concurrency-limits/src/test/java/org/springframework/cloud/netflix/concurrency/limits/test/Responses.java b/spring-cloud-netflix-concurrency-limits/src/test/java/org/springframework/cloud/netflix/concurrency/limits/test/Responses.java index eeef56ab2..dd7e21fc9 100644 --- a/spring-cloud-netflix-concurrency-limits/src/test/java/org/springframework/cloud/netflix/concurrency/limits/test/Responses.java +++ b/spring-cloud-netflix-concurrency-limits/src/test/java/org/springframework/cloud/netflix/concurrency/limits/test/Responses.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,26 +12,26 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.concurrency.limits.test; -import org.springframework.core.style.ToStringCreator; - import java.util.concurrent.atomic.AtomicInteger; +import org.springframework.core.style.ToStringCreator; + public class Responses { + public AtomicInteger success = new AtomicInteger(0); + public AtomicInteger tooManyReqs = new AtomicInteger(0); + public AtomicInteger other = new AtomicInteger(0); @Override public String toString() { - return new ToStringCreator(this) - .append("success", success) - .append("tooManyReqs", tooManyReqs) - .append("other", other) - .toString(); + return new ToStringCreator(this).append("success", success) + .append("tooManyReqs", tooManyReqs).append("other", other).toString(); } + } diff --git a/spring-cloud-netflix-concurrency-limits/src/test/java/org/springframework/cloud/netflix/concurrency/limits/web/ConcurrencyLimitsHandlerInterceptorTests.java b/spring-cloud-netflix-concurrency-limits/src/test/java/org/springframework/cloud/netflix/concurrency/limits/web/ConcurrencyLimitsHandlerInterceptorTests.java index 315d960d1..fb9f8c3eb 100644 --- a/spring-cloud-netflix-concurrency-limits/src/test/java/org/springframework/cloud/netflix/concurrency/limits/web/ConcurrencyLimitsHandlerInterceptorTests.java +++ b/spring-cloud-netflix-concurrency-limits/src/test/java/org/springframework/cloud/netflix/concurrency/limits/web/ConcurrencyLimitsHandlerInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.concurrency.limits.web; @@ -39,14 +38,15 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen @RunWith(SpringRunner.class) @SpringBootTest(properties = "logging.level.reactor.netty=DEBUG", webEnvironment = RANDOM_PORT) -public class ConcurrencyLimitsHandlerInterceptorTests extends AbstractConcurrencyLimitsTests { +public class ConcurrencyLimitsHandlerInterceptorTests + extends AbstractConcurrencyLimitsTests { @LocalServerPort public int port; @Before public void init() { - client = WebClient.create("http://localhost:"+port); + client = WebClient.create("http://localhost:" + port); } @Test @@ -61,9 +61,9 @@ public class ConcurrencyLimitsHandlerInterceptorTests extends AbstractConcurrenc @Bean public Consumer limiterBuilderConfigurer() { - return servletLimiterBuilder -> servletLimiterBuilder - .limit(FixedLimit.of(1)); + return servletLimiterBuilder -> servletLimiterBuilder.limit(FixedLimit.of(1)); } + } } diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/core/CoreAutoConfiguration.java b/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/core/CoreAutoConfiguration.java index 21f4b474e..40e070b6f 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/core/CoreAutoConfiguration.java +++ b/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/core/CoreAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,21 +18,25 @@ package org.springframework.cloud.netflix.core; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.context.annotation.Configuration; /** * @author Olga Maciaszek-Sharma * @since 2.1.0 - * @deprecated Module spring-cloud-netflix-core is deprecated as of 2.1.0, use spring-cloud-netflix-hystrix instead. + * @deprecated Module spring-cloud-netflix-core is deprecated as of 2.1.0, use + * spring-cloud-netflix-hystrix instead. */ @Configuration @Deprecated public class CoreAutoConfiguration { - private static final Log LOG = LogFactory.getLog(CoreAutoConfiguration.class); + private static final Log LOG = LogFactory.getLog(CoreAutoConfiguration.class); + + public CoreAutoConfiguration() { + LOG.warn( + "This module is deprecated. It will be removed in the next major release. " + + "Please use spring-cloud-netflix-hystrix instead."); + } - public CoreAutoConfiguration() { - LOG.warn("This module is deprecated. It will be removed in the next major release. " + - "Please use spring-cloud-netflix-hystrix instead."); - } } diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/CloudEurekaClient.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/CloudEurekaClient.java index d1c8ead7d..adc9d2448 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/CloudEurekaClient.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/CloudEurekaClient.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,13 +20,6 @@ import java.lang.reflect.Field; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.cloud.client.discovery.event.HeartbeatEvent; -import org.springframework.context.ApplicationEventPublisher; -import org.springframework.http.HttpStatus; -import org.springframework.util.ReflectionUtils; - import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.InstanceStatus; @@ -35,35 +28,47 @@ import com.netflix.discovery.DiscoveryClient; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.EurekaHttpResponse; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.cloud.client.discovery.event.HeartbeatEvent; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.http.HttpStatus; +import org.springframework.util.ReflectionUtils; /** * Subclass of {@link DiscoveryClient} that sends a {@link HeartbeatEvent} when * {@link CloudEurekaClient#onCacheRefreshed()} is called. + * * @author Spencer Gibb */ public class CloudEurekaClient extends DiscoveryClient { + private static final Log log = LogFactory.getLog(CloudEurekaClient.class); private final AtomicLong cacheRefreshedCount = new AtomicLong(0); private ApplicationEventPublisher publisher; + private Field eurekaTransportField; + private ApplicationInfoManager applicationInfoManager; + private AtomicReference eurekaHttpClient = new AtomicReference<>(); public CloudEurekaClient(ApplicationInfoManager applicationInfoManager, - EurekaClientConfig config, ApplicationEventPublisher publisher) { + EurekaClientConfig config, ApplicationEventPublisher publisher) { this(applicationInfoManager, config, null, publisher); } public CloudEurekaClient(ApplicationInfoManager applicationInfoManager, - EurekaClientConfig config, - AbstractDiscoveryClientOptionalArgs args, - ApplicationEventPublisher publisher) { + EurekaClientConfig config, AbstractDiscoveryClientOptionalArgs args, + ApplicationEventPublisher publisher) { super(applicationInfoManager, config, args); this.applicationInfoManager = applicationInfoManager; this.publisher = publisher; - this.eurekaTransportField = ReflectionUtils.findField(DiscoveryClient.class, "eurekaTransport"); + this.eurekaTransportField = ReflectionUtils.findField(DiscoveryClient.class, + "eurekaTransport"); ReflectionUtils.makeAccessible(this.eurekaTransportField); } @@ -76,7 +81,8 @@ public class CloudEurekaClient extends DiscoveryClient { } public InstanceInfo getInstanceInfo(String appname, String instanceId) { - EurekaHttpResponse response = getEurekaHttpClient().getInstance(appname, instanceId); + EurekaHttpResponse response = getEurekaHttpClient() + .getInstance(appname, instanceId); HttpStatus httpStatus = HttpStatus.valueOf(response.getStatusCode()); if (httpStatus.is2xxSuccessful() && response.getEntity() != null) { return response.getEntity(); @@ -88,10 +94,13 @@ public class CloudEurekaClient extends DiscoveryClient { if (this.eurekaHttpClient.get() == null) { try { Object eurekaTransport = this.eurekaTransportField.get(this); - Field registrationClientField = ReflectionUtils.findField(eurekaTransport.getClass(), "registrationClient"); + Field registrationClientField = ReflectionUtils + .findField(eurekaTransport.getClass(), "registrationClient"); ReflectionUtils.makeAccessible(registrationClientField); - this.eurekaHttpClient.compareAndSet(null, (EurekaHttpClient) registrationClientField.get(eurekaTransport)); - } catch (IllegalAccessException e) { + this.eurekaHttpClient.compareAndSet(null, + (EurekaHttpClient) registrationClientField.get(eurekaTransport)); + } + catch (IllegalAccessException e) { log.error("error getting EurekaHttpClient", e); } } @@ -99,17 +108,20 @@ public class CloudEurekaClient extends DiscoveryClient { } public void setStatus(InstanceStatus newStatus, InstanceInfo info) { - getEurekaHttpClient().statusUpdate(info.getAppName(), info.getId(), newStatus, info); + getEurekaHttpClient().statusUpdate(info.getAppName(), info.getId(), newStatus, + info); } @Override protected void onCacheRefreshed() { super.onCacheRefreshed(); - if (this.cacheRefreshedCount != null) { //might be called during construction and will be null + if (this.cacheRefreshedCount != null) { // might be called during construction and + // will be null long newCount = this.cacheRefreshedCount.incrementAndGet(); log.trace("onCacheRefreshed called with count: " + newCount); this.publisher.publishEvent(new HeartbeatEvent(this, newCount)); } } + } diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/CloudEurekaInstanceConfig.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/CloudEurekaInstanceConfig.java index 6ea3e8892..c22734423 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/CloudEurekaInstanceConfig.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/CloudEurekaInstanceConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +23,11 @@ import com.netflix.appinfo.InstanceInfo; * @author Spencer Gibb */ public interface CloudEurekaInstanceConfig extends EurekaInstanceConfig { + void setNonSecurePort(int port); + void setSecurePort(int securePort); + InstanceInfo.InstanceStatus getInitialStatus(); + } diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/CloudEurekaTransportConfig.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/CloudEurekaTransportConfig.java index 5eb211639..1c27bf742 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/CloudEurekaTransportConfig.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/CloudEurekaTransportConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,10 +16,10 @@ package org.springframework.cloud.netflix.eureka; -import com.netflix.discovery.shared.transport.EurekaTransportConfig; - import java.util.Objects; +import com.netflix.discovery.shared.transport.EurekaTransportConfig; + /** * @author Spencer Gibb * @author Gregor Zurowski @@ -162,21 +162,27 @@ public class CloudEurekaTransportConfig implements EurekaTransportConfig { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } CloudEurekaTransportConfig that = (CloudEurekaTransportConfig) o; - return sessionedClientReconnectIntervalSeconds == that.sessionedClientReconnectIntervalSeconds && - Double.compare(retryableClientQuarantineRefreshPercentage, that.retryableClientQuarantineRefreshPercentage) == 0 && - bootstrapResolverRefreshIntervalSeconds == that.bootstrapResolverRefreshIntervalSeconds && - applicationsResolverDataStalenessThresholdSeconds == that.applicationsResolverDataStalenessThresholdSeconds && - asyncResolverRefreshIntervalMs == that.asyncResolverRefreshIntervalMs && - asyncResolverWarmUpTimeoutMs == that.asyncResolverWarmUpTimeoutMs && - asyncExecutorThreadPoolSize == that.asyncExecutorThreadPoolSize && - Objects.equals(readClusterVip, that.readClusterVip) && - Objects.equals(writeClusterVip, that.writeClusterVip) && - bootstrapResolverForQuery == that.bootstrapResolverForQuery && - Objects.equals(bootstrapResolverStrategy, that.bootstrapResolverStrategy) && - applicationsResolverUseIp == that.applicationsResolverUseIp; + return sessionedClientReconnectIntervalSeconds == that.sessionedClientReconnectIntervalSeconds + && Double.compare(retryableClientQuarantineRefreshPercentage, + that.retryableClientQuarantineRefreshPercentage) == 0 + && bootstrapResolverRefreshIntervalSeconds == that.bootstrapResolverRefreshIntervalSeconds + && applicationsResolverDataStalenessThresholdSeconds == that.applicationsResolverDataStalenessThresholdSeconds + && asyncResolverRefreshIntervalMs == that.asyncResolverRefreshIntervalMs + && asyncResolverWarmUpTimeoutMs == that.asyncResolverWarmUpTimeoutMs + && asyncExecutorThreadPoolSize == that.asyncExecutorThreadPoolSize + && Objects.equals(readClusterVip, that.readClusterVip) + && Objects.equals(writeClusterVip, that.writeClusterVip) + && bootstrapResolverForQuery == that.bootstrapResolverForQuery + && Objects.equals(bootstrapResolverStrategy, + that.bootstrapResolverStrategy) + && applicationsResolverUseIp == that.applicationsResolverUseIp; } @Override @@ -194,18 +200,27 @@ public class CloudEurekaTransportConfig implements EurekaTransportConfig { @Override public String toString() { return new StringBuilder("CloudEurekaTransportConfig{") - .append("sessionedClientReconnectIntervalSeconds=").append(sessionedClientReconnectIntervalSeconds).append(", ") - .append("retryableClientQuarantineRefreshPercentage=").append(retryableClientQuarantineRefreshPercentage).append(", ") - .append("bootstrapResolverRefreshIntervalSeconds=").append(bootstrapResolverRefreshIntervalSeconds).append(", ") - .append("applicationsResolverDataStalenessThresholdSeconds=").append(applicationsResolverDataStalenessThresholdSeconds).append(", ") - .append("asyncResolverRefreshIntervalMs=").append(asyncResolverRefreshIntervalMs).append(", ") - .append("asyncResolverWarmUpTimeoutMs=").append(asyncResolverWarmUpTimeoutMs).append(", ") - .append("asyncExecutorThreadPoolSize=").append(asyncExecutorThreadPoolSize).append(", ") + .append("sessionedClientReconnectIntervalSeconds=") + .append(sessionedClientReconnectIntervalSeconds).append(", ") + .append("retryableClientQuarantineRefreshPercentage=") + .append(retryableClientQuarantineRefreshPercentage).append(", ") + .append("bootstrapResolverRefreshIntervalSeconds=") + .append(bootstrapResolverRefreshIntervalSeconds).append(", ") + .append("applicationsResolverDataStalenessThresholdSeconds=") + .append(applicationsResolverDataStalenessThresholdSeconds).append(", ") + .append("asyncResolverRefreshIntervalMs=") + .append(asyncResolverRefreshIntervalMs).append(", ") + .append("asyncResolverWarmUpTimeoutMs=") + .append(asyncResolverWarmUpTimeoutMs).append(", ") + .append("asyncExecutorThreadPoolSize=") + .append(asyncExecutorThreadPoolSize).append(", ") .append("readClusterVip='").append(readClusterVip).append("', ") .append("writeClusterVip='").append(writeClusterVip).append("', ") - .append("bootstrapResolverForQuery=").append(bootstrapResolverForQuery).append(", ") - .append("bootstrapResolverStrategy='").append(bootstrapResolverStrategy).append("', ") - .append("applicationsResolverUseIp=").append(applicationsResolverUseIp).append(", ").append("}") - .toString(); + .append("bootstrapResolverForQuery=").append(bootstrapResolverForQuery) + .append(", ").append("bootstrapResolverStrategy='") + .append(bootstrapResolverStrategy).append("', ") + .append("applicationsResolverUseIp=").append(applicationsResolverUseIp) + .append(", ").append("}").toString(); } + } diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaClientAutoConfiguration.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaClientAutoConfiguration.java index 9441fb3ce..21bf93380 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaClientAutoConfiguration.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaClientAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +23,14 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.Map; +import com.netflix.appinfo.ApplicationInfoManager; +import com.netflix.appinfo.EurekaInstanceConfig; +import com.netflix.appinfo.HealthCheckHandler; +import com.netflix.appinfo.InstanceInfo; +import com.netflix.discovery.AbstractDiscoveryClientOptionalArgs; +import com.netflix.discovery.EurekaClient; +import com.netflix.discovery.EurekaClientConfig; + import org.springframework.aop.support.AopUtils; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Autowired; @@ -64,14 +72,6 @@ import org.springframework.context.annotation.Lazy; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.util.StringUtils; -import com.netflix.appinfo.ApplicationInfoManager; -import com.netflix.appinfo.EurekaInstanceConfig; -import com.netflix.appinfo.HealthCheckHandler; -import com.netflix.appinfo.InstanceInfo; -import com.netflix.discovery.AbstractDiscoveryClientOptionalArgs; -import com.netflix.discovery.EurekaClient; -import com.netflix.discovery.EurekaClientConfig; - import static org.springframework.cloud.commons.util.IdUtils.getDefaultInstanceId; /** @@ -90,9 +90,10 @@ import static org.springframework.cloud.commons.util.IdUtils.getDefaultInstanceI @ConditionalOnProperty(value = "eureka.client.enabled", matchIfMissing = true) @AutoConfigureBefore({ NoopDiscoveryClientAutoConfiguration.class, CommonsClientAutoConfiguration.class, ServiceRegistryAutoConfiguration.class }) -@AutoConfigureAfter(name = {"org.springframework.cloud.autoconfigure.RefreshAutoConfiguration", +@AutoConfigureAfter(name = { + "org.springframework.cloud.autoconfigure.RefreshAutoConfiguration", "org.springframework.cloud.netflix.eureka.EurekaDiscoveryClientConfiguration", - "org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationAutoConfiguration"}) + "org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationAutoConfiguration" }) public class EurekaClientAutoConfiguration { private ConfigurableEnvironment env; @@ -131,18 +132,31 @@ public class EurekaClientAutoConfiguration { @Bean @ConditionalOnMissingBean(value = EurekaInstanceConfig.class, search = SearchStrategy.CURRENT) public EurekaInstanceConfigBean eurekaInstanceConfigBean(InetUtils inetUtils, - ManagementMetadataProvider managementMetadataProvider) { + ManagementMetadataProvider managementMetadataProvider) { String hostname = getProperty("eureka.instance.hostname"); - boolean preferIpAddress = Boolean.parseBoolean(getProperty("eureka.instance.prefer-ip-address")); + boolean preferIpAddress = Boolean + .parseBoolean(getProperty("eureka.instance.prefer-ip-address")); String ipAddress = getProperty("eureka.instance.ip-address"); - boolean isSecurePortEnabled = Boolean.parseBoolean(getProperty("eureka.instance.secure-port-enabled")); + boolean isSecurePortEnabled = Boolean + .parseBoolean(getProperty("eureka.instance.secure-port-enabled")); String serverContextPath = env.getProperty("server.context-path", "/"); - int serverPort = Integer.valueOf(env.getProperty("server.port", env.getProperty("port", "8080"))); + int serverPort = Integer + .valueOf(env.getProperty("server.port", env.getProperty("port", "8080"))); - Integer managementPort = env.getProperty("management.server.port", Integer.class);// nullable. should be wrapped into optional - String managementContextPath = env.getProperty("management.server.servlet.context-path");// nullable. should be wrapped into optional - Integer jmxPort = env.getProperty("com.sun.management.jmxremote.port", Integer.class);//nullable + Integer managementPort = env.getProperty("management.server.port", Integer.class); // nullable. + // should + // be + // wrapped + // into + // optional + String managementContextPath = env + .getProperty("management.server.servlet.context-path"); // nullable. + // should + // be wrapped into + // optional + Integer jmxPort = env.getProperty("com.sun.management.jmxremote.port", + Integer.class); // nullable EurekaInstanceConfigBean instance = new EurekaInstanceConfigBean(inetUtils); instance.setNonSecurePort(serverPort); @@ -153,7 +167,7 @@ public class EurekaClientAutoConfiguration { instance.setIpAddress(ipAddress); } - if(isSecurePortEnabled) { + if (isSecurePortEnabled) { instance.setSecurePort(serverPort); } @@ -173,23 +187,25 @@ public class EurekaClientAutoConfiguration { ManagementMetadata metadata = managementMetadataProvider.get(instance, serverPort, serverContextPath, managementContextPath, managementPort); - if(metadata != null) { + if (metadata != null) { instance.setStatusPageUrl(metadata.getStatusPageUrl()); instance.setHealthCheckUrl(metadata.getHealthCheckUrl()); - if(instance.isSecurePortEnabled()) { + if (instance.isSecurePortEnabled()) { instance.setSecureHealthCheckUrl(metadata.getSecureHealthCheckUrl()); } Map metadataMap = instance.getMetadataMap(); - if (metadataMap.get("management.port") == null) { - metadataMap.put("management.port", String.valueOf(metadata.getManagementPort())); - } - } else { - //without the metadata the status and health check URLs will not be set - //and the status page and health check url paths will not include the - //context path so set them here - if(StringUtils.hasText(managementContextPath)) { - instance.setHealthCheckUrlPath(managementContextPath + instance.getHealthCheckUrlPath()); - instance.setStatusPageUrlPath(managementContextPath + instance.getStatusPageUrlPath()); + metadataMap.computeIfAbsent("management.port", + k -> String.valueOf(metadata.getManagementPort())); + } + else { + // without the metadata the status and health check URLs will not be set + // and the status page and health check url paths will not include the + // context path so set them here + if (StringUtils.hasText(managementContextPath)) { + instance.setHealthCheckUrlPath( + managementContextPath + instance.getHealthCheckUrlPath()); + instance.setStatusPageUrlPath( + managementContextPath + instance.getStatusPageUrlPath()); } } @@ -205,7 +221,8 @@ public class EurekaClientAutoConfiguration { } @Bean - public DiscoveryClient discoveryClient(EurekaClient client, EurekaClientConfig clientConfig) { + public DiscoveryClient discoveryClient(EurekaClient client, + EurekaClientConfig clientConfig) { return new EurekaDiscoveryClient(client, clientConfig); } @@ -214,22 +231,26 @@ public class EurekaClientAutoConfiguration { return new EurekaServiceRegistry(); } -// @Bean -// @ConditionalOnBean(AutoServiceRegistrationProperties.class) -// @ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true) -// public EurekaRegistration eurekaRegistration(EurekaClient eurekaClient, CloudEurekaInstanceConfig instanceConfig, ApplicationInfoManager applicationInfoManager, ObjectProvider healthCheckHandler) { -// return EurekaRegistration.builder(instanceConfig) -// .with(applicationInfoManager) -// .with(eurekaClient) -// .with(healthCheckHandler) -// .build(); -// } + // @Bean + // @ConditionalOnBean(AutoServiceRegistrationProperties.class) + // @ConditionalOnProperty(value = + // "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true) + // public EurekaRegistration eurekaRegistration(EurekaClient eurekaClient, + // CloudEurekaInstanceConfig instanceConfig, ApplicationInfoManager + // applicationInfoManager, ObjectProvider healthCheckHandler) { + // return EurekaRegistration.builder(instanceConfig) + // .with(applicationInfoManager) + // .with(eurekaClient) + // .with(healthCheckHandler) + // .build(); + // } @Bean @ConditionalOnBean(AutoServiceRegistrationProperties.class) @ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true) - public EurekaAutoServiceRegistration eurekaAutoServiceRegistration(ApplicationContext context, EurekaServiceRegistry registry, - EurekaRegistration registration) { + public EurekaAutoServiceRegistration eurekaAutoServiceRegistration( + ApplicationContext context, EurekaServiceRegistry registry, + EurekaRegistration registration) { return new EurekaAutoServiceRegistration(context, registry, registration); } @@ -245,7 +266,8 @@ public class EurekaClientAutoConfiguration { @Bean(destroyMethod = "shutdown") @ConditionalOnMissingBean(value = EurekaClient.class, search = SearchStrategy.CURRENT) - public EurekaClient eurekaClient(ApplicationInfoManager manager, EurekaClientConfig config) { + public EurekaClient eurekaClient(ApplicationInfoManager manager, + EurekaClientConfig config) { return new CloudEurekaClient(manager, config, this.optionalArgs, this.context); } @@ -262,15 +284,13 @@ public class EurekaClientAutoConfiguration { @ConditionalOnBean(AutoServiceRegistrationProperties.class) @ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true) public EurekaRegistration eurekaRegistration(EurekaClient eurekaClient, - CloudEurekaInstanceConfig instanceConfig, - ApplicationInfoManager applicationInfoManager, - @Autowired(required = false) ObjectProvider healthCheckHandler) { - return EurekaRegistration.builder(instanceConfig) - .with(applicationInfoManager) - .with(eurekaClient) - .with(healthCheckHandler) - .build(); + CloudEurekaInstanceConfig instanceConfig, + ApplicationInfoManager applicationInfoManager, + @Autowired(required = false) ObjectProvider healthCheckHandler) { + return EurekaRegistration.builder(instanceConfig).with(applicationInfoManager) + .with(eurekaClient).with(healthCheckHandler).build(); } + } @Configuration @@ -287,20 +307,25 @@ public class EurekaClientAutoConfiguration { @ConditionalOnMissingBean(value = EurekaClient.class, search = SearchStrategy.CURRENT) @org.springframework.cloud.context.config.annotation.RefreshScope @Lazy - public EurekaClient eurekaClient(ApplicationInfoManager manager, EurekaClientConfig config, EurekaInstanceConfig instance, - @Autowired(required = false) HealthCheckHandler healthCheckHandler) { - //If we use the proxy of the ApplicationInfoManager we could run into a problem - //when shutdown is called on the CloudEurekaClient where the ApplicationInfoManager bean is - //requested but wont be allowed because we are shutting down. To avoid this we use the - //object directly. + public EurekaClient eurekaClient(ApplicationInfoManager manager, + EurekaClientConfig config, EurekaInstanceConfig instance, + @Autowired(required = false) HealthCheckHandler healthCheckHandler) { + // If we use the proxy of the ApplicationInfoManager we could run into a + // problem + // when shutdown is called on the CloudEurekaClient where the + // ApplicationInfoManager bean is + // requested but wont be allowed because we are shutting down. To avoid this + // we use the + // object directly. ApplicationInfoManager appManager; - if(AopUtils.isAopProxy(manager)) { + if (AopUtils.isAopProxy(manager)) { appManager = ProxyUtils.getTargetObject(manager); - } else { + } + else { appManager = manager; } - CloudEurekaClient cloudEurekaClient = new CloudEurekaClient(appManager, config, this.optionalArgs, - this.context); + CloudEurekaClient cloudEurekaClient = new CloudEurekaClient(appManager, + config, this.optionalArgs, this.context); cloudEurekaClient.registerHealthCheck(healthCheckHandler); return cloudEurekaClient; } @@ -309,7 +334,8 @@ public class EurekaClientAutoConfiguration { @ConditionalOnMissingBean(value = ApplicationInfoManager.class, search = SearchStrategy.CURRENT) @org.springframework.cloud.context.config.annotation.RefreshScope @Lazy - public ApplicationInfoManager eurekaApplicationInfoManager(EurekaInstanceConfig config) { + public ApplicationInfoManager eurekaApplicationInfoManager( + EurekaInstanceConfig config) { InstanceInfo instanceInfo = new InstanceInfoFactory().create(config); return new ApplicationInfoManager(config, instanceInfo); } @@ -319,14 +345,11 @@ public class EurekaClientAutoConfiguration { @ConditionalOnBean(AutoServiceRegistrationProperties.class) @ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true) public EurekaRegistration eurekaRegistration(EurekaClient eurekaClient, - CloudEurekaInstanceConfig instanceConfig, - ApplicationInfoManager applicationInfoManager, - @Autowired(required = false) ObjectProvider healthCheckHandler) { - return EurekaRegistration.builder(instanceConfig) - .with(applicationInfoManager) - .with(eurekaClient) - .with(healthCheckHandler) - .build(); + CloudEurekaInstanceConfig instanceConfig, + ApplicationInfoManager applicationInfoManager, + @Autowired(required = false) ObjectProvider healthCheckHandler) { + return EurekaRegistration.builder(instanceConfig).with(applicationInfoManager) + .with(eurekaClient).with(healthCheckHandler).build(); } } @@ -350,16 +373,18 @@ public class EurekaClientAutoConfiguration { private static class OnMissingRefreshScopeCondition extends AnyNestedCondition { - public OnMissingRefreshScopeCondition() { + OnMissingRefreshScopeCondition() { super(ConfigurationPhase.REGISTER_BEAN); } @ConditionalOnMissingClass("org.springframework.cloud.context.scope.refresh.RefreshScope") static class MissingClass { + } @ConditionalOnMissingBean(RefreshAutoConfiguration.class) static class MissingScope { + } } @@ -367,12 +392,15 @@ public class EurekaClientAutoConfiguration { @Configuration @ConditionalOnClass(Health.class) protected static class EurekaHealthIndicatorConfiguration { + @Bean @ConditionalOnMissingBean @ConditionalOnEnabledHealthIndicator("eureka") public EurekaHealthIndicator eurekaHealthIndicator(EurekaClient eurekaClient, - EurekaInstanceConfig instanceConfig, EurekaClientConfig clientConfig) { + EurekaInstanceConfig instanceConfig, EurekaClientConfig clientConfig) { return new EurekaHealthIndicator(eurekaClient, instanceConfig, clientConfig); } + } + } diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaClientConfigBean.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaClientConfigBean.java index e136a39b4..a96ece424 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaClientConfigBean.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaClientConfigBean.java @@ -1,18 +1,18 @@ /* -* Copyright 2013-2014 the original author or authors. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Copyright 2013-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.springframework.cloud.netflix.eureka; @@ -36,17 +36,28 @@ import org.springframework.util.StringUtils; import static org.springframework.cloud.netflix.eureka.EurekaConstants.DEFAULT_PREFIX; /** + * Eureka client configuration bean. + * * @author Dave Syer * @author Gregor Zurowski */ @ConfigurationProperties(EurekaClientConfigBean.PREFIX) public class EurekaClientConfigBean implements EurekaClientConfig, Ordered { + /** + * Default prefix for Eureka client config properties. + */ public static final String PREFIX = "eureka.client"; + /** + * Default Eureka URL. + */ public static final String DEFAULT_URL = "http://localhost:8761" + DEFAULT_PREFIX + "/"; + /** + * Default availability zone if none is resolved based on region. + */ public static final String DEFAULT_ZONE = "defaultZone"; private static final int MINUTES = 60; @@ -76,7 +87,7 @@ public class EurekaClientConfigBean implements EurekaClientConfig, Ordered { /** * Indicates how long initially (in seconds) to replicate instance info to the eureka - * server + * server. */ private int initialInstanceInfoReplicationIntervalSeconds = 40; @@ -191,7 +202,7 @@ public class EurekaClientConfigBean implements EurekaClientConfig, Ordered { * * In the AWS environment, it is recommended that the values is 30 seconds or less, * since the firewall cleans up the connection information after a few mins leaving - * the connection hanging in limbo + * the connection hanging in limbo. */ private int eurekaConnectionIdleTimeoutSeconds = 30; @@ -202,7 +213,7 @@ public class EurekaClientConfigBean implements EurekaClientConfig, Ordered { private String registryRefreshSingleVipAddress; /** - * The thread pool size for the heartbeatExecutor to initialise with + * The thread pool size for the heartbeatExecutor to initialise with. */ private int heartbeatExecutorThreadPoolSize = 2; @@ -213,7 +224,7 @@ public class EurekaClientConfigBean implements EurekaClientConfig, Ordered { private int heartbeatExecutorExponentialBackOffBound = 10; /** - * The thread pool size for the cacheRefreshExecutor to initialise with + * The thread pool size for the cacheRefreshExecutor to initialise with. */ private int cacheRefreshExecutorThreadPoolSize = 2; @@ -349,8 +360,8 @@ public class EurekaClientConfigBean implements EurekaClientConfig, Ordered { private String dollarReplacement = "_-"; /** - * Get a replacement string for underscore sign _ during - * serializing/deserializing information in eureka server. + * Get a replacement string for underscore sign _ during serializing/ + * deserializing information in eureka server. */ private String escapeCharReplacement = "__"; @@ -363,40 +374,42 @@ public class EurekaClientConfigBean implements EurekaClientConfig, Ordered { /** * If set to true, local status updates via ApplicationInfoManager will trigger - * on-demand (but rate limited) register/updates to remote eureka servers + * on-demand (but rate limited) register/updates to remote eureka servers. */ private boolean onDemandUpdateStatusChange = true; /** * This is a transient config and once the latest codecs are stable, can be removed - * (as there will only be one) + * (as there will only be one). */ private String encoderName; /** * This is a transient config and once the latest codecs are stable, can be removed - * (as there will only be one) + * (as there will only be one). */ private String decoderName; /** - * EurekaAccept name for client data accept + * EurekaAccept name for client data accept. */ private String clientDataAccept = EurekaAccept.full.name(); /** - * Indicates whether the client should explicitly unregister itself from the remote server - * on client shutdown. + * Indicates whether the client should explicitly unregister itself from the remote + * server on client shutdown. */ private boolean shouldUnregisterOnShutdown = true; /** - * Indicates whether the client should enforce registration during initialization. Defaults to false. + * Indicates whether the client should enforce registration during initialization. + * Defaults to false. */ private boolean shouldEnforceRegistrationAtInit = false; /** - * Order of the discovery client used by `CompositeDiscoveryClient` for sorting available clients. + * Order of the discovery client used by `CompositeDiscoveryClient` for sorting + * available clients. */ private int order = 0; @@ -461,7 +474,8 @@ public class EurekaClientConfigBean implements EurekaClientConfig, Ordered { serviceUrls = this.serviceUrl.get(DEFAULT_ZONE); } if (!StringUtils.isEmpty(serviceUrls)) { - final String[] serviceUrlsSplit = StringUtils.commaDelimitedListToStringArray(serviceUrls); + final String[] serviceUrlsSplit = StringUtils + .commaDelimitedListToStringArray(serviceUrls); List eurekaServiceUrls = new ArrayList<>(serviceUrlsSplit.length); for (String eurekaServiceUrl : serviceUrlsSplit) { if (!endsWithSlash(eurekaServiceUrl)) { @@ -915,7 +929,8 @@ public class EurekaClientConfigBean implements EurekaClientConfig, Ordered { return shouldEnforceRegistrationAtInit; } - public void setShouldEnforceRegistrationAtInit(boolean shouldEnforceRegistrationAtInit) { + public void setShouldEnforceRegistrationAtInit( + boolean shouldEnforceRegistrationAtInit) { this.shouldEnforceRegistrationAtInit = shouldEnforceRegistrationAtInit; } @@ -930,56 +945,60 @@ public class EurekaClientConfigBean implements EurekaClientConfig, Ordered { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } EurekaClientConfigBean that = (EurekaClientConfigBean) o; - return Objects.equals(propertyResolver, that.propertyResolver) && - enabled == that.enabled && - Objects.equals(transport, that.transport) && - registryFetchIntervalSeconds == that.registryFetchIntervalSeconds && - instanceInfoReplicationIntervalSeconds == that.instanceInfoReplicationIntervalSeconds && - initialInstanceInfoReplicationIntervalSeconds == that.initialInstanceInfoReplicationIntervalSeconds && - eurekaServiceUrlPollIntervalSeconds == that.eurekaServiceUrlPollIntervalSeconds && - eurekaServerReadTimeoutSeconds == that.eurekaServerReadTimeoutSeconds && - eurekaServerConnectTimeoutSeconds == that.eurekaServerConnectTimeoutSeconds && - eurekaServerTotalConnections == that.eurekaServerTotalConnections && - eurekaServerTotalConnectionsPerHost == that.eurekaServerTotalConnectionsPerHost && - eurekaConnectionIdleTimeoutSeconds == that.eurekaConnectionIdleTimeoutSeconds && - heartbeatExecutorThreadPoolSize == that.heartbeatExecutorThreadPoolSize && - heartbeatExecutorExponentialBackOffBound == that.heartbeatExecutorExponentialBackOffBound && - cacheRefreshExecutorThreadPoolSize == that.cacheRefreshExecutorThreadPoolSize && - cacheRefreshExecutorExponentialBackOffBound == that.cacheRefreshExecutorExponentialBackOffBound && - gZipContent == that.gZipContent && - useDnsForFetchingServiceUrls == that.useDnsForFetchingServiceUrls && - registerWithEureka == that.registerWithEureka && - preferSameZoneEureka == that.preferSameZoneEureka && - logDeltaDiff == that.logDeltaDiff && - disableDelta == that.disableDelta && - filterOnlyUpInstances == that.filterOnlyUpInstances && - fetchRegistry == that.fetchRegistry && - allowRedirects == that.allowRedirects && - onDemandUpdateStatusChange == that.onDemandUpdateStatusChange && - shouldUnregisterOnShutdown == that.shouldUnregisterOnShutdown && - shouldEnforceRegistrationAtInit == that.shouldEnforceRegistrationAtInit && - Objects.equals(proxyPort, that.proxyPort) && - Objects.equals(proxyHost, that.proxyHost) && - Objects.equals(proxyUserName, that.proxyUserName) && - Objects.equals(proxyPassword, that.proxyPassword) && - Objects.equals(backupRegistryImpl, that.backupRegistryImpl) && - Objects.equals(eurekaServerURLContext, that.eurekaServerURLContext) && - Objects.equals(eurekaServerPort, that.eurekaServerPort) && - Objects.equals(eurekaServerDNSName, that.eurekaServerDNSName) && - Objects.equals(region, that.region) && - Objects.equals(registryRefreshSingleVipAddress, that.registryRefreshSingleVipAddress) && - Objects.equals(serviceUrl, that.serviceUrl) && - Objects.equals(fetchRemoteRegionsRegistry, that.fetchRemoteRegionsRegistry) && - Objects.equals(availabilityZones, that.availabilityZones) && - Objects.equals(dollarReplacement, that.dollarReplacement) && - Objects.equals(escapeCharReplacement, that.escapeCharReplacement) && - Objects.equals(encoderName, that.encoderName) && - Objects.equals(decoderName, that.decoderName) && - Objects.equals(clientDataAccept, that.clientDataAccept) && - Objects.equals(order, that.order); + return Objects.equals(propertyResolver, that.propertyResolver) + && enabled == that.enabled && Objects.equals(transport, that.transport) + && registryFetchIntervalSeconds == that.registryFetchIntervalSeconds + && instanceInfoReplicationIntervalSeconds == that.instanceInfoReplicationIntervalSeconds + && initialInstanceInfoReplicationIntervalSeconds == that.initialInstanceInfoReplicationIntervalSeconds + && eurekaServiceUrlPollIntervalSeconds == that.eurekaServiceUrlPollIntervalSeconds + && eurekaServerReadTimeoutSeconds == that.eurekaServerReadTimeoutSeconds + && eurekaServerConnectTimeoutSeconds == that.eurekaServerConnectTimeoutSeconds + && eurekaServerTotalConnections == that.eurekaServerTotalConnections + && eurekaServerTotalConnectionsPerHost == that.eurekaServerTotalConnectionsPerHost + && eurekaConnectionIdleTimeoutSeconds == that.eurekaConnectionIdleTimeoutSeconds + && heartbeatExecutorThreadPoolSize == that.heartbeatExecutorThreadPoolSize + && heartbeatExecutorExponentialBackOffBound == that.heartbeatExecutorExponentialBackOffBound + && cacheRefreshExecutorThreadPoolSize == that.cacheRefreshExecutorThreadPoolSize + && cacheRefreshExecutorExponentialBackOffBound == that.cacheRefreshExecutorExponentialBackOffBound + && gZipContent == that.gZipContent + && useDnsForFetchingServiceUrls == that.useDnsForFetchingServiceUrls + && registerWithEureka == that.registerWithEureka + && preferSameZoneEureka == that.preferSameZoneEureka + && logDeltaDiff == that.logDeltaDiff && disableDelta == that.disableDelta + && filterOnlyUpInstances == that.filterOnlyUpInstances + && fetchRegistry == that.fetchRegistry + && allowRedirects == that.allowRedirects + && onDemandUpdateStatusChange == that.onDemandUpdateStatusChange + && shouldUnregisterOnShutdown == that.shouldUnregisterOnShutdown + && shouldEnforceRegistrationAtInit == that.shouldEnforceRegistrationAtInit + && Objects.equals(proxyPort, that.proxyPort) + && Objects.equals(proxyHost, that.proxyHost) + && Objects.equals(proxyUserName, that.proxyUserName) + && Objects.equals(proxyPassword, that.proxyPassword) + && Objects.equals(backupRegistryImpl, that.backupRegistryImpl) + && Objects.equals(eurekaServerURLContext, that.eurekaServerURLContext) + && Objects.equals(eurekaServerPort, that.eurekaServerPort) + && Objects.equals(eurekaServerDNSName, that.eurekaServerDNSName) + && Objects.equals(region, that.region) + && Objects.equals(registryRefreshSingleVipAddress, + that.registryRefreshSingleVipAddress) + && Objects.equals(serviceUrl, that.serviceUrl) + && Objects.equals(fetchRemoteRegionsRegistry, + that.fetchRemoteRegionsRegistry) + && Objects.equals(availabilityZones, that.availabilityZones) + && Objects.equals(dollarReplacement, that.dollarReplacement) + && Objects.equals(escapeCharReplacement, that.escapeCharReplacement) + && Objects.equals(encoderName, that.encoderName) + && Objects.equals(decoderName, that.decoderName) + && Objects.equals(clientDataAccept, that.clientDataAccept) + && Objects.equals(order, that.order); } @Override @@ -1006,54 +1025,70 @@ public class EurekaClientConfigBean implements EurekaClientConfig, Ordered { @Override public String toString() { - return new StringBuilder("EurekaClientConfigBean{") - .append("propertyResolver=").append(propertyResolver).append(", ") - .append("enabled=").append(enabled).append(", ") - .append("transport=").append(transport).append(", ") - .append("registryFetchIntervalSeconds=").append(registryFetchIntervalSeconds).append(", ") - .append("instanceInfoReplicationIntervalSeconds=").append(instanceInfoReplicationIntervalSeconds).append(", ") - .append("initialInstanceInfoReplicationIntervalSeconds=").append(initialInstanceInfoReplicationIntervalSeconds).append(", ") - .append("eurekaServiceUrlPollIntervalSeconds=").append(eurekaServiceUrlPollIntervalSeconds).append(", ") + return new StringBuilder("EurekaClientConfigBean{").append("propertyResolver=") + .append(propertyResolver).append(", ").append("enabled=").append(enabled) + .append(", ").append("transport=").append(transport).append(", ") + .append("registryFetchIntervalSeconds=") + .append(registryFetchIntervalSeconds).append(", ") + .append("instanceInfoReplicationIntervalSeconds=") + .append(instanceInfoReplicationIntervalSeconds).append(", ") + .append("initialInstanceInfoReplicationIntervalSeconds=") + .append(initialInstanceInfoReplicationIntervalSeconds).append(", ") + .append("eurekaServiceUrlPollIntervalSeconds=") + .append(eurekaServiceUrlPollIntervalSeconds).append(", ") .append("proxyPort='").append(proxyPort).append("', ") .append("proxyHost='").append(proxyHost).append("', ") .append("proxyUserName='").append(proxyUserName).append("', ") .append("proxyPassword='").append(proxyPassword).append("', ") - .append("eurekaServerReadTimeoutSeconds=").append(eurekaServerReadTimeoutSeconds).append(", ") - .append("eurekaServerConnectTimeoutSeconds=").append(eurekaServerConnectTimeoutSeconds).append(", ") + .append("eurekaServerReadTimeoutSeconds=") + .append(eurekaServerReadTimeoutSeconds).append(", ") + .append("eurekaServerConnectTimeoutSeconds=") + .append(eurekaServerConnectTimeoutSeconds).append(", ") .append("backupRegistryImpl='").append(backupRegistryImpl).append("', ") - .append("eurekaServerTotalConnections=").append(eurekaServerTotalConnections).append(", ") - .append("eurekaServerTotalConnectionsPerHost=").append(eurekaServerTotalConnectionsPerHost).append(", ") - .append("eurekaServerURLContext='").append(eurekaServerURLContext).append("', ") - .append("eurekaServerPort='").append(eurekaServerPort).append("', ") - .append("eurekaServerDNSName='").append(eurekaServerDNSName).append("', ") - .append("region='").append(region).append("', ") - .append("eurekaConnectionIdleTimeoutSeconds=").append(eurekaConnectionIdleTimeoutSeconds).append(", ") - .append("registryRefreshSingleVipAddress='").append(registryRefreshSingleVipAddress).append("', ") - .append("heartbeatExecutorThreadPoolSize=").append(heartbeatExecutorThreadPoolSize).append(", ") - .append("heartbeatExecutorExponentialBackOffBound=").append(heartbeatExecutorExponentialBackOffBound).append(", ") - .append("cacheRefreshExecutorThreadPoolSize=").append(cacheRefreshExecutorThreadPoolSize).append(", ") - .append("cacheRefreshExecutorExponentialBackOffBound=").append(cacheRefreshExecutorExponentialBackOffBound).append(", ") + .append("eurekaServerTotalConnections=") + .append(eurekaServerTotalConnections).append(", ") + .append("eurekaServerTotalConnectionsPerHost=") + .append(eurekaServerTotalConnectionsPerHost).append(", ") + .append("eurekaServerURLContext='").append(eurekaServerURLContext) + .append("', ").append("eurekaServerPort='").append(eurekaServerPort) + .append("', ").append("eurekaServerDNSName='").append(eurekaServerDNSName) + .append("', ").append("region='").append(region).append("', ") + .append("eurekaConnectionIdleTimeoutSeconds=") + .append(eurekaConnectionIdleTimeoutSeconds).append(", ") + .append("registryRefreshSingleVipAddress='") + .append(registryRefreshSingleVipAddress).append("', ") + .append("heartbeatExecutorThreadPoolSize=") + .append(heartbeatExecutorThreadPoolSize).append(", ") + .append("heartbeatExecutorExponentialBackOffBound=") + .append(heartbeatExecutorExponentialBackOffBound).append(", ") + .append("cacheRefreshExecutorThreadPoolSize=") + .append(cacheRefreshExecutorThreadPoolSize).append(", ") + .append("cacheRefreshExecutorExponentialBackOffBound=") + .append(cacheRefreshExecutorExponentialBackOffBound).append(", ") .append("serviceUrl=").append(serviceUrl).append(", ") .append("gZipContent=").append(gZipContent).append(", ") - .append("useDnsForFetchingServiceUrls=").append(useDnsForFetchingServiceUrls).append(", ") + .append("useDnsForFetchingServiceUrls=") + .append(useDnsForFetchingServiceUrls).append(", ") .append("registerWithEureka=").append(registerWithEureka).append(", ") .append("preferSameZoneEureka=").append(preferSameZoneEureka).append(", ") .append("logDeltaDiff=").append(logDeltaDiff).append(", ") .append("disableDelta=").append(disableDelta).append(", ") - .append("fetchRemoteRegionsRegistry='").append(fetchRemoteRegionsRegistry).append("', ") - .append("availabilityZones=").append(availabilityZones).append(", ") - .append("filterOnlyUpInstances=").append(filterOnlyUpInstances).append(", ") - .append("fetchRegistry=").append(fetchRegistry).append(", ") - .append("dollarReplacement='").append(dollarReplacement).append("', ") - .append("escapeCharReplacement='").append(escapeCharReplacement).append("', ") - .append("allowRedirects=").append(allowRedirects).append(", ") - .append("onDemandUpdateStatusChange=").append(onDemandUpdateStatusChange).append(", ") - .append("encoderName='").append(encoderName).append("', ") - .append("decoderName='").append(decoderName).append("', ") - .append("clientDataAccept='").append(clientDataAccept).append("', ") - .append("shouldUnregisterOnShutdown='").append(shouldUnregisterOnShutdown).append("', ") - .append("shouldEnforceRegistrationAtInit='").append(shouldEnforceRegistrationAtInit).append("', ") - .append("order='").append(order).append("'}") - .toString(); + .append("fetchRemoteRegionsRegistry='").append(fetchRemoteRegionsRegistry) + .append("', ").append("availabilityZones=").append(availabilityZones) + .append(", ").append("filterOnlyUpInstances=") + .append(filterOnlyUpInstances).append(", ").append("fetchRegistry=") + .append(fetchRegistry).append(", ").append("dollarReplacement='") + .append(dollarReplacement).append("', ").append("escapeCharReplacement='") + .append(escapeCharReplacement).append("', ").append("allowRedirects=") + .append(allowRedirects).append(", ").append("onDemandUpdateStatusChange=") + .append(onDemandUpdateStatusChange).append(", ").append("encoderName='") + .append(encoderName).append("', ").append("decoderName='") + .append(decoderName).append("', ").append("clientDataAccept='") + .append(clientDataAccept).append("', ") + .append("shouldUnregisterOnShutdown='").append(shouldUnregisterOnShutdown) + .append("', ").append("shouldEnforceRegistrationAtInit='") + .append(shouldEnforceRegistrationAtInit).append("', ").append("order='") + .append(order).append("'}").toString(); } + } diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaConstants.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaConstants.java index 1f24480a7..e9f1607cb 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaConstants.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaConstants.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,10 +17,15 @@ package org.springframework.cloud.netflix.eureka; /** + * Class containing Eureka-specific constants. + * * @author Spencer Gibb */ -public class EurekaConstants { +public final class EurekaConstants { + /** + * Default Eureka prefix. + */ public static final String DEFAULT_PREFIX = "/eureka"; private EurekaConstants() { diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaDiscoveryClient.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaDiscoveryClient.java index abc09fa05..23575b2d9 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaDiscoveryClient.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaDiscoveryClient.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,14 +38,20 @@ import org.springframework.util.Assert; import static com.netflix.appinfo.InstanceInfo.PortType.SECURE; /** + * A {@link DiscoveryClient} implementation for Eureka. + * * @author Spencer Gibb * @author Tim Ysewyn */ public class EurekaDiscoveryClient implements DiscoveryClient { + /** + * Client description {@link String}. + */ public static final String DESCRIPTION = "Spring Cloud Eureka Discovery Client"; private final EurekaClient eurekaClient; + private final EurekaClientConfig clientConfig; @Deprecated @@ -53,7 +59,8 @@ public class EurekaDiscoveryClient implements DiscoveryClient { this(eurekaClient, eurekaClient.getEurekaClientConfig()); } - public EurekaDiscoveryClient(EurekaClient eurekaClient, EurekaClientConfig clientConfig) { + public EurekaDiscoveryClient(EurekaClient eurekaClient, + EurekaClientConfig clientConfig) { this.clientConfig = clientConfig; this.eurekaClient = eurekaClient; } @@ -74,7 +81,35 @@ public class EurekaDiscoveryClient implements DiscoveryClient { return instances; } + @Override + public List getServices() { + Applications applications = this.eurekaClient.getApplications(); + if (applications == null) { + return Collections.emptyList(); + } + List registered = applications.getRegisteredApplications(); + List names = new ArrayList<>(); + for (Application app : registered) { + if (app.getInstances().isEmpty()) { + continue; + } + names.add(app.getName().toLowerCase()); + + } + return names; + } + + @Override + public int getOrder() { + return clientConfig instanceof Ordered ? ((Ordered) clientConfig).getOrder() + : DiscoveryClient.DEFAULT_ORDER; + } + + /** + * An Eureka-specific {@link ServiceInstance} implementation. + */ public static class EurekaServiceInstance implements ServiceInstance { + private InstanceInfo instance; public EurekaServiceInstance(InstanceInfo instance) { @@ -124,28 +159,7 @@ public class EurekaDiscoveryClient implements DiscoveryClient { public Map getMetadata() { return this.instance.getMetadata(); } + } - @Override - public List getServices() { - Applications applications = this.eurekaClient.getApplications(); - if (applications == null) { - return Collections.emptyList(); - } - List registered = applications.getRegisteredApplications(); - List names = new ArrayList<>(); - for (Application app : registered) { - if (app.getInstances().isEmpty()) { - continue; - } - names.add(app.getName().toLowerCase()); - - } - return names; - } - - @Override - public int getOrder() { - return clientConfig instanceof Ordered ? ((Ordered) clientConfig).getOrder() : DiscoveryClient.DEFAULT_ORDER; - } } diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaDiscoveryClientConfiguration.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaDiscoveryClientConfiguration.java index c026766ca..d911f2b67 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaDiscoveryClientConfiguration.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaDiscoveryClientConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.eureka; @@ -46,38 +45,11 @@ import org.springframework.context.annotation.Configuration; @ConditionalOnProperty(value = "eureka.client.enabled", matchIfMissing = true) public class EurekaDiscoveryClientConfiguration { - class Marker {} - @Bean public Marker eurekaDiscoverClientMarker() { return new Marker(); } - @Configuration - @ConditionalOnClass(RefreshScopeRefreshedEvent.class) - protected static class EurekaClientConfigurationRefresher implements ApplicationListener { - - @Autowired(required = false) - private EurekaClient eurekaClient; - - @Autowired(required = false) - private EurekaAutoServiceRegistration autoRegistration; - - public void onApplicationEvent(RefreshScopeRefreshedEvent event) { - //This will force the creation of the EurkaClient bean if not already created - //to make sure the client will be reregistered after a refresh event - if(eurekaClient != null) { - eurekaClient.getApplications(); - } - if (autoRegistration != null) { - // register in case meta data changed - this.autoRegistration.stop(); - this.autoRegistration.start(); - } - } - } - - @Configuration @ConditionalOnProperty(value = "eureka.client.healthcheck.enabled", matchIfMissing = false) protected static class EurekaHealthCheckHandlerConfiguration { @@ -90,5 +62,37 @@ public class EurekaDiscoveryClientConfiguration { public EurekaHealthCheckHandler eurekaHealthCheckHandler() { return new EurekaHealthCheckHandler(this.healthAggregator); } + } + + class Marker { + + } + + @Configuration + @ConditionalOnClass(RefreshScopeRefreshedEvent.class) + protected static class EurekaClientConfigurationRefresher + implements ApplicationListener { + + @Autowired(required = false) + private EurekaClient eurekaClient; + + @Autowired(required = false) + private EurekaAutoServiceRegistration autoRegistration; + + public void onApplicationEvent(RefreshScopeRefreshedEvent event) { + // This will force the creation of the EurkaClient bean if not already created + // to make sure the client will be reregistered after a refresh event + if (eurekaClient != null) { + eurekaClient.getApplications(); + } + if (autoRegistration != null) { + // register in case meta data changed + this.autoRegistration.stop(); + this.autoRegistration.start(); + } + } + + } + } diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaHealthCheckHandler.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaHealthCheckHandler.java index 0ab3d7457..488fec383 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaHealthCheckHandler.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaHealthCheckHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,26 +36,28 @@ import org.springframework.util.Assert; import static com.netflix.appinfo.InstanceInfo.InstanceStatus; /** - * A Eureka health checker, maps the application status into {@link InstanceStatus} - * that will be propagated to Eureka registry. + * A Eureka health checker, maps the application status into {@link InstanceStatus} that + * will be propagated to Eureka registry. * - * On each heartbeat Eureka performs the health check invoking registered {@link HealthCheckHandler}. By default this - * implementation will perform aggregation of all registered {@link HealthIndicator} - * through registered {@link HealthAggregator}. + * On each heartbeat Eureka performs the health check invoking registered + * {@link HealthCheckHandler}. By default this implementation will perform aggregation of + * all registered {@link HealthIndicator} through registered {@link HealthAggregator}. * * @author Jakub Narloch * @see HealthCheckHandler * @see HealthAggregator */ -public class EurekaHealthCheckHandler implements HealthCheckHandler, ApplicationContextAware, InitializingBean { +public class EurekaHealthCheckHandler + implements HealthCheckHandler, ApplicationContextAware, InitializingBean { - private static final Map STATUS_MAPPING = - new HashMap() {{ - put(Status.UNKNOWN, InstanceStatus.UNKNOWN); - put(Status.OUT_OF_SERVICE, InstanceStatus.OUT_OF_SERVICE); - put(Status.DOWN, InstanceStatus.DOWN); - put(Status.UP, InstanceStatus.UP); - }}; + private static final Map STATUS_MAPPING = new HashMap() { + { + put(Status.UNKNOWN, InstanceStatus.UNKNOWN); + put(Status.OUT_OF_SERVICE, InstanceStatus.OUT_OF_SERVICE); + put(Status.DOWN, InstanceStatus.DOWN); + put(Status.UP, InstanceStatus.UP); + } + }; private final CompositeHealthIndicator healthIndicator; @@ -67,23 +69,28 @@ public class EurekaHealthCheckHandler implements HealthCheckHandler, Application } @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) + throws BeansException { this.applicationContext = applicationContext; } @Override public void afterPropertiesSet() throws Exception { - final Map healthIndicators = applicationContext.getBeansOfType(HealthIndicator.class); + final Map healthIndicators = applicationContext + .getBeansOfType(HealthIndicator.class); for (Map.Entry entry : healthIndicators.entrySet()) { - //ignore EurekaHealthIndicator and flatten the rest of the composite - //otherwise there is a never ending cycle of down. See gh-643 + // ignore EurekaHealthIndicator and flatten the rest of the composite + // otherwise there is a never ending cycle of down. See gh-643 if (entry.getValue() instanceof DiscoveryCompositeHealthIndicator) { - DiscoveryCompositeHealthIndicator indicator = (DiscoveryCompositeHealthIndicator) entry.getValue(); - for (DiscoveryCompositeHealthIndicator.Holder holder : indicator.getHealthIndicators()) { + DiscoveryCompositeHealthIndicator indicator = (DiscoveryCompositeHealthIndicator) entry + .getValue(); + for (DiscoveryCompositeHealthIndicator.Holder holder : indicator + .getHealthIndicators()) { if (!(holder.getDelegate() instanceof EurekaHealthIndicator)) { - healthIndicator.addHealthIndicator(holder.getDelegate().getName(), holder); + healthIndicator.addHealthIndicator(holder.getDelegate().getName(), + holder); } } @@ -114,4 +121,5 @@ public class EurekaHealthCheckHandler implements HealthCheckHandler, Application protected CompositeHealthIndicator getHealthIndicator() { return healthIndicator; } + } diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaHealthIndicator.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaHealthIndicator.java index e705375bd..e4472db4f 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaHealthIndicator.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,13 +20,6 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; -import org.springframework.aop.support.AopUtils; -import org.springframework.boot.actuate.health.Health; -import org.springframework.boot.actuate.health.Health.Builder; -import org.springframework.boot.actuate.health.Status; -import org.springframework.cloud.client.discovery.health.DiscoveryHealthIndicator; -import org.springframework.cloud.util.ProxyUtils; - import com.netflix.appinfo.EurekaInstanceConfig; import com.netflix.discovery.DiscoveryClient; import com.netflix.discovery.EurekaClient; @@ -34,6 +27,13 @@ import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; +import org.springframework.aop.support.AopUtils; +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.Health.Builder; +import org.springframework.boot.actuate.health.Status; +import org.springframework.cloud.client.discovery.health.DiscoveryHealthIndicator; +import org.springframework.cloud.util.ProxyUtils; + /** * @author Dave Syer */ @@ -67,8 +67,7 @@ public class EurekaHealthIndicator implements DiscoveryHealthIndicator { } private Status getStatus(Builder builder) { - Status status = new Status( - this.eurekaClient.getInstanceRemoteStatus().toString(), + Status status = new Status(this.eurekaClient.getInstanceRemoteStatus().toString(), "Remote status from Eureka server"); DiscoveryClient discoveryClient = getDiscoveryClient(); if (discoveryClient != null && clientConfig.shouldFetchRegistry()) { @@ -93,10 +92,11 @@ public class EurekaHealthIndicator implements DiscoveryHealthIndicator { private DiscoveryClient getDiscoveryClient() { DiscoveryClient discoveryClient = null; - if(AopUtils.isAopProxy(eurekaClient)) { + if (AopUtils.isAopProxy(eurekaClient)) { discoveryClient = ProxyUtils.getTargetObject(eurekaClient); - } else if(DiscoveryClient.class.isInstance(eurekaClient)) { - discoveryClient = (DiscoveryClient)eurekaClient; + } + else if (DiscoveryClient.class.isInstance(eurekaClient)) { + discoveryClient = (DiscoveryClient) eurekaClient; } return discoveryClient; } diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaInstanceConfigBean.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaInstanceConfigBean.java index 6a37460b0..7304beb08 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaInstanceConfigBean.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaInstanceConfigBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,10 @@ import java.util.HashMap; import java.util.Map; import java.util.Objects; +import com.netflix.appinfo.DataCenterInfo; +import com.netflix.appinfo.InstanceInfo.InstanceStatus; +import com.netflix.appinfo.MyDataCenterInfo; + import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.commons.util.InetUtils; import org.springframework.cloud.commons.util.InetUtils.HostInfo; @@ -28,10 +32,6 @@ import org.springframework.context.EnvironmentAware; import org.springframework.core.env.Environment; import org.springframework.util.StringUtils; -import com.netflix.appinfo.DataCenterInfo; -import com.netflix.appinfo.InstanceInfo.InstanceStatus; -import com.netflix.appinfo.MyDataCenterInfo; - /** * @author Dave Syer * @author Spencer Gibb @@ -39,7 +39,8 @@ import com.netflix.appinfo.MyDataCenterInfo; * @author Gregor Zurowski */ @ConfigurationProperties("eureka.instance") -public class EurekaInstanceConfigBean implements CloudEurekaInstanceConfig, EnvironmentAware { +public class EurekaInstanceConfigBean + implements CloudEurekaInstanceConfig, EnvironmentAware { private static final String UNKNOWN = "unknown"; @@ -48,7 +49,7 @@ public class EurekaInstanceConfigBean implements CloudEurekaInstanceConfig, Envi private InetUtils inetUtils; /** - * Default prefix for actuator endpoints + * Default prefix for actuator endpoints. */ private String actuatorPrefix = "/actuator"; @@ -275,6 +276,7 @@ public class EurekaInstanceConfigBean implements CloudEurekaInstanceConfig, Envi private InstanceStatus initialStatus = InstanceStatus.UP; private String[] defaultAddressResolutionOrder = new String[0]; + private Environment environment; public String getHostname() { @@ -327,8 +329,10 @@ public class EurekaInstanceConfigBean implements CloudEurekaInstanceConfig, Envi @Override public void setEnvironment(Environment environment) { this.environment = environment; - // set some defaults from the environment, but allow the defaults to use relaxed binding - String springAppName = this.environment.getProperty("spring.application.name", ""); + // set some defaults from the environment, but allow the defaults to use relaxed + // binding + String springAppName = this.environment.getProperty("spring.application.name", + ""); if (StringUtils.hasText(springAppName)) { setAppname(springAppName); setVirtualHostName(springAppName); @@ -567,40 +571,44 @@ public class EurekaInstanceConfigBean implements CloudEurekaInstanceConfig, Envi @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } EurekaInstanceConfigBean that = (EurekaInstanceConfigBean) o; - return Objects.equals(hostInfo, that.hostInfo) && - Objects.equals(inetUtils, that.inetUtils) && - Objects.equals(appname, that.appname) && - Objects.equals(appGroupName, that.appGroupName) && - instanceEnabledOnit == that.instanceEnabledOnit && - nonSecurePort == that.nonSecurePort && - securePort == that.securePort && - nonSecurePortEnabled == that.nonSecurePortEnabled && - securePortEnabled == that.securePortEnabled && - leaseRenewalIntervalInSeconds == that.leaseRenewalIntervalInSeconds && - leaseExpirationDurationInSeconds == that.leaseExpirationDurationInSeconds && - Objects.equals(virtualHostName, that.virtualHostName) && - Objects.equals(instanceId, that.instanceId) && - Objects.equals(secureVirtualHostName, that.secureVirtualHostName) && - Objects.equals(aSGName, that.aSGName) && - Objects.equals(metadataMap, that.metadataMap) && - Objects.equals(dataCenterInfo, that.dataCenterInfo) && - Objects.equals(ipAddress, that.ipAddress) && - Objects.equals(statusPageUrlPath, that.statusPageUrlPath) && - Objects.equals(statusPageUrl, that.statusPageUrl) && - Objects.equals(homePageUrlPath, that.homePageUrlPath) && - Objects.equals(homePageUrl, that.homePageUrl) && - Objects.equals(healthCheckUrlPath, that.healthCheckUrlPath) && - Objects.equals(healthCheckUrl, that.healthCheckUrl) && - Objects.equals(secureHealthCheckUrl, that.secureHealthCheckUrl) && - Objects.equals(namespace, that.namespace) && - Objects.equals(hostname, that.hostname) && - preferIpAddress == that.preferIpAddress && - Objects.equals(initialStatus, that.initialStatus) && - Arrays.equals(defaultAddressResolutionOrder, that.defaultAddressResolutionOrder) && - Objects.equals(environment, that.environment); + return Objects.equals(hostInfo, that.hostInfo) + && Objects.equals(inetUtils, that.inetUtils) + && Objects.equals(appname, that.appname) + && Objects.equals(appGroupName, that.appGroupName) + && instanceEnabledOnit == that.instanceEnabledOnit + && nonSecurePort == that.nonSecurePort && securePort == that.securePort + && nonSecurePortEnabled == that.nonSecurePortEnabled + && securePortEnabled == that.securePortEnabled + && leaseRenewalIntervalInSeconds == that.leaseRenewalIntervalInSeconds + && leaseExpirationDurationInSeconds == that.leaseExpirationDurationInSeconds + && Objects.equals(virtualHostName, that.virtualHostName) + && Objects.equals(instanceId, that.instanceId) + && Objects.equals(secureVirtualHostName, that.secureVirtualHostName) + && Objects.equals(aSGName, that.aSGName) + && Objects.equals(metadataMap, that.metadataMap) + && Objects.equals(dataCenterInfo, that.dataCenterInfo) + && Objects.equals(ipAddress, that.ipAddress) + && Objects.equals(statusPageUrlPath, that.statusPageUrlPath) + && Objects.equals(statusPageUrl, that.statusPageUrl) + && Objects.equals(homePageUrlPath, that.homePageUrlPath) + && Objects.equals(homePageUrl, that.homePageUrl) + && Objects.equals(healthCheckUrlPath, that.healthCheckUrlPath) + && Objects.equals(healthCheckUrl, that.healthCheckUrl) + && Objects.equals(secureHealthCheckUrl, that.secureHealthCheckUrl) + && Objects.equals(namespace, that.namespace) + && Objects.equals(hostname, that.hostname) + && preferIpAddress == that.preferIpAddress + && Objects.equals(initialStatus, that.initialStatus) + && Arrays.equals(defaultAddressResolutionOrder, + that.defaultAddressResolutionOrder) + && Objects.equals(environment, that.environment); } @Override @@ -612,27 +620,29 @@ public class EurekaInstanceConfigBean implements CloudEurekaInstanceConfig, Envi secureVirtualHostName, aSGName, metadataMap, dataCenterInfo, ipAddress, statusPageUrlPath, statusPageUrl, homePageUrlPath, homePageUrl, healthCheckUrlPath, healthCheckUrl, secureHealthCheckUrl, namespace, - hostname, preferIpAddress, initialStatus, defaultAddressResolutionOrder, environment); + hostname, preferIpAddress, initialStatus, defaultAddressResolutionOrder, + environment); } @Override public String toString() { - return new StringBuilder("EurekaInstanceConfigBean{") - .append("hostInfo=").append(hostInfo).append(", ") - .append("inetUtils=").append(inetUtils).append(", ") - .append("appname='").append(appname).append("', ") + return new StringBuilder("EurekaInstanceConfigBean{").append("hostInfo=") + .append(hostInfo).append(", ").append("inetUtils=").append(inetUtils) + .append(", ").append("appname='").append(appname).append("', ") .append("appGroupName='").append(appGroupName).append("', ") .append("instanceEnabledOnit=").append(instanceEnabledOnit).append(", ") .append("nonSecurePort=").append(nonSecurePort).append(", ") .append("securePort=").append(securePort).append(", ") .append("nonSecurePortEnabled=").append(nonSecurePortEnabled).append(", ") .append("securePortEnabled=").append(securePortEnabled).append(", ") - .append("leaseRenewalIntervalInSeconds=").append(leaseRenewalIntervalInSeconds).append(", ") - .append("leaseExpirationDurationInSeconds=").append(leaseExpirationDurationInSeconds).append(", ") + .append("leaseRenewalIntervalInSeconds=") + .append(leaseRenewalIntervalInSeconds).append(", ") + .append("leaseExpirationDurationInSeconds=") + .append(leaseExpirationDurationInSeconds).append(", ") .append("virtualHostName='").append(virtualHostName).append("', ") .append("instanceId='").append(instanceId).append("', ") - .append("secureVirtualHostName='").append(secureVirtualHostName).append("', ") - .append("aSGName='").append(aSGName).append("', ") + .append("secureVirtualHostName='").append(secureVirtualHostName) + .append("', ").append("aSGName='").append(aSGName).append("', ") .append("metadataMap=").append(metadataMap).append(", ") .append("dataCenterInfo=").append(dataCenterInfo).append(", ") .append("ipAddress='").append(ipAddress).append("', ") @@ -642,13 +652,15 @@ public class EurekaInstanceConfigBean implements CloudEurekaInstanceConfig, Envi .append("homePageUrl='").append(homePageUrl).append("', ") .append("healthCheckUrlPath='").append(healthCheckUrlPath).append("', ") .append("healthCheckUrl='").append(healthCheckUrl).append("', ") - .append("secureHealthCheckUrl='").append(secureHealthCheckUrl).append("', ") - .append("namespace='").append(namespace).append("', ") + .append("secureHealthCheckUrl='").append(secureHealthCheckUrl) + .append("', ").append("namespace='").append(namespace).append("', ") .append("hostname='").append(hostname).append("', ") .append("preferIpAddress=").append(preferIpAddress).append(", ") .append("initialStatus=").append(initialStatus).append(", ") - .append("defaultAddressResolutionOrder=").append(Arrays.toString(defaultAddressResolutionOrder)).append(", ") + .append("defaultAddressResolutionOrder=") + .append(Arrays.toString(defaultAddressResolutionOrder)).append(", ") .append("environment=").append(environment).append(", ").append("}") .toString(); } + } diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/InstanceInfoFactory.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/InstanceInfoFactory.java index ef7c95efc..33d946ff6 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/InstanceInfoFactory.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/InstanceInfoFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,8 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** - * See com.netflix.appinfo.providers.EurekaConfigBasedInstanceInfoProvider + * See com.netflix.appinfo.providers.EurekaConfigBasedInstanceInfoProvider. + * * @author Spencer Gibb */ public class InstanceInfoFactory { @@ -95,4 +96,5 @@ public class InstanceInfoFactory { instanceInfo.setLeaseInfo(leaseInfoBuilder.build()); return instanceInfo; } + } diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/DiscoveryClientOptionalArgsConfiguration.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/DiscoveryClientOptionalArgsConfiguration.java index d0439afb5..0d6a6c649 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/DiscoveryClientOptionalArgsConfiguration.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/DiscoveryClientOptionalArgsConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ package org.springframework.cloud.netflix.eureka.config; +import com.netflix.discovery.AbstractDiscoveryClientOptionalArgs; + import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; @@ -25,13 +27,12 @@ import org.springframework.cloud.netflix.eureka.http.RestTemplateDiscoveryClient import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import com.netflix.discovery.AbstractDiscoveryClientOptionalArgs; - /** * @author Daniel Lavoie */ @Configuration public class DiscoveryClientOptionalArgsConfiguration { + @Bean @ConditionalOnMissingClass("com.sun.jersey.api.client.filter.ClientFilter") @ConditionalOnMissingBean(value = AbstractDiscoveryClientOptionalArgs.class, search = SearchStrategy.CURRENT) @@ -45,4 +46,5 @@ public class DiscoveryClientOptionalArgsConfiguration { public MutableDiscoveryClientOptionalArgs discoveryClientOptionalArgs() { return new MutableDiscoveryClientOptionalArgs(); } + } diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/EurekaClientConfigServerAutoConfiguration.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/EurekaClientConfigServerAutoConfiguration.java index 5043a9922..be37673b0 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/EurekaClientConfigServerAutoConfiguration.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/EurekaClientConfigServerAutoConfiguration.java @@ -18,6 +18,9 @@ package org.springframework.cloud.netflix.eureka.config; import javax.annotation.PostConstruct; +import com.netflix.appinfo.EurekaInstanceConfig; +import com.netflix.discovery.EurekaClient; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.context.properties.EnableConfigurationProperties; @@ -26,9 +29,6 @@ import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean; import org.springframework.context.annotation.Configuration; import org.springframework.util.StringUtils; -import com.netflix.appinfo.EurekaInstanceConfig; -import com.netflix.discovery.EurekaClient; - /** * Extra configuration for config server if it happens to be a Eureka instance. * @@ -52,7 +52,8 @@ public class EurekaClientConfigServerAutoConfiguration { return; } String prefix = this.server.getPrefix(); - if (StringUtils.hasText(prefix) && !StringUtils.hasText(this.instance.getMetadataMap().get("configPath"))) { + if (StringUtils.hasText(prefix) && !StringUtils + .hasText(this.instance.getMetadataMap().get("configPath"))) { this.instance.getMetadataMap().put("configPath", prefix); } } diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/EurekaDiscoveryClientConfigServiceAutoConfiguration.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/EurekaDiscoveryClientConfigServiceAutoConfiguration.java index bbfcc0943..9b2c06fc7 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/EurekaDiscoveryClientConfigServiceAutoConfiguration.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/EurekaDiscoveryClientConfigServiceAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,14 +18,14 @@ package org.springframework.cloud.netflix.eureka.config; import javax.annotation.PostConstruct; +import com.netflix.discovery.EurekaClient; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.cloud.netflix.eureka.EurekaDiscoveryClientConfiguration; import org.springframework.context.ConfigurableApplicationContext; -import com.netflix.discovery.EurekaClient; - /** * Bootstrap configuration for a config client that wants to lookup the config server via * discovery. diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/EurekaDiscoveryClientConfigServiceBootstrapConfiguration.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/EurekaDiscoveryClientConfigServiceBootstrapConfiguration.java index e194076b3..e5bfcd70d 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/EurekaDiscoveryClientConfigServiceBootstrapConfiguration.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/EurekaDiscoveryClientConfigServiceBootstrapConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,7 +33,11 @@ import org.springframework.context.annotation.Import; @ConditionalOnClass(ConfigServicePropertySourceLocator.class) @ConditionalOnProperty(value = "spring.cloud.config.discovery.enabled", matchIfMissing = false) @Configuration -@Import({ EurekaDiscoveryClientConfiguration.class, // this emulates @EnableDiscoveryClient, the import selector doesn't run before the bootstrap phase +@Import({ EurekaDiscoveryClientConfiguration.class, // this emulates + // @EnableDiscoveryClient, the import + // selector doesn't run before the + // bootstrap phase EurekaClientAutoConfiguration.class }) public class EurekaDiscoveryClientConfigServiceBootstrapConfiguration { + } diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/EurekaApplications.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/EurekaApplications.java index 44906b1b0..5a23391b1 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/EurekaApplications.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/EurekaApplications.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,7 +26,7 @@ import com.netflix.discovery.shared.Applications; /** * A simple wrapper class for {@link Applications} that insure proprer Jackson * serialization through the JsonPropert overwrites. - * + * * @author Daniel Lavoie */ public class EurekaApplications extends com.netflix.discovery.shared.Applications { @@ -37,4 +37,5 @@ public class EurekaApplications extends com.netflix.discovery.shared.Application @JsonProperty("application") List registeredApplications) { super(appsHashCode, versionDelta, registeredApplications); } -} \ No newline at end of file + +} diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateDiscoveryClientOptionalArgs.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateDiscoveryClientOptionalArgs.java index b0eba96fd..6364b5aca 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateDiscoveryClientOptionalArgs.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateDiscoveryClientOptionalArgs.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +23,9 @@ import com.netflix.discovery.AbstractDiscoveryClientOptionalArgs; */ public class RestTemplateDiscoveryClientOptionalArgs extends AbstractDiscoveryClientOptionalArgs { + public RestTemplateDiscoveryClientOptionalArgs() { setTransportClientFactories(new RestTemplateTransportClientFactories()); } + } diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateEurekaHttpClient.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateEurekaHttpClient.java index ec4ca1795..784898f2e 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateEurekaHttpClient.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateEurekaHttpClient.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,24 +16,12 @@ package org.springframework.cloud.netflix.eureka.http; -import static com.netflix.discovery.shared.transport.EurekaHttpResponse.anEurekaHttpResponse; - import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.client.RestTemplate; - import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.InstanceStatus; import com.netflix.discovery.shared.Application; @@ -42,6 +30,18 @@ import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.EurekaHttpResponse; import com.netflix.discovery.shared.transport.EurekaHttpResponse.EurekaHttpResponseBuilder; import com.netflix.discovery.util.StringUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +import static com.netflix.discovery.shared.transport.EurekaHttpResponse.anEurekaHttpResponse; /** * @author Daniel Lavoie @@ -51,13 +51,14 @@ public class RestTemplateEurekaHttpClient implements EurekaHttpClient { protected final Log logger = LogFactory.getLog(getClass()); private RestTemplate restTemplate; + private String serviceUrl; public RestTemplateEurekaHttpClient(RestTemplate restTemplate, String serviceUrl) { this.restTemplate = restTemplate; this.serviceUrl = serviceUrl; if (!serviceUrl.endsWith("/")) { - this.serviceUrl = this.serviceUrl+"/"; + this.serviceUrl = this.serviceUrl + "/"; } } @@ -102,8 +103,9 @@ public class RestTemplateEurekaHttpClient implements EurekaHttpClient { response.getStatusCodeValue(), InstanceInfo.class) .headers(headersOf(response)); - if (response.hasBody()) + if (response.hasBody()) { eurekaResponseBuilder.entity(response.getBody()); + } return eurekaResponseBuilder.build(); } @@ -228,4 +230,5 @@ public class RestTemplateEurekaHttpClient implements EurekaHttpClient { } return headers; } + } diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateTransportClientFactories.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateTransportClientFactories.java index d437703ba..c1f7941be 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateTransportClientFactories.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateTransportClientFactories.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,15 +19,15 @@ package org.springframework.cloud.netflix.eureka.http; import java.util.Collection; import java.util.Optional; +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLContext; + import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.shared.transport.TransportClientFactory; import com.netflix.discovery.shared.transport.jersey.EurekaJerseyClient; import com.netflix.discovery.shared.transport.jersey.TransportClientFactories; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLContext; - /** * @author Daniel Lavoie */ @@ -48,11 +48,12 @@ public class RestTemplateTransportClientFactories } @Override - public TransportClientFactory newTransportClientFactory(final EurekaClientConfig clientConfig, - final Collection additionalFilters, - final InstanceInfo myInstanceInfo, - final Optional sslContext, - final Optional hostnameVerifier) { + public TransportClientFactory newTransportClientFactory( + final EurekaClientConfig clientConfig, + final Collection additionalFilters, final InstanceInfo myInstanceInfo, + final Optional sslContext, + final Optional hostnameVerifier) { return new RestTemplateTransportClientFactory(); } + } diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateTransportClientFactory.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateTransportClientFactory.java index ffb181de0..bbe7208d1 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateTransportClientFactory.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateTransportClientFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,12 +19,6 @@ package org.springframework.cloud.netflix.eureka.http; import java.net.URI; import java.net.URISyntaxException; -import org.springframework.http.HttpStatus; -import org.springframework.http.client.support.BasicAuthorizationInterceptor; -import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; -import org.springframework.web.client.DefaultResponseErrorHandler; -import org.springframework.web.client.RestTemplate; - import com.fasterxml.jackson.databind.BeanDescription; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonSerializer; @@ -44,11 +38,17 @@ import com.netflix.discovery.shared.resolver.EurekaEndpoint; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.TransportClientFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.client.support.BasicAuthorizationInterceptor; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.web.client.DefaultResponseErrorHandler; +import org.springframework.web.client.RestTemplate; + /** * Provides the custom {@link RestTemplate} required by the * {@link RestTemplateEurekaHttpClient}. Relies on Jackson for serialization and * deserialization. - * + * * @author Daniel Lavoie */ public class RestTemplateTransportClientFactory implements TransportClientFactory { @@ -85,13 +85,11 @@ public class RestTemplateTransportClientFactory implements TransportClientFactor * Provides the serialization configurations required by the Eureka Server. JSON * content exchanged with eureka requires a root node matching the entity being * serialized or deserialized. Achived with - * {@link SerializationFeature.WRAP_ROOT_VALUE} and - * {@link DeserializationFeature.UNWRAP_ROOT_VALUE}. + * {@link SerializationFeature#WRAP_ROOT_VALUE} and + * {@link DeserializationFeature#UNWRAP_ROOT_VALUE}. * {@link PropertyNamingStrategy.SnakeCaseStrategy} is applied to the underlying * {@link ObjectMapper}. - * - * - * @return + * @return a {@link MappingJackson2HttpMessageConverter} object */ public MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter() { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); @@ -99,34 +97,49 @@ public class RestTemplateTransportClientFactory implements TransportClientFactor .setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE)); SimpleModule jsonModule = new SimpleModule(); - jsonModule.setSerializerModifier(createJsonSerializerModifier());//keyFormatter, compact)); + jsonModule.setSerializerModifier(createJsonSerializerModifier()); // keyFormatter, + // compact)); converter.getObjectMapper().registerModule(jsonModule); converter.getObjectMapper().configure(SerializationFeature.WRAP_ROOT_VALUE, true); converter.getObjectMapper().configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); - converter.getObjectMapper().addMixIn(Applications.class, ApplicationsJsonMixIn.class); - converter.getObjectMapper().addMixIn(InstanceInfo.class, InstanceInfoJsonMixIn.class); - - // converter.getObjectMapper().addMixIn(DataCenterInfo.class, DataCenterInfoXmlMixIn.class); - // converter.getObjectMapper().addMixIn(InstanceInfo.PortWrapper.class, PortWrapperXmlMixIn.class); - // converter.getObjectMapper().addMixIn(Application.class, ApplicationXmlMixIn.class); - // converter.getObjectMapper().addMixIn(Applications.class, ApplicationsXmlMixIn.class); + converter.getObjectMapper().addMixIn(Applications.class, + ApplicationsJsonMixIn.class); + converter.getObjectMapper().addMixIn(InstanceInfo.class, + InstanceInfoJsonMixIn.class); + // converter.getObjectMapper().addMixIn(DataCenterInfo.class, + // DataCenterInfoXmlMixIn.class); + // converter.getObjectMapper().addMixIn(InstanceInfo.PortWrapper.class, + // PortWrapperXmlMixIn.class); + // converter.getObjectMapper().addMixIn(Application.class, + // ApplicationXmlMixIn.class); + // converter.getObjectMapper().addMixIn(Applications.class, + // ApplicationsXmlMixIn.class); return converter; } - public static BeanSerializerModifier createJsonSerializerModifier() {//final KeyFormatter keyFormatter, final boolean compactMode) { + public static BeanSerializerModifier createJsonSerializerModifier() { // final + // KeyFormatter + // keyFormatter, + // final + // boolean + // compactMode) + // { return new BeanSerializerModifier() { @Override public JsonSerializer modifySerializer(SerializationConfig config, - BeanDescription beanDesc, JsonSerializer serializer) { - /*if (beanDesc.getBeanClass().isAssignableFrom(Applications.class)) { - return new ApplicationsJsonBeanSerializer((BeanSerializerBase) serializer, keyFormatter); - }*/ + BeanDescription beanDesc, JsonSerializer serializer) { + /* + * if (beanDesc.getBeanClass().isAssignableFrom(Applications.class)) { + * return new ApplicationsJsonBeanSerializer((BeanSerializerBase) + * serializer, keyFormatter); } + */ if (beanDesc.getBeanClass().isAssignableFrom(InstanceInfo.class)) { - return new InstanceInfoJsonBeanSerializer((BeanSerializerBase) serializer, false); + return new InstanceInfoJsonBeanSerializer( + (BeanSerializerBase) serializer, false); } return serializer; } @@ -138,19 +151,21 @@ public class RestTemplateTransportClientFactory implements TransportClientFactor } class ErrorHanlder extends DefaultResponseErrorHandler { + @Override protected boolean hasError(HttpStatus statusCode) { /** - * When the Eureka server restarts and a client tries to sent a heartbeat the server - * will respond with a 404. By default RestTemplate will throw an exception in this case. - * What we want is to return the 404 to the upstream code so it will send another registration - * request to the server. + * When the Eureka server restarts and a client tries to sent a heartbeat the + * server will respond with a 404. By default RestTemplate will throw an + * exception in this case. What we want is to return the 404 to the upstream + * code so it will send another registration request to the server. */ - if(statusCode.is4xxClientError()) { + if (statusCode.is4xxClientError()) { return false; } return super.hasError(statusCode); } + } } diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/metadata/DefaultManagementMetadataProvider.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/metadata/DefaultManagementMetadataProvider.java index 745c8c1e7..cf2a09cfc 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/metadata/DefaultManagementMetadataProvider.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/metadata/DefaultManagementMetadataProvider.java @@ -1,107 +1,143 @@ -package org.springframework.cloud.netflix.eureka.metadata; +/* + * Copyright 2017-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean; -import org.springframework.util.StringUtils; +package org.springframework.cloud.netflix.eureka.metadata; import java.net.MalformedURLException; import java.net.URL; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean; +import org.springframework.util.StringUtils; + +/** + * Default implementation of {@link DefaultManagementMetadataProvider}. + * + * @author Anastasiia Smirnova + */ public class DefaultManagementMetadataProvider implements ManagementMetadataProvider { - private static final int RANDOM_PORT = 0; - private static final Log log = LogFactory.getLog(DefaultManagementMetadataProvider.class); + private static final int RANDOM_PORT = 0; - @Override - public ManagementMetadata get(EurekaInstanceConfigBean instance, int serverPort, - String serverContextPath, String managementContextPath, - Integer managementPort) { + private static final Log log = LogFactory + .getLog(DefaultManagementMetadataProvider.class); + + @Override + public ManagementMetadata get(EurekaInstanceConfigBean instance, int serverPort, + String serverContextPath, String managementContextPath, + Integer managementPort) { if (isRandom(managementPort)) { return null; } if (managementPort == null && isRandom(serverPort)) { return null; } - String healthCheckUrl = getHealthCheckUrl(instance, serverPort, serverContextPath, - managementContextPath, managementPort, false); - String statusPageUrl = getStatusPageUrl(instance, serverPort, serverContextPath, - managementContextPath, managementPort); + String healthCheckUrl = getHealthCheckUrl(instance, serverPort, serverContextPath, + managementContextPath, managementPort, false); + String statusPageUrl = getStatusPageUrl(instance, serverPort, serverContextPath, + managementContextPath, managementPort); - ManagementMetadata metadata = new ManagementMetadata(healthCheckUrl, statusPageUrl, managementPort == null ? serverPort : managementPort); - if(instance.isSecurePortEnabled()) { - metadata.setSecureHealthCheckUrl(getHealthCheckUrl(instance, serverPort, serverContextPath, - managementContextPath, managementPort, true)); - } - return metadata; + ManagementMetadata metadata = new ManagementMetadata(healthCheckUrl, + statusPageUrl, managementPort == null ? serverPort : managementPort); + if (instance.isSecurePortEnabled()) { + metadata.setSecureHealthCheckUrl(getHealthCheckUrl(instance, serverPort, + serverContextPath, managementContextPath, managementPort, true)); + } + return metadata; } private boolean isRandom(Integer port) { return port != null && port == RANDOM_PORT; } - protected String getHealthCheckUrl(EurekaInstanceConfigBean instance, int serverPort, String serverContextPath, - String managementContextPath, Integer managementPort, boolean isSecure) { - String healthCheckUrlPath = instance.getHealthCheckUrlPath(); - String healthCheckUrl = getUrl(instance, serverPort, serverContextPath, managementContextPath, - managementPort, healthCheckUrlPath, isSecure); - log.debug("Constructed eureka meta-data healthcheckUrl: " + healthCheckUrl); - return healthCheckUrl; - } + protected String getHealthCheckUrl(EurekaInstanceConfigBean instance, int serverPort, + String serverContextPath, String managementContextPath, + Integer managementPort, boolean isSecure) { + String healthCheckUrlPath = instance.getHealthCheckUrlPath(); + String healthCheckUrl = getUrl(instance, serverPort, serverContextPath, + managementContextPath, managementPort, healthCheckUrlPath, isSecure); + log.debug("Constructed eureka meta-data healthcheckUrl: " + healthCheckUrl); + return healthCheckUrl; + } - public String getStatusPageUrl(EurekaInstanceConfigBean instance, int serverPort, String serverContextPath, - String managementContextPath, Integer managementPort) { - String statusPageUrlPath = instance.getStatusPageUrlPath(); - String statusPageUrl = getUrl(instance, serverPort, serverContextPath, managementContextPath, - managementPort, statusPageUrlPath, false); - log.debug("Constructed eureka meta-data statusPageUrl: " + statusPageUrl); - return statusPageUrl; - } + public String getStatusPageUrl(EurekaInstanceConfigBean instance, int serverPort, + String serverContextPath, String managementContextPath, + Integer managementPort) { + String statusPageUrlPath = instance.getStatusPageUrlPath(); + String statusPageUrl = getUrl(instance, serverPort, serverContextPath, + managementContextPath, managementPort, statusPageUrlPath, false); + log.debug("Constructed eureka meta-data statusPageUrl: " + statusPageUrl); + return statusPageUrl; + } - private String getUrl(EurekaInstanceConfigBean instance, int serverPort, - String serverContextPath, String managementContextPath, - Integer managementPort, String urlPath, boolean isSecure) { - managementContextPath = refineManagementContextPath(serverContextPath, managementContextPath, managementPort); - if (managementPort == null) { - managementPort = serverPort; - } - String scheme = isSecure ? "https" : "http"; - return constructValidUrl(scheme, instance.getHostname(), managementPort, managementContextPath, urlPath); - } + private String getUrl(EurekaInstanceConfigBean instance, int serverPort, + String serverContextPath, String managementContextPath, + Integer managementPort, String urlPath, boolean isSecure) { + managementContextPath = refineManagementContextPath(serverContextPath, + managementContextPath, managementPort); + if (managementPort == null) { + managementPort = serverPort; + } + String scheme = isSecure ? "https" : "http"; + return constructValidUrl(scheme, instance.getHostname(), managementPort, + managementContextPath, urlPath); + } - private String refineManagementContextPath(String serverContextPath, String managementContextPath, - Integer managementPort) { - // management context path is relative to server context path when no management port is set - if (managementContextPath != null && managementPort == null) { - return serverContextPath + managementContextPath; - } - if(managementContextPath != null) { - return managementContextPath; - } - if(managementPort != null) { - return "/"; - } - return serverContextPath; - } + private String refineManagementContextPath(String serverContextPath, + String managementContextPath, Integer managementPort) { + // management context path is relative to server context path when no management + // port is set + if (managementContextPath != null && managementPort == null) { + return serverContextPath + managementContextPath; + } + if (managementContextPath != null) { + return managementContextPath; + } + if (managementPort != null) { + return "/"; + } + return serverContextPath; + } - private String constructValidUrl(String scheme, String hostname, int port, - String contextPath, String statusPath) { - try { - if (!contextPath.endsWith("/")) { - contextPath = contextPath + "/"; - } - String refinedContextPath = '/' + StringUtils.trimLeadingCharacter(contextPath, '/') ; - URL base = new URL(scheme, hostname, port, refinedContextPath); - String refinedStatusPath = StringUtils.trimLeadingCharacter(statusPath, '/'); - return new URL(base, refinedStatusPath).toString(); - } catch (MalformedURLException e) { - String message = getErrorMessage(scheme, hostname, port, contextPath, statusPath); - throw new IllegalStateException(message, e); - } - } + private String constructValidUrl(String scheme, String hostname, int port, + String contextPath, String statusPath) { + try { + if (!contextPath.endsWith("/")) { + contextPath = contextPath + "/"; + } + String refinedContextPath = '/' + + StringUtils.trimLeadingCharacter(contextPath, '/'); + URL base = new URL(scheme, hostname, port, refinedContextPath); + String refinedStatusPath = StringUtils.trimLeadingCharacter(statusPath, '/'); + return new URL(base, refinedStatusPath).toString(); + } + catch (MalformedURLException e) { + String message = getErrorMessage(scheme, hostname, port, contextPath, + statusPath); + throw new IllegalStateException(message, e); + } + } + + private String getErrorMessage(String scheme, String hostname, int port, + String contextPath, String statusPath) { + return String.format( + "Failed to construct url for scheme: %s, hostName: %s port: %s contextPath: %s statusPath: %s", + scheme, hostname, port, contextPath, statusPath); + } - private String getErrorMessage(String scheme, String hostname, int port, String contextPath, String statusPath) { - return String.format("Failed to construct url for scheme: %s, hostName: %s port: %s contextPath: %s statusPath: %s", - scheme, hostname, port, contextPath, statusPath); - } } diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/metadata/ManagementMetadata.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/metadata/ManagementMetadata.java index f7c573bd1..006388f04 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/metadata/ManagementMetadata.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/metadata/ManagementMetadata.java @@ -1,63 +1,94 @@ +/* + * Copyright 2017-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.springframework.cloud.netflix.eureka.metadata; import java.util.Objects; +/** + * Stores management metadata for Eureka. + * + * @author Anastasiia Smirnova + * @author Ryan Baxter + */ public class ManagementMetadata { - private final String healthCheckUrl; - private final String statusPageUrl; - private final Integer managementPort; - private String secureHealthCheckUrl; + private final String healthCheckUrl; - public ManagementMetadata(String healthCheckUrl, String statusPageUrl, Integer managementPort) { - this.healthCheckUrl = healthCheckUrl; - this.statusPageUrl = statusPageUrl; - this.managementPort = managementPort; - this.secureHealthCheckUrl = null; - } + private final String statusPageUrl; - public String getHealthCheckUrl() { - return healthCheckUrl; - } + private final Integer managementPort; - public String getStatusPageUrl() { - return statusPageUrl; - } + private String secureHealthCheckUrl; - public Integer getManagementPort() { - return managementPort; - } + public ManagementMetadata(String healthCheckUrl, String statusPageUrl, + Integer managementPort) { + this.healthCheckUrl = healthCheckUrl; + this.statusPageUrl = statusPageUrl; + this.managementPort = managementPort; + this.secureHealthCheckUrl = null; + } - public String getSecureHealthCheckUrl() { - return secureHealthCheckUrl; - } + public String getHealthCheckUrl() { + return healthCheckUrl; + } - public void setSecureHealthCheckUrl(String secureHealthCheckUrl) { - this.secureHealthCheckUrl = secureHealthCheckUrl; - } + public String getStatusPageUrl() { + return statusPageUrl; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - ManagementMetadata that = (ManagementMetadata) o; - return Objects.equals(healthCheckUrl, that.healthCheckUrl) && - Objects.equals(statusPageUrl, that.statusPageUrl) && - Objects.equals(managementPort, that.managementPort); - } + public Integer getManagementPort() { + return managementPort; + } - @Override - public int hashCode() { - return Objects.hash(healthCheckUrl, statusPageUrl, managementPort); - } + public String getSecureHealthCheckUrl() { + return secureHealthCheckUrl; + } + + public void setSecureHealthCheckUrl(String secureHealthCheckUrl) { + this.secureHealthCheckUrl = secureHealthCheckUrl; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ManagementMetadata that = (ManagementMetadata) o; + return Objects.equals(healthCheckUrl, that.healthCheckUrl) + && Objects.equals(statusPageUrl, that.statusPageUrl) + && Objects.equals(managementPort, that.managementPort); + } + + @Override + public int hashCode() { + return Objects.hash(healthCheckUrl, statusPageUrl, managementPort); + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("ManagementMetadata{"); + sb.append("healthCheckUrl='").append(healthCheckUrl).append('\''); + sb.append(", statusPageUrl='").append(statusPageUrl).append('\''); + sb.append(", managementPort=").append(managementPort); + sb.append('}'); + return sb.toString(); + } - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("ManagementMetadata{"); - sb.append("healthCheckUrl='").append(healthCheckUrl).append('\''); - sb.append(", statusPageUrl='").append(statusPageUrl).append('\''); - sb.append(", managementPort=").append(managementPort); - sb.append('}'); - return sb.toString(); - } } diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/metadata/ManagementMetadataProvider.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/metadata/ManagementMetadataProvider.java index 98bc770e1..5925c0f2d 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/metadata/ManagementMetadataProvider.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/metadata/ManagementMetadataProvider.java @@ -1,10 +1,32 @@ +/* + * Copyright 2017-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.springframework.cloud.netflix.eureka.metadata; import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean; +/** + * Provider for Eureka-specific management metadata. + * + * @author Anastasiia Smirnova + */ public interface ManagementMetadataProvider { - ManagementMetadata get(EurekaInstanceConfigBean instance, int serverPort, - String serverContextPath, String managementContextPath, Integer managementPort); + ManagementMetadata get(EurekaInstanceConfigBean instance, int serverPort, + String serverContextPath, String managementContextPath, + Integer managementPort); } diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaAutoServiceRegistration.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaAutoServiceRegistration.java index 70b0883e7..3d7a948d9 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaAutoServiceRegistration.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaAutoServiceRegistration.java @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.eureka.serviceregistry; @@ -38,9 +37,10 @@ import org.springframework.core.Ordered; * @author Spencer Gibb * @author Jon Schneider * @author Jakub Narloch - * @author raiyan + * @author Raiyan Raiyan */ -public class EurekaAutoServiceRegistration implements AutoServiceRegistration, SmartLifecycle, Ordered, SmartApplicationListener { +public class EurekaAutoServiceRegistration implements AutoServiceRegistration, + SmartLifecycle, Ordered, SmartApplicationListener { private static final Log log = LogFactory.getLog(EurekaAutoServiceRegistration.class); @@ -56,7 +56,8 @@ public class EurekaAutoServiceRegistration implements AutoServiceRegistration, S private EurekaRegistration registration; - public EurekaAutoServiceRegistration(ApplicationContext context, EurekaServiceRegistry serviceRegistry, EurekaRegistration registration) { + public EurekaAutoServiceRegistration(ApplicationContext context, + EurekaServiceRegistry serviceRegistry, EurekaRegistration registration) { this.context = context; this.serviceRegistry = serviceRegistry; this.registration = registration; @@ -81,11 +82,12 @@ public class EurekaAutoServiceRegistration implements AutoServiceRegistration, S this.serviceRegistry.register(this.registration); - this.context.publishEvent( - new InstanceRegisteredEvent<>(this, this.registration.getInstanceConfig())); + this.context.publishEvent(new InstanceRegisteredEvent<>(this, + this.registration.getInstanceConfig())); this.running.set(true); } } + @Override public void stop() { this.serviceRegistry.deregister(this.registration); @@ -118,7 +120,6 @@ public class EurekaAutoServiceRegistration implements AutoServiceRegistration, S return this.order; } - @Override public boolean supportsEventType(Class eventType) { return WebServerInitializedEvent.class.isAssignableFrom(eventType) @@ -129,7 +130,8 @@ public class EurekaAutoServiceRegistration implements AutoServiceRegistration, S public void onApplicationEvent(ApplicationEvent event) { if (event instanceof WebServerInitializedEvent) { onApplicationEvent((WebServerInitializedEvent) event); - } else if (event instanceof ContextClosedEvent) { + } + else if (event instanceof ContextClosedEvent) { onApplicationEvent((ContextClosedEvent) event); } } @@ -145,7 +147,7 @@ public class EurekaAutoServiceRegistration implements AutoServiceRegistration, S } public void onApplicationEvent(ContextClosedEvent event) { - if( event.getApplicationContext() == context ) { + if (event.getApplicationContext() == context) { stop(); } } diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaRegistration.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaRegistration.java index 7044959c0..6e3f9cd92 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaRegistration.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaRegistration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.eureka.serviceregistry; @@ -21,8 +20,14 @@ import java.net.URI; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; +import com.netflix.appinfo.ApplicationInfoManager; +import com.netflix.appinfo.HealthCheckHandler; +import com.netflix.appinfo.InstanceInfo; +import com.netflix.discovery.EurekaClient; +import com.netflix.discovery.EurekaClientConfig; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.aop.framework.Advised; import org.springframework.aop.support.AopUtils; import org.springframework.beans.factory.ObjectProvider; @@ -34,26 +39,29 @@ import org.springframework.cloud.netflix.eureka.InstanceInfoFactory; import org.springframework.context.ApplicationEventPublisher; import org.springframework.util.Assert; -import com.netflix.appinfo.ApplicationInfoManager; -import com.netflix.appinfo.HealthCheckHandler; -import com.netflix.appinfo.InstanceInfo; -import com.netflix.discovery.EurekaClient; -import com.netflix.discovery.EurekaClientConfig; - /** + * Eureka-specific implementation of service instance {@link Registration}. + * * @author Spencer Gibb * @author Tim Ysewyn */ public class EurekaRegistration implements Registration { + private static final Log log = LogFactory.getLog(EurekaRegistration.class); private final EurekaClient eurekaClient; + private final AtomicReference cloudEurekaClient = new AtomicReference<>(); + private final CloudEurekaInstanceConfig instanceConfig; + private final ApplicationInfoManager applicationInfoManager; + private ObjectProvider healthCheckHandler; - private EurekaRegistration(CloudEurekaInstanceConfig instanceConfig, EurekaClient eurekaClient, ApplicationInfoManager applicationInfoManager, ObjectProvider healthCheckHandler) { + private EurekaRegistration(CloudEurekaInstanceConfig instanceConfig, + EurekaClient eurekaClient, ApplicationInfoManager applicationInfoManager, + ObjectProvider healthCheckHandler) { this.eurekaClient = eurekaClient; this.instanceConfig = instanceConfig; this.applicationInfoManager = applicationInfoManager; @@ -64,58 +72,6 @@ public class EurekaRegistration implements Registration { return new Builder(instanceConfig); } - public static class Builder { - private final CloudEurekaInstanceConfig instanceConfig; - private ApplicationInfoManager applicationInfoManager; - private EurekaClient eurekaClient; - private ObjectProvider healthCheckHandler; - - private EurekaClientConfig clientConfig; - private ApplicationEventPublisher publisher; - - Builder(CloudEurekaInstanceConfig instanceConfig) { - this.instanceConfig = instanceConfig; - } - - public Builder with(ApplicationInfoManager applicationInfoManager) { - this.applicationInfoManager = applicationInfoManager; - return this; - } - - public Builder with(EurekaClient eurekaClient) { - this.eurekaClient = eurekaClient; - return this; - } - - public Builder with(ObjectProvider healthCheckHandler) { - this.healthCheckHandler = healthCheckHandler; - return this; - } - - public Builder with(EurekaClientConfig clientConfig, ApplicationEventPublisher publisher) { - this.clientConfig = clientConfig; - this.publisher = publisher; - return this; - } - - public EurekaRegistration build() { - Assert.notNull(instanceConfig, "instanceConfig may not be null"); - - if (this.applicationInfoManager == null) { - InstanceInfo instanceInfo = new InstanceInfoFactory().create(this.instanceConfig); - this.applicationInfoManager = new ApplicationInfoManager(this.instanceConfig, instanceInfo); - } - if (this.eurekaClient == null) { - Assert.notNull(this.clientConfig, "if eurekaClient is null, EurekaClientConfig may not be null"); - Assert.notNull(this.publisher, "if eurekaClient is null, ApplicationEventPublisher may not be null"); - - this.eurekaClient = new CloudEurekaClient(this.applicationInfoManager, this.clientConfig, this.publisher); - } - return new EurekaRegistration(instanceConfig, eurekaClient, applicationInfoManager, healthCheckHandler); - } - - } - @Override public String getInstanceId() { return this.instanceConfig.getInstanceId(); @@ -157,20 +113,24 @@ public class EurekaRegistration implements Registration { public CloudEurekaClient getEurekaClient() { if (this.cloudEurekaClient.get() == null) { try { - this.cloudEurekaClient.compareAndSet(null, getTargetObject(eurekaClient, CloudEurekaClient.class)); - } catch (Exception e) { + this.cloudEurekaClient.compareAndSet(null, + getTargetObject(eurekaClient, CloudEurekaClient.class)); + } + catch (Exception e) { log.error("error getting CloudEurekaClient", e); } } return this.cloudEurekaClient.get(); } - @SuppressWarnings({"unchecked"}) + @SuppressWarnings({ "unchecked" }) protected T getTargetObject(Object proxy, Class targetClass) throws Exception { if (AopUtils.isJdkDynamicProxy(proxy)) { return (T) ((Advised) proxy).getTargetSource().getTarget(); - } else { - return (T) proxy; // expected to be cglib proxy then, which is simply a specialized class + } + else { + return (T) proxy; // expected to be cglib proxy then, which is simply a + // specialized class } } @@ -186,7 +146,8 @@ public class EurekaRegistration implements Registration { return healthCheckHandler; } - public void setHealthCheckHandler(ObjectProvider healthCheckHandler) { + public void setHealthCheckHandler( + ObjectProvider healthCheckHandler) { this.healthCheckHandler = healthCheckHandler; } @@ -206,4 +167,71 @@ public class EurekaRegistration implements Registration { return this.instanceConfig.getSecurePort(); } + /** + * A builder for {@link EurekaRegistration} objects. + */ + public static class Builder { + + private final CloudEurekaInstanceConfig instanceConfig; + + private ApplicationInfoManager applicationInfoManager; + + private EurekaClient eurekaClient; + + private ObjectProvider healthCheckHandler; + + private EurekaClientConfig clientConfig; + + private ApplicationEventPublisher publisher; + + Builder(CloudEurekaInstanceConfig instanceConfig) { + this.instanceConfig = instanceConfig; + } + + public Builder with(ApplicationInfoManager applicationInfoManager) { + this.applicationInfoManager = applicationInfoManager; + return this; + } + + public Builder with(EurekaClient eurekaClient) { + this.eurekaClient = eurekaClient; + return this; + } + + public Builder with(ObjectProvider healthCheckHandler) { + this.healthCheckHandler = healthCheckHandler; + return this; + } + + public Builder with(EurekaClientConfig clientConfig, + ApplicationEventPublisher publisher) { + this.clientConfig = clientConfig; + this.publisher = publisher; + return this; + } + + public EurekaRegistration build() { + Assert.notNull(instanceConfig, "instanceConfig may not be null"); + + if (this.applicationInfoManager == null) { + InstanceInfo instanceInfo = new InstanceInfoFactory() + .create(this.instanceConfig); + this.applicationInfoManager = new ApplicationInfoManager( + this.instanceConfig, instanceInfo); + } + if (this.eurekaClient == null) { + Assert.notNull(this.clientConfig, + "if eurekaClient is null, EurekaClientConfig may not be null"); + Assert.notNull(this.publisher, + "if eurekaClient is null, ApplicationEventPublisher may not be null"); + + this.eurekaClient = new CloudEurekaClient(this.applicationInfoManager, + this.clientConfig, this.publisher); + } + return new EurekaRegistration(instanceConfig, eurekaClient, + applicationInfoManager, healthCheckHandler); + } + + } + } diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaServiceRegistry.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaServiceRegistry.java index 84f3f3d96..4e91a8fbb 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaServiceRegistry.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaServiceRegistry.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,18 +12,17 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.eureka.serviceregistry; import java.util.HashMap; +import com.netflix.appinfo.InstanceInfo; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.springframework.cloud.client.serviceregistry.ServiceRegistry; -import com.netflix.appinfo.InstanceInfo; +import org.springframework.cloud.client.serviceregistry.ServiceRegistry; import static com.netflix.appinfo.InstanceInfo.InstanceStatus.UNKNOWN; @@ -39,7 +38,8 @@ public class EurekaServiceRegistry implements ServiceRegistry - reg.getEurekaClient().registerHealthCheck(healthCheckHandler)); + reg.getHealthCheckHandler().ifAvailable(healthCheckHandler -> reg + .getEurekaClient().registerHealthCheck(healthCheckHandler)); } - + private void maybeInitializeClient(EurekaRegistration reg) { // force initialization of possibly scoped proxies reg.getApplicationInfoManager().getInfo(); reg.getEurekaClient().getApplications(); } - + @Override public void deregister(EurekaRegistration reg) { if (reg.getApplicationInfoManager().getInfo() != null) { if (log.isInfoEnabled()) { - log.info("Unregistering application " + reg.getApplicationInfoManager().getInfo().getAppName() + log.info("Unregistering application " + + reg.getApplicationInfoManager().getInfo().getAppName() + " with eureka with status DOWN"); } - reg.getApplicationInfoManager().setInstanceStatus(InstanceInfo.InstanceStatus.DOWN); + reg.getApplicationInfoManager() + .setInstanceStatus(InstanceInfo.InstanceStatus.DOWN); - //shutdown of eureka client should happen with EurekaRegistration.close() - //auto registration will create a bean which will be properly disposed - //manual registrations will need to call close() + // shutdown of eureka client should happen with EurekaRegistration.close() + // auto registration will create a bean which will be properly disposed + // manual registrations will need to call close() } } @@ -78,14 +80,15 @@ public class EurekaServiceRegistry implements ServiceRegistry status = new HashMap<>(); if (info != null) { status.put("status", info.getStatus().toString()); status.put("overriddenStatus", info.getOverriddenStatus().toString()); - } else { + } + else { status.put("status", UNKNOWN.toString()); } diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/ConditionalOnRibbonAndEurekaEnabled.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/ConditionalOnRibbonAndEurekaEnabled.java index 5df8b539a..59c73ede5 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/ConditionalOnRibbonAndEurekaEnabled.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/ConditionalOnRibbonAndEurekaEnabled.java @@ -1,3 +1,19 @@ +/* + * Copyright 2013-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.springframework.cloud.netflix.ribbon.eureka; import java.lang.annotation.Documented; @@ -6,6 +22,9 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import com.netflix.discovery.EurekaClient; +import com.netflix.niws.loadbalancer.DiscoveryEnabledNIWSServerList; + import org.springframework.boot.autoconfigure.condition.AllNestedConditions; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; @@ -13,30 +32,40 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.cloud.netflix.ribbon.SpringClientFactory; import org.springframework.context.annotation.Conditional; -import com.netflix.discovery.EurekaClient; -import com.netflix.niws.loadbalancer.DiscoveryEnabledNIWSServerList; - -@Target({ElementType.TYPE, ElementType.METHOD}) +/** + * Conditional that requires both Ribbon and Eureka to be enabled. + * @author Ihor Kryvenko + * @author Spencer Gibb + */ +@Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Documented @Conditional(ConditionalOnRibbonAndEurekaEnabled.OnRibbonAndEurekaEnabledCondition.class) public @interface ConditionalOnRibbonAndEurekaEnabled { - class OnRibbonAndEurekaEnabledCondition extends AllNestedConditions { + class OnRibbonAndEurekaEnabledCondition extends AllNestedConditions { - public OnRibbonAndEurekaEnabledCondition() { - super(ConfigurationPhase.REGISTER_BEAN); - } + OnRibbonAndEurekaEnabledCondition() { + super(ConfigurationPhase.REGISTER_BEAN); + } - @ConditionalOnClass(DiscoveryEnabledNIWSServerList.class) - @ConditionalOnBean(SpringClientFactory.class) - @ConditionalOnProperty(value = "ribbon.eureka.enabled", matchIfMissing = true) - static class Defaults {} + @ConditionalOnClass(DiscoveryEnabledNIWSServerList.class) + @ConditionalOnBean(SpringClientFactory.class) + @ConditionalOnProperty(value = "ribbon.eureka.enabled", matchIfMissing = true) + static class Defaults { - @ConditionalOnBean(EurekaClient.class) - static class EurekaBeans {} + } + + @ConditionalOnBean(EurekaClient.class) + static class EurekaBeans { + + } + + @ConditionalOnProperty(value = "eureka.client.enabled", matchIfMissing = true) + static class OnEurekaClientEnabled { + + } + + } - @ConditionalOnProperty(value = "eureka.client.enabled", matchIfMissing = true) - static class OnEurekaClientEnabled {} - } } diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/DomainExtractingServerList.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/DomainExtractingServerList.java index 714e57a48..d9d4456ae 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/DomainExtractingServerList.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/DomainExtractingServerList.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,20 +19,21 @@ package org.springframework.cloud.netflix.ribbon.eureka; import java.util.ArrayList; import java.util.List; -import org.springframework.cloud.netflix.ribbon.RibbonProperties; - import com.netflix.appinfo.InstanceInfo; import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.Server; import com.netflix.loadbalancer.ServerList; import com.netflix.niws.loadbalancer.DiscoveryEnabledServer; +import org.springframework.cloud.netflix.ribbon.RibbonProperties; + /** * @author Dave Syer */ public class DomainExtractingServerList implements ServerList { private ServerList list; + private final RibbonProperties ribbon; private boolean approximateZoneFromHostname; @@ -46,15 +47,15 @@ public class DomainExtractingServerList implements ServerList getInitialListOfServers() { - List servers = setZones(this.list - .getInitialListOfServers()); + List servers = setZones( + this.list.getInitialListOfServers()); return servers; } @Override public List getUpdatedListOfServers() { - List servers = setZones(this.list - .getUpdatedListOfServers()); + List servers = setZones( + this.list.getUpdatedListOfServers()); return servers; } @@ -85,7 +86,7 @@ class DomainExtractingServer extends DiscoveryEnabledServer { this.id = id; } - public DomainExtractingServer(DiscoveryEnabledServer server, boolean useSecurePort, + DomainExtractingServer(DiscoveryEnabledServer server, boolean useSecurePort, boolean useIpAddr, boolean approximateZoneFromHostname) { // host and port are set in super() super(server.getInstanceInfo(), useSecurePort, useIpAddr); @@ -108,9 +109,11 @@ class DomainExtractingServer extends DiscoveryEnabledServer { DiscoveryEnabledServer enabled = (DiscoveryEnabledServer) server; InstanceInfo instance = enabled.getInstanceInfo(); if (instance.getMetadata().containsKey("instanceId")) { - return instance.getHostName()+":"+instance.getMetadata().get("instanceId"); + return instance.getHostName() + ":" + + instance.getMetadata().get("instanceId"); } } return super.getId(); } + } diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaRibbonClientConfiguration.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaRibbonClientConfiguration.java index 512d3b193..4f56c9719 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaRibbonClientConfiguration.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaRibbonClientConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,9 +19,19 @@ package org.springframework.cloud.netflix.ribbon.eureka; import javax.annotation.PostConstruct; import javax.inject.Provider; +import com.netflix.appinfo.EurekaInstanceConfig; +import com.netflix.client.config.IClientConfig; +import com.netflix.config.ConfigurationManager; +import com.netflix.config.DeploymentContext.ContextKey; import com.netflix.discovery.EurekaClient; +import com.netflix.discovery.EurekaClientConfig; +import com.netflix.loadbalancer.IPing; +import com.netflix.loadbalancer.ServerList; +import com.netflix.niws.loadbalancer.DiscoveryEnabledNIWSServerList; +import com.netflix.niws.loadbalancer.NIWSDiscoveryPing; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; @@ -33,16 +43,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.util.StringUtils; -import com.netflix.appinfo.EurekaInstanceConfig; -import com.netflix.client.config.IClientConfig; -import com.netflix.config.ConfigurationManager; -import com.netflix.config.DeploymentContext.ContextKey; -import com.netflix.discovery.EurekaClientConfig; -import com.netflix.loadbalancer.IPing; -import com.netflix.loadbalancer.ServerList; -import com.netflix.niws.loadbalancer.DiscoveryEnabledNIWSServerList; -import com.netflix.niws.loadbalancer.NIWSDiscoveryPing; - /** * Preprocessor that configures defaults for eureka-discovered ribbon clients. Such as: * @zone, NIWSServerListClassName, DeploymentContextBasedVipAddresses, @@ -55,7 +55,8 @@ import com.netflix.niws.loadbalancer.NIWSDiscoveryPing; @Configuration public class EurekaRibbonClientConfiguration { - private static final Log log = LogFactory.getLog(EurekaRibbonClientConfiguration.class); + private static final Log log = LogFactory + .getLog(EurekaRibbonClientConfiguration.class); @Value("${ribbon.eureka.approximateZoneFromHostname:false}") private boolean approximateZoneFromHostname = false; @@ -97,7 +98,8 @@ public class EurekaRibbonClientConfiguration { @Bean @ConditionalOnMissingBean - public ServerList ribbonServerList(IClientConfig config, Provider eurekaClientProvider) { + public ServerList ribbonServerList(IClientConfig config, + Provider eurekaClientProvider) { if (this.propertiesFactory.isSet(ServerList.class, serviceId)) { return this.propertiesFactory.get(ServerList.class, config, serviceId); } diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaServerIntrospector.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaServerIntrospector.java index 4bf4f74ac..ee19f0887 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaServerIntrospector.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaServerIntrospector.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,12 +18,12 @@ package org.springframework.cloud.netflix.ribbon.eureka; import java.util.Map; -import org.springframework.cloud.netflix.ribbon.DefaultServerIntrospector; - import com.netflix.appinfo.InstanceInfo; import com.netflix.loadbalancer.Server; import com.netflix.niws.loadbalancer.DiscoveryEnabledServer; +import org.springframework.cloud.netflix.ribbon.DefaultServerIntrospector; + /** * @author Spencer Gibb */ @@ -33,7 +33,8 @@ public class EurekaServerIntrospector extends DefaultServerIntrospector { public boolean isSecure(Server server) { if (server instanceof DiscoveryEnabledServer) { DiscoveryEnabledServer discoveryServer = (DiscoveryEnabledServer) server; - return discoveryServer.getInstanceInfo().isPortEnabled(InstanceInfo.PortType.SECURE); + return discoveryServer.getInstanceInfo() + .isPortEnabled(InstanceInfo.PortType.SECURE); } return super.isSecure(server); } @@ -46,4 +47,5 @@ public class EurekaServerIntrospector extends DefaultServerIntrospector { } return super.getMetadata(server); } + } diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/RibbonEurekaAutoConfiguration.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/RibbonEurekaAutoConfiguration.java index 0419690ac..fbe7348e7 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/RibbonEurekaAutoConfiguration.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/RibbonEurekaAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,9 +23,9 @@ import org.springframework.cloud.netflix.ribbon.RibbonClients; import org.springframework.context.annotation.Configuration; /** - * Spring configuration for configuring Ribbon defaults to be Eureka based - * if Eureka client is enabled - * + * Spring configuration for configuring Ribbon defaults to be Eureka based if Eureka + * client is enabled. + * * @author Dave Syer * @author Biju Kunjummen */ @@ -36,5 +36,4 @@ import org.springframework.context.annotation.Configuration; @RibbonClients(defaultConfiguration = EurekaRibbonClientConfiguration.class) public class RibbonEurekaAutoConfiguration { - } diff --git a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/ZoneUtils.java b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/ZoneUtils.java index fa8677a5c..02bbd9e2d 100644 --- a/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/ZoneUtils.java +++ b/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/ribbon/eureka/ZoneUtils.java @@ -1,4 +1,5 @@ -/* Copyright 2013-2015 the original author or authors. +/* + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,16 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.netflix.ribbon.eureka; import org.springframework.util.StringUtils; /** * Utility class for dealing with zones. + * * @author Ryan Baxter * */ -public class ZoneUtils { +public final class ZoneUtils { + + private ZoneUtils() { + throw new AssertionError("Must not instantiate utility class."); + } /** * Approximates Eureka zones from a host name. This method approximates the zone to be diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/ConditionalOnRefreshScopeTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/ConditionalOnRefreshScopeTests.java index f94d8ce5c..f7e83b046 100644 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/ConditionalOnRefreshScopeTests.java +++ b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/ConditionalOnRefreshScopeTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ package org.springframework.cloud.netflix.eureka; import org.junit.Test; + import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration; @@ -35,12 +36,12 @@ public class ConditionalOnRefreshScopeTests { @Test public void refreshScopeIncluded() { new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RefreshAutoConfiguration.class)) - .withUserConfiguration(Beans.class).run(c -> { - assertThat(c).hasSingleBean( - org.springframework.cloud.context.scope.refresh.RefreshScope.class); - assertThat(c.getBean("foo")).isEqualTo("foo"); - }); + .withConfiguration(AutoConfigurations.of(RefreshAutoConfiguration.class)) + .withUserConfiguration(Beans.class).run(c -> { + assertThat(c).hasSingleBean( + org.springframework.cloud.context.scope.refresh.RefreshScope.class); + assertThat(c.getBean("foo")).isEqualTo("foo"); + }); } @Test @@ -52,11 +53,13 @@ public class ConditionalOnRefreshScopeTests { @Configuration protected static class Beans { + @Bean @ConditionalOnRefreshScope public String foo() { return "foo"; } + } -} \ No newline at end of file +} diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaClientAutoConfigurationRandomPortTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaClientAutoConfigurationRandomPortTests.java index fd50521c4..3f4ac8d45 100644 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaClientAutoConfigurationRandomPortTests.java +++ b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaClientAutoConfigurationRandomPortTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.eureka; @@ -52,4 +51,5 @@ public class EurekaClientAutoConfigurationRandomPortTests { public static class TestConfig { } + } diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaClientAutoConfigurationTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaClientAutoConfigurationTests.java index 3d2d5865e..89145c9bf 100644 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaClientAutoConfigurationTests.java +++ b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaClientAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.eureka; @@ -21,9 +20,17 @@ import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; + +import com.netflix.appinfo.ApplicationInfoManager; +import com.netflix.appinfo.HealthCheckHandler; +import com.netflix.discovery.EurekaClient; +import com.netflix.discovery.EurekaClientConfig; +import com.netflix.discovery.shared.transport.jersey.EurekaJerseyClient; +import com.sun.jersey.client.apache4.ApacheHttpClient4; import org.junit.After; import org.junit.Test; import org.mockito.Mockito; + import org.springframework.aop.framework.Advised; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.SearchStrategy; @@ -45,22 +52,15 @@ import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.SystemEnvironmentPropertySource; import org.springframework.test.util.ReflectionTestUtils; -import com.netflix.appinfo.ApplicationInfoManager; -import com.netflix.appinfo.HealthCheckHandler; -import com.netflix.discovery.EurekaClient; -import com.netflix.discovery.EurekaClientConfig; -import com.netflix.discovery.shared.transport.jersey.EurekaJerseyClient; -import com.sun.jersey.client.apache4.ApacheHttpClient4; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * @author Spencer Gibb * @author Matt Jenkins */ public class EurekaClientAutoConfigurationTests { + private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); @After @@ -72,7 +72,8 @@ public class EurekaClientAutoConfigurationTests { private void setupContext(Class... config) { ConfigurationPropertySources.attach(this.context.getEnvironment()); - this.context.register(PropertyPlaceholderAutoConfiguration.class, EurekaDiscoveryClientConfiguration.class); + this.context.register(PropertyPlaceholderAutoConfiguration.class, + EurekaDiscoveryClientConfiguration.class); for (Class value : config) { this.context.register(value); } @@ -81,26 +82,28 @@ public class EurekaClientAutoConfigurationTests { } @Test - public void shouldSetManagementPortInMetadataMapIfEqualToServerPort() throws Exception { + public void shouldSetManagementPortInMetadataMapIfEqualToServerPort() + throws Exception { TestPropertyValues.of("server.port=8989").applyTo(this.context); setupContext(RefreshAutoConfiguration.class); EurekaInstanceConfigBean instance = this.context .getBean(EurekaInstanceConfigBean.class); - assertEquals("8989", instance.getMetadataMap().get("management.port")); + assertThat(instance.getMetadataMap().get("management.port")).isEqualTo("8989"); } @Test public void shouldNotSetManagementAndJmxPortsInMetadataMap() throws Exception { - TestPropertyValues.of("server.port=8989", "management.server.port=0").applyTo(this.context); + TestPropertyValues.of("server.port=8989", "management.server.port=0") + .applyTo(this.context); setupContext(RefreshAutoConfiguration.class); EurekaInstanceConfigBean instance = this.context .getBean(EurekaInstanceConfigBean.class); - assertEquals(null, instance.getMetadataMap().get("management.port")); - assertEquals(null, instance.getMetadataMap().get("jmx.port")); + assertThat(instance.getMetadataMap().get("management.port")).isEqualTo(null); + assertThat(instance.getMetadataMap().get("jmx.port")).isEqualTo(null); } @Test @@ -111,21 +114,23 @@ public class EurekaClientAutoConfigurationTests { EurekaInstanceConfigBean instance = this.context .getBean(EurekaInstanceConfigBean.class); - assertEquals("9999", instance.getMetadataMap().get("management.port")); - assertEquals("6789", instance.getMetadataMap().get("jmx.port")); + assertThat(instance.getMetadataMap().get("management.port")).isEqualTo("9999"); + assertThat(instance.getMetadataMap().get("jmx.port")).isEqualTo("6789"); } @Test public void shouldNotResetManagementAndJmxPortsInMetadataMap() throws Exception { - TestPropertyValues.of("management.server.port=9999", - "eureka.instance.metadata-map.jmx.port=9898", - "eureka.instance.metadata-map.management.port=7878").applyTo(this.context); + TestPropertyValues + .of("management.server.port=9999", + "eureka.instance.metadata-map.jmx.port=9898", + "eureka.instance.metadata-map.management.port=7878") + .applyTo(this.context); setupContext(RefreshAutoConfiguration.class); EurekaInstanceConfigBean instance = this.context .getBean(EurekaInstanceConfigBean.class); - assertEquals("7878", instance.getMetadataMap().get("management.port")); - assertEquals("9898", instance.getMetadataMap().get("jmx.port")); + assertThat(instance.getMetadataMap().get("management.port")).isEqualTo("7878"); + assertThat(instance.getMetadataMap().get("jmx.port")).isEqualTo("9898"); } @Test @@ -141,8 +146,8 @@ public class EurekaClientAutoConfigurationTests { @Test public void nonSecurePort() { testNonSecurePortSystemProp("PORT"); - assertEquals("eurekaClient", - this.context.getBeanDefinition("eurekaClient").getFactoryMethodName()); + assertThat(this.context.getBeanDefinition("eurekaClient").getFactoryMethodName()) + .isEqualTo("eurekaClient"); } @Test @@ -152,176 +157,196 @@ public class EurekaClientAutoConfigurationTests { @Test public void securePortUnderscores() { - TestPropertyValues.of("eureka.instance.secure-port-enabled=true").applyTo(this.context); + TestPropertyValues.of("eureka.instance.secure-port-enabled=true") + .applyTo(this.context); addSystemEnvironment(this.context.getEnvironment(), "SERVER_PORT:8443"); setupContext(); - assertEquals(8443, getInstanceConfig().getSecurePort()); + assertThat(getInstanceConfig().getSecurePort()).isEqualTo(8443); } @Test public void securePort() { testSecurePort("PORT"); - assertEquals("eurekaClient", - this.context.getBeanDefinition("eurekaClient").getFactoryMethodName()); + assertThat(this.context.getBeanDefinition("eurekaClient").getFactoryMethodName()) + .isEqualTo("eurekaClient"); } @Test public void managementPort() { - TestPropertyValues.of("server.port=8989", - "management.server.port=9999").applyTo(this.context); + TestPropertyValues.of("server.port=8989", "management.server.port=9999") + .applyTo(this.context); setupContext(RefreshAutoConfiguration.class); EurekaInstanceConfigBean instance = this.context .getBean(EurekaInstanceConfigBean.class); - assertTrue("Wrong status page: " + instance.getStatusPageUrl(), - instance.getStatusPageUrl().contains("9999")); + assertThat(instance.getStatusPageUrl().contains("9999")) + .as("Wrong status page: " + instance.getStatusPageUrl()).isTrue(); } @Test public void statusPageUrlPathAndManagementPort() { - TestPropertyValues.of( "server.port=8989", - "management.server.port=9999", - "eureka.instance.statusPageUrlPath=/myStatusPage").applyTo(this.context); + TestPropertyValues + .of("server.port=8989", "management.server.port=9999", + "eureka.instance.statusPageUrlPath=/myStatusPage") + .applyTo(this.context); setupContext(RefreshAutoConfiguration.class); EurekaInstanceConfigBean instance = this.context .getBean(EurekaInstanceConfigBean.class); - assertTrue("Wrong status page: " + instance.getStatusPageUrl(), - instance.getStatusPageUrl().contains("/myStatusPage")); + assertThat(instance.getStatusPageUrl().contains("/myStatusPage")) + .as("Wrong status page: " + instance.getStatusPageUrl()).isTrue(); } @Test public void healthCheckUrlPathAndManagementPort() { - TestPropertyValues.of( "server.port=8989", - "management.server.port=9999", - "eureka.instance.healthCheckUrlPath=/myHealthCheck").applyTo(this.context); + TestPropertyValues + .of("server.port=8989", "management.server.port=9999", + "eureka.instance.healthCheckUrlPath=/myHealthCheck") + .applyTo(this.context); setupContext(RefreshAutoConfiguration.class); EurekaInstanceConfigBean instance = this.context .getBean(EurekaInstanceConfigBean.class); - assertTrue("Wrong health check: " + instance.getHealthCheckUrl(), - instance.getHealthCheckUrl().contains("/myHealthCheck")); + assertThat(instance.getHealthCheckUrl().contains("/myHealthCheck")) + .as("Wrong health check: " + instance.getHealthCheckUrl()).isTrue(); } @Test - public void statusPageUrl_and_healthCheckUrl_do_not_contain_server_context_path() throws Exception { - TestPropertyValues.of("server.port=8989", - "management.server.port=9999", "server.contextPath=/service").applyTo(this.context); + public void statusPageUrl_and_healthCheckUrl_do_not_contain_server_context_path() + throws Exception { + TestPropertyValues.of("server.port=8989", "management.server.port=9999", + "server.contextPath=/service").applyTo(this.context); setupContext(RefreshAutoConfiguration.class); EurekaInstanceConfigBean instance = this.context .getBean(EurekaInstanceConfigBean.class); - assertTrue("Wrong status page: " + instance.getStatusPageUrl(), - instance.getStatusPageUrl().endsWith(":9999/actuator/info")); - assertTrue("Wrong health check: " + instance.getHealthCheckUrl(), - instance.getHealthCheckUrl().endsWith(":9999/actuator/health")); + assertThat(instance.getStatusPageUrl().endsWith(":9999/actuator/info")) + .as("Wrong status page: " + instance.getStatusPageUrl()).isTrue(); + assertThat(instance.getHealthCheckUrl().endsWith(":9999/actuator/health")) + .as("Wrong health check: " + instance.getHealthCheckUrl()).isTrue(); } @Test - public void statusPageUrl_and_healthCheckUrl_contain_management_context_path() throws Exception { - TestPropertyValues.of( - "server.port=8989", "management.server.servlet.context-path=/management").applyTo(this.context); + public void statusPageUrl_and_healthCheckUrl_contain_management_context_path() + throws Exception { + TestPropertyValues + .of("server.port=8989", + "management.server.servlet.context-path=/management") + .applyTo(this.context); setupContext(RefreshAutoConfiguration.class); EurekaInstanceConfigBean instance = this.context .getBean(EurekaInstanceConfigBean.class); - assertTrue("Wrong status page: " + instance.getStatusPageUrl(), - instance.getStatusPageUrl().endsWith(":8989/management/actuator/info")); - assertTrue("Wrong health check: " + instance.getHealthCheckUrl(), - instance.getHealthCheckUrl().endsWith(":8989/management/actuator/health")); + assertThat(instance.getStatusPageUrl().endsWith(":8989/management/actuator/info")) + .as("Wrong status page: " + instance.getStatusPageUrl()).isTrue(); + assertThat( + instance.getHealthCheckUrl().endsWith(":8989/management/actuator/health")) + .as("Wrong health check: " + instance.getHealthCheckUrl()) + .isTrue(); } @Test - public void statusPageUrl_and_healthCheckUrl_contain_management_context_path_random_port() throws Exception { - TestPropertyValues.of( - "server.port=0", "management.server.servlet.context-path=/management").applyTo(this.context); + public void statusPageUrl_and_healthCheckUrl_contain_management_context_path_random_port() + throws Exception { + TestPropertyValues + .of("server.port=0", "management.server.servlet.context-path=/management") + .applyTo(this.context); setupContext(RefreshAutoConfiguration.class); EurekaInstanceConfigBean instance = this.context .getBean(EurekaInstanceConfigBean.class); - assertTrue("Wrong status page: " + instance.getStatusPageUrlPath(), - instance.getStatusPageUrlPath().equals("/management/actuator/info")); - assertTrue("Wrong health check: " + instance.getHealthCheckUrlPath(), - instance.getHealthCheckUrlPath().equals("/management/actuator/health")); + assertThat(instance.getStatusPageUrlPath().equals("/management/actuator/info")) + .as("Wrong status page: " + instance.getStatusPageUrlPath()).isTrue(); + assertThat(instance.getHealthCheckUrlPath().equals("/management/actuator/health")) + .as("Wrong health check: " + instance.getHealthCheckUrlPath()).isTrue(); } @Test public void statusPageUrlPathAndManagementPortAndContextPath() { - TestPropertyValues.of( "server.port=8989", - "management.server.port=9999", "management.server.servlet.context-path=/manage", - "eureka.instance.status-page-url-path=/myStatusPage").applyTo(this.context); + TestPropertyValues + .of("server.port=8989", "management.server.port=9999", + "management.server.servlet.context-path=/manage", + "eureka.instance.status-page-url-path=/myStatusPage") + .applyTo(this.context); setupContext(RefreshAutoConfiguration.class); EurekaInstanceConfigBean instance = this.context .getBean(EurekaInstanceConfigBean.class); - assertTrue("Wrong status page: " + instance.getStatusPageUrl(), - instance.getStatusPageUrl().endsWith(":9999/manage/myStatusPage")); + assertThat(instance.getStatusPageUrl().endsWith(":9999/manage/myStatusPage")) + .as("Wrong status page: " + instance.getStatusPageUrl()).isTrue(); } @Test public void healthCheckUrlPathAndManagementPortAndContextPath() { - TestPropertyValues.of( "server.port=8989", - "management.server.port=9999", "management.server.servlet.context-path=/manage", - "eureka.instance.health-check-url-path=/myHealthCheck").applyTo(this.context); + TestPropertyValues + .of("server.port=8989", "management.server.port=9999", + "management.server.servlet.context-path=/manage", + "eureka.instance.health-check-url-path=/myHealthCheck") + .applyTo(this.context); setupContext(RefreshAutoConfiguration.class); EurekaInstanceConfigBean instance = this.context .getBean(EurekaInstanceConfigBean.class); - assertTrue("Wrong health check: " + instance.getHealthCheckUrl(), - instance.getHealthCheckUrl().endsWith(":9999/manage/myHealthCheck")); + assertThat(instance.getHealthCheckUrl().endsWith(":9999/manage/myHealthCheck")) + .as("Wrong health check: " + instance.getHealthCheckUrl()).isTrue(); } @Test public void statusPageUrlPathAndManagementPortAndContextPathKebobCase() { - TestPropertyValues.of( "server.port=8989", - "management.server.port=9999", "management.server.servlet.context-path=/manage", - "eureka.instance.status-page-url-path=/myStatusPage").applyTo(this.context); + TestPropertyValues + .of("server.port=8989", "management.server.port=9999", + "management.server.servlet.context-path=/manage", + "eureka.instance.status-page-url-path=/myStatusPage") + .applyTo(this.context); setupContext(RefreshAutoConfiguration.class); EurekaInstanceConfigBean instance = this.context .getBean(EurekaInstanceConfigBean.class); - assertTrue("Wrong status page: " + instance.getStatusPageUrl(), - instance.getStatusPageUrl().endsWith(":9999/manage/myStatusPage")); + assertThat(instance.getStatusPageUrl().endsWith(":9999/manage/myStatusPage")) + .as("Wrong status page: " + instance.getStatusPageUrl()).isTrue(); } @Test public void healthCheckUrlPathAndManagementPortAndContextPathKebobCase() { - TestPropertyValues.of( "server.port=8989", - "management.server.port=9999", "management.server.servlet.context-path=/manage", - "eureka.instance.health-check-url-path=/myHealthCheck").applyTo(this.context); + TestPropertyValues + .of("server.port=8989", "management.server.port=9999", + "management.server.servlet.context-path=/manage", + "eureka.instance.health-check-url-path=/myHealthCheck") + .applyTo(this.context); setupContext(RefreshAutoConfiguration.class); EurekaInstanceConfigBean instance = this.context .getBean(EurekaInstanceConfigBean.class); - assertTrue("Wrong health check: " + instance.getHealthCheckUrl(), - instance.getHealthCheckUrl().endsWith(":9999/manage/myHealthCheck")); + assertThat(instance.getHealthCheckUrl().endsWith(":9999/manage/myHealthCheck")) + .as("Wrong health check: " + instance.getHealthCheckUrl()).isTrue(); } @Test public void statusPageUrlPathAndManagementPortKabobCase() { - TestPropertyValues.of( "server.port=8989", - "management.server.port=9999", - "eureka.instance.status-page-url-path=/myStatusPage").applyTo(this.context); + TestPropertyValues + .of("server.port=8989", "management.server.port=9999", + "eureka.instance.status-page-url-path=/myStatusPage") + .applyTo(this.context); setupContext(RefreshAutoConfiguration.class); EurekaInstanceConfigBean instance = this.context .getBean(EurekaInstanceConfigBean.class); - assertTrue("Wrong status page: " + instance.getStatusPageUrl(), - instance.getStatusPageUrl().contains("/myStatusPage")); + assertThat(instance.getStatusPageUrl().contains("/myStatusPage")) + .as("Wrong status page: " + instance.getStatusPageUrl()).isTrue(); } @Test public void statusPageUrlAndPreferIpAddress() { - TestPropertyValues.of( "server.port=8989", - "management.server.port=9999", "eureka.instance.hostname=foo", - "eureka.instance.prefer-ip-address:true").applyTo(this.context); + TestPropertyValues.of("server.port=8989", "management.server.port=9999", + "eureka.instance.hostname=foo", "eureka.instance.prefer-ip-address:true") + .applyTo(this.context); setupContext(RefreshAutoConfiguration.class); EurekaInstanceConfigBean instance = this.context .getBean(EurekaInstanceConfigBean.class); - assertEquals("statusPageUrl is wrong", "http://" + instance.getIpAddress() + ":9999/actuator/info", - instance.getStatusPageUrl()); - assertEquals("healthCheckUrl is wrong", "http://" + instance.getIpAddress() + ":9999/actuator/health", - instance.getHealthCheckUrl()); + assertThat(instance.getStatusPageUrl()).as("statusPageUrl is wrong") + .isEqualTo("http://" + instance.getIpAddress() + ":9999/actuator/info"); + assertThat(instance.getHealthCheckUrl()).as("healthCheckUrl is wrong") + .isEqualTo("http://" + instance.getIpAddress() + ":9999/actuator/health"); } @Test public void statusPageAndHealthCheckUrlsShouldSetUserDefinedIpAddress() { - TestPropertyValues.of("server.port=8989", - "management.server.port=9999", "eureka.instance.hostname=foo", + TestPropertyValues.of("server.port=8989", "management.server.port=9999", + "eureka.instance.hostname=foo", "eureka.instance.ip-address:192.168.13.90", "eureka.instance.prefer-ip-address:true").applyTo(this.context); @@ -329,85 +354,95 @@ public class EurekaClientAutoConfigurationTests { EurekaInstanceConfigBean instance = this.context .getBean(EurekaInstanceConfigBean.class); - assertEquals("statusPageUrl is wrong", "http://192.168.13.90:9999/actuator/info", - instance.getStatusPageUrl()); - assertEquals("healthCheckUrl is wrong", "http://192.168.13.90:9999/actuator/health", - instance.getHealthCheckUrl()); + assertThat(instance.getStatusPageUrl()).as("statusPageUrl is wrong") + .isEqualTo("http://192.168.13.90:9999/actuator/info"); + assertThat(instance.getHealthCheckUrl()).as("healthCheckUrl is wrong") + .isEqualTo("http://192.168.13.90:9999/actuator/health"); } @Test public void healthCheckUrlPathAndManagementPortKabobCase() { - TestPropertyValues.of( "server.port=8989", - "management.server.port=9999", - "eureka.instance.health-check-url-path=/myHealthCheck").applyTo(this.context); + TestPropertyValues + .of("server.port=8989", "management.server.port=9999", + "eureka.instance.health-check-url-path=/myHealthCheck") + .applyTo(this.context); setupContext(RefreshAutoConfiguration.class); EurekaInstanceConfigBean instance = this.context .getBean(EurekaInstanceConfigBean.class); - assertTrue("Wrong health check: " + instance.getHealthCheckUrl(), - instance.getHealthCheckUrl().contains("/myHealthCheck")); + assertThat(instance.getHealthCheckUrl().contains("/myHealthCheck")) + .as("Wrong health check: " + instance.getHealthCheckUrl()).isTrue(); } @Test public void statusPageUrlPathAndManagementPortUpperCase() { - TestPropertyValues.of( "server.port=8989", - "management.server.port=9999").applyTo(this.context); - addSystemEnvironment(this.context.getEnvironment(), "EUREKA_INSTANCE_STATUS_PAGE_URL_PATH=/myStatusPage"); + TestPropertyValues.of("server.port=8989", "management.server.port=9999") + .applyTo(this.context); + addSystemEnvironment(this.context.getEnvironment(), + "EUREKA_INSTANCE_STATUS_PAGE_URL_PATH=/myStatusPage"); setupContext(RefreshAutoConfiguration.class); EurekaInstanceConfigBean instance = this.context .getBean(EurekaInstanceConfigBean.class); - assertTrue("Wrong status page: " + instance.getStatusPageUrl(), - instance.getStatusPageUrl().contains("/myStatusPage")); + assertThat(instance.getStatusPageUrl().contains("/myStatusPage")) + .as("Wrong status page: " + instance.getStatusPageUrl()).isTrue(); } @Test public void healthCheckUrlPathAndManagementPortUpperCase() { - TestPropertyValues.of( "server.port=8989", - "management.server.port=9999").applyTo(this.context); - addSystemEnvironment(this.context.getEnvironment(), "EUREKA_INSTANCE_HEALTH_CHECK_URL_PATH=/myHealthCheck"); + TestPropertyValues.of("server.port=8989", "management.server.port=9999") + .applyTo(this.context); + addSystemEnvironment(this.context.getEnvironment(), + "EUREKA_INSTANCE_HEALTH_CHECK_URL_PATH=/myHealthCheck"); setupContext(RefreshAutoConfiguration.class); EurekaInstanceConfigBean instance = this.context .getBean(EurekaInstanceConfigBean.class); - assertTrue("Wrong health check: " + instance.getHealthCheckUrl(), - instance.getHealthCheckUrl().contains("/myHealthCheck")); + assertThat(instance.getHealthCheckUrl().contains("/myHealthCheck")) + .as("Wrong health check: " + instance.getHealthCheckUrl()).isTrue(); } @Test public void hostname() { - TestPropertyValues.of( "server.port=8989", - "management.server.port=9999", "eureka.instance.hostname=foo").applyTo(this.context); + TestPropertyValues.of("server.port=8989", "management.server.port=9999", + "eureka.instance.hostname=foo").applyTo(this.context); setupContext(RefreshAutoConfiguration.class); EurekaInstanceConfigBean instance = this.context .getBean(EurekaInstanceConfigBean.class); - assertTrue("Wrong status page: " + instance.getStatusPageUrl(), - instance.getStatusPageUrl().contains("foo")); + assertThat(instance.getStatusPageUrl().contains("foo")) + .as("Wrong status page: " + instance.getStatusPageUrl()).isTrue(); } @Test public void refreshScopedBeans() { setupContext(RefreshAutoConfiguration.class); assertThat(this.context.getBeanDefinition("eurekaClient").getBeanClassName()) - .startsWith(GenericScope.class.getName()+"$LockedScopedProxyFactoryBean"); - assertThat(this.context.getBeanDefinition("eurekaApplicationInfoManager").getBeanClassName()) - .startsWith(GenericScope.class.getName()+"$LockedScopedProxyFactoryBean"); + .startsWith( + GenericScope.class.getName() + "$LockedScopedProxyFactoryBean"); + assertThat(this.context.getBeanDefinition("eurekaApplicationInfoManager") + .getBeanClassName()).startsWith( + GenericScope.class.getName() + "$LockedScopedProxyFactoryBean"); } @Test public void shouldReregisterHealthCheckHandlerAfterRefresh() throws Exception { - TestPropertyValues.of("eureka.client.healthcheck.enabled=true").applyTo(this.context); - setupContext(RefreshAutoConfiguration.class, AutoServiceRegistrationConfiguration.class); + TestPropertyValues.of("eureka.client.healthcheck.enabled=true") + .applyTo(this.context); + setupContext(RefreshAutoConfiguration.class, + AutoServiceRegistrationConfiguration.class); EurekaClient oldEurekaClient = getLazyInitEurekaClient(); - HealthCheckHandler healthCheckHandler = this.context.getBean("eurekaHealthCheckHandler", HealthCheckHandler.class); + HealthCheckHandler healthCheckHandler = this.context + .getBean("eurekaHealthCheckHandler", HealthCheckHandler.class); assertThat(healthCheckHandler).isInstanceOf(EurekaHealthCheckHandler.class); assertThat(oldEurekaClient.getHealthCheckHandler()).isSameAs(healthCheckHandler); - ContextRefresher refresher = this.context.getBean("contextRefresher", ContextRefresher.class); + ContextRefresher refresher = this.context.getBean("contextRefresher", + ContextRefresher.class); refresher.refresh(); EurekaClient newEurekaClient = getLazyInitEurekaClient(); - HealthCheckHandler newHealthCheckHandler = this.context.getBean("eurekaHealthCheckHandler", HealthCheckHandler.class); + HealthCheckHandler newHealthCheckHandler = this.context + .getBean("eurekaHealthCheckHandler", HealthCheckHandler.class); assertThat(healthCheckHandler).isSameAs(newHealthCheckHandler); assertThat(oldEurekaClient).isNotSameAs(newEurekaClient); @@ -416,10 +451,13 @@ public class EurekaClientAutoConfigurationTests { @Test public void shouldCloseDiscoveryClient() throws Exception { - TestPropertyValues.of("eureka.client.healthcheck.enabled=true").applyTo(this.context); - setupContext(RefreshAutoConfiguration.class, AutoServiceRegistrationConfiguration.class); + TestPropertyValues.of("eureka.client.healthcheck.enabled=true") + .applyTo(this.context); + setupContext(RefreshAutoConfiguration.class, + AutoServiceRegistrationConfiguration.class); - AtomicBoolean isShutdown = (AtomicBoolean) ReflectionTestUtils.getField(getLazyInitEurekaClient(), "isShutdown"); + AtomicBoolean isShutdown = (AtomicBoolean) ReflectionTestUtils + .getField(getLazyInitEurekaClient(), "isShutdown"); assertThat(isShutdown.get()).isFalse(); @@ -430,8 +468,9 @@ public class EurekaClientAutoConfigurationTests { @Test public void basicAuth() { - TestPropertyValues.of( "server.port=8989", - "eureka.client.serviceUrl.defaultZone=http://user:foo@example.com:80/eureka").applyTo(this.context); + TestPropertyValues.of("server.port=8989", + "eureka.client.serviceUrl.defaultZone=http://user:foo@example.com:80/eureka") + .applyTo(this.context); setupContext(MockClientConfiguration.class); // ApacheHttpClient4 http = this.context.getBean(ApacheHttpClient4.class); // Mockito.verify(http).addFilter(Matchers.any(HTTPBasicAuthFilter.class)); @@ -440,30 +479,33 @@ public class EurekaClientAutoConfigurationTests { @Test public void testDefaultAppName() throws Exception { setupContext(); - assertEquals("unknown", getInstanceConfig().getAppname()); - assertEquals("unknown", getInstanceConfig().getVirtualHostName()); - assertEquals("unknown", getInstanceConfig().getSecureVirtualHostName()); + assertThat(getInstanceConfig().getAppname()).isEqualTo("unknown"); + assertThat(getInstanceConfig().getVirtualHostName()).isEqualTo("unknown"); + assertThat(getInstanceConfig().getSecureVirtualHostName()).isEqualTo("unknown"); } @Test public void testAppName() throws Exception { - TestPropertyValues.of( "spring.application.name=mytest").applyTo(this.context); + TestPropertyValues.of("spring.application.name=mytest").applyTo(this.context); setupContext(); - assertEquals("mytest", getInstanceConfig().getAppname()); - assertEquals("mytest", getInstanceConfig().getVirtualHostName()); - assertEquals("mytest", getInstanceConfig().getSecureVirtualHostName()); + assertThat(getInstanceConfig().getAppname()).isEqualTo("mytest"); + assertThat(getInstanceConfig().getVirtualHostName()).isEqualTo("mytest"); + assertThat(getInstanceConfig().getSecureVirtualHostName()).isEqualTo("mytest"); } @Test public void testAppNameUpper() throws Exception { - addSystemEnvironment(this.context.getEnvironment(), "SPRING_APPLICATION_NAME=mytestupper"); + addSystemEnvironment(this.context.getEnvironment(), + "SPRING_APPLICATION_NAME=mytestupper"); setupContext(); - assertEquals("mytestupper", getInstanceConfig().getAppname()); - assertEquals("mytestupper", getInstanceConfig().getVirtualHostName()); - assertEquals("mytestupper", getInstanceConfig().getSecureVirtualHostName()); + assertThat(getInstanceConfig().getAppname()).isEqualTo("mytestupper"); + assertThat(getInstanceConfig().getVirtualHostName()).isEqualTo("mytestupper"); + assertThat(getInstanceConfig().getSecureVirtualHostName()) + .isEqualTo("mytestupper"); } - private void addSystemEnvironment(ConfigurableEnvironment environment, String... pairs) { + private void addSystemEnvironment(ConfigurableEnvironment environment, + String... pairs) { MutablePropertySources sources = environment.getPropertySources(); Map map = getOrAdd(sources, "testsysenv"); for (String pair : pairs) { @@ -476,7 +518,7 @@ public class EurekaClientAutoConfigurationTests { @SuppressWarnings("unchecked") private static Map getOrAdd(MutablePropertySources sources, - String name) { + String name) { if (sources.contains(name)) { return (Map) sources.get(name).getSource(); } @@ -499,10 +541,12 @@ public class EurekaClientAutoConfigurationTests { @Test public void testInstanceNamePreferred() throws Exception { - addSystemEnvironment(this.context.getEnvironment(), "SPRING_APPLICATION_NAME=mytestspringappname"); - TestPropertyValues.of( "eureka.instance.appname=mytesteurekaappname").applyTo(this.context); + addSystemEnvironment(this.context.getEnvironment(), + "SPRING_APPLICATION_NAME=mytestspringappname"); + TestPropertyValues.of("eureka.instance.appname=mytesteurekaappname") + .applyTo(this.context); setupContext(); - assertEquals("mytesteurekaappname", getInstanceConfig().getAppname()); + assertThat(getInstanceConfig().getAppname()).isEqualTo("mytesteurekaappname"); } @Test @@ -524,19 +568,21 @@ public class EurekaClientAutoConfigurationTests { private void testNonSecurePortSystemProp(String propName) { addSystemEnvironment(this.context.getEnvironment(), propName + ":8888"); setupContext(); - assertEquals(8888, getInstanceConfig().getNonSecurePort()); + assertThat(getInstanceConfig().getNonSecurePort()).isEqualTo(8888); } private void testNonSecurePort(String propName) { TestPropertyValues.of(propName + ":8888").applyTo(this.context); setupContext(); - assertEquals(8888, getInstanceConfig().getNonSecurePort()); + assertThat(getInstanceConfig().getNonSecurePort()).isEqualTo(8888); } private void testSecurePort(String propName) { - TestPropertyValues.of("eureka.instance.secure-port-enabled=true", propName+":8443").applyTo(this.context); + TestPropertyValues + .of("eureka.instance.secure-port-enabled=true", propName + ":8443") + .applyTo(this.context); setupContext(); - assertEquals(8443, getInstanceConfig().getSecurePort()); + assertThat(getInstanceConfig().getSecurePort()).isEqualTo(8443); } private EurekaInstanceConfigBean getInstanceConfig() { @@ -544,13 +590,16 @@ public class EurekaClientAutoConfigurationTests { } private EurekaClient getLazyInitEurekaClient() throws Exception { - return (EurekaClient)((Advised) this.context.getBean("eurekaClient", EurekaClient.class)).getTargetSource().getTarget(); + return (EurekaClient) ((Advised) this.context.getBean("eurekaClient", + EurekaClient.class)).getTargetSource().getTarget(); } @Configuration @EnableConfigurationProperties @Import({ UtilAutoConfiguration.class, EurekaClientAutoConfiguration.class }) - protected static class TestConfiguration { } + protected static class TestConfiguration { + + } @Configuration protected static class TestEurekaClientConfiguration { @@ -562,7 +611,8 @@ public class EurekaClientAutoConfigurationTests { @Bean(destroyMethod = "shutdown") @ConditionalOnMissingBean(value = EurekaClient.class, search = SearchStrategy.CURRENT) - public EurekaClient eurekaClient(ApplicationInfoManager manager, EurekaClientConfig config, ApplicationContext context) { + public EurekaClient eurekaClient(ApplicationInfoManager manager, + EurekaClientConfig config, ApplicationContext context) { return new CloudEurekaClient(manager, config, null, context) { @Override public synchronized void shutdown() { @@ -574,6 +624,7 @@ public class EurekaClientAutoConfigurationTests { } }; } + } @Configuration @@ -597,6 +648,7 @@ public class EurekaClientAutoConfigurationTests { public ApacheHttpClient4 apacheClient() { return Mockito.mock(ApacheHttpClient4.class); } + } @Configuration @@ -604,4 +656,5 @@ public class EurekaClientAutoConfigurationTests { public static class AutoServiceRegistrationConfiguration { } + } diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaClientConfigBeanTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaClientConfigBeanTests.java index 1faa2a4b0..3f09942dc 100644 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaClientConfigBeanTests.java +++ b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaClientConfigBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.eureka; @@ -21,6 +20,7 @@ import java.util.Collections; import org.junit.After; import org.junit.Test; + import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.util.TestPropertyValues; @@ -29,7 +29,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.env.CompositePropertySource; import org.springframework.core.env.MapPropertySource; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -52,8 +52,8 @@ public class EurekaClientConfigBeanTests { this.context.register(PropertyPlaceholderAutoConfiguration.class, TestConfiguration.class); this.context.refresh(); - assertEquals("example.com", this.context.getBean(EurekaClientConfigBean.class) - .getProxyHost()); + assertThat(this.context.getBean(EurekaClientConfigBean.class).getProxyHost()) + .isEqualTo("example.com"); } @Test @@ -63,27 +63,28 @@ public class EurekaClientConfigBeanTests { this.context.register(PropertyPlaceholderAutoConfiguration.class, TestConfiguration.class); this.context.refresh(); - assertEquals("{defaultZone=http://example.com}", - this.context.getBean(EurekaClientConfigBean.class).getServiceUrl() - .toString()); - assertEquals("[http://example.com/]", getEurekaServiceUrlsForDefaultZone()); + assertThat(this.context.getBean(EurekaClientConfigBean.class).getServiceUrl() + .toString()).isEqualTo("{defaultZone=http://example.com}"); + assertThat(getEurekaServiceUrlsForDefaultZone()) + .isEqualTo("[http://example.com/]"); } @Test public void serviceUrlWithCompositePropertySource() { CompositePropertySource source = new CompositePropertySource("composite"); this.context.getEnvironment().getPropertySources().addFirst(source); - source.addPropertySource(new MapPropertySource("config", Collections - . singletonMap("eureka.client.serviceUrl.defaultZone", + source.addPropertySource(new MapPropertySource("config", + Collections.singletonMap( + "eureka.client.serviceUrl.defaultZone", "http://example.com,http://example2.com, http://example3.com"))); this.context.register(PropertyPlaceholderAutoConfiguration.class, TestConfiguration.class); this.context.refresh(); - assertEquals("{defaultZone=http://example.com,http://example2.com, http://example3.com}", - this.context.getBean(EurekaClientConfigBean.class).getServiceUrl() - .toString()); - assertEquals("[http://example.com/, http://example2.com/, http://example3.com/]", - getEurekaServiceUrlsForDefaultZone()); + assertThat(this.context.getBean(EurekaClientConfigBean.class).getServiceUrl() + .toString()).isEqualTo( + "{defaultZone=http://example.com,http://example2.com, http://example3.com}"); + assertThat(getEurekaServiceUrlsForDefaultZone()).isEqualTo( + "[http://example.com/, http://example2.com/, http://example3.com/]"); } @Test @@ -93,17 +94,20 @@ public class EurekaClientConfigBeanTests { this.context.register(PropertyPlaceholderAutoConfiguration.class, TestConfiguration.class); this.context.refresh(); - assertEquals("[http://example.com/]", getEurekaServiceUrlsForDefaultZone()); + assertThat(getEurekaServiceUrlsForDefaultZone()) + .isEqualTo("[http://example.com/]"); } @Test public void serviceUrlWithCustomZone() { - TestPropertyValues.of("eureka.client.serviceUrl.customZone:http://custom-example.com") + TestPropertyValues + .of("eureka.client.serviceUrl.customZone:http://custom-example.com") .applyTo(this.context); this.context.register(PropertyPlaceholderAutoConfiguration.class, TestConfiguration.class); this.context.refresh(); - assertEquals("[http://custom-example.com/]", getEurekaServiceUrls("customZone")); + assertThat(getEurekaServiceUrls("customZone")) + .isEqualTo("[http://custom-example.com/]"); } @Test @@ -113,7 +117,7 @@ public class EurekaClientConfigBeanTests { this.context.register(PropertyPlaceholderAutoConfiguration.class, TestConfiguration.class); this.context.refresh(); - assertEquals("[]", getEurekaServiceUrlsForDefaultZone()); + assertThat(getEurekaServiceUrlsForDefaultZone()).isEqualTo("[]"); } private String getEurekaServiceUrlsForDefaultZone() { diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaHealthCheckHandlerTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaHealthCheckHandlerTests.java index 605f70974..3dd6ce5c1 100644 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaHealthCheckHandlerTests.java +++ b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaHealthCheckHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,9 +19,9 @@ package org.springframework.cloud.netflix.eureka; import java.util.List; import com.netflix.appinfo.InstanceInfo.InstanceStatus; - import org.junit.Before; import org.junit.Test; + import org.springframework.boot.actuate.health.AbstractHealthIndicator; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; @@ -33,7 +33,7 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests the {@link EurekaHealthCheckHandler} with different health indicator registered. @@ -54,7 +54,7 @@ public class EurekaHealthCheckHandlerTests { public void testNoHealthCheckRegistered() throws Exception { InstanceStatus status = healthCheckHandler.getStatus(InstanceStatus.UNKNOWN); - assertEquals(InstanceStatus.UNKNOWN, status); + assertThat(status).isEqualTo(InstanceStatus.UNKNOWN); } @Test @@ -63,7 +63,7 @@ public class EurekaHealthCheckHandlerTests { initialize(UpHealthConfiguration.class); InstanceStatus status = healthCheckHandler.getStatus(InstanceStatus.UNKNOWN); - assertEquals(InstanceStatus.UP, status); + assertThat(status).isEqualTo(InstanceStatus.UP); } @Test @@ -72,7 +72,7 @@ public class EurekaHealthCheckHandlerTests { initialize(UpHealthConfiguration.class, DownHealthConfiguration.class); InstanceStatus status = healthCheckHandler.getStatus(InstanceStatus.UNKNOWN); - assertEquals(InstanceStatus.DOWN, status); + assertThat(status).isEqualTo(InstanceStatus.DOWN); } @Test @@ -81,7 +81,7 @@ public class EurekaHealthCheckHandlerTests { initialize(FatalHealthConfiguration.class); InstanceStatus status = healthCheckHandler.getStatus(InstanceStatus.UNKNOWN); - assertEquals(InstanceStatus.UNKNOWN, status); + assertThat(status).isEqualTo(InstanceStatus.UNKNOWN); } @Test @@ -90,11 +90,12 @@ public class EurekaHealthCheckHandlerTests { initialize(EurekaDownHealthConfiguration.class); InstanceStatus status = healthCheckHandler.getStatus(InstanceStatus.UP); - assertEquals(InstanceStatus.UP, status); + assertThat(status).isEqualTo(InstanceStatus.UP); } private void initialize(Class... configurations) throws Exception { - ApplicationContext applicationContext = new AnnotationConfigApplicationContext(configurations); + ApplicationContext applicationContext = new AnnotationConfigApplicationContext( + configurations); healthCheckHandler.setApplicationContext(applicationContext); healthCheckHandler.afterPropertiesSet(); } @@ -106,10 +107,11 @@ public class EurekaHealthCheckHandlerTests { return new AbstractHealthIndicator() { @Override protected void doHealthCheck(Health.Builder builder) throws Exception { - builder.up(); + builder.up(); } }; } + } public static class DownHealthConfiguration { @@ -123,6 +125,7 @@ public class EurekaHealthCheckHandlerTests { } }; } + } public static class FatalHealthConfiguration { @@ -136,10 +139,11 @@ public class EurekaHealthCheckHandlerTests { } }; } + } - public static class EurekaDownHealthConfiguration { + @Bean public DiscoveryHealthIndicator discoveryHealthIndicator() { return new DiscoveryClientHealthIndicator(null, null) { @@ -161,8 +165,12 @@ public class EurekaHealthCheckHandlerTests { } @Bean - public DiscoveryCompositeHealthIndicator discoveryCompositeHealthIndicator(List indicators) { - return new DiscoveryCompositeHealthIndicator(new OrderedHealthAggregator(), indicators); + public DiscoveryCompositeHealthIndicator discoveryCompositeHealthIndicator( + List indicators) { + return new DiscoveryCompositeHealthIndicator(new OrderedHealthAggregator(), + indicators); } + } -} \ No newline at end of file + +} diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaInstanceConfigBeanTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaInstanceConfigBeanTests.java index 80c5a46eb..ea399b07b 100644 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaInstanceConfigBeanTests.java +++ b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/EurekaInstanceConfigBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,14 +12,15 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.eureka; +import com.netflix.appinfo.InstanceInfo.InstanceStatus; import org.junit.After; import org.junit.Before; import org.junit.Test; + import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; @@ -33,10 +34,8 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.util.StringUtils; -import com.netflix.appinfo.InstanceInfo.InstanceStatus; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -47,7 +46,9 @@ import static org.junit.Assert.assertTrue; public class EurekaInstanceConfigBeanTests { private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); + private String hostName; + private String ipAddress; @Before @@ -68,16 +69,17 @@ public class EurekaInstanceConfigBeanTests { @Test public void basicBinding() { - TestPropertyValues.of("eureka.instance.appGroupName=mygroup").applyTo(this.context); + TestPropertyValues.of("eureka.instance.appGroupName=mygroup") + .applyTo(this.context); setupContext(); - assertEquals("mygroup", getInstanceConfig().getAppGroupName()); + assertThat(getInstanceConfig().getAppGroupName()).isEqualTo("mygroup"); } @Test public void nonSecurePort() { TestPropertyValues.of("eureka.instance.nonSecurePort:8888").applyTo(this.context); setupContext(); - assertEquals(8888, getInstanceConfig().getNonSecurePort()); + assertThat(getInstanceConfig().getNonSecurePort()).isEqualTo(8888); } @Test @@ -85,76 +87,82 @@ public class EurekaInstanceConfigBeanTests { TestPropertyValues.of("eureka.instance.instanceId:special").applyTo(this.context); setupContext(); EurekaInstanceConfigBean instance = getInstanceConfig(); - assertEquals("special", instance.getInstanceId()); + assertThat(instance.getInstanceId()).isEqualTo("special"); } @Test public void initialHostName() { - TestPropertyValues.of("eureka.instance.appGroupName=mygroup").applyTo(this.context); + TestPropertyValues.of("eureka.instance.appGroupName=mygroup") + .applyTo(this.context); setupContext(); if (this.hostName != null) { - assertEquals(this.hostName, getInstanceConfig().getHostname()); + assertThat(getInstanceConfig().getHostname()).isEqualTo(this.hostName); } } @Test public void refreshHostName() { - TestPropertyValues.of("eureka.instance.appGroupName=mygroup").applyTo(this.context); + TestPropertyValues.of("eureka.instance.appGroupName=mygroup") + .applyTo(this.context); setupContext(); ReflectionTestUtils.setField(getInstanceConfig(), "hostname", "marvin"); - assertEquals("marvin", getInstanceConfig().getHostname()); + assertThat(getInstanceConfig().getHostname()).isEqualTo("marvin"); getInstanceConfig().getHostName(true); if (this.hostName != null) { - assertEquals(this.hostName, getInstanceConfig().getHostname()); + assertThat(getInstanceConfig().getHostname()).isEqualTo(this.hostName); } } @Test public void refreshHostNameWhenSetByUser() { - TestPropertyValues.of("eureka.instance.appGroupName=mygroup").applyTo(this.context); + TestPropertyValues.of("eureka.instance.appGroupName=mygroup") + .applyTo(this.context); setupContext(); getInstanceConfig().setHostname("marvin"); - assertEquals("marvin", getInstanceConfig().getHostname()); + assertThat(getInstanceConfig().getHostname()).isEqualTo("marvin"); getInstanceConfig().getHostName(true); - assertEquals("marvin", getInstanceConfig().getHostname()); + assertThat(getInstanceConfig().getHostname()).isEqualTo("marvin"); } @Test public void initialIpAddress() { - TestPropertyValues.of("eureka.instance.appGroupName=mygroup").applyTo(this.context); + TestPropertyValues.of("eureka.instance.appGroupName=mygroup") + .applyTo(this.context); setupContext(); if (this.ipAddress != null) { - assertEquals(this.ipAddress, getInstanceConfig().getIpAddress()); + assertThat(getInstanceConfig().getIpAddress()).isEqualTo(this.ipAddress); } } @Test public void refreshIpAddress() { - TestPropertyValues.of("eureka.instance.appGroupName=mygroup").applyTo(this.context); + TestPropertyValues.of("eureka.instance.appGroupName=mygroup") + .applyTo(this.context); setupContext(); ReflectionTestUtils.setField(getInstanceConfig(), "ipAddress", "10.0.0.1"); - assertEquals("10.0.0.1", getInstanceConfig().getIpAddress()); + assertThat(getInstanceConfig().getIpAddress()).isEqualTo("10.0.0.1"); getInstanceConfig().getHostName(true); if (this.ipAddress != null) { - assertEquals(this.ipAddress, getInstanceConfig().getIpAddress()); + assertThat(getInstanceConfig().getIpAddress()).isEqualTo(this.ipAddress); } } @Test public void refreshIpAddressWhenSetByUser() { - TestPropertyValues.of("eureka.instance.appGroupName=mygroup").applyTo(this.context); + TestPropertyValues.of("eureka.instance.appGroupName=mygroup") + .applyTo(this.context); setupContext(); getInstanceConfig().setIpAddress("10.0.0.1"); - assertEquals("10.0.0.1", getInstanceConfig().getIpAddress()); + assertThat(getInstanceConfig().getIpAddress()).isEqualTo("10.0.0.1"); getInstanceConfig().getHostName(true); - assertEquals("10.0.0.1", getInstanceConfig().getIpAddress()); + assertThat(getInstanceConfig().getIpAddress()).isEqualTo("10.0.0.1"); } @Test public void testDefaultInitialStatus() { setupContext(); - assertEquals("initialStatus wrong", InstanceStatus.UP, - getInstanceConfig().getInitialStatus()); + assertThat(getInstanceConfig().getInitialStatus()).as("initialStatus wrong") + .isEqualTo(InstanceStatus.UP); } @Test(expected = BeanCreationException.class) @@ -165,19 +173,21 @@ public class EurekaInstanceConfigBeanTests { @Test public void testCustomInitialStatus() { - TestPropertyValues.of("eureka.instance.initial-status:STARTING").applyTo(this.context); + TestPropertyValues.of("eureka.instance.initial-status:STARTING") + .applyTo(this.context); setupContext(); - assertEquals("initialStatus wrong", InstanceStatus.STARTING, - getInstanceConfig().getInitialStatus()); + assertThat(getInstanceConfig().getInitialStatus()).as("initialStatus wrong") + .isEqualTo(InstanceStatus.STARTING); } @Test public void testPreferIpAddress() throws Exception { - TestPropertyValues.of("eureka.instance.preferIpAddress:true").applyTo(this.context); + TestPropertyValues.of("eureka.instance.preferIpAddress:true") + .applyTo(this.context); setupContext(); EurekaInstanceConfigBean instance = getInstanceConfig(); - assertTrue("Wrong hostname: " + instance.getHostname(), - getInstanceConfig().getHostname().equals(instance.getIpAddress())); + assertThat(getInstanceConfig().getHostname().equals(instance.getIpAddress())) + .as("Wrong hostname: " + instance.getHostname()).isTrue(); } @@ -185,47 +195,62 @@ public class EurekaInstanceConfigBeanTests { public void testDefaultVirtualHostName() throws Exception { TestPropertyValues.of("spring.application.name:myapp").applyTo(this.context); setupContext(); - assertEquals("virtualHostName wrong", "myapp", getInstanceConfig().getVirtualHostName()); - assertEquals("secureVirtualHostName wrong", "myapp", getInstanceConfig().getSecureVirtualHostName()); + assertThat(getInstanceConfig().getVirtualHostName()).as("virtualHostName wrong") + .isEqualTo("myapp"); + assertThat(getInstanceConfig().getSecureVirtualHostName()) + .as("secureVirtualHostName wrong").isEqualTo("myapp"); } @Test public void testCustomVirtualHostName() throws Exception { - TestPropertyValues.of("spring.application.name:myapp", "eureka.instance.virtualHostName=myvirthost", - "eureka.instance.secureVirtualHostName=mysecurevirthost").applyTo(this.context); + TestPropertyValues + .of("spring.application.name:myapp", + "eureka.instance.virtualHostName=myvirthost", + "eureka.instance.secureVirtualHostName=mysecurevirthost") + .applyTo(this.context); setupContext(); - assertEquals("virtualHostName wrong", "myvirthost", getInstanceConfig().getVirtualHostName()); - assertEquals("secureVirtualHostName wrong", "mysecurevirthost", getInstanceConfig().getSecureVirtualHostName()); + assertThat(getInstanceConfig().getVirtualHostName()).as("virtualHostName wrong") + .isEqualTo("myvirthost"); + assertThat(getInstanceConfig().getSecureVirtualHostName()) + .as("secureVirtualHostName wrong").isEqualTo("mysecurevirthost"); } @Test public void testDefaultAppName() throws Exception { setupContext(); - assertEquals("default app name is wrong", "unknown", getInstanceConfig().getAppname()); - assertEquals("default virtual hostname is wrong", "unknown", getInstanceConfig().getVirtualHostName()); - assertEquals("default secure virtual hostname is wrong", "unknown", getInstanceConfig().getSecureVirtualHostName()); + assertThat(getInstanceConfig().getAppname()).as("default app name is wrong") + .isEqualTo("unknown"); + assertThat(getInstanceConfig().getVirtualHostName()) + .as("default virtual hostname is wrong").isEqualTo("unknown"); + assertThat(getInstanceConfig().getSecureVirtualHostName()) + .as("default secure virtual hostname is wrong").isEqualTo("unknown"); } @Test public void testCustomInstanceId() throws Exception { - TestPropertyValues.of("eureka.instance.instanceId=myinstance").applyTo(this.context); + TestPropertyValues.of("eureka.instance.instanceId=myinstance") + .applyTo(this.context); setupContext(); - assertEquals("instance id is wrong", "myinstance", getInstanceConfig().getInstanceId()); + assertThat(getInstanceConfig().getInstanceId()).as("instance id is wrong") + .isEqualTo("myinstance"); } @Test public void testCustomInstanceIdWithMetadata() throws Exception { - TestPropertyValues.of("eureka.instance.metadataMap.instanceId=myinstance").applyTo(this.context); + TestPropertyValues.of("eureka.instance.metadataMap.instanceId=myinstance") + .applyTo(this.context); setupContext(); - assertEquals("instance id is wrong", "myinstance", getInstanceConfig().getInstanceId()); + assertThat(getInstanceConfig().getInstanceId()).as("instance id is wrong") + .isEqualTo("myinstance"); } @Test public void testDefaultInstanceId() throws Exception { setupContext(); - assertEquals("default instance id is wrong", null, getInstanceConfig().getInstanceId()); + assertThat(getInstanceConfig().getInstanceId()).as("default instance id is wrong") + .isEqualTo(null); } private void setupContext() { @@ -241,13 +266,16 @@ public class EurekaInstanceConfigBeanTests { @Configuration @EnableConfigurationProperties protected static class TestConfiguration { + @Autowired ConfigurableEnvironment env; + @Bean public EurekaInstanceConfigBean eurekaInstanceConfigBean() { - EurekaInstanceConfigBean configBean = new EurekaInstanceConfigBean(new InetUtils(new InetUtilsProperties())); + EurekaInstanceConfigBean configBean = new EurekaInstanceConfigBean( + new InetUtils(new InetUtilsProperties())); String springAppName = this.env.getProperty("spring.application.name", ""); - if(StringUtils.hasText(springAppName)) { + if (StringUtils.hasText(springAppName)) { configBean.setSecureVirtualHostName(springAppName); configBean.setVirtualHostName(springAppName); configBean.setAppname(springAppName); diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/InstanceInfoFactoryTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/InstanceInfoFactoryTests.java index 1ad77e6e2..d5e2464c9 100644 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/InstanceInfoFactoryTests.java +++ b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/InstanceInfoFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,14 +12,15 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.eureka; import java.io.IOException; +import com.netflix.appinfo.InstanceInfo; import org.junit.Test; + import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.util.TestPropertyValues; @@ -29,33 +30,31 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import com.netflix.appinfo.InstanceInfo; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class InstanceInfoFactoryTests { + private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); @Test public void instanceIdIsHostNameByDefault() throws IOException { InstanceInfo instanceInfo = setupInstance(); try (InetUtils utils = new InetUtils(new InetUtilsProperties())) { - assertEquals(utils.findFirstNonLoopbackHostInfo().getHostname(), - instanceInfo.getId()); + assertThat(instanceInfo.getId()) + .isEqualTo(utils.findFirstNonLoopbackHostInfo().getHostname()); } } @Test public void instanceIdIsIpWhenIpPreferred() throws Exception { InstanceInfo instanceInfo = setupInstance("eureka.instance.preferIpAddress:true"); - assertTrue(instanceInfo.getId().matches("(\\d+\\.){3}\\d+")); + assertThat(instanceInfo.getId().matches("(\\d+\\.){3}\\d+")).isTrue(); } @Test public void instanceInfoIdIsInstanceIdWhenSet() { InstanceInfo instanceInfo = setupInstance("eureka.instance.instanceId:special"); - assertEquals("special", instanceInfo.getId()); + assertThat(instanceInfo.getId()).isEqualTo("special"); } private InstanceInfo setupInstance(String... pairs) { @@ -76,9 +75,12 @@ public class InstanceInfoFactoryTests { @Configuration @EnableConfigurationProperties protected static class TestConfiguration { + @Bean public EurekaInstanceConfigBean eurekaInstanceConfigBean() { return new EurekaInstanceConfigBean(new InetUtils(new InetUtilsProperties())); } + } + } diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/ConfigRefreshTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/ConfigRefreshTests.java index e5c9e76d5..94e810c2b 100644 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/ConfigRefreshTests.java +++ b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/ConfigRefreshTests.java @@ -1,25 +1,25 @@ /* + * Copyright 2013-2019 the original author or authors. * - * * Copyright 2013-2016 the original author or authors. - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.netflix.eureka.config; +import com.netflix.discovery.EurekaClient; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.context.scope.refresh.RefreshScopeRefreshedEvent; @@ -27,8 +27,6 @@ import org.springframework.cloud.netflix.eureka.sample.RefreshEurekaSampleApplic import org.springframework.context.ApplicationEventPublisher; import org.springframework.test.context.junit4.SpringRunner; -import com.netflix.discovery.EurekaClient; - import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; @@ -44,18 +42,22 @@ public class ConfigRefreshTests { private ApplicationEventPublisher publisher; @Autowired - //Mocked in RefreshEurekaSampleApplication + // Mocked in RefreshEurekaSampleApplication private EurekaClient client; @Test - // This test is used to verify that getApplications is called the correct number of times - // when a refresh event is fired. The getApplications call in EurekaClientConfigurationRefresher.onApplicationEvent - // ensures that the EurekaClient bean is recreated after a refresh event and that we reregister the client with - //the server + // This test is used to verify that getApplications is called the correct number of + // times + // when a refresh event is fired. The getApplications call in + // EurekaClientConfigurationRefresher.onApplicationEvent + // ensures that the EurekaClient bean is recreated after a refresh event and that we + // reregister the client with + // the server public void verifyGetApplications() { - if(publisher != null) { + if (publisher != null) { publisher.publishEvent(new RefreshScopeRefreshedEvent()); } verify(client, times(3)).getApplications(); } + } diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/DiscoveryClientConfigServiceAutoConfigurationTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/DiscoveryClientConfigServiceAutoConfigurationTests.java index c14e5a58a..4adafca58 100644 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/DiscoveryClientConfigServiceAutoConfigurationTests.java +++ b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/DiscoveryClientConfigServiceAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,16 +12,19 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.eureka.config; import java.util.Arrays; +import com.netflix.appinfo.ApplicationInfoManager; +import com.netflix.appinfo.InstanceInfo; +import com.netflix.discovery.EurekaClient; import org.junit.After; import org.junit.Test; import org.mockito.Mockito; + import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.cloud.commons.util.UtilAutoConfiguration; @@ -34,11 +37,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import com.netflix.appinfo.ApplicationInfoManager; -import com.netflix.appinfo.InstanceInfo; -import com.netflix.discovery.EurekaClient; - -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.times; import static org.springframework.cloud.config.client.ConfigClientProperties.Discovery.DEFAULT_CONFIG_SERVER; @@ -65,18 +64,19 @@ public class DiscoveryClientConfigServiceAutoConfigurationTests { setup("spring.cloud.config.discovery.enabled=true", "eureka.instance.metadataMap.foo:bar", "eureka.instance.nonSecurePort:7001", "eureka.instance.hostname:foo"); - assertEquals(1, this.context.getBeanNamesForType( - EurekaDiscoveryClientConfigServiceAutoConfiguration.class).length); + assertThat(this.context.getBeanNamesForType( + EurekaDiscoveryClientConfigServiceAutoConfiguration.class).length) + .isEqualTo(1); EurekaClient eurekaClient = this.context.getParent().getBean(EurekaClient.class); - Mockito.verify(eurekaClient, times(2)).getInstancesByVipAddress(DEFAULT_CONFIG_SERVER, - false); + Mockito.verify(eurekaClient, times(2)) + .getInstancesByVipAddress(DEFAULT_CONFIG_SERVER, false); Mockito.verify(eurekaClient, times(1)).shutdown(); ConfigClientProperties locator = this.context .getBean(ConfigClientProperties.class); - assertEquals("http://foo:7001/", locator.getUri()[0]); + assertThat(locator.getUri()[0]).isEqualTo("http://foo:7001/"); ApplicationInfoManager infoManager = this.context .getBean(ApplicationInfoManager.class); - assertEquals("bar", infoManager.getInfo().getMetadata().get("foo")); + assertThat(infoManager.getInfo().getMetadata().get("foo")).isEqualTo("bar"); } private void setup(String... env) { diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/EurekaClientConfigServerAutoConfigurationTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/EurekaClientConfigServerAutoConfigurationTests.java index 75a94c045..4af7723af 100644 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/EurekaClientConfigServerAutoConfigurationTests.java +++ b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/EurekaClientConfigServerAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,15 +16,15 @@ package org.springframework.cloud.netflix.eureka.config; +import com.netflix.appinfo.EurekaInstanceConfig; import org.junit.Test; + import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.cloud.config.server.config.ConfigServerProperties; import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean; -import com.netflix.appinfo.EurekaInstanceConfig; - -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -35,42 +35,46 @@ public class EurekaClientConfigServerAutoConfigurationTests { @Test public void offByDefault() { new ApplicationContextRunner().withConfiguration( - AutoConfigurations.of(EurekaClientConfigServerAutoConfiguration.class)) - .run(c -> { - assertEquals(0, - c.getBeanNamesForType(EurekaInstanceConfigBean.class).length); - }); + AutoConfigurations.of(EurekaClientConfigServerAutoConfiguration.class)) + .run(c -> { + assertThat( + c.getBeanNamesForType(EurekaInstanceConfigBean.class).length) + .isEqualTo(0); + }); } - @Test - public void onWhenRequested() { - new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of( - EurekaClientConfigServerAutoConfiguration.class, - ConfigServerProperties.class, EurekaInstanceConfigBean.class)) - .withPropertyValues("spring.cloud.config.server.prefix=/config") - .run(c -> { - assertEquals(1, - c.getBeanNamesForType(EurekaInstanceConfig.class).length); - EurekaInstanceConfig instance = c.getBean(EurekaInstanceConfig.class); - assertEquals("/config", instance.getMetadataMap().get("configPath")); - }); - } + @Test + public void onWhenRequested() { + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of( + EurekaClientConfigServerAutoConfiguration.class, + ConfigServerProperties.class, EurekaInstanceConfigBean.class)) + .withPropertyValues("spring.cloud.config.server.prefix=/config") + .run(c -> { + assertThat(c.getBeanNamesForType(EurekaInstanceConfig.class).length) + .isEqualTo(1); + EurekaInstanceConfig instance = c.getBean(EurekaInstanceConfig.class); + assertThat(instance.getMetadataMap().get("configPath")) + .isEqualTo("/config"); + }); + } - @Test - public void notOverridingMetamapSettings() { - new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of( - EurekaClientConfigServerAutoConfiguration.class, - ConfigServerProperties.class, EurekaInstanceConfigBean.class)) - .withPropertyValues("spring.cloud.config.server.prefix=/config") - .withPropertyValues("eureka.instance.metadataMap.configPath=/differentpath") - .run(c -> { - assertEquals(1, - c.getBeanNamesForType(EurekaInstanceConfig.class).length); - EurekaInstanceConfig instance = c.getBean(EurekaInstanceConfig.class); - assertEquals("/differentpath", instance.getMetadataMap().get("configPath")); - }); - } + @Test + public void notOverridingMetamapSettings() { + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of( + EurekaClientConfigServerAutoConfiguration.class, + ConfigServerProperties.class, EurekaInstanceConfigBean.class)) + .withPropertyValues("spring.cloud.config.server.prefix=/config") + .withPropertyValues( + "eureka.instance.metadataMap.configPath=/differentpath") + .run(c -> { + assertThat(c.getBeanNamesForType(EurekaInstanceConfig.class).length) + .isEqualTo(1); + EurekaInstanceConfig instance = c.getBean(EurekaInstanceConfig.class); + assertThat(instance.getMetadataMap().get("configPath")) + .isEqualTo("/differentpath"); + }); + } -} \ No newline at end of file +} diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/JerseyOptionalArgsConfigurationTest.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/JerseyOptionalArgsConfigurationTest.java index ed2930a1c..5904d6607 100644 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/JerseyOptionalArgsConfigurationTest.java +++ b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/JerseyOptionalArgsConfigurationTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,9 +16,10 @@ package org.springframework.cloud.netflix.eureka.config; -import org.junit.Assert; +import com.netflix.discovery.DiscoveryClient.DiscoveryClientOptionalArgs; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; @@ -26,7 +27,7 @@ import org.springframework.cloud.netflix.eureka.sample.EurekaSampleApplication; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.netflix.discovery.DiscoveryClient.DiscoveryClientOptionalArgs; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Daniel Lavoie @@ -35,11 +36,13 @@ import com.netflix.discovery.DiscoveryClient.DiscoveryClientOptionalArgs; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = EurekaSampleApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class JerseyOptionalArgsConfigurationTest { + @Autowired private DiscoveryClientOptionalArgs optionalArgs; @Test public void contextLoads() { - Assert.assertNotNull(optionalArgs); + assertThat(optionalArgs).isNotNull(); } + } diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/RestTemplateOptionalArgsConfigurationTest.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/RestTemplateOptionalArgsConfigurationTest.java index 32ebc9a7d..e5562336a 100644 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/RestTemplateOptionalArgsConfigurationTest.java +++ b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/RestTemplateOptionalArgsConfigurationTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,9 +16,9 @@ package org.springframework.cloud.netflix.eureka.config; -import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.boot.WebApplicationType; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.test.context.SpringBootTest; @@ -29,6 +29,8 @@ import org.springframework.cloud.test.ClassPathExclusions; import org.springframework.cloud.test.ModifiedClassPathRunner; import org.springframework.context.ConfigurableApplicationContext; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Daniel Lavoie */ @@ -36,12 +38,15 @@ import org.springframework.context.ConfigurableApplicationContext; @ClassPathExclusions({ "jersey-client-*", "jersey-core-*", "jersey-apache-client4-*" }) @SpringBootTest(classes = EurekaSampleApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class RestTemplateOptionalArgsConfigurationTest { + @Test public void contextLoads() { try (ConfigurableApplicationContext context = new SpringApplicationBuilder() - .web(WebApplicationType.NONE).sources(EurekaSampleApplication.class).run()) { - Assert.assertNotNull( - context.getBean(RestTemplateDiscoveryClientOptionalArgs.class)); + .web(WebApplicationType.NONE).sources(EurekaSampleApplication.class) + .run()) { + assertThat(context.getBean(RestTemplateDiscoveryClientOptionalArgs.class)) + .isNotNull(); } } + } diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/healthcheck/EurekaHealthCheckTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/healthcheck/EurekaHealthCheckTests.java index f9b5e7c24..37a9ade36 100644 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/healthcheck/EurekaHealthCheckTests.java +++ b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/healthcheck/EurekaHealthCheckTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,11 @@ package org.springframework.cloud.netflix.eureka.healthcheck; +import com.netflix.appinfo.InstanceInfo; +import com.netflix.discovery.EurekaClient; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; @@ -29,11 +32,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.netflix.appinfo.InstanceInfo; -import com.netflix.discovery.EurekaClient; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests the Eureka health check handler. @@ -55,8 +54,8 @@ public class EurekaHealthCheckTests { InstanceInfo.InstanceStatus status = this.discoveryClient.getHealthCheckHandler() .getStatus(InstanceInfo.InstanceStatus.UNKNOWN); - assertNotNull(status); - assertEquals(InstanceInfo.InstanceStatus.OUT_OF_SERVICE, status); + assertThat(status).isNotNull(); + assertThat(status).isEqualTo(InstanceInfo.InstanceStatus.OUT_OF_SERVICE); } @Configuration @@ -72,5 +71,7 @@ public class EurekaHealthCheckTests { } }; } + } + } diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/http/EurekaServerMockApplication.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/http/EurekaServerMockApplication.java index 8f528e79b..a25c5c62d 100644 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/http/EurekaServerMockApplication.java +++ b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/http/EurekaServerMockApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,26 +55,21 @@ import static org.springframework.util.Assert.isTrue; /** * Mocked Eureka Server - * + * * @author Daniel Lavoie */ @Configuration @RestController @SpringBootApplication public class EurekaServerMockApplication { + private static final InstanceInfo INFO = InstanceInfo.Builder.newBuilder() - .setInstanceId("app1instance1") - .setAppName("app1") - .setAppNameForDeser("app1fordeser") - .setAppGroupName("app1group") - .setAppGroupNameForDeser("app1group1fordeser") - .setHostName("app1host1") + .setInstanceId("app1instance1").setAppName("app1") + .setAppNameForDeser("app1fordeser").setAppGroupName("app1group") + .setAppGroupNameForDeser("app1group1fordeser").setHostName("app1host1") .setStatus(InstanceInfo.InstanceStatus.UP) - .setOverriddenStatus(InstanceInfo.InstanceStatus.DOWN) - .setIPAddr("127.0.0.1") - .setSID("app1sid") - .setPort(8080) - .setSecurePort(4443) + .setOverriddenStatus(InstanceInfo.InstanceStatus.DOWN).setIPAddr("127.0.0.1") + .setSID("app1sid").setPort(8080).setSecurePort(4443) .enablePort(InstanceInfo.PortType.UNSECURE, true) .setHomePageUrl("/", "http://localhost/") .setHomePageUrlForDeser("http://localhost/") @@ -82,25 +77,20 @@ public class EurekaServerMockApplication { .setStatusPageUrlForDeser("http://localhost/status") .setHealthCheckUrls("/ping", "http://localhost/ping", null) .setHealthCheckUrlsForDeser("http://localhost/ping", null) - .setVIPAddress("localhost:8080") - .setVIPAddressDeser("localhost:8080") + .setVIPAddress("localhost:8080").setVIPAddressDeser("localhost:8080") .setSecureVIPAddress("localhost:4443") .setSecureVIPAddressDeser("localhost:4443") .setDataCenterInfo(new MyDataCenterInfo(DataCenterInfo.Name.MyOwn)) - .setLeaseInfo(LeaseInfo.Builder.newBuilder() - .setDurationInSecs(30) + .setLeaseInfo(LeaseInfo.Builder.newBuilder().setDurationInSecs(30) .setRenewalIntervalInSecs(30) - .setEvictionTimestamp(System.currentTimeMillis()+30000) - .setRenewalTimestamp(System.currentTimeMillis()-1000) - .setRegistrationTimestamp(System.currentTimeMillis()-2000) - .build()) - .add("metadatakey1", "metadatavalue1") - .setASGName("asg1") + .setEvictionTimestamp(System.currentTimeMillis() + 30000) + .setRenewalTimestamp(System.currentTimeMillis() - 1000) + .setRegistrationTimestamp(System.currentTimeMillis() - 2000).build()) + .add("metadatakey1", "metadatavalue1").setASGName("asg1") .setIsCoordinatingDiscoveryServer(false) .setLastUpdatedTimestamp(System.currentTimeMillis()) .setLastDirtyTimestamp(System.currentTimeMillis()) - .setActionType(InstanceInfo.ActionType.ADDED) - .setNamespace("namespace1") + .setActionType(InstanceInfo.ActionType.ADDED).setNamespace("namespace1") .build(); /** @@ -119,7 +109,8 @@ public class EurekaServerMockApplication { @RequestBody InstanceInfo instanceInfo) { isTrue(instanceInfo.getPort() != DEFAULT_PORT && instanceInfo.getPort() != 0, "Port not received from client"); - isTrue(instanceInfo.getSecurePort() != DEFAULT_SECURE_PORT && instanceInfo.getSecurePort() != 0, + isTrue(instanceInfo.getSecurePort() != DEFAULT_SECURE_PORT + && instanceInfo.getSecurePort() != 0, "Secure Port not received from client"); // Nothing to do } @@ -134,15 +125,16 @@ public class EurekaServerMockApplication { @PutMapping(value = "/apps/{appName}/{id}", params = { "status", "lastDirtyTimestamp" }) public ResponseEntity sendHeartBeat(@PathVariable String appName, - @PathVariable String id, @RequestParam String status, - @RequestParam String lastDirtyTimestamp, - @RequestParam(required = false) String overriddenstatus) { - if("fourOFour".equals(appName)) { + @PathVariable String id, @RequestParam String status, + @RequestParam String lastDirtyTimestamp, + @RequestParam(required = false) String overriddenstatus) { + if ("fourOFour".equals(appName)) { return new ResponseEntity(HttpStatus.NOT_FOUND); } - return new ResponseEntity(new InstanceInfo(null, null, null, null, null, null, null, null, null, - null, null, null, null, 0, null, null, null, null, null, null, null, new HashMap(), 0l, - 0l, null, null), HttpStatus.OK); + return new ResponseEntity(new InstanceInfo(null, null, null, null, + null, null, null, null, null, null, null, null, null, 0, null, null, null, + null, null, null, null, new HashMap<>(), 0L, 0L, null, null), + HttpStatus.OK); } @ResponseStatus(HttpStatus.OK) @@ -160,20 +152,21 @@ public class EurekaServerMockApplication { } - @GetMapping(value = { "/apps", "/apps/delta", "/vips/{address}", "/svips/{address}" }) + @GetMapping({ "/apps", "/apps/delta", "/vips/{address}", "/svips/{address}" }) public Applications getApplications(@PathVariable(required = false) String address, @RequestParam(required = false) String regions) { Applications applications = new Applications(); - applications.addApplication(new Application("app1", Collections.singletonList(INFO))); + applications + .addApplication(new Application("app1", Collections.singletonList(INFO))); return applications; } - @GetMapping(value = "/apps/{appName}") + @GetMapping("/apps/{appName}") public Application getApplication(@PathVariable String appName) { return new Application(); } - @GetMapping(value = { "/apps/{appName}/{id}", "/instances/{id}" }) + @GetMapping({ "/apps/{appName}/{id}", "/instances/{id}" }) public InstanceInfo getInstance(@PathVariable(required = false) String appName, @PathVariable String id) { return INFO; @@ -181,8 +174,8 @@ public class EurekaServerMockApplication { @Configuration @Order(Ordered.HIGHEST_PRECEDENCE) - protected static class TestSecurityConfiguration extends WebSecurityConfigurerAdapter { - + protected static class TestSecurityConfiguration + extends WebSecurityConfigurerAdapter { TestSecurityConfiguration() { super(true); @@ -191,16 +184,17 @@ public class EurekaServerMockApplication { @Bean public UserDetailsService userDetailsService() { InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); - manager.createUser(User.withUsername("test").password("{noop}test").roles("USER").build()); + manager.createUser(User.withUsername("test").password("{noop}test") + .roles("USER").build()); return manager; } @Override protected void configure(HttpSecurity http) throws Exception { // super.configure(http); - http.antMatcher("/apps/**") - .httpBasic(); + http.antMatcher("/apps/**").httpBasic(); } } + } diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/http/RestTemplateEurekaHttpClientTest.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/http/RestTemplateEurekaHttpClientTest.java index 3f20a92f5..87de11491 100644 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/http/RestTemplateEurekaHttpClientTest.java +++ b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/http/RestTemplateEurekaHttpClientTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,11 +16,16 @@ package org.springframework.cloud.netflix.eureka.http; +import com.netflix.appinfo.InstanceInfo; +import com.netflix.appinfo.InstanceInfo.InstanceStatus; +import com.netflix.appinfo.providers.EurekaConfigBasedInstanceInfoProvider; import com.netflix.discovery.shared.Applications; -import org.junit.Assert; +import com.netflix.discovery.shared.resolver.DefaultEndpoint; +import com.netflix.discovery.shared.transport.EurekaHttpClient; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; @@ -31,11 +36,7 @@ import org.springframework.http.HttpStatus; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.netflix.appinfo.InstanceInfo; -import com.netflix.appinfo.InstanceInfo.InstanceStatus; -import com.netflix.appinfo.providers.EurekaConfigBasedInstanceInfoProvider; -import com.netflix.discovery.shared.resolver.DefaultEndpoint; -import com.netflix.discovery.shared.transport.EurekaHttpClient; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Daniel Lavoie @@ -45,6 +46,7 @@ import com.netflix.discovery.shared.transport.EurekaHttpClient; "security.basic.enabled=true" }, webEnvironment = WebEnvironment.RANDOM_PORT) @DirtiesContext public class RestTemplateEurekaHttpClientTest { + @Autowired private InetUtils inetUtils; @@ -52,6 +54,7 @@ public class RestTemplateEurekaHttpClientTest { private String serviceUrl; private EurekaHttpClient eurekaHttpClient; + private InstanceInfo info; @Before @@ -76,45 +79,45 @@ public class RestTemplateEurekaHttpClientTest { @Test public void testRegister() { - Assert.assertEquals(HttpStatus.OK.value(), - eurekaHttpClient.register(info).getStatusCode()); + assertThat(eurekaHttpClient.register(info).getStatusCode()) + .isEqualTo(HttpStatus.OK.value()); } @Test public void testCancel() { - Assert.assertEquals(HttpStatus.OK.value(), - eurekaHttpClient.cancel("test", "test").getStatusCode()); + assertThat(eurekaHttpClient.cancel("test", "test").getStatusCode()) + .isEqualTo(HttpStatus.OK.value()); } @Test public void testSendHeartBeat() { - Assert.assertEquals(HttpStatus.OK.value(), eurekaHttpClient - .sendHeartBeat("test", "test", info, null).getStatusCode()); + assertThat(eurekaHttpClient.sendHeartBeat("test", "test", info, null) + .getStatusCode()).isEqualTo(HttpStatus.OK.value()); } @Test public void testSendHeartBeatFourOFour() { - Assert.assertEquals(HttpStatus.NOT_FOUND.value(), eurekaHttpClient - .sendHeartBeat("fourOFour", "test", info, null).getStatusCode()); + assertThat(eurekaHttpClient.sendHeartBeat("fourOFour", "test", info, null) + .getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND.value()); } @Test public void testStatusUpdate() { - Assert.assertEquals(HttpStatus.OK.value(), eurekaHttpClient - .statusUpdate("test", "test", InstanceStatus.UP, info).getStatusCode()); + assertThat(eurekaHttpClient.statusUpdate("test", "test", InstanceStatus.UP, info) + .getStatusCode()).isEqualTo(HttpStatus.OK.value()); } @Test public void testDeleteStatusOverride() { - Assert.assertEquals(HttpStatus.OK.value(), eurekaHttpClient - .deleteStatusOverride("test", "test", info).getStatusCode()); + assertThat(eurekaHttpClient.deleteStatusOverride("test", "test", info) + .getStatusCode()).isEqualTo(HttpStatus.OK.value()); } @Test public void testGetApplications() { Applications entity = eurekaHttpClient.getApplications().getEntity(); - Assert.assertNotNull(entity); - Assert.assertNotNull(eurekaHttpClient.getApplications("us", "eu").getEntity()); + assertThat(entity).isNotNull(); + assertThat(eurekaHttpClient.getApplications("us", "eu").getEntity()).isNotNull(); } @Test @@ -145,4 +148,5 @@ public class RestTemplateEurekaHttpClientTest { eurekaHttpClient.getInstance("test"); eurekaHttpClient.getInstance("test", "test"); } + } diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/http/RestTemplateTransportClientFactoriesTest.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/http/RestTemplateTransportClientFactoriesTest.java index 88d02636e..a0d1959a9 100644 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/http/RestTemplateTransportClientFactoriesTest.java +++ b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/http/RestTemplateTransportClientFactoriesTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,8 +22,10 @@ import org.junit.Test; * @author Daniel Lavoie */ public class RestTemplateTransportClientFactoriesTest { + @Test(expected = UnsupportedOperationException.class) public void testJerseyIsUnsuported() { new RestTemplateTransportClientFactories().newTransportClientFactory(null, null); } + } diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/http/RestTemplateTransportClientFactoryTest.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/http/RestTemplateTransportClientFactoryTest.java index 50de78aec..8a0917486 100644 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/http/RestTemplateTransportClientFactoryTest.java +++ b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/http/RestTemplateTransportClientFactoryTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,16 +16,16 @@ package org.springframework.cloud.netflix.eureka.http; +import com.netflix.discovery.shared.resolver.DefaultEndpoint; import org.junit.After; import org.junit.Before; import org.junit.Test; -import com.netflix.discovery.shared.resolver.DefaultEndpoint; - /** * @author Daniel Lavoie */ public class RestTemplateTransportClientFactoryTest { + private RestTemplateTransportClientFactory transportClientFatory; @Before @@ -54,4 +54,5 @@ public class RestTemplateTransportClientFactoryTest { public void shutdown() { transportClientFatory.shutdown(); } + } diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/metadata/DefaultManagementMetadataProviderTest.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/metadata/DefaultManagementMetadataProviderTest.java index 50739b10d..7e9b2d837 100644 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/metadata/DefaultManagementMetadataProviderTest.java +++ b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/metadata/DefaultManagementMetadataProviderTest.java @@ -1,7 +1,24 @@ +/* + * Copyright 2017-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.springframework.cloud.netflix.eureka.metadata; import org.junit.Before; import org.junit.Test; + import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean; import static org.assertj.core.api.Assertions.assertThat; @@ -11,167 +28,191 @@ import static org.mockito.Mockito.when; public class DefaultManagementMetadataProviderTest { - private static final EurekaInstanceConfigBean INSTANCE = mock(EurekaInstanceConfigBean.class); - private final ManagementMetadataProvider provider = new DefaultManagementMetadataProvider(); + private static final EurekaInstanceConfigBean INSTANCE = mock( + EurekaInstanceConfigBean.class); - @Before - public void setUp() throws Exception { - when(INSTANCE.getHostname()).thenReturn("host"); - when(INSTANCE.getHealthCheckUrlPath()).thenReturn("health"); - when(INSTANCE.getStatusPageUrlPath()).thenReturn("info"); - when(INSTANCE.isSecurePortEnabled()).thenReturn(false); - } + private final ManagementMetadataProvider provider = new DefaultManagementMetadataProvider(); - @Test - public void serverPortIsRandomAndManagementPortIsNull() throws Exception { - int serverPort = 0; - String serverContextPath = "/"; - String managementContextPath = null; - Integer managementPort = null; - ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort); + @Before + public void setUp() throws Exception { + when(INSTANCE.getHostname()).thenReturn("host"); + when(INSTANCE.getHealthCheckUrlPath()).thenReturn("health"); + when(INSTANCE.getStatusPageUrlPath()).thenReturn("info"); + when(INSTANCE.isSecurePortEnabled()).thenReturn(false); + } - assertThat(actual).isNull(); - } + @Test + public void serverPortIsRandomAndManagementPortIsNull() throws Exception { + int serverPort = 0; + String serverContextPath = "/"; + String managementContextPath = null; + Integer managementPort = null; + ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, + managementContextPath, managementPort); - @Test - public void managementPortIsRandom() throws Exception { - int serverPort = 0; - String serverContextPath = "/"; - String managementContextPath = null; - Integer managementPort = 0; - ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort); + assertThat(actual).isNull(); + } - assertThat(actual).isNull(); - } + @Test + public void managementPortIsRandom() throws Exception { + int serverPort = 0; + String serverContextPath = "/"; + String managementContextPath = null; + Integer managementPort = 0; + ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, + managementContextPath, managementPort); - @Test - public void serverPort() throws Exception { - int serverPort = 7777; - String serverContextPath = "/"; - String managementContextPath = null; - Integer managementPort = null; - ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort); + assertThat(actual).isNull(); + } - assertThat(actual.getHealthCheckUrl()).isEqualTo("http://host:7777/health"); - assertThat(actual.getSecureHealthCheckUrl()).isNullOrEmpty(); - assertThat(actual.getStatusPageUrl()).isEqualTo("http://host:7777/info"); - assertThat(actual.getManagementPort()).isEqualTo(7777); - } + @Test + public void serverPort() throws Exception { + int serverPort = 7777; + String serverContextPath = "/"; + String managementContextPath = null; + Integer managementPort = null; + ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, + managementContextPath, managementPort); - @Test - public void serverPortManagementPort() throws Exception { - int serverPort = 7777; - String serverContextPath = "/"; - String managementContextPath = null; - Integer managementPort = 8888; - ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort); + assertThat(actual.getHealthCheckUrl()).isEqualTo("http://host:7777/health"); + assertThat(actual.getSecureHealthCheckUrl()).isNullOrEmpty(); + assertThat(actual.getStatusPageUrl()).isEqualTo("http://host:7777/info"); + assertThat(actual.getManagementPort()).isEqualTo(7777); + } - assertThat(actual.getHealthCheckUrl()).isEqualTo("http://host:8888/health"); - assertThat(actual.getSecureHealthCheckUrl()).isNullOrEmpty(); - assertThat(actual.getStatusPageUrl()).isEqualTo("http://host:8888/info"); - assertThat(actual.getManagementPort()).isEqualTo(8888); - } + @Test + public void serverPortManagementPort() throws Exception { + int serverPort = 7777; + String serverContextPath = "/"; + String managementContextPath = null; + Integer managementPort = 8888; + ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, + managementContextPath, managementPort); - @Test - public void serverPortManagementPortServerContextPath() throws Exception { - int serverPort = 7777; - String serverContextPath = "/Server"; - String managementContextPath = null; - Integer managementPort = 8888; - ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort); + assertThat(actual.getHealthCheckUrl()).isEqualTo("http://host:8888/health"); + assertThat(actual.getSecureHealthCheckUrl()).isNullOrEmpty(); + assertThat(actual.getStatusPageUrl()).isEqualTo("http://host:8888/info"); + assertThat(actual.getManagementPort()).isEqualTo(8888); + } - assertThat(actual.getHealthCheckUrl()).isEqualTo("http://host:8888/health"); - assertThat(actual.getSecureHealthCheckUrl()).isNullOrEmpty(); - assertThat(actual.getStatusPageUrl()).isEqualTo("http://host:8888/info"); - assertThat(actual.getManagementPort()).isEqualTo(8888); - } + @Test + public void serverPortManagementPortServerContextPath() throws Exception { + int serverPort = 7777; + String serverContextPath = "/Server"; + String managementContextPath = null; + Integer managementPort = 8888; + ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, + managementContextPath, managementPort); - @Test - public void serverPortManagementPortServerContextPathManagementContextPath() throws Exception { - int serverPort = 7777; - String serverContextPath = "/Server"; - String managementContextPath = "/Management"; - Integer managementPort = 8888; - ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort); + assertThat(actual.getHealthCheckUrl()).isEqualTo("http://host:8888/health"); + assertThat(actual.getSecureHealthCheckUrl()).isNullOrEmpty(); + assertThat(actual.getStatusPageUrl()).isEqualTo("http://host:8888/info"); + assertThat(actual.getManagementPort()).isEqualTo(8888); + } - assertThat(actual.getHealthCheckUrl()).isEqualTo("http://host:8888/Management/health"); - assertThat(actual.getSecureHealthCheckUrl()).isNullOrEmpty(); - assertThat(actual.getStatusPageUrl()).isEqualTo("http://host:8888/Management/info"); - assertThat(actual.getManagementPort()).isEqualTo(8888); - } + @Test + public void serverPortManagementPortServerContextPathManagementContextPath() + throws Exception { + int serverPort = 7777; + String serverContextPath = "/Server"; + String managementContextPath = "/Management"; + Integer managementPort = 8888; + ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, + managementContextPath, managementPort); - @Test - public void serverPortServerContextPathManagementContextPath() throws Exception { - int serverPort = 7777; - String serverContextPath = "/Server"; - String managementContextPath = "/Management"; - Integer managementPort = null; - ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort); + assertThat(actual.getHealthCheckUrl()) + .isEqualTo("http://host:8888/Management/health"); + assertThat(actual.getSecureHealthCheckUrl()).isNullOrEmpty(); + assertThat(actual.getStatusPageUrl()) + .isEqualTo("http://host:8888/Management/info"); + assertThat(actual.getManagementPort()).isEqualTo(8888); + } - assertThat(actual.getHealthCheckUrl()).isEqualTo("http://host:7777/Server/Management/health"); - assertThat(actual.getSecureHealthCheckUrl()).isNullOrEmpty(); - assertThat(actual.getStatusPageUrl()).isEqualTo("http://host:7777/Server/Management/info"); - assertThat(actual.getManagementPort()).isEqualTo(7777); - } + @Test + public void serverPortServerContextPathManagementContextPath() throws Exception { + int serverPort = 7777; + String serverContextPath = "/Server"; + String managementContextPath = "/Management"; + Integer managementPort = null; + ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, + managementContextPath, managementPort); - @Test - public void serverPortManagementContextPath() throws Exception { - int serverPort = 7777; - String serverContextPath = "/"; - String managementContextPath = "/Management"; - Integer managementPort = null; - ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort); + assertThat(actual.getHealthCheckUrl()) + .isEqualTo("http://host:7777/Server/Management/health"); + assertThat(actual.getSecureHealthCheckUrl()).isNullOrEmpty(); + assertThat(actual.getStatusPageUrl()) + .isEqualTo("http://host:7777/Server/Management/info"); + assertThat(actual.getManagementPort()).isEqualTo(7777); + } - assertThat(actual.getHealthCheckUrl()).isEqualTo("http://host:7777/Management/health"); - assertThat(actual.getSecureHealthCheckUrl()).isNullOrEmpty(); - assertThat(actual.getStatusPageUrl()).isEqualTo("http://host:7777/Management/info"); - assertThat(actual.getManagementPort()).isEqualTo(7777); - } + @Test + public void serverPortManagementContextPath() throws Exception { + int serverPort = 7777; + String serverContextPath = "/"; + String managementContextPath = "/Management"; + Integer managementPort = null; + ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, + managementContextPath, managementPort); - @Test - public void serverPortServerContextPath() throws Exception { - int serverPort = 7777; - String serverContextPath = "/Server"; - String managementContextPath = null; - Integer managementPort = null; - ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort); + assertThat(actual.getHealthCheckUrl()) + .isEqualTo("http://host:7777/Management/health"); + assertThat(actual.getSecureHealthCheckUrl()).isNullOrEmpty(); + assertThat(actual.getStatusPageUrl()) + .isEqualTo("http://host:7777/Management/info"); + assertThat(actual.getManagementPort()).isEqualTo(7777); + } - assertThat(actual.getHealthCheckUrl()).isEqualTo("http://host:7777/Server/health"); - assertThat(actual.getSecureHealthCheckUrl()).isNullOrEmpty(); - assertThat(actual.getStatusPageUrl()).isEqualTo("http://host:7777/Server/info"); - assertThat(actual.getManagementPort()).isEqualTo(7777); - } + @Test + public void serverPortServerContextPath() throws Exception { + int serverPort = 7777; + String serverContextPath = "/Server"; + String managementContextPath = null; + Integer managementPort = null; + ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, + managementContextPath, managementPort); - @Test - public void serverPortManagementPortManagementContextPath() throws Exception { - int serverPort = 7777; - String serverContextPath = "/"; - String managementContextPath = "/Management"; - Integer managementPort = 8888; - ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort); + assertThat(actual.getHealthCheckUrl()) + .isEqualTo("http://host:7777/Server/health"); + assertThat(actual.getSecureHealthCheckUrl()).isNullOrEmpty(); + assertThat(actual.getStatusPageUrl()).isEqualTo("http://host:7777/Server/info"); + assertThat(actual.getManagementPort()).isEqualTo(7777); + } - assertThat(actual.getHealthCheckUrl()).isEqualTo("http://host:8888/Management/health"); - assertThat(actual.getSecureHealthCheckUrl()).isNullOrEmpty(); - assertThat(actual.getStatusPageUrl()).isEqualTo("http://host:8888/Management/info"); - assertThat(actual.getManagementPort()).isEqualTo(8888); + @Test + public void serverPortManagementPortManagementContextPath() throws Exception { + int serverPort = 7777; + String serverContextPath = "/"; + String managementContextPath = "/Management"; + Integer managementPort = 8888; + ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, + managementContextPath, managementPort); - } + assertThat(actual.getHealthCheckUrl()) + .isEqualTo("http://host:8888/Management/health"); + assertThat(actual.getSecureHealthCheckUrl()).isNullOrEmpty(); + assertThat(actual.getStatusPageUrl()) + .isEqualTo("http://host:8888/Management/info"); + assertThat(actual.getManagementPort()).isEqualTo(8888); - @Test - public void setSecureHealthCheckUrl() throws Exception { - int serverPort = 7777; - String serverContextPath = "/"; - String managementContextPath = "/Management"; - Integer managementPort = 8888; - doReturn(true).when(INSTANCE).isSecurePortEnabled(); - ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort); + } - assertThat(actual.getHealthCheckUrl()).isEqualTo("http://host:8888/Management/health"); - assertThat(actual.getSecureHealthCheckUrl()).isEqualTo("https://host:8888/Management/health"); - assertThat(actual.getStatusPageUrl()).isEqualTo("http://host:8888/Management/info"); - assertThat(actual.getManagementPort()).isEqualTo(8888); + @Test + public void setSecureHealthCheckUrl() throws Exception { + int serverPort = 7777; + String serverContextPath = "/"; + String managementContextPath = "/Management"; + Integer managementPort = 8888; + doReturn(true).when(INSTANCE).isSecurePortEnabled(); + ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, + managementContextPath, managementPort); - } + assertThat(actual.getHealthCheckUrl()) + .isEqualTo("http://host:8888/Management/health"); + assertThat(actual.getSecureHealthCheckUrl()) + .isEqualTo("https://host:8888/Management/health"); + assertThat(actual.getStatusPageUrl()) + .isEqualTo("http://host:8888/Management/info"); + assertThat(actual.getManagementPort()).isEqualTo(8888); + } - -} \ No newline at end of file +} diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/sample/ApplicationTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/sample/ApplicationTests.java index 3b72e97e5..0086d1b59 100644 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/sample/ApplicationTests.java +++ b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/sample/ApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,6 +18,7 @@ package org.springframework.cloud.netflix.eureka.sample; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.annotation.DirtiesContext; diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/sample/EurekaSampleApplication.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/sample/EurekaSampleApplication.java index 390e63011..a3710a00b 100644 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/sample/EurekaSampleApplication.java +++ b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/sample/EurekaSampleApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,9 @@ package org.springframework.cloud.netflix.eureka.sample; import java.io.Closeable; import java.io.IOException; +import com.netflix.appinfo.HealthCheckHandler; +import com.netflix.appinfo.InstanceInfo; + import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -36,9 +39,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import com.netflix.appinfo.HealthCheckHandler; -import com.netflix.appinfo.InstanceInfo; - import static org.springframework.web.bind.annotation.RequestMethod.POST; @Configuration @@ -76,7 +76,7 @@ public class EurekaSampleApplication implements ApplicationContextAware, Closeab @RequestMapping("/") public String home() { - return "Hello world "+ registration.getUri(); + return "Hello world " + registration.getUri(); } @Override @@ -97,8 +97,7 @@ public class EurekaSampleApplication implements ApplicationContextAware, Closeab config.setInstanceId("127.0.0.1:customapp:4444"); this.registration = EurekaRegistration.builder(config) - .with(this.clientConfig, this.context) - .build(); + .with(this.clientConfig, this.context).build(); this.serviceRegistry.register(this.registration); return config.getInstanceId(); @@ -114,4 +113,5 @@ public class EurekaSampleApplication implements ApplicationContextAware, Closeab public void close() throws IOException { deregister(); } + } diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/sample/RefreshEurekaSampleApplication.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/sample/RefreshEurekaSampleApplication.java index 6cbca2ee8..fa10f704b 100644 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/sample/RefreshEurekaSampleApplication.java +++ b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/sample/RefreshEurekaSampleApplication.java @@ -1,23 +1,23 @@ /* + * Copyright 2017-2019 the original author or authors. * - * * Copyright 2013-2016 the original author or authors. - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.netflix.eureka.sample; +import com.netflix.discovery.EurekaClient; + import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.cloud.netflix.eureka.CloudEurekaClient; import org.springframework.context.annotation.Bean; @@ -25,8 +25,6 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.bind.annotation.RestController; -import com.netflix.discovery.EurekaClient; - import static org.mockito.Mockito.mock; /** @@ -42,4 +40,5 @@ public class RefreshEurekaSampleApplication { public EurekaClient getClient() { return mock(CloudEurekaClient.class); } + } diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaServiceRegistryTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaServiceRegistryTests.java index a8afe30b1..f41a92be5 100644 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaServiceRegistryTests.java +++ b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaServiceRegistryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,14 +12,16 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.eureka.serviceregistry; import java.util.Map; +import com.netflix.appinfo.ApplicationInfoManager; +import com.netflix.appinfo.InstanceInfo; import org.junit.Test; + import org.springframework.cloud.commons.util.InetUtils; import org.springframework.cloud.commons.util.InetUtilsProperties; import org.springframework.cloud.netflix.eureka.CloudEurekaClient; @@ -27,9 +29,6 @@ import org.springframework.cloud.netflix.eureka.EurekaClientConfigBean; import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean; import org.springframework.context.ApplicationEventPublisher; -import com.netflix.appinfo.ApplicationInfoManager; -import com.netflix.appinfo.InstanceInfo; - import static com.netflix.appinfo.InstanceInfo.InstanceStatus.DOWN; import static com.netflix.appinfo.InstanceInfo.InstanceStatus.OUT_OF_SERVICE; import static com.netflix.appinfo.InstanceInfo.InstanceStatus.UNKNOWN; @@ -49,13 +48,15 @@ public class EurekaServiceRegistryTests { EurekaServiceRegistry registry = new EurekaServiceRegistry(); CloudEurekaClient eurekaClient = mock(CloudEurekaClient.class); - ApplicationInfoManager applicationInfoManager = mock(ApplicationInfoManager.class); + ApplicationInfoManager applicationInfoManager = mock( + ApplicationInfoManager.class); when(applicationInfoManager.getInfo()).thenReturn(mock(InstanceInfo.class)); - EurekaRegistration registration = EurekaRegistration.builder(new EurekaInstanceConfigBean(new InetUtils(new InetUtilsProperties()))) - .with(eurekaClient) - .with(applicationInfoManager) + EurekaRegistration registration = EurekaRegistration + .builder(new EurekaInstanceConfigBean( + new InetUtils(new InetUtilsProperties()))) + .with(eurekaClient).with(applicationInfoManager) .with(new EurekaClientConfigBean(), mock(ApplicationEventPublisher.class)) .build(); @@ -68,33 +69,28 @@ public class EurekaServiceRegistryTests { public void eurekaClientGetStatus() { EurekaServiceRegistry registry = new EurekaServiceRegistry(); - EurekaInstanceConfigBean config = new EurekaInstanceConfigBean(new InetUtils(new InetUtilsProperties())); + EurekaInstanceConfigBean config = new EurekaInstanceConfigBean( + new InetUtils(new InetUtilsProperties())); config.setAppname("myapp"); config.setInstanceId("1234"); - InstanceInfo local = InstanceInfo.Builder.newBuilder() - .setAppName("myapp") - .setInstanceId("1234") - .setStatus(DOWN) - .build(); + InstanceInfo local = InstanceInfo.Builder.newBuilder().setAppName("myapp") + .setInstanceId("1234").setStatus(DOWN).build(); - InstanceInfo remote = InstanceInfo.Builder.newBuilder() - .setAppName("myapp") - .setInstanceId("1234") - .setStatus(DOWN) - .setOverriddenStatus(OUT_OF_SERVICE) + InstanceInfo remote = InstanceInfo.Builder.newBuilder().setAppName("myapp") + .setInstanceId("1234").setStatus(DOWN).setOverriddenStatus(OUT_OF_SERVICE) .build(); CloudEurekaClient eurekaClient = mock(CloudEurekaClient.class); when(eurekaClient.getInstanceInfo(local.getAppName(), local.getId())) .thenReturn(remote); - ApplicationInfoManager applicationInfoManager = mock(ApplicationInfoManager.class); + ApplicationInfoManager applicationInfoManager = mock( + ApplicationInfoManager.class); when(applicationInfoManager.getInfo()).thenReturn(local); EurekaRegistration registration = EurekaRegistration.builder(config) - .with(eurekaClient) - .with(applicationInfoManager) + .with(eurekaClient).with(applicationInfoManager) .with(new EurekaClientConfigBean(), mock(ApplicationEventPublisher.class)) .build(); @@ -106,31 +102,29 @@ public class EurekaServiceRegistryTests { Map map = (Map) status; - assertThat(map).hasSize(2) - .containsEntry("status", DOWN.toString()) + assertThat(map).hasSize(2).containsEntry("status", DOWN.toString()) .containsEntry("overriddenStatus", OUT_OF_SERVICE.toString()); } - @Test public void eurekaClientGetStatusNoInstance() { EurekaServiceRegistry registry = new EurekaServiceRegistry(); - EurekaInstanceConfigBean config = new EurekaInstanceConfigBean(new InetUtils(new InetUtilsProperties())); + EurekaInstanceConfigBean config = new EurekaInstanceConfigBean( + new InetUtils(new InetUtilsProperties())); config.setAppname("myapp"); config.setInstanceId("1234"); CloudEurekaClient eurekaClient = mock(CloudEurekaClient.class); - when(eurekaClient.getInstanceInfo("myapp", "1234")) - .thenReturn(null); + when(eurekaClient.getInstanceInfo("myapp", "1234")).thenReturn(null); - ApplicationInfoManager applicationInfoManager = mock(ApplicationInfoManager.class); + ApplicationInfoManager applicationInfoManager = mock( + ApplicationInfoManager.class); when(applicationInfoManager.getInfo()).thenReturn(mock(InstanceInfo.class)); EurekaRegistration registration = EurekaRegistration.builder(config) - .with(eurekaClient) - .with(applicationInfoManager) + .with(eurekaClient).with(applicationInfoManager) .with(new EurekaClientConfigBean(), mock(ApplicationEventPublisher.class)) .build(); @@ -142,7 +136,7 @@ public class EurekaServiceRegistryTests { Map map = (Map) status; - assertThat(map).hasSize(1) - .containsEntry("status", UNKNOWN.toString()); + assertThat(map).hasSize(1).containsEntry("status", UNKNOWN.toString()); } + } diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/DomainExtractingServerListTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/DomainExtractingServerListTests.java index 79a0b5d57..28c2a953f 100644 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/DomainExtractingServerListTests.java +++ b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/DomainExtractingServerListTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,18 +22,15 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.junit.Test; - import com.netflix.appinfo.InstanceInfo; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.loadbalancer.Server; import com.netflix.loadbalancer.ServerList; import com.netflix.niws.loadbalancer.DiscoveryEnabledServer; +import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -52,18 +49,19 @@ public class DomainExtractingServerListTests { static final String INSTANCE_ID = "myInstanceId"; - private Map metadata = Collections. singletonMap( - "instanceId", INSTANCE_ID); + private Map metadata = Collections + .singletonMap("instanceId", INSTANCE_ID); @Test public void testDomainExtractingServer() { DomainExtractingServerList serverList = getDomainExtractingServerList( new DefaultClientConfigImpl(), true); List servers = serverList.getInitialListOfServers(); - assertNotNull("servers was null", servers); - assertEquals("servers was not size 1", 1, servers.size()); + assertThat(servers).as("servers was null").isNotNull(); + assertThat(servers.size()).as("servers was not size 1").isEqualTo(1); DomainExtractingServer des = assertDomainExtractingServer(servers, ZONE); - assertEquals("hostPort was wrong", HOST_NAME + ":" + PORT, des.getHostPort()); + assertThat(des.getHostPort()).as("hostPort was wrong") + .isEqualTo(HOST_NAME + ":" + PORT); } @Test @@ -74,10 +72,10 @@ public class DomainExtractingServerListTests { DomainExtractingServerList serverList = getDomainExtractingServerList( new DefaultClientConfigImpl(), false); List servers = serverList.getInitialListOfServers(); - assertNotNull("servers was null", servers); - assertEquals("servers was not size 1", 1, servers.size()); + assertThat(servers).as("servers was null").isNotNull(); + assertThat(servers.size()).as("servers was not size 1").isEqualTo(1); DomainExtractingServer des = assertDomainExtractingServer(servers, "us-west-1"); - assertEquals("Zone was wrong", "us-west-1", des.getZone()); + assertThat(des.getZone()).as("Zone was wrong").isEqualTo("us-west-1"); } @Test @@ -85,20 +83,22 @@ public class DomainExtractingServerListTests { DomainExtractingServerList serverList = getDomainExtractingServerList( new DefaultClientConfigImpl(), false); List servers = serverList.getInitialListOfServers(); - assertNotNull("servers was null", servers); - assertEquals("servers was not size 1", 1, servers.size()); + assertThat(servers).as("servers was null").isNotNull(); + assertThat(servers.size()).as("servers was not size 1").isEqualTo(1); DomainExtractingServer des = assertDomainExtractingServer(servers, null); - assertEquals("hostPort was wrong", HOST_NAME + ":" + PORT, des.getHostPort()); + assertThat(des.getHostPort()).as("hostPort was wrong") + .isEqualTo(HOST_NAME + ":" + PORT); } protected DomainExtractingServer assertDomainExtractingServer( List servers, String zone) { Server actualServer = servers.get(0); - assertTrue("server was not a DomainExtractingServer", - actualServer instanceof DomainExtractingServer); + assertThat(actualServer instanceof DomainExtractingServer) + .as("server was not a DomainExtractingServer").isTrue(); DomainExtractingServer des = DomainExtractingServer.class.cast(actualServer); - assertEquals("zone was wrong", zone, des.getZone()); - assertEquals("instanceId was wrong", HOST_NAME + ":" + INSTANCE_ID, des.getId()); + assertThat(des.getZone()).as("zone was wrong").isEqualTo(zone); + assertThat(des.getId()).as("instanceId was wrong") + .isEqualTo(HOST_NAME + ":" + INSTANCE_ID); return des; } @@ -109,10 +109,11 @@ public class DomainExtractingServerListTests { DomainExtractingServerList serverList = getDomainExtractingServerList(config, true); List servers = serverList.getInitialListOfServers(); - assertNotNull("servers was null", servers); - assertEquals("servers was not size 1", 1, servers.size()); + assertThat(servers).as("servers was null").isNotNull(); + assertThat(servers.size()).as("servers was not size 1").isEqualTo(1); DomainExtractingServer des = assertDomainExtractingServer(servers, ZONE); - assertEquals("hostPort was wrong", IP_ADDR + ":" + PORT, des.getHostPort()); + assertThat(des.getHostPort()).as("hostPort was wrong") + .isEqualTo(IP_ADDR + ":" + PORT); } protected DomainExtractingServerList getDomainExtractingServerList( @@ -127,8 +128,8 @@ public class DomainExtractingServerListTests { given(instanceInfo.getHostName()).willReturn(HOST_NAME); given(instanceInfo.getIPAddr()).willReturn(IP_ADDR); given(instanceInfo.getPort()).willReturn(PORT); - given(originalServerList.getInitialListOfServers()).willReturn( - Arrays.asList(server)); + given(originalServerList.getInitialListOfServers()) + .willReturn(Arrays.asList(server)); return new DomainExtractingServerList(originalServerList, config, approximateZoneFromHostname); } diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaDisabledRibbonClientIntegrationTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaDisabledRibbonClientIntegrationTests.java index 2ced93eaa..086ad9ce3 100644 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaDisabledRibbonClientIntegrationTests.java +++ b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaDisabledRibbonClientIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,6 +22,7 @@ import com.netflix.loadbalancer.ZoneAwareLoadBalancer; import com.netflix.niws.loadbalancer.NIWSDiscoveryPing; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -42,8 +43,8 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.assertj.core.api.Assertions.assertThat; /** - * Ribbon Eureka client should be disabled if Eureka client is not enabled - * + * Ribbon Eureka client should be disabled if Eureka client is not enabled. + * * @author Biju Kunjummen */ @RunWith(SpringJUnit4ClassRunner.class) diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaRibbonClientConfigurationTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaRibbonClientConfigurationTests.java index 0aee77093..86fb1ab6d 100644 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaRibbonClientConfigurationTests.java +++ b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaRibbonClientConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,26 +16,24 @@ package org.springframework.cloud.netflix.ribbon.eureka; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.springframework.cloud.commons.util.InetUtils; -import org.springframework.cloud.commons.util.InetUtilsProperties; -import org.springframework.cloud.netflix.eureka.EurekaClientConfigBean; -import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean; -import org.springframework.cloud.netflix.ribbon.SpringClientFactory; - import com.netflix.config.ConfigurationManager; import com.netflix.config.DeploymentContext.ContextKey; import com.netflix.config.DynamicStringProperty; import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.loadbalancer.ZoneAwareLoadBalancer; import com.netflix.niws.loadbalancer.DiscoveryEnabledServer; +import org.junit.After; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import org.springframework.cloud.commons.util.InetUtils; +import org.springframework.cloud.commons.util.InetUtilsProperties; +import org.springframework.cloud.netflix.eureka.EurekaClientConfigBean; +import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean; +import org.springframework.cloud.netflix.ribbon.SpringClientFactory; + +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.cloud.netflix.ribbon.RibbonUtils.VALUE_NOT_SET; import static org.springframework.cloud.netflix.ribbon.RibbonUtils.getProperty; import static org.springframework.cloud.netflix.ribbon.RibbonUtils.getRibbonKey; @@ -64,12 +62,13 @@ public class EurekaRibbonClientConfigurationTests { client, "service", configBean, false); clientPreprocessor.preprocess(); ILoadBalancer balancer = clientFactory.getLoadBalancer("service"); - assertNotNull(balancer); + assertThat(balancer).isNotNull(); @SuppressWarnings("unchecked") ZoneAwareLoadBalancer aware = (ZoneAwareLoadBalancer) balancer; - assertTrue(aware.getServerListImpl() instanceof DomainExtractingServerList); - assertEquals("foo", - ConfigurationManager.getDeploymentContext().getValue(ContextKey.zone)); + assertThat(aware.getServerListImpl() instanceof DomainExtractingServerList) + .isTrue(); + assertThat(ConfigurationManager.getDeploymentContext().getValue(ContextKey.zone)) + .isEqualTo("foo"); } private EurekaInstanceConfigBean getEurekaInstanceConfigBean() { @@ -86,12 +85,12 @@ public class EurekaRibbonClientConfigurationTests { String suffix = "mySuffix"; String value = "myValue"; DynamicStringProperty property = getProperty(getRibbonKey(serviceId, suffix)); - assertEquals("property doesn't have default value", VALUE_NOT_SET, - property.get()); + assertThat(property.get()).as("property doesn't have default value") + .isEqualTo(VALUE_NOT_SET); setRibbonProperty(serviceId, suffix, value); - assertEquals("property has wrong value", value, property.get()); + assertThat(property.get()).as("property has wrong value").isEqualTo(value); setRibbonProperty(serviceId, suffix, value); - assertEquals("property has wrong value", value, property.get()); + assertThat(property.get()).as("property has wrong value").isEqualTo(value); } @Test @@ -102,8 +101,8 @@ public class EurekaRibbonClientConfigurationTests { EurekaRibbonClientConfiguration preprocessor = new EurekaRibbonClientConfiguration( client, "myService", configBean, false); preprocessor.preprocess(); - assertEquals("myZone", - ConfigurationManager.getDeploymentContext().getValue(ContextKey.zone)); + assertThat(ConfigurationManager.getDeploymentContext().getValue(ContextKey.zone)) + .isEqualTo("myZone"); } @Test @@ -113,8 +112,8 @@ public class EurekaRibbonClientConfigurationTests { EurekaRibbonClientConfiguration preprocessor = new EurekaRibbonClientConfiguration( client, "myService", configBean, false); preprocessor.preprocess(); - assertEquals("defaultZone", - ConfigurationManager.getDeploymentContext().getValue(ContextKey.zone)); + assertThat(ConfigurationManager.getDeploymentContext().getValue(ContextKey.zone)) + .isEqualTo("defaultZone"); } @Test @@ -125,8 +124,8 @@ public class EurekaRibbonClientConfigurationTests { EurekaRibbonClientConfiguration preprocessor = new EurekaRibbonClientConfiguration( client, "myService", configBean, true); preprocessor.preprocess(); - assertEquals("is.a.test.com", - ConfigurationManager.getDeploymentContext().getValue(ContextKey.zone)); + assertThat(ConfigurationManager.getDeploymentContext().getValue(ContextKey.zone)) + .isEqualTo("is.a.test.com"); } } diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaRibbonClientPreprocessorIntegrationTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaRibbonClientPreprocessorIntegrationTests.java index 3b02fe8ab..410f6e919 100644 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaRibbonClientPreprocessorIntegrationTests.java +++ b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaRibbonClientPreprocessorIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,13 @@ package org.springframework.cloud.netflix.ribbon.eureka; +import com.netflix.loadbalancer.Server; +import com.netflix.loadbalancer.ZoneAvoidanceRule; +import com.netflix.loadbalancer.ZoneAwareLoadBalancer; +import com.netflix.niws.loadbalancer.NIWSDiscoveryPing; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -35,11 +40,6 @@ import org.springframework.context.annotation.Import; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ZoneAvoidanceRule; -import com.netflix.loadbalancer.ZoneAwareLoadBalancer; -import com.netflix.niws.loadbalancer.NIWSDiscoveryPing; - /** * @author Dave Syer */ @@ -68,13 +68,13 @@ public class EurekaRibbonClientPreprocessorIntegrationTests { @Test public void serverIntrospectorDefaultsToEureka() throws Exception { - EurekaServerIntrospector.class.cast(this.factory.getInstance("foo", ServerIntrospector.class)); + EurekaServerIntrospector.class + .cast(this.factory.getInstance("foo", ServerIntrospector.class)); } @SuppressWarnings("unchecked") private ZoneAwareLoadBalancer getLoadBalancer() { - return (ZoneAwareLoadBalancer) this.factory - .getLoadBalancer("foo"); + return (ZoneAwareLoadBalancer) this.factory.getLoadBalancer("foo"); } @Configuration diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaRibbonClientPropertyOverrideIntegrationTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaRibbonClientPropertyOverrideIntegrationTests.java index faffa8451..2bddba930 100644 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaRibbonClientPropertyOverrideIntegrationTests.java +++ b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/EurekaRibbonClientPropertyOverrideIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,15 @@ package org.springframework.cloud.netflix.ribbon.eureka; +import com.netflix.discovery.EurekaClient; +import com.netflix.loadbalancer.ConfigurationBasedServerList; +import com.netflix.loadbalancer.DummyPing; +import com.netflix.loadbalancer.Server; +import com.netflix.loadbalancer.ZoneAwareLoadBalancer; +import com.netflix.niws.loadbalancer.NIWSDiscoveryPing; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; @@ -32,13 +39,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; -import com.netflix.discovery.EurekaClient; -import com.netflix.loadbalancer.ConfigurationBasedServerList; -import com.netflix.loadbalancer.DummyPing; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ZoneAwareLoadBalancer; -import com.netflix.niws.loadbalancer.NIWSDiscoveryPing; - import static org.mockito.Mockito.mock; /** @@ -72,13 +72,16 @@ public class EurekaRibbonClientPropertyOverrideIntegrationTests { @Configuration @RibbonClients - @ImportAutoConfiguration({ UtilAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, - ArchaiusAutoConfiguration.class, RibbonAutoConfiguration.class, - RibbonEurekaAutoConfiguration.class }) + @ImportAutoConfiguration({ UtilAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, ArchaiusAutoConfiguration.class, + RibbonAutoConfiguration.class, RibbonEurekaAutoConfiguration.class }) protected static class TestConfiguration { + @Bean public EurekaClient eurekaClient() { return mock(EurekaClient.class); } + } + } diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/RibbonClientPreprocessorIntegrationTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/RibbonClientPreprocessorIntegrationTests.java index cfc55a1d1..6cca562cd 100644 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/RibbonClientPreprocessorIntegrationTests.java +++ b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/RibbonClientPreprocessorIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,9 +16,14 @@ package org.springframework.cloud.netflix.ribbon.eureka; +import com.netflix.discovery.EurekaClient; +import com.netflix.loadbalancer.Server; +import com.netflix.loadbalancer.ZoneAvoidanceRule; +import com.netflix.loadbalancer.ZoneAwareLoadBalancer; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; @@ -37,12 +42,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.netflix.discovery.EurekaClient; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ZoneAvoidanceRule; -import com.netflix.loadbalancer.ZoneAwareLoadBalancer; - -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -76,9 +76,8 @@ public class RibbonClientPreprocessorIntegrationTests { @SuppressWarnings("unchecked") ZoneAwareLoadBalancer loadBalancer = (ZoneAwareLoadBalancer) this.factory .getLoadBalancer("foo"); - assertEquals("myTestZone", - ZonePreferenceServerListFilter.class.cast(loadBalancer.getFilter()) - .getZone()); + assertThat(ZonePreferenceServerListFilter.class.cast(loadBalancer.getFilter()) + .getZone()).isEqualTo("myTestZone"); } @Configuration @@ -86,6 +85,7 @@ public class RibbonClientPreprocessorIntegrationTests { @ImportAutoConfiguration({ PropertyPlaceholderAutoConfiguration.class, ArchaiusAutoConfiguration.class, RibbonAutoConfiguration.class }) protected static class PlainConfiguration { + } @Configuration @@ -94,14 +94,17 @@ public class RibbonClientPreprocessorIntegrationTests { ArchaiusAutoConfiguration.class, RibbonAutoConfiguration.class, RibbonEurekaAutoConfiguration.class }) protected static class TestConfiguration { + @Bean EurekaClient eurekaClient() { return Mockito.mock(EurekaClient.class); } + } @Configuration protected static class FooConfiguration { + @Bean public ZonePreferenceServerListFilter serverListFilter() { ZonePreferenceServerListFilter filter = new ZonePreferenceServerListFilter(); @@ -111,10 +114,11 @@ public class RibbonClientPreprocessorIntegrationTests { @Bean public EurekaInstanceConfigBean getEurekaInstanceConfigBean() { - EurekaInstanceConfigBean bean = new EurekaInstanceConfigBean(new InetUtils( - new InetUtilsProperties())); + EurekaInstanceConfigBean bean = new EurekaInstanceConfigBean( + new InetUtils(new InetUtilsProperties())); return bean; } + } } diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/RibbonEurekaAutoConfigurationTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/RibbonEurekaAutoConfigurationTests.java index d84bdf040..6128646ef 100644 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/RibbonEurekaAutoConfigurationTests.java +++ b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/RibbonEurekaAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2016-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.ribbon.eureka; @@ -21,6 +20,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringBootConfiguration; @@ -39,9 +39,9 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Spencer Gibb */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = RibbonEurekaAutoConfigurationTests.EurekaClientDisabledApp.class, - properties = { "eureka.client.enabled=false", "spring.application.name=eurekadisabledtest" }, - webEnvironment = RANDOM_PORT) +@SpringBootTest(classes = RibbonEurekaAutoConfigurationTests.EurekaClientDisabledApp.class, properties = { + "eureka.client.enabled=false", + "spring.application.name=eurekadisabledtest" }, webEnvironment = RANDOM_PORT) @DirtiesContext public class RibbonEurekaAutoConfigurationTests { @@ -58,12 +58,14 @@ public class RibbonEurekaAutoConfigurationTests { public static class EurekaClientDisabledApp { @Bean - public TestLoadbalancerClient testLoadbalanceClient(LoadBalancerClient loadBalancerClient) { + public TestLoadbalancerClient testLoadbalanceClient( + LoadBalancerClient loadBalancerClient) { return new TestLoadbalancerClient(loadBalancerClient); } @Bean - public CommandLineRunner commandLineRunner(final TestLoadbalancerClient testLoadbalancerClient) { + public CommandLineRunner commandLineRunner( + final TestLoadbalancerClient testLoadbalancerClient) { return new CommandLineRunner() { @Override public void run(String... args) throws Exception { @@ -71,6 +73,7 @@ public class RibbonEurekaAutoConfigurationTests { } }; } + } private static class TestLoadbalancerClient { @@ -78,22 +81,27 @@ public class RibbonEurekaAutoConfigurationTests { Log log = LogFactory.getLog(this.getClass()); private LoadBalancerClient loadBalancerClient; + private boolean instanceFound = false; - public TestLoadbalancerClient(LoadBalancerClient loadBalancerClient) { + TestLoadbalancerClient(LoadBalancerClient loadBalancerClient) { this.loadBalancerClient = loadBalancerClient; } public void doStuff() { - ServiceInstance serviceInstance = loadBalancerClient.choose("http://host/doStuff"); + ServiceInstance serviceInstance = loadBalancerClient + .choose("http://host/doStuff"); if (serviceInstance != null) { - log.info("There is a service instance, because Eureka discovery is enabled and the service is registered"); + log.info( + "There is a service instance, because Eureka discovery is enabled and the service is registered"); instanceFound = true; } else { - log.warn("No instance found, because Eureka is disabled or there is no service matching."); + log.warn( + "No instance found, because Eureka is disabled or there is no service matching."); } } + } } diff --git a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/ZoneUtilsTests.java b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/ZoneUtilsTests.java index c5fb44a10..0a3ec3b1e 100644 --- a/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/ZoneUtilsTests.java +++ b/spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/ribbon/eureka/ZoneUtilsTests.java @@ -1,4 +1,5 @@ -/* Copyright 2013-2015 the original author or authors. +/* + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,14 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.cloud.netflix.ribbon.eureka; -import static org.junit.Assert.assertTrue; +package org.springframework.cloud.netflix.ribbon.eureka; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; + /** - * * @author Ryan Baxter * */ @@ -27,9 +28,11 @@ public class ZoneUtilsTests { @Test public void extractApproximateZoneTest() { - assertTrue("foo".equals(ZoneUtils.extractApproximateZone("foo"))); - assertTrue("bar".equals(ZoneUtils.extractApproximateZone("foo.bar"))); - assertTrue("world.foo.bar".equals(ZoneUtils - .extractApproximateZone("hello.world.foo.bar"))); + assertThat("foo".equals(ZoneUtils.extractApproximateZone("foo"))).isTrue(); + assertThat("bar".equals(ZoneUtils.extractApproximateZone("foo.bar"))).isTrue(); + assertThat("world.foo.bar" + .equals(ZoneUtils.extractApproximateZone("hello.world.foo.bar"))) + .isTrue(); } + } diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/CloudJacksonJson.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/CloudJacksonJson.java index 1c2f99e6c..a89e7ee6c 100644 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/CloudJacksonJson.java +++ b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/CloudJacksonJson.java @@ -1,3 +1,19 @@ +/* + * Copyright 2013-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.springframework.cloud.netflix.eureka.server; import java.io.IOException; @@ -7,9 +23,6 @@ import java.lang.reflect.Field; import java.util.HashMap; import java.util.function.Supplier; -import org.springframework.util.ReflectionUtils; -import org.springframework.util.StringUtils; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; @@ -30,6 +43,9 @@ import com.netflix.discovery.converters.wrappers.CodecWrappers.LegacyJacksonJson import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; +import org.springframework.util.ReflectionUtils; +import org.springframework.util.StringUtils; + import static com.netflix.discovery.converters.wrappers.CodecWrappers.getCodecName; /** @@ -68,11 +84,27 @@ public class CloudJacksonJson extends LegacyJacksonJson { return this.codec.readValue(type, inputStream); } + static InstanceInfo updateIfNeeded(final InstanceInfo info) { + if (info.getInstanceId() == null && info.getMetadata() != null) { + String instanceId = info.getMetadata().get("instanceId"); + if (StringUtils.hasText(instanceId)) { + // backwards compatibility for Angel + if (StringUtils.hasText(info.getHostName()) + && !instanceId.startsWith(info.getHostName())) { + instanceId = info.getHostName() + ":" + instanceId; + } + return new InstanceInfo.Builder(info).setInstanceId(instanceId).build(); + } + } + return info; + } + static class CloudJacksonCodec extends EurekaJacksonCodec { + private static final Version VERSION = new Version(1, 1, 0, null, null, null); @SuppressWarnings("deprecation") - public CloudJacksonCodec() { + CloudJacksonCodec() { super(); ObjectMapper mapper = new ObjectMapper(); @@ -87,7 +119,7 @@ public class CloudJacksonJson extends LegacyJacksonJson { // TODO: Watch if this causes problems // module.addDeserializer(DataCenterInfo.class, - // new DataCenterInfoDeserializer()); + // new DataCenterInfoDeserializer()); module.addDeserializer(LeaseInfo.class, new LeaseInfoDeserializer()); module.addDeserializer(InstanceInfo.class, new CloudInstanceInfoDeserializer(mapper)); @@ -99,12 +131,12 @@ public class CloudJacksonJson extends LegacyJacksonJson { mapper.registerModule(module); HashMap, Supplier> readers = new HashMap<>(); - readers.put(InstanceInfo.class, ()-> mapper.reader().withType(InstanceInfo.class) - .withRootName("instance")); - readers.put(Application.class, ()-> mapper.reader().withType(Application.class) - .withRootName("application")); - readers.put(Applications.class, ()-> mapper.reader().withType(Applications.class) - .withRootName("applications")); + readers.put(InstanceInfo.class, () -> mapper.reader() + .withType(InstanceInfo.class).withRootName("instance")); + readers.put(Application.class, () -> mapper.reader() + .withType(Application.class).withRootName("application")); + readers.put(Applications.class, () -> mapper.reader() + .withType(Applications.class).withRootName("applications")); setField("objectReaderByClass", readers); HashMap, ObjectWriter> writers = new HashMap<>(); @@ -124,9 +156,11 @@ public class CloudJacksonJson extends LegacyJacksonJson { ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, this, value); } + } static class CloudInstanceInfoSerializer extends InstanceInfoSerializer { + @Override public void serialize(final InstanceInfo info, JsonGenerator jgen, SerializerProvider provider) throws IOException { @@ -134,20 +168,7 @@ public class CloudJacksonJson extends LegacyJacksonJson { InstanceInfo updated = updateIfNeeded(info); super.serialize(updated, jgen, provider); } - } - static InstanceInfo updateIfNeeded(final InstanceInfo info) { - if (info.getInstanceId() == null && info.getMetadata() != null) { - String instanceId = info.getMetadata().get("instanceId"); - if (StringUtils.hasText(instanceId)) { - // backwards compatibility for Angel - if (StringUtils.hasText(info.getHostName()) && !instanceId.startsWith(info.getHostName())) { - instanceId = info.getHostName()+":"+instanceId; - } - return new InstanceInfo.Builder(info).setInstanceId(instanceId).build(); - } - } - return info; } static class CloudInstanceInfoDeserializer extends InstanceInfoDeserializer { @@ -157,10 +178,13 @@ public class CloudJacksonJson extends LegacyJacksonJson { } @Override - public InstanceInfo deserialize(JsonParser jp, DeserializationContext context) throws IOException { + public InstanceInfo deserialize(JsonParser jp, DeserializationContext context) + throws IOException { InstanceInfo info = super.deserialize(jp, context); InstanceInfo updated = updateIfNeeded(info); return updated; } + } + } diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EnableEurekaServer.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EnableEurekaServer.java index e1cb02384..6d026238d 100644 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EnableEurekaServer.java +++ b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EnableEurekaServer.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,8 @@ import java.lang.annotation.Target; import org.springframework.context.annotation.Import; /** - * Annotation to activate Eureka Server related configuration {@link EurekaServerAutoConfiguration} + * Annotation to activate Eureka Server related configuration. + * {@link EurekaServerAutoConfiguration} * * @author Dave Syer * @author Biju Kunjummen diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaController.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaController.java index 3c0689984..db06f8eaf 100644 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaController.java +++ b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaController.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,15 +27,6 @@ import java.util.Map; import javax.servlet.http.HttpServletRequest; -import com.netflix.eureka.EurekaServerContext; -import com.netflix.eureka.EurekaServerContextHolder; -import com.netflix.eureka.registry.PeerAwareInstanceRegistry; -import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - import com.netflix.appinfo.AmazonInfo; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.DataCenterInfo; @@ -43,10 +34,19 @@ import com.netflix.appinfo.InstanceInfo; import com.netflix.config.ConfigurationManager; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Pair; +import com.netflix.eureka.EurekaServerContext; +import com.netflix.eureka.EurekaServerContextHolder; import com.netflix.eureka.cluster.PeerEurekaNode; +import com.netflix.eureka.registry.PeerAwareInstanceRegistry; +import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl; import com.netflix.eureka.resources.StatusResource; import com.netflix.eureka.util.StatusInfo; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + /** * @author Spencer Gibb * @author Gang Li @@ -57,6 +57,7 @@ public class EurekaController { @Value("${eureka.dashboard.path:/}") private String dashboardPath = ""; + private ApplicationInfoManager applicationInfoManager; public EurekaController(ApplicationInfoManager applicationInfoManager) { @@ -109,8 +110,8 @@ public class EurekaController { protected void populateBase(HttpServletRequest request, Map model) { model.put("time", new Date()); model.put("basePath", "/"); - model.put("dashboardPath", this.dashboardPath.equals("/") ? "" - : this.dashboardPath); + model.put("dashboardPath", + this.dashboardPath.equals("/") ? "" : this.dashboardPath); populateHeader(model); populateNavbar(request, model); } @@ -118,10 +119,10 @@ public class EurekaController { private void populateHeader(Map model) { model.put("currentTime", StatusResource.getCurrentTimeAsString()); model.put("upTime", StatusInfo.getUpTime()); - model.put("environment", ConfigurationManager.getDeploymentContext() - .getDeploymentEnvironment()); - model.put("datacenter", ConfigurationManager.getDeploymentContext() - .getDeploymentDatacenter()); + model.put("environment", + ConfigurationManager.getDeploymentContext().getDeploymentEnvironment()); + model.put("datacenter", + ConfigurationManager.getDeploymentContext().getDeploymentDatacenter()); PeerAwareInstanceRegistry registry = getRegistry(); model.put("registry", registry); model.put("isBelowRenewThresold", registry.isBelowRenewThresold() == 1); @@ -146,7 +147,8 @@ public class EurekaController { private void populateNavbar(HttpServletRequest request, Map model) { Map replicas = new LinkedHashMap<>(); - List list = getServerContext().getPeerEurekaNodes().getPeerNodesView(); + List list = getServerContext().getPeerEurekaNodes() + .getPeerNodesView(); for (PeerEurekaNode node : list) { try { URI uri = new URI(node.getServiceUrl()); @@ -274,28 +276,34 @@ public class EurekaController { protected void filterReplicas(Map model, StatusInfo statusInfo) { Map applicationStats = statusInfo.getApplicationStats(); - if(applicationStats.get("registered-replicas").contains("@")){ - applicationStats.put("registered-replicas", scrubBasicAuth(applicationStats.get("registered-replicas"))); + if (applicationStats.get("registered-replicas").contains("@")) { + applicationStats.put("registered-replicas", + scrubBasicAuth(applicationStats.get("registered-replicas"))); } - if(applicationStats.get("unavailable-replicas").contains("@")){ - applicationStats.put("unavailable-replicas",scrubBasicAuth(applicationStats.get("unavailable-replicas"))); + if (applicationStats.get("unavailable-replicas").contains("@")) { + applicationStats.put("unavailable-replicas", + scrubBasicAuth(applicationStats.get("unavailable-replicas"))); } - if(applicationStats.get("available-replicas").contains("@")){ - applicationStats.put("available-replicas",scrubBasicAuth(applicationStats.get("available-replicas"))); + if (applicationStats.get("available-replicas").contains("@")) { + applicationStats.put("available-replicas", + scrubBasicAuth(applicationStats.get("available-replicas"))); } model.put("applicationStats", applicationStats); } - private String scrubBasicAuth(String urlList){ - String[] urls=urlList.split(","); + private String scrubBasicAuth(String urlList) { + String[] urls = urlList.split(","); StringBuilder filteredUrls = new StringBuilder(); - for(String u : urls){ - if(u.contains("@")){ - filteredUrls.append(u.substring(0,u.indexOf("//")+2)).append(u.substring(u.indexOf("@")+1,u.length())).append(","); - }else{ + for (String u : urls) { + if (u.contains("@")) { + filteredUrls.append(u.substring(0, u.indexOf("//") + 2)) + .append(u.substring(u.indexOf("@") + 1, u.length())).append(","); + } + else { filteredUrls.append(u).append(","); } } - return filteredUrls.substring(0,filteredUrls.length()-1); + return filteredUrls.substring(0, filteredUrls.length() - 1); } + } diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaDashboardProperties.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaDashboardProperties.java index a6f0b8d69..a40c20c2b 100644 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaDashboardProperties.java +++ b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaDashboardProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,10 +16,10 @@ package org.springframework.cloud.netflix.eureka.server; -import org.springframework.boot.context.properties.ConfigurationProperties; - import java.util.Objects; +import org.springframework.boot.context.properties.ConfigurationProperties; + /** * Configuration properties for the Eureka dashboard (UI). * @@ -56,11 +56,14 @@ public class EurekaDashboardProperties { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } EurekaDashboardProperties that = (EurekaDashboardProperties) o; - return enabled == that.enabled && - Objects.equals(path, that.path); + return enabled == that.enabled && Objects.equals(path, that.path); } @Override @@ -76,4 +79,5 @@ public class EurekaDashboardProperties { sb.append('}'); return sb.toString(); } + } diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerAutoConfiguration.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerAutoConfiguration.java index 490aa581a..2ef828a70 100644 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerAutoConfiguration.java +++ b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,8 +24,25 @@ import java.util.Set; import javax.servlet.Filter; import javax.ws.rs.Path; +import javax.ws.rs.core.Application; import javax.ws.rs.ext.Provider; +import com.netflix.appinfo.ApplicationInfoManager; +import com.netflix.discovery.EurekaClient; +import com.netflix.discovery.EurekaClientConfig; +import com.netflix.discovery.converters.EurekaJacksonCodec; +import com.netflix.discovery.converters.wrappers.CodecWrapper; +import com.netflix.discovery.converters.wrappers.CodecWrappers; +import com.netflix.eureka.DefaultEurekaServerContext; +import com.netflix.eureka.EurekaServerConfig; +import com.netflix.eureka.EurekaServerContext; +import com.netflix.eureka.cluster.PeerEurekaNodes; +import com.netflix.eureka.registry.PeerAwareInstanceRegistry; +import com.netflix.eureka.resources.DefaultServerCodecs; +import com.netflix.eureka.resources.ServerCodecs; +import com.sun.jersey.api.core.DefaultResourceConfig; +import com.sun.jersey.spi.container.servlet.ServletContainer; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.config.BeanDefinition; @@ -50,22 +67,6 @@ import org.springframework.core.type.filter.AnnotationTypeFilter; import org.springframework.util.ClassUtils; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -import com.netflix.appinfo.ApplicationInfoManager; -import com.netflix.discovery.EurekaClient; -import com.netflix.discovery.EurekaClientConfig; -import com.netflix.discovery.converters.EurekaJacksonCodec; -import com.netflix.discovery.converters.wrappers.CodecWrapper; -import com.netflix.discovery.converters.wrappers.CodecWrappers; -import com.netflix.eureka.DefaultEurekaServerContext; -import com.netflix.eureka.EurekaServerConfig; -import com.netflix.eureka.EurekaServerContext; -import com.netflix.eureka.cluster.PeerEurekaNodes; -import com.netflix.eureka.registry.PeerAwareInstanceRegistry; -import com.netflix.eureka.resources.DefaultServerCodecs; -import com.netflix.eureka.resources.ServerCodecs; -import com.sun.jersey.api.core.DefaultResourceConfig; -import com.sun.jersey.spi.container.servlet.ServletContainer; - /** * @author Gunnar Hillert * @author Biju Kunjummen @@ -78,11 +79,12 @@ import com.sun.jersey.spi.container.servlet.ServletContainer; InstanceRegistryProperties.class }) @PropertySource("classpath:/eureka/server.properties") public class EurekaServerAutoConfiguration extends WebMvcConfigurerAdapter { + /** - * List of packages containing Jersey resources required by the Eureka server + * List of packages containing Jersey resources required by the Eureka server. */ - private static final String[] EUREKA_PACKAGES = new String[] { "com.netflix.discovery", - "com.netflix.eureka" }; + private static final String[] EUREKA_PACKAGES = new String[] { + "com.netflix.discovery", "com.netflix.eureka" }; @Autowired private ApplicationInfoManager applicationInfoManager; @@ -99,6 +101,9 @@ public class EurekaServerAutoConfiguration extends WebMvcConfigurerAdapter { @Autowired private InstanceRegistryProperties instanceRegistryProperties; + /** + * A {@link CloudJacksonJson} instance. + */ public static final CloudJacksonJson JACKSON_JSON = new CloudJacksonJson(); @Bean @@ -107,20 +112,6 @@ public class EurekaServerAutoConfiguration extends WebMvcConfigurerAdapter { EurekaServerAutoConfiguration.class); } - @Configuration - protected static class EurekaServerConfigBeanConfiguration { - @Bean - @ConditionalOnMissingBean - public EurekaServerConfig eurekaServerConfig(EurekaClientConfig clientConfig) { - EurekaServerConfigBean server = new EurekaServerConfigBean(); - if (clientConfig.shouldRegisterWithEureka()) { - // Set a sensible default if we are supposed to replicate - server.setRegistrySyncRetries(5); - } - return server; - } - } - @Bean @ConditionalOnProperty(prefix = "eureka.dashboard", name = "enabled", matchIfMissing = true) public EurekaController eurekaController() { @@ -148,16 +139,6 @@ public class EurekaServerAutoConfiguration extends WebMvcConfigurerAdapter { : codec; } - class CloudServerCodecs extends DefaultServerCodecs { - - public CloudServerCodecs(EurekaServerConfig serverConfig) { - super(getFullJson(serverConfig), - CodecWrappers.getCodec(CodecWrappers.JacksonJsonMini.class), - getFullXml(serverConfig), - CodecWrappers.getCodec(CodecWrappers.JacksonXmlMini.class)); - } - } - @Bean public PeerAwareInstanceRegistry peerAwareInstanceRegistry( ServerCodecs serverCodecs) { @@ -175,65 +156,6 @@ public class EurekaServerAutoConfiguration extends WebMvcConfigurerAdapter { return new RefreshablePeerEurekaNodes(registry, this.eurekaServerConfig, this.eurekaClientConfig, serverCodecs, this.applicationInfoManager); } - - /** - * {@link PeerEurekaNodes} which updates peers when /refresh is invoked. - * Peers are updated only if - * eureka.client.use-dns-for-fetching-service-urls is - * false and one of following properties have changed. - *

- *
    - *
  • eureka.client.availability-zones
  • - *
  • eureka.client.region
  • - *
  • eureka.client.service-url.<zone>
  • - *
- */ - static class RefreshablePeerEurekaNodes extends PeerEurekaNodes - implements ApplicationListener { - - public RefreshablePeerEurekaNodes( - final PeerAwareInstanceRegistry registry, - final EurekaServerConfig serverConfig, - final EurekaClientConfig clientConfig, - final ServerCodecs serverCodecs, - final ApplicationInfoManager applicationInfoManager) { - super(registry, serverConfig, clientConfig, serverCodecs, applicationInfoManager); - } - - @Override - public void onApplicationEvent(final EnvironmentChangeEvent event) { - if (shouldUpdate(event.getKeys())) { - updatePeerEurekaNodes(resolvePeerUrls()); - } - } - - /* - * Check whether specific properties have changed. - */ - protected boolean shouldUpdate(final Set changedKeys) { - assert changedKeys != null; - - // if eureka.client.use-dns-for-fetching-service-urls is true, then - // service-url will not be fetched from environment. - if (clientConfig.shouldUseDnsForFetchingServiceUrls()) { - return false; - } - - if (changedKeys.contains("eureka.client.region")) { - return true; - } - - for (final String key : changedKeys) { - // property keys are not expected to be null. - if (key.startsWith("eureka.client.service-url.") || - key.startsWith("eureka.client.availability-zones.")) { - return true; - } - } - - return false; - } - } @Bean public EurekaServerContext eurekaServerContext(ServerCodecs serverCodecs, @@ -251,7 +173,9 @@ public class EurekaServerAutoConfiguration extends WebMvcConfigurerAdapter { } /** - * Register the Jersey filter + * Register the Jersey filter. + * @param eurekaJerseyApp an {@link Application} for the filter to be registered + * @return a jersey {@link FilterRegistrationBean} */ @Bean public FilterRegistrationBean jerseyFilterRegistration( @@ -268,6 +192,9 @@ public class EurekaServerAutoConfiguration extends WebMvcConfigurerAdapter { /** * Construct a Jersey {@link javax.ws.rs.core.Application} with all the resources * required by the Eureka server. + * @param environment an {@link Environment} instance to retrieve classpath resources + * @param resourceLoader a {@link ResourceLoader} instance to get classloader from + * @return created {@link Application} object */ @Bean public javax.ws.rs.core.Application jerseyApplication(Environment environment, @@ -294,7 +221,6 @@ public class EurekaServerAutoConfiguration extends WebMvcConfigurerAdapter { } // Construct the Jersey ResourceConfig - // Map propsAndFeatures = new HashMap<>(); propsAndFeatures.put( // Skip static content used by the webapp @@ -315,4 +241,90 @@ public class EurekaServerAutoConfiguration extends WebMvcConfigurerAdapter { bean.setOrder(Ordered.LOWEST_PRECEDENCE - 10); return bean; } + + @Configuration + protected static class EurekaServerConfigBeanConfiguration { + + @Bean + @ConditionalOnMissingBean + public EurekaServerConfig eurekaServerConfig(EurekaClientConfig clientConfig) { + EurekaServerConfigBean server = new EurekaServerConfigBean(); + if (clientConfig.shouldRegisterWithEureka()) { + // Set a sensible default if we are supposed to replicate + server.setRegistrySyncRetries(5); + } + return server; + } + + } + + /** + * {@link PeerEurekaNodes} which updates peers when /refresh is invoked. Peers are + * updated only if eureka.client.use-dns-for-fetching-service-urls is + * false and one of following properties have changed. + *

+ *

+ *
    + *
  • eureka.client.availability-zones
  • + *
  • eureka.client.region
  • + *
  • eureka.client.service-url.<zone>
  • + *
+ */ + static class RefreshablePeerEurekaNodes extends PeerEurekaNodes + implements ApplicationListener { + + RefreshablePeerEurekaNodes(final PeerAwareInstanceRegistry registry, + final EurekaServerConfig serverConfig, + final EurekaClientConfig clientConfig, final ServerCodecs serverCodecs, + final ApplicationInfoManager applicationInfoManager) { + super(registry, serverConfig, clientConfig, serverCodecs, + applicationInfoManager); + } + + @Override + public void onApplicationEvent(final EnvironmentChangeEvent event) { + if (shouldUpdate(event.getKeys())) { + updatePeerEurekaNodes(resolvePeerUrls()); + } + } + + /* + * Check whether specific properties have changed. + */ + protected boolean shouldUpdate(final Set changedKeys) { + assert changedKeys != null; + + // if eureka.client.use-dns-for-fetching-service-urls is true, then + // service-url will not be fetched from environment. + if (clientConfig.shouldUseDnsForFetchingServiceUrls()) { + return false; + } + + if (changedKeys.contains("eureka.client.region")) { + return true; + } + + for (final String key : changedKeys) { + // property keys are not expected to be null. + if (key.startsWith("eureka.client.service-url.") + || key.startsWith("eureka.client.availability-zones.")) { + return true; + } + } + return false; + } + + } + + class CloudServerCodecs extends DefaultServerCodecs { + + CloudServerCodecs(EurekaServerConfig serverConfig) { + super(getFullJson(serverConfig), + CodecWrappers.getCodec(CodecWrappers.JacksonJsonMini.class), + getFullXml(serverConfig), + CodecWrappers.getCodec(CodecWrappers.JacksonXmlMini.class)); + } + + } + } diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerBootstrap.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerBootstrap.java index c689a2ea3..ecedde3c1 100644 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerBootstrap.java +++ b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerBootstrap.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -65,6 +65,7 @@ public class EurekaServerBootstrap { protected PeerAwareInstanceRegistry registry; protected volatile EurekaServerContext serverContext; + protected volatile AwsBinder awsBinder; public EurekaServerBootstrap(ApplicationInfoManager applicationInfoManager, @@ -161,6 +162,8 @@ public class EurekaServerBootstrap { /** * Server context shutdown hook. Override for custom logic + * @throws Exception - calling {@link AwsBinder#shutdown()} or + * {@link EurekaServerContext#shutdown()} may result in an exception */ protected void destroyEurekaServerContext() throws Exception { EurekaMonitors.shutdown(); @@ -174,6 +177,7 @@ public class EurekaServerBootstrap { /** * Users can override to clean up the environment themselves. + * @throws Exception - shutting down Eureka servers may result in an exception */ protected void destroyEurekaEnvironment() throws Exception { } diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerConfigBean.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerConfigBean.java index fec993a0d..b0679db66 100644 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerConfigBean.java +++ b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerConfigBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,12 +23,12 @@ import java.util.Map; import java.util.Objects; import java.util.Set; +import com.netflix.eureka.EurekaServerConfig; +import com.netflix.eureka.aws.AwsBindingStrategy; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.core.env.PropertyResolver; - -import com.netflix.eureka.EurekaServerConfig; -import com.netflix.eureka.aws.AwsBindingStrategy; import org.springframework.core.style.ToStringCreator; /** @@ -38,6 +38,9 @@ import org.springframework.core.style.ToStringCreator; @ConfigurationProperties(EurekaServerConfigBean.PREFIX) public class EurekaServerConfigBean implements EurekaServerConfig { + /** + * Eureka server configuration properties prefix. + */ public static final String PREFIX = "eureka.server"; private static final int MINUTES = 60 * 1000; @@ -90,6 +93,7 @@ public class EurekaServerConfigBean implements EurekaServerConfig { private long aSGUpdateIntervalMs = 5 * MINUTES; private long aSGCacheExpiryTimeoutMs = 10 * MINUTES; // defaults to longer than the + // asg update interval private long responseCacheAutoExpirationInSeconds = 180; @@ -296,7 +300,6 @@ public class EurekaServerConfigBean implements EurekaServerConfig { this.initialCapacityOfResponseCache = initialCapacityOfResponseCache; } - @Override public int getHealthStatusMinNumberOfAvailablePeers() { return this.minAvailableInstancesForPeerReplication; @@ -378,7 +381,8 @@ public class EurekaServerConfigBean implements EurekaServerConfig { return this.expectedClientRenewalIntervalSeconds; } - public void setExpectedClientRenewalIntervalSeconds(int expectedClientRenewalIntervalSeconds) { + public void setExpectedClientRenewalIntervalSeconds( + int expectedClientRenewalIntervalSeconds) { this.expectedClientRenewalIntervalSeconds = expectedClientRenewalIntervalSeconds; } @@ -965,130 +969,135 @@ public class EurekaServerConfigBean implements EurekaServerConfig { this.minAvailableInstancesForPeerReplication = minAvailableInstancesForPeerReplication; } - @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } EurekaServerConfigBean that = (EurekaServerConfigBean) o; - return aSGCacheExpiryTimeoutMs == that.aSGCacheExpiryTimeoutMs && - aSGQueryTimeoutMs == that.aSGQueryTimeoutMs && - aSGUpdateIntervalMs == that.aSGUpdateIntervalMs && - Objects.equals(aWSAccessId, that.aWSAccessId) && - Objects.equals(aWSSecretKey, that.aWSSecretKey) && - batchReplication == that.batchReplication && - bindingStrategy == that.bindingStrategy && - deltaRetentionTimerIntervalInMs == that.deltaRetentionTimerIntervalInMs && - disableDelta == that.disableDelta && - disableDeltaForRemoteRegions == that.disableDeltaForRemoteRegions && - disableTransparentFallbackToOtherRegion == that.disableTransparentFallbackToOtherRegion && - eIPBindingRetryIntervalMs == that.eIPBindingRetryIntervalMs && - eIPBindingRetryIntervalMsWhenUnbound == that.eIPBindingRetryIntervalMsWhenUnbound && - eIPBindRebindRetries == that.eIPBindRebindRetries && - enableReplicatedRequestCompression == that.enableReplicatedRequestCompression && - enableSelfPreservation == that.enableSelfPreservation && - evictionIntervalTimerInMs == that.evictionIntervalTimerInMs && - gZipContentFromRemoteRegion == that.gZipContentFromRemoteRegion && - Objects.equals(jsonCodecName, that.jsonCodecName) && - Objects.equals(listAutoScalingGroupsRoleName, that.listAutoScalingGroupsRoleName) && - logIdentityHeaders == that.logIdentityHeaders && - maxElementsInPeerReplicationPool == that.maxElementsInPeerReplicationPool && - maxElementsInStatusReplicationPool == that.maxElementsInStatusReplicationPool && - maxIdleThreadAgeInMinutesForPeerReplication == that.maxIdleThreadAgeInMinutesForPeerReplication && - maxIdleThreadInMinutesAgeForStatusReplication == that.maxIdleThreadInMinutesAgeForStatusReplication && - maxThreadsForPeerReplication == that.maxThreadsForPeerReplication && - maxThreadsForStatusReplication == that.maxThreadsForStatusReplication && - maxTimeForReplication == that.maxTimeForReplication && - minAvailableInstancesForPeerReplication == that.minAvailableInstancesForPeerReplication && - minThreadsForPeerReplication == that.minThreadsForPeerReplication && - minThreadsForStatusReplication == that.minThreadsForStatusReplication && - numberOfReplicationRetries == that.numberOfReplicationRetries && - peerEurekaNodesUpdateIntervalMs == that.peerEurekaNodesUpdateIntervalMs && - peerEurekaStatusRefreshTimeIntervalMs == that.peerEurekaStatusRefreshTimeIntervalMs && - peerNodeConnectionIdleTimeoutSeconds == that.peerNodeConnectionIdleTimeoutSeconds && - peerNodeConnectTimeoutMs == that.peerNodeConnectTimeoutMs && - peerNodeReadTimeoutMs == that.peerNodeReadTimeoutMs && - peerNodeTotalConnections == that.peerNodeTotalConnections && - peerNodeTotalConnectionsPerHost == that.peerNodeTotalConnectionsPerHost && - primeAwsReplicaConnections == that.primeAwsReplicaConnections && - Objects.equals(propertyResolver, that.propertyResolver) && - rateLimiterBurstSize == that.rateLimiterBurstSize && - rateLimiterEnabled == that.rateLimiterEnabled && - rateLimiterFullFetchAverageRate == that.rateLimiterFullFetchAverageRate && - Objects.equals(rateLimiterPrivilegedClients, that.rateLimiterPrivilegedClients) && - rateLimiterRegistryFetchAverageRate == that.rateLimiterRegistryFetchAverageRate && - rateLimiterThrottleStandardClients == that.rateLimiterThrottleStandardClients && - registrySyncRetries == that.registrySyncRetries && - registrySyncRetryWaitMs == that.registrySyncRetryWaitMs && - Objects.equals(remoteRegionAppWhitelist, that.remoteRegionAppWhitelist) && - remoteRegionConnectionIdleTimeoutSeconds == that.remoteRegionConnectionIdleTimeoutSeconds && - remoteRegionConnectTimeoutMs == that.remoteRegionConnectTimeoutMs && - remoteRegionFetchThreadPoolSize == that.remoteRegionFetchThreadPoolSize && - remoteRegionReadTimeoutMs == that.remoteRegionReadTimeoutMs && - remoteRegionRegistryFetchInterval == that.remoteRegionRegistryFetchInterval && - remoteRegionTotalConnections == that.remoteRegionTotalConnections && - remoteRegionTotalConnectionsPerHost == that.remoteRegionTotalConnectionsPerHost && - Objects.equals(remoteRegionTrustStore, that.remoteRegionTrustStore) && - Objects.equals(remoteRegionTrustStorePassword, that.remoteRegionTrustStorePassword) && - Arrays.equals(remoteRegionUrls, that.remoteRegionUrls) && - Objects.equals(remoteRegionUrlsWithName, that.remoteRegionUrlsWithName) && - Double.compare(that.renewalPercentThreshold, renewalPercentThreshold) == 0 && - renewalThresholdUpdateIntervalMs == that.renewalThresholdUpdateIntervalMs && - responseCacheAutoExpirationInSeconds == that.responseCacheAutoExpirationInSeconds && - responseCacheUpdateIntervalMs == that.responseCacheUpdateIntervalMs && - retentionTimeInMSInDeltaQueue == that.retentionTimeInMSInDeltaQueue && - route53BindingRetryIntervalMs == that.route53BindingRetryIntervalMs && - route53BindRebindRetries == that.route53BindRebindRetries && - route53DomainTTL == that.route53DomainTTL && - syncWhenTimestampDiffers == that.syncWhenTimestampDiffers && - useReadOnlyResponseCache == that.useReadOnlyResponseCache && - waitTimeInMsWhenSyncEmpty == that.waitTimeInMsWhenSyncEmpty && - Objects.equals(xmlCodecName, that.xmlCodecName) && - initialCapacityOfResponseCache == that.initialCapacityOfResponseCache && - expectedClientRenewalIntervalSeconds == that.expectedClientRenewalIntervalSeconds && - useAwsAsgApi == that.useAwsAsgApi && - Objects.equals(myUrl, that.myUrl); + return aSGCacheExpiryTimeoutMs == that.aSGCacheExpiryTimeoutMs + && aSGQueryTimeoutMs == that.aSGQueryTimeoutMs + && aSGUpdateIntervalMs == that.aSGUpdateIntervalMs + && Objects.equals(aWSAccessId, that.aWSAccessId) + && Objects.equals(aWSSecretKey, that.aWSSecretKey) + && batchReplication == that.batchReplication + && bindingStrategy == that.bindingStrategy + && deltaRetentionTimerIntervalInMs == that.deltaRetentionTimerIntervalInMs + && disableDelta == that.disableDelta + && disableDeltaForRemoteRegions == that.disableDeltaForRemoteRegions + && disableTransparentFallbackToOtherRegion == that.disableTransparentFallbackToOtherRegion + && eIPBindingRetryIntervalMs == that.eIPBindingRetryIntervalMs + && eIPBindingRetryIntervalMsWhenUnbound == that.eIPBindingRetryIntervalMsWhenUnbound + && eIPBindRebindRetries == that.eIPBindRebindRetries + && enableReplicatedRequestCompression == that.enableReplicatedRequestCompression + && enableSelfPreservation == that.enableSelfPreservation + && evictionIntervalTimerInMs == that.evictionIntervalTimerInMs + && gZipContentFromRemoteRegion == that.gZipContentFromRemoteRegion + && Objects.equals(jsonCodecName, that.jsonCodecName) + && Objects.equals(listAutoScalingGroupsRoleName, + that.listAutoScalingGroupsRoleName) + && logIdentityHeaders == that.logIdentityHeaders + && maxElementsInPeerReplicationPool == that.maxElementsInPeerReplicationPool + && maxElementsInStatusReplicationPool == that.maxElementsInStatusReplicationPool + && maxIdleThreadAgeInMinutesForPeerReplication == that.maxIdleThreadAgeInMinutesForPeerReplication + && maxIdleThreadInMinutesAgeForStatusReplication == that.maxIdleThreadInMinutesAgeForStatusReplication + && maxThreadsForPeerReplication == that.maxThreadsForPeerReplication + && maxThreadsForStatusReplication == that.maxThreadsForStatusReplication + && maxTimeForReplication == that.maxTimeForReplication + && minAvailableInstancesForPeerReplication == that.minAvailableInstancesForPeerReplication + && minThreadsForPeerReplication == that.minThreadsForPeerReplication + && minThreadsForStatusReplication == that.minThreadsForStatusReplication + && numberOfReplicationRetries == that.numberOfReplicationRetries + && peerEurekaNodesUpdateIntervalMs == that.peerEurekaNodesUpdateIntervalMs + && peerEurekaStatusRefreshTimeIntervalMs == that.peerEurekaStatusRefreshTimeIntervalMs + && peerNodeConnectionIdleTimeoutSeconds == that.peerNodeConnectionIdleTimeoutSeconds + && peerNodeConnectTimeoutMs == that.peerNodeConnectTimeoutMs + && peerNodeReadTimeoutMs == that.peerNodeReadTimeoutMs + && peerNodeTotalConnections == that.peerNodeTotalConnections + && peerNodeTotalConnectionsPerHost == that.peerNodeTotalConnectionsPerHost + && primeAwsReplicaConnections == that.primeAwsReplicaConnections + && Objects.equals(propertyResolver, that.propertyResolver) + && rateLimiterBurstSize == that.rateLimiterBurstSize + && rateLimiterEnabled == that.rateLimiterEnabled + && rateLimiterFullFetchAverageRate == that.rateLimiterFullFetchAverageRate + && Objects.equals(rateLimiterPrivilegedClients, + that.rateLimiterPrivilegedClients) + && rateLimiterRegistryFetchAverageRate == that.rateLimiterRegistryFetchAverageRate + && rateLimiterThrottleStandardClients == that.rateLimiterThrottleStandardClients + && registrySyncRetries == that.registrySyncRetries + && registrySyncRetryWaitMs == that.registrySyncRetryWaitMs + && Objects.equals(remoteRegionAppWhitelist, that.remoteRegionAppWhitelist) + && remoteRegionConnectionIdleTimeoutSeconds == that.remoteRegionConnectionIdleTimeoutSeconds + && remoteRegionConnectTimeoutMs == that.remoteRegionConnectTimeoutMs + && remoteRegionFetchThreadPoolSize == that.remoteRegionFetchThreadPoolSize + && remoteRegionReadTimeoutMs == that.remoteRegionReadTimeoutMs + && remoteRegionRegistryFetchInterval == that.remoteRegionRegistryFetchInterval + && remoteRegionTotalConnections == that.remoteRegionTotalConnections + && remoteRegionTotalConnectionsPerHost == that.remoteRegionTotalConnectionsPerHost + && Objects.equals(remoteRegionTrustStore, that.remoteRegionTrustStore) + && Objects.equals(remoteRegionTrustStorePassword, + that.remoteRegionTrustStorePassword) + && Arrays.equals(remoteRegionUrls, that.remoteRegionUrls) + && Objects.equals(remoteRegionUrlsWithName, that.remoteRegionUrlsWithName) + && Double.compare(that.renewalPercentThreshold, + renewalPercentThreshold) == 0 + && renewalThresholdUpdateIntervalMs == that.renewalThresholdUpdateIntervalMs + && responseCacheAutoExpirationInSeconds == that.responseCacheAutoExpirationInSeconds + && responseCacheUpdateIntervalMs == that.responseCacheUpdateIntervalMs + && retentionTimeInMSInDeltaQueue == that.retentionTimeInMSInDeltaQueue + && route53BindingRetryIntervalMs == that.route53BindingRetryIntervalMs + && route53BindRebindRetries == that.route53BindRebindRetries + && route53DomainTTL == that.route53DomainTTL + && syncWhenTimestampDiffers == that.syncWhenTimestampDiffers + && useReadOnlyResponseCache == that.useReadOnlyResponseCache + && waitTimeInMsWhenSyncEmpty == that.waitTimeInMsWhenSyncEmpty + && Objects.equals(xmlCodecName, that.xmlCodecName) + && initialCapacityOfResponseCache == that.initialCapacityOfResponseCache + && expectedClientRenewalIntervalSeconds == that.expectedClientRenewalIntervalSeconds + && useAwsAsgApi == that.useAwsAsgApi && Objects.equals(myUrl, that.myUrl); } @Override public int hashCode() { return Objects.hash(aSGCacheExpiryTimeoutMs, aSGQueryTimeoutMs, - aSGUpdateIntervalMs, aWSAccessId, aWSSecretKey, batchReplication, - bindingStrategy, deltaRetentionTimerIntervalInMs, disableDelta, - disableDeltaForRemoteRegions, - disableTransparentFallbackToOtherRegion, eIPBindRebindRetries, - eIPBindingRetryIntervalMs, eIPBindingRetryIntervalMsWhenUnbound, - enableReplicatedRequestCompression, enableSelfPreservation, - evictionIntervalTimerInMs, gZipContentFromRemoteRegion, - jsonCodecName, listAutoScalingGroupsRoleName, logIdentityHeaders, - maxElementsInPeerReplicationPool, maxElementsInStatusReplicationPool, - maxIdleThreadAgeInMinutesForPeerReplication, - maxIdleThreadInMinutesAgeForStatusReplication, - maxThreadsForPeerReplication, maxThreadsForStatusReplication, - maxTimeForReplication, minAvailableInstancesForPeerReplication, - minThreadsForPeerReplication, minThreadsForStatusReplication, - numberOfReplicationRetries, peerEurekaNodesUpdateIntervalMs, - peerEurekaStatusRefreshTimeIntervalMs, peerNodeConnectTimeoutMs, - peerNodeConnectionIdleTimeoutSeconds, peerNodeReadTimeoutMs, - peerNodeTotalConnections, peerNodeTotalConnectionsPerHost, - primeAwsReplicaConnections, propertyResolver, rateLimiterBurstSize, - rateLimiterEnabled, rateLimiterFullFetchAverageRate, - rateLimiterPrivilegedClients, rateLimiterRegistryFetchAverageRate, - rateLimiterThrottleStandardClients, registrySyncRetries, - registrySyncRetryWaitMs, remoteRegionAppWhitelist, - remoteRegionConnectTimeoutMs, - remoteRegionConnectionIdleTimeoutSeconds, - remoteRegionFetchThreadPoolSize, remoteRegionReadTimeoutMs, - remoteRegionRegistryFetchInterval, remoteRegionTotalConnections, - remoteRegionTotalConnectionsPerHost, remoteRegionTrustStore, - remoteRegionTrustStorePassword, remoteRegionUrls, - remoteRegionUrlsWithName, renewalPercentThreshold, - renewalThresholdUpdateIntervalMs, - responseCacheAutoExpirationInSeconds, - responseCacheUpdateIntervalMs, retentionTimeInMSInDeltaQueue, - route53BindRebindRetries, route53BindingRetryIntervalMs, - route53DomainTTL, syncWhenTimestampDiffers, - useReadOnlyResponseCache, waitTimeInMsWhenSyncEmpty, xmlCodecName, - initialCapacityOfResponseCache, expectedClientRenewalIntervalSeconds, - useAwsAsgApi, myUrl); + aSGUpdateIntervalMs, aWSAccessId, aWSSecretKey, batchReplication, + bindingStrategy, deltaRetentionTimerIntervalInMs, disableDelta, + disableDeltaForRemoteRegions, disableTransparentFallbackToOtherRegion, + eIPBindRebindRetries, eIPBindingRetryIntervalMs, + eIPBindingRetryIntervalMsWhenUnbound, enableReplicatedRequestCompression, + enableSelfPreservation, evictionIntervalTimerInMs, + gZipContentFromRemoteRegion, jsonCodecName, listAutoScalingGroupsRoleName, + logIdentityHeaders, maxElementsInPeerReplicationPool, + maxElementsInStatusReplicationPool, + maxIdleThreadAgeInMinutesForPeerReplication, + maxIdleThreadInMinutesAgeForStatusReplication, + maxThreadsForPeerReplication, maxThreadsForStatusReplication, + maxTimeForReplication, minAvailableInstancesForPeerReplication, + minThreadsForPeerReplication, minThreadsForStatusReplication, + numberOfReplicationRetries, peerEurekaNodesUpdateIntervalMs, + peerEurekaStatusRefreshTimeIntervalMs, peerNodeConnectTimeoutMs, + peerNodeConnectionIdleTimeoutSeconds, peerNodeReadTimeoutMs, + peerNodeTotalConnections, peerNodeTotalConnectionsPerHost, + primeAwsReplicaConnections, propertyResolver, rateLimiterBurstSize, + rateLimiterEnabled, rateLimiterFullFetchAverageRate, + rateLimiterPrivilegedClients, rateLimiterRegistryFetchAverageRate, + rateLimiterThrottleStandardClients, registrySyncRetries, + registrySyncRetryWaitMs, remoteRegionAppWhitelist, + remoteRegionConnectTimeoutMs, remoteRegionConnectionIdleTimeoutSeconds, + remoteRegionFetchThreadPoolSize, remoteRegionReadTimeoutMs, + remoteRegionRegistryFetchInterval, remoteRegionTotalConnections, + remoteRegionTotalConnectionsPerHost, remoteRegionTrustStore, + remoteRegionTrustStorePassword, remoteRegionUrls, + remoteRegionUrlsWithName, renewalPercentThreshold, + renewalThresholdUpdateIntervalMs, responseCacheAutoExpirationInSeconds, + responseCacheUpdateIntervalMs, retentionTimeInMSInDeltaQueue, + route53BindRebindRetries, route53BindingRetryIntervalMs, route53DomainTTL, + syncWhenTimestampDiffers, useReadOnlyResponseCache, + waitTimeInMsWhenSyncEmpty, xmlCodecName, initialCapacityOfResponseCache, + expectedClientRenewalIntervalSeconds, useAwsAsgApi, myUrl); } @Override @@ -1101,76 +1110,106 @@ public class EurekaServerConfigBean implements EurekaServerConfig { .append("aWSSecretKey", this.aWSSecretKey) .append("batchReplication", this.batchReplication) .append("bindingStrategy", this.bindingStrategy) - .append("deltaRetentionTimerIntervalInMs", this.deltaRetentionTimerIntervalInMs) + .append("deltaRetentionTimerIntervalInMs", + this.deltaRetentionTimerIntervalInMs) .append("disableDelta", this.disableDelta) .append("disableDeltaForRemoteRegions", this.disableDeltaForRemoteRegions) - .append("disableTransparentFallbackToOtherRegion", this.disableTransparentFallbackToOtherRegion) + .append("disableTransparentFallbackToOtherRegion", + this.disableTransparentFallbackToOtherRegion) .append("eIPBindRebindRetries", this.eIPBindRebindRetries) .append("eIPBindingRetryIntervalMs", this.eIPBindingRetryIntervalMs) - .append("eIPBindingRetryIntervalMsWhenUnbound", this.eIPBindingRetryIntervalMsWhenUnbound) - .append("enableReplicatedRequestCompression", this.enableReplicatedRequestCompression) + .append("eIPBindingRetryIntervalMsWhenUnbound", + this.eIPBindingRetryIntervalMsWhenUnbound) + .append("enableReplicatedRequestCompression", + this.enableReplicatedRequestCompression) .append("enableSelfPreservation", this.enableSelfPreservation) .append("evictionIntervalTimerInMs", this.evictionIntervalTimerInMs) .append("gZipContentFromRemoteRegion", this.gZipContentFromRemoteRegion) .append("jsonCodecName", this.jsonCodecName) - .append("listAutoScalingGroupsRoleName", this.listAutoScalingGroupsRoleName) + .append("listAutoScalingGroupsRoleName", + this.listAutoScalingGroupsRoleName) .append("logIdentityHeaders", this.logIdentityHeaders) - .append("maxElementsInPeerReplicationPool", this.maxElementsInPeerReplicationPool) - .append("maxElementsInStatusReplicationPool", this.maxElementsInStatusReplicationPool) - .append("maxIdleThreadAgeInMinutesForPeerReplication", this.maxIdleThreadAgeInMinutesForPeerReplication) - .append("maxIdleThreadInMinutesAgeForStatusReplication", this.maxIdleThreadInMinutesAgeForStatusReplication) + .append("maxElementsInPeerReplicationPool", + this.maxElementsInPeerReplicationPool) + .append("maxElementsInStatusReplicationPool", + this.maxElementsInStatusReplicationPool) + .append("maxIdleThreadAgeInMinutesForPeerReplication", + this.maxIdleThreadAgeInMinutesForPeerReplication) + .append("maxIdleThreadInMinutesAgeForStatusReplication", + this.maxIdleThreadInMinutesAgeForStatusReplication) .append("maxThreadsForPeerReplication", this.maxThreadsForPeerReplication) - .append("maxThreadsForStatusReplication", this.maxThreadsForStatusReplication) + .append("maxThreadsForStatusReplication", + this.maxThreadsForStatusReplication) .append("maxTimeForReplication", this.maxTimeForReplication) - .append("minAvailableInstancesForPeerReplication", this.minAvailableInstancesForPeerReplication) + .append("minAvailableInstancesForPeerReplication", + this.minAvailableInstancesForPeerReplication) .append("minThreadsForPeerReplication", this.minThreadsForPeerReplication) - .append("minThreadsForStatusReplication", this.minThreadsForStatusReplication) + .append("minThreadsForStatusReplication", + this.minThreadsForStatusReplication) .append("numberOfReplicationRetries", this.numberOfReplicationRetries) - .append("peerEurekaNodesUpdateIntervalMs", this.peerEurekaNodesUpdateIntervalMs) - .append("peerEurekaStatusRefreshTimeIntervalMs", this.peerEurekaStatusRefreshTimeIntervalMs) + .append("peerEurekaNodesUpdateIntervalMs", + this.peerEurekaNodesUpdateIntervalMs) + .append("peerEurekaStatusRefreshTimeIntervalMs", + this.peerEurekaStatusRefreshTimeIntervalMs) .append("peerNodeConnectTimeoutMs", this.peerNodeConnectTimeoutMs) - .append("peerNodeConnectionIdleTimeoutSeconds", this.peerNodeConnectionIdleTimeoutSeconds) + .append("peerNodeConnectionIdleTimeoutSeconds", + this.peerNodeConnectionIdleTimeoutSeconds) .append("peerNodeReadTimeoutMs", this.peerNodeReadTimeoutMs) .append("peerNodeTotalConnections", this.peerNodeTotalConnections) - .append("peerNodeTotalConnectionsPerHost", this.peerNodeTotalConnectionsPerHost) + .append("peerNodeTotalConnectionsPerHost", + this.peerNodeTotalConnectionsPerHost) .append("primeAwsReplicaConnections", this.primeAwsReplicaConnections) .append("propertyResolver", this.propertyResolver) .append("rateLimiterBurstSize", this.rateLimiterBurstSize) .append("rateLimiterEnabled", this.rateLimiterEnabled) - .append("rateLimiterFullFetchAverageRate", this.rateLimiterFullFetchAverageRate) + .append("rateLimiterFullFetchAverageRate", + this.rateLimiterFullFetchAverageRate) .append("rateLimiterPrivilegedClients", this.rateLimiterPrivilegedClients) - .append("rateLimiterRegistryFetchAverageRate", this.rateLimiterRegistryFetchAverageRate) - .append("rateLimiterThrottleStandardClients", this.rateLimiterThrottleStandardClients) + .append("rateLimiterRegistryFetchAverageRate", + this.rateLimiterRegistryFetchAverageRate) + .append("rateLimiterThrottleStandardClients", + this.rateLimiterThrottleStandardClients) .append("registrySyncRetries", this.registrySyncRetries) .append("registrySyncRetryWaitMs", this.registrySyncRetryWaitMs) .append("remoteRegionAppWhitelist", this.remoteRegionAppWhitelist) .append("remoteRegionConnectTimeoutMs", this.remoteRegionConnectTimeoutMs) - .append("remoteRegionConnectionIdleTimeoutSeconds", this.remoteRegionConnectionIdleTimeoutSeconds) - .append("remoteRegionFetchThreadPoolSize", this.remoteRegionFetchThreadPoolSize) + .append("remoteRegionConnectionIdleTimeoutSeconds", + this.remoteRegionConnectionIdleTimeoutSeconds) + .append("remoteRegionFetchThreadPoolSize", + this.remoteRegionFetchThreadPoolSize) .append("remoteRegionReadTimeoutMs", this.remoteRegionReadTimeoutMs) - .append("remoteRegionRegistryFetchInterval", this.remoteRegionRegistryFetchInterval) + .append("remoteRegionRegistryFetchInterval", + this.remoteRegionRegistryFetchInterval) .append("remoteRegionTotalConnections", this.remoteRegionTotalConnections) - .append("remoteRegionTotalConnectionsPerHost", this.remoteRegionTotalConnectionsPerHost) + .append("remoteRegionTotalConnectionsPerHost", + this.remoteRegionTotalConnectionsPerHost) .append("remoteRegionTrustStore", this.remoteRegionTrustStore) - .append("remoteRegionTrustStorePassword", this.remoteRegionTrustStorePassword) + .append("remoteRegionTrustStorePassword", + this.remoteRegionTrustStorePassword) .append("remoteRegionUrls", this.remoteRegionUrls) .append("remoteRegionUrlsWithName", this.remoteRegionUrlsWithName) .append("renewalPercentThreshold", this.renewalPercentThreshold) - .append("renewalThresholdUpdateIntervalMs", this.renewalThresholdUpdateIntervalMs) - .append("responseCacheAutoExpirationInSeconds", this.responseCacheAutoExpirationInSeconds) - .append("responseCacheUpdateIntervalMs", this.responseCacheUpdateIntervalMs) - .append("retentionTimeInMSInDeltaQueue", this.retentionTimeInMSInDeltaQueue) + .append("renewalThresholdUpdateIntervalMs", + this.renewalThresholdUpdateIntervalMs) + .append("responseCacheAutoExpirationInSeconds", + this.responseCacheAutoExpirationInSeconds) + .append("responseCacheUpdateIntervalMs", + this.responseCacheUpdateIntervalMs) + .append("retentionTimeInMSInDeltaQueue", + this.retentionTimeInMSInDeltaQueue) .append("route53BindRebindRetries", this.route53BindRebindRetries) - .append("route53BindingRetryIntervalMs", this.route53BindingRetryIntervalMs) + .append("route53BindingRetryIntervalMs", + this.route53BindingRetryIntervalMs) .append("route53DomainTTL", this.route53DomainTTL) .append("syncWhenTimestampDiffers", this.syncWhenTimestampDiffers) .append("useReadOnlyResponseCache", this.useReadOnlyResponseCache) .append("waitTimeInMsWhenSyncEmpty", this.waitTimeInMsWhenSyncEmpty) .append("xmlCodecName", this.xmlCodecName) - .append("initialCapacityOfResponseCache", this.initialCapacityOfResponseCache) - .append("expectedClientRenewalIntervalSeconds", this.expectedClientRenewalIntervalSeconds) - .append("useAwsAsgApi", this.useAwsAsgApi) - .append("myUrl", this.myUrl) + .append("initialCapacityOfResponseCache", + this.initialCapacityOfResponseCache) + .append("expectedClientRenewalIntervalSeconds", + this.expectedClientRenewalIntervalSeconds) + .append("useAwsAsgApi", this.useAwsAsgApi).append("myUrl", this.myUrl) .toString(); } diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerInitializerConfiguration.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerInitializerConfiguration.java index 5a8d5ca15..cece2bb34 100644 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerInitializerConfiguration.java +++ b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerInitializerConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,8 +18,10 @@ package org.springframework.cloud.netflix.eureka.server; import javax.servlet.ServletContext; +import com.netflix.eureka.EurekaServerConfig; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.netflix.eureka.server.event.EurekaRegistryAvailableEvent; import org.springframework.cloud.netflix.eureka.server.event.EurekaServerStartedEvent; @@ -30,8 +32,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.web.context.ServletContextAware; -import com.netflix.eureka.EurekaServerConfig; - /** * @author Dave Syer */ @@ -39,7 +39,8 @@ import com.netflix.eureka.EurekaServerConfig; public class EurekaServerInitializerConfiguration implements ServletContextAware, SmartLifecycle, Ordered { - private static final Log log = LogFactory.getLog(EurekaServerInitializerConfiguration.class); + private static final Log log = LogFactory + .getLog(EurekaServerInitializerConfiguration.class); @Autowired private EurekaServerConfig eurekaServerConfig; @@ -67,8 +68,9 @@ public class EurekaServerInitializerConfiguration @Override public void run() { try { - //TODO: is this class even needed now? - eurekaServerBootstrap.contextInitialized(EurekaServerInitializerConfiguration.this.servletContext); + // TODO: is this class even needed now? + eurekaServerBootstrap.contextInitialized( + EurekaServerInitializerConfiguration.this.servletContext); log.info("Started Eureka Server"); publish(new EurekaRegistryAvailableEvent(getEurekaServerConfig())); diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerMarkerConfiguration.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerMarkerConfiguration.java index 20ab2b4af..b5023dfaa 100644 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerMarkerConfiguration.java +++ b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerMarkerConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import org.springframework.context.annotation.Configuration; /** * Responsible for adding in a marker bean to activate - * {@link EurekaServerAutoConfiguration} + * {@link EurekaServerAutoConfiguration}. * * @author Biju Kunjummen */ @@ -34,5 +34,7 @@ public class EurekaServerMarkerConfiguration { } class Marker { + } + } diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/InstanceRegistry.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/InstanceRegistry.java index 135c40d79..fd1284257 100644 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/InstanceRegistry.java +++ b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/InstanceRegistry.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,25 +18,24 @@ package org.springframework.cloud.netflix.eureka.server; import java.util.List; -import com.netflix.eureka.lease.Lease; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.beans.BeansException; -import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceCanceledEvent; -import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceRegisteredEvent; -import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceRenewedEvent; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; - import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.EurekaClient; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.shared.Application; import com.netflix.eureka.EurekaServerConfig; +import com.netflix.eureka.lease.Lease; import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl; import com.netflix.eureka.resources.ServerCodecs; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.beans.BeansException; +import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceCanceledEvent; +import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceRegisteredEvent; +import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceRenewedEvent; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationEvent; /** @@ -48,6 +47,7 @@ public class InstanceRegistry extends PeerAwareInstanceRegistryImpl private static final Log log = LogFactory.getLog(InstanceRegistry.class); private ApplicationContext ctxt; + private int defaultOpenForTrafficCount; public InstanceRegistry(EurekaServerConfig serverConfig, @@ -128,7 +128,8 @@ public class InstanceRegistry extends PeerAwareInstanceRegistryImpl } private void handleCancelation(String appName, String id, boolean isReplication) { - log("cancel " + appName + ", serverId " + id + ", isReplication " + isReplication); + log("cancel " + appName + ", serverId " + id + ", isReplication " + + isReplication); publishEvent(new EurekaInstanceCanceledEvent(this, appName, id, isReplication)); } @@ -140,7 +141,7 @@ public class InstanceRegistry extends PeerAwareInstanceRegistryImpl publishEvent(new EurekaInstanceRegisteredEvent(this, info, leaseDuration, isReplication)); } - + private void log(String message) { if (log.isDebugEnabled()) { log.debug(message); @@ -158,4 +159,5 @@ public class InstanceRegistry extends PeerAwareInstanceRegistryImpl } return leaseDuration; } + } diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/InstanceRegistryProperties.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/InstanceRegistryProperties.java index 77b800905..6af299295 100644 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/InstanceRegistryProperties.java +++ b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/InstanceRegistryProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.eureka.server; @@ -29,19 +28,26 @@ import static org.springframework.cloud.netflix.eureka.server.InstanceRegistryPr @ConfigurationProperties(PREFIX) public class InstanceRegistryProperties { + /** + * Prefix for Eureka instance registry properties. + */ public static final String PREFIX = "eureka.instance.registry"; - /* Default number of expected client, defaults to 1. - * Setting expectedNumberOfClientsSendingRenews to non-zero to ensure that even an isolated + /* + * Default number of expected client, defaults to 1. Setting + * expectedNumberOfClientsSendingRenews to non-zero to ensure that even an isolated * server can adjust its eviction policy to the number of registrations (when it's * zero, even a successful registration won't reset the rate threshold in * InstanceRegistry.register()). */ - @Value("${eureka.server.expectedNumberOfRenewsPerMin:1}") // for backwards compatibility + @Value("${eureka.server.expectedNumberOfRenewsPerMin:1}") // for backwards + // compatibility private int expectedNumberOfClientsSendingRenews = 1; - /** Value used in determining when leases are cancelled, default to 1 for standalone. - * Should be set to 0 for peer replicated eurekas */ + /** + * Value used in determining when leases are cancelled, default to 1 for standalone. + * Should be set to 0 for peer replicated eurekas + */ @Value("${eureka.server.defaultOpenForTrafficCount:1}") // for backwards compatibility private int defaultOpenForTrafficCount = 1; @@ -49,11 +55,13 @@ public class InstanceRegistryProperties { return expectedNumberOfClientsSendingRenews; } - public void setExpectedNumberOfClientsSendingRenews(int expectedNumberOfClientsSendingRenews) { + public void setExpectedNumberOfClientsSendingRenews( + int expectedNumberOfClientsSendingRenews) { this.expectedNumberOfClientsSendingRenews = expectedNumberOfClientsSendingRenews; } - @DeprecatedConfigurationProperty(replacement = PREFIX+".expected-number-of-clients-sending-renews") + @DeprecatedConfigurationProperty(replacement = PREFIX + + ".expected-number-of-clients-sending-renews") @Deprecated public int getExpectedNumberOfRenewsPerMin() { return getExpectedNumberOfClientsSendingRenews(); @@ -71,4 +79,5 @@ public class InstanceRegistryProperties { public void setDefaultOpenForTrafficCount(int defaultOpenForTrafficCount) { this.defaultOpenForTrafficCount = defaultOpenForTrafficCount; } + } diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaInstanceCanceledEvent.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaInstanceCanceledEvent.java index 9db92f1f9..463d2ce85 100644 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaInstanceCanceledEvent.java +++ b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaInstanceCanceledEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,10 +16,10 @@ package org.springframework.cloud.netflix.eureka.server.event; -import org.springframework.context.ApplicationEvent; - import java.util.Objects; +import org.springframework.context.ApplicationEvent; + /** * @author Spencer Gibb * @author Gregor Zurowski @@ -67,12 +67,15 @@ public class EurekaInstanceCanceledEvent extends ApplicationEvent { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } EurekaInstanceCanceledEvent that = (EurekaInstanceCanceledEvent) o; - return Objects.equals(appName, that.appName) && - Objects.equals(serverId, that.serverId) && - replication == replication; + return Objects.equals(appName, that.appName) + && Objects.equals(serverId, that.serverId) && replication == replication; } @Override @@ -82,10 +85,9 @@ public class EurekaInstanceCanceledEvent extends ApplicationEvent { @Override public String toString() { - return new StringBuilder("EurekaInstanceCanceledEvent{") - .append("appName='").append(appName).append("', ") - .append("serverId='").append(serverId).append("', ") - .append("replication=").append(replication).append("}") + return new StringBuilder("EurekaInstanceCanceledEvent{").append("appName='") + .append(appName).append("', ").append("serverId='").append(serverId) + .append("', ").append("replication=").append(replication).append("}") .toString(); } diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaInstanceRegisteredEvent.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaInstanceRegisteredEvent.java index 87c91dcee..fca8b317f 100644 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaInstanceRegisteredEvent.java +++ b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaInstanceRegisteredEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,11 +16,11 @@ package org.springframework.cloud.netflix.eureka.server.event; -import org.springframework.context.ApplicationEvent; +import java.util.Objects; import com.netflix.appinfo.InstanceInfo; -import java.util.Objects; +import org.springframework.context.ApplicationEvent; /** * @author Spencer Gibb @@ -69,12 +69,15 @@ public class EurekaInstanceRegisteredEvent extends ApplicationEvent { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } EurekaInstanceRegisteredEvent that = (EurekaInstanceRegisteredEvent) o; - return Objects.equals(instanceInfo, that.instanceInfo) && - leaseDuration == leaseDuration && - replication == replication; + return Objects.equals(instanceInfo, that.instanceInfo) + && leaseDuration == leaseDuration && replication == replication; } @Override @@ -84,10 +87,10 @@ public class EurekaInstanceRegisteredEvent extends ApplicationEvent { @Override public String toString() { - return new StringBuilder("EurekaInstanceRegisteredEvent{") - .append("instanceInfo=").append(instanceInfo).append(", ") - .append("leaseDuration=").append(leaseDuration).append(", ") - .append("replication=").append(replication).append("}") - .toString(); + return new StringBuilder("EurekaInstanceRegisteredEvent{").append("instanceInfo=") + .append(instanceInfo).append(", ").append("leaseDuration=") + .append(leaseDuration).append(", ").append("replication=") + .append(replication).append("}").toString(); } + } diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaInstanceRenewedEvent.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaInstanceRenewedEvent.java index e04b95a2b..acbf1e56f 100644 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaInstanceRenewedEvent.java +++ b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaInstanceRenewedEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,11 +16,11 @@ package org.springframework.cloud.netflix.eureka.server.event; -import org.springframework.context.ApplicationEvent; +import java.util.Objects; import com.netflix.appinfo.InstanceInfo; -import java.util.Objects; +import org.springframework.context.ApplicationEvent; /** * @author Spencer Gibb @@ -80,13 +80,17 @@ public class EurekaInstanceRenewedEvent extends ApplicationEvent { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } EurekaInstanceRenewedEvent that = (EurekaInstanceRenewedEvent) o; - return Objects.equals(appName, that.appName) && - Objects.equals(serverId, that.serverId) && - Objects.equals(instanceInfo, that.instanceInfo) && - replication == that.replication; + return Objects.equals(appName, that.appName) + && Objects.equals(serverId, that.serverId) + && Objects.equals(instanceInfo, that.instanceInfo) + && replication == that.replication; } @Override @@ -96,12 +100,10 @@ public class EurekaInstanceRenewedEvent extends ApplicationEvent { @Override public String toString() { - return new StringBuilder("EurekaInstanceRenewedEvent{") - .append("appName='").append(appName).append("', ") - .append("serverId='").append(serverId).append("', ") - .append("instanceInfo=").append(instanceInfo).append(", ") - .append("replication=").append(replication).append("}") - .toString(); + return new StringBuilder("EurekaInstanceRenewedEvent{").append("appName='") + .append(appName).append("', ").append("serverId='").append(serverId) + .append("', ").append("instanceInfo=").append(instanceInfo).append(", ") + .append("replication=").append(replication).append("}").toString(); } } diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaRegistryAvailableEvent.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaRegistryAvailableEvent.java index 588dca22c..6cd17d96b 100644 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaRegistryAvailableEvent.java +++ b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaRegistryAvailableEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,10 +16,10 @@ package org.springframework.cloud.netflix.eureka.server.event; -import org.springframework.context.ApplicationEvent; - import com.netflix.eureka.EurekaServerConfig; +import org.springframework.context.ApplicationEvent; + /** * @author Dave Syer */ @@ -27,7 +27,7 @@ import com.netflix.eureka.EurekaServerConfig; public class EurekaRegistryAvailableEvent extends ApplicationEvent { /** - * @param eurekaServerConfig + * @param eurekaServerConfig {@link EurekaServerConfig} event source */ public EurekaRegistryAvailableEvent(EurekaServerConfig eurekaServerConfig) { super(eurekaServerConfig); diff --git a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaServerStartedEvent.java b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaServerStartedEvent.java index 4b9f7cedc..954b3768b 100644 --- a/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaServerStartedEvent.java +++ b/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaServerStartedEvent.java @@ -16,10 +16,10 @@ package org.springframework.cloud.netflix.eureka.server.event; -import org.springframework.context.ApplicationEvent; - import com.netflix.eureka.EurekaServerConfig; +import org.springframework.context.ApplicationEvent; + /** * @author Dave Syer */ @@ -27,7 +27,7 @@ import com.netflix.eureka.EurekaServerConfig; public class EurekaServerStartedEvent extends ApplicationEvent { /** - * @param eurekaServerConfig + * @param eurekaServerConfig {@link EurekaServerConfig} event source */ public EurekaServerStartedEvent(EurekaServerConfig eurekaServerConfig) { super(eurekaServerConfig); diff --git a/spring-cloud-netflix-eureka-server/src/main/resources/eureka/server.properties b/spring-cloud-netflix-eureka-server/src/main/resources/eureka/server.properties index 02c4c287e..7d62014aa 100644 --- a/spring-cloud-netflix-eureka-server/src/main/resources/eureka/server.properties +++ b/spring-cloud-netflix-eureka-server/src/main/resources/eureka/server.properties @@ -1 +1,2 @@ -spring.http.encoding.force=false \ No newline at end of file +spring.http.encoding.force=false + diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationContextTests.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationContextTests.java index e655c842a..8989b0ed6 100644 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationContextTests.java +++ b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.eureka.server; @@ -22,6 +21,7 @@ import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -38,14 +38,15 @@ import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT, - properties = {"spring.application.name=eureka", "server.servlet.context-path=/context", - "management.security.enabled=false", "management.endpoints.web.exposure.include=*" }) +@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT, properties = { + "spring.application.name=eureka", "server.servlet.context-path=/context", + "management.security.enabled=false", + "management.endpoints.web.exposure.include=*" }) public class ApplicationContextTests { + private static final String BASE_PATH = new WebEndpointProperties().getBasePath(); @LocalServerPort @@ -56,21 +57,22 @@ public class ApplicationContextTests { @SuppressWarnings("rawtypes") ResponseEntity entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/context/eureka/apps", Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void dashboardLoads() { ResponseEntity entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/context/", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); String body = entity.getBody(); // System.err.println(body); - assertTrue(body.contains("eureka/js")); - assertTrue(body.contains("eureka/css")); + assertThat(body.contains("eureka/js")).isTrue(); + assertThat(body.contains("eureka/css")).isTrue(); // The "DS Replicas" - assertTrue( - body.contains("localhost")); + assertThat( + body.contains("localhost")) + .isTrue(); } @Test @@ -78,7 +80,7 @@ public class ApplicationContextTests { ResponseEntity entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/context/eureka/css/wro.css", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test @@ -86,7 +88,7 @@ public class ApplicationContextTests { ResponseEntity entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/context/eureka/js/wro.js", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test @@ -96,14 +98,16 @@ public class ApplicationContextTests { @SuppressWarnings("rawtypes") ResponseEntity entity = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/context" + BASE_PATH + "/env", HttpMethod.GET, - new HttpEntity<>("parameters", headers), Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + "http://localhost:" + this.port + "/context" + BASE_PATH + "/env", + HttpMethod.GET, new HttpEntity<>("parameters", headers), Map.class); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Configuration @EnableAutoConfiguration @EnableEurekaServer protected static class Application { + } + } diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationDashboardDisabledTests.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationDashboardDisabledTests.java index 69b9abaa9..1b5052a6e 100644 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationDashboardDisabledTests.java +++ b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationDashboardDisabledTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,12 +16,11 @@ package org.springframework.cloud.netflix.eureka.server; -import static org.junit.Assert.assertEquals; - import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; @@ -31,9 +30,11 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import static org.assertj.core.api.Assertions.assertThat; + @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT, value = { "spring.application.name=eureka", - "eureka.dashboard.enabled=false" }) +@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT, value = { + "spring.application.name=eureka", "eureka.dashboard.enabled=false" }) public class ApplicationDashboardDisabledTests { @Value("${local.server.port}") @@ -44,14 +45,14 @@ public class ApplicationDashboardDisabledTests { @SuppressWarnings("rawtypes") ResponseEntity entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/eureka/apps", Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void dashboardLoads() { - ResponseEntity entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.port + "/", String.class); - assertEquals(HttpStatus.NOT_FOUND, entity.getStatusCode()); + ResponseEntity entity = new TestRestTemplate() + .getForEntity("http://localhost:" + this.port + "/", String.class); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } } diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationDashboardPathTests.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationDashboardPathTests.java index d3fd0004f..c714d96a7 100644 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationDashboardPathTests.java +++ b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationDashboardPathTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,13 +16,11 @@ package org.springframework.cloud.netflix.eureka.server; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; @@ -32,6 +30,8 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import static org.assertj.core.api.Assertions.assertThat; + @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT, value = { "spring.application.name=eureka", "eureka.dashboard.path=/dashboard" }) @@ -45,39 +45,40 @@ public class ApplicationDashboardPathTests { @SuppressWarnings("rawtypes") ResponseEntity entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/eureka/apps", Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void dashboardLoads() { ResponseEntity entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/dashboard", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); String body = entity.getBody(); // System.err.println(body); - assertTrue(body.contains("eureka/js")); - assertTrue(body.contains("eureka/css")); + assertThat(body.contains("eureka/js")).isTrue(); + assertThat(body.contains("eureka/css")).isTrue(); // The "DS Replicas" - assertTrue( - body.contains("localhost")); + assertThat( + body.contains("localhost")) + .isTrue(); // The Home - assertTrue(body.contains("Home")); + assertThat(body.contains("Home")).isTrue(); // The Lastn - assertTrue(body.contains("Last")); + assertThat(body.contains("Last")).isTrue(); } @Test public void cssAvailable() { ResponseEntity entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/eureka/css/wro.css", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void jsAvailable() { ResponseEntity entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/eureka/js/wro.js", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } } diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationServletPathTests.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationServletPathTests.java index a3eb8f559..acf42b3ca 100644 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationServletPathTests.java +++ b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationServletPathTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.eureka.server; @@ -22,6 +21,7 @@ import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -37,46 +37,42 @@ import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class, webEnvironment = RANDOM_PORT, properties = { "spring.application.name=eureka", "server.servlet.context-path=/servlet", - "management.security.enabled=false", "management.endpoints.web.exposure.include=*" }) + "management.security.enabled=false", + "management.endpoints.web.exposure.include=*" }) public class ApplicationServletPathTests { + private static final String BASE_PATH = new WebEndpointProperties().getBasePath(); @LocalServerPort private int port = 0; - @Configuration - @EnableAutoConfiguration - @EnableEurekaServer - protected static class Application { - } - @Test public void catalogLoads() { @SuppressWarnings("rawtypes") ResponseEntity entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/servlet/eureka/apps", Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void dashboardLoads() { ResponseEntity entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/servlet/", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); String body = entity.getBody(); // System.err.println(body); - assertTrue(body.contains("eureka/js")); - assertTrue(body.contains("eureka/css")); + assertThat(body.contains("eureka/js")).isTrue(); + assertThat(body.contains("eureka/css")).isTrue(); // The "DS Replicas" - assertTrue( - body.contains("localhost")); + assertThat( + body.contains("localhost")) + .isTrue(); } @Test @@ -84,7 +80,7 @@ public class ApplicationServletPathTests { ResponseEntity entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/servlet/eureka/css/wro.css", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test @@ -92,7 +88,7 @@ public class ApplicationServletPathTests { ResponseEntity entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/servlet/eureka/js/wro.js", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test @@ -102,9 +98,16 @@ public class ApplicationServletPathTests { @SuppressWarnings("rawtypes") ResponseEntity entity = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/servlet" + BASE_PATH + "/env", HttpMethod.GET, - new HttpEntity<>("parameters", headers), Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + "http://localhost:" + this.port + "/servlet" + BASE_PATH + "/env", + HttpMethod.GET, new HttpEntity<>("parameters", headers), Map.class); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + } + + @Configuration + @EnableAutoConfiguration + @EnableEurekaServer + protected static class Application { + } } diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationTests.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationTests.java index 1a4350920..21fbff06a 100644 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationTests.java +++ b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,12 @@ package org.springframework.cloud.netflix.eureka.server; import java.util.Collections; import java.util.Map; +import com.netflix.appinfo.InstanceInfo; +import com.netflix.discovery.converters.wrappers.CodecWrapper; +import com.netflix.eureka.resources.ServerCodecs; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -37,23 +41,15 @@ import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; -import com.netflix.appinfo.InstanceInfo; -import com.netflix.discovery.converters.wrappers.CodecWrapper; -import com.netflix.eureka.resources.ServerCodecs; - -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class, webEnvironment = RANDOM_PORT, properties = { - "spring.jmx.enabled=true", "management.security.enabled=false", "management.endpoints.web.exposure.include=*" }) + "spring.jmx.enabled=true", "management.security.enabled=false", + "management.endpoints.web.exposure.include=*" }) public class ApplicationTests { + private static final String BASE_PATH = new WebEndpointProperties().getBasePath(); @LocalServerPort @@ -67,7 +63,7 @@ public class ApplicationTests { @SuppressWarnings("rawtypes") ResponseEntity entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/eureka/apps", Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test @@ -79,7 +75,7 @@ public class ApplicationTests { ResponseEntity entity = new TestRestTemplate().exchange( "http://localhost:" + this.port + BASE_PATH + "/env", HttpMethod.GET, new HttpEntity<>("parameters", headers), Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test @@ -87,10 +83,11 @@ public class ApplicationTests { String basePath = "http://localhost:" + this.port + "/"; ResponseEntity entity = new TestRestTemplate().getForEntity(basePath, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); String body = entity.getBody(); - assertNotNull(body); - assertFalse("basePath contains double slashes", body.contains(basePath + "/")); + assertThat(body).isNotNull(); + assertThat(body.contains(basePath + "/")).as("basePath contains double slashes") + .isFalse(); } @Test @@ -98,30 +95,31 @@ public class ApplicationTests { String basePath = "http://localhost:" + this.port + "/eureka/css/wro.css"; ResponseEntity entity = new TestRestTemplate().getForEntity(basePath, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); String body = entity.getBody(); - assertNotNull(body); - assertTrue("css wasn't preprocessed", body.contains("spring-logo")); + assertThat(body).isNotNull(); + assertThat(body.contains("spring-logo")).as("css wasn't preprocessed").isTrue(); } @Test public void customCodecWorks() throws Exception { - assertThat("serverCodecs is wrong type", this.serverCodecs, - is(instanceOf(EurekaServerAutoConfiguration.CloudServerCodecs.class))); + assertThat(this.serverCodecs).as("serverCodecs is wrong type") + .isInstanceOf(EurekaServerAutoConfiguration.CloudServerCodecs.class); CodecWrapper codec = this.serverCodecs.getFullJsonCodec(); - assertThat("codec is wrong type", codec, is(instanceOf(CloudJacksonJson.class))); + assertThat(codec).as("codec is wrong type").isInstanceOf(CloudJacksonJson.class); InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder().setAppName("fooapp") .add("instanceId", "foo").build(); String encoded = codec.encode(instanceInfo); InstanceInfo decoded = codec.decode(encoded, InstanceInfo.class); - assertThat("instanceId was wrong", decoded.getInstanceId(), is("foo")); + assertThat(decoded.getInstanceId()).as("instanceId was wrong").isEqualTo("foo"); } @Configuration @EnableAutoConfiguration @EnableEurekaServer protected static class Application { + } } diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/EurekaControllerReplicasTests.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/EurekaControllerReplicasTests.java index 4ce33e4f5..6c63d22c1 100644 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/EurekaControllerReplicasTests.java +++ b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/EurekaControllerReplicasTests.java @@ -1,40 +1,61 @@ -package org.springframework.cloud.netflix.eureka.server; +/* + * Copyright 2016-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ -import static org.junit.Assert.*; -import static org.mockito.Mockito.mock; -import static org.springframework.cloud.netflix.eureka.server.EurekaControllerTests.setInstance; +package org.springframework.cloud.netflix.eureka.server; import java.util.HashMap; import java.util.Map; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.InstanceInfo; +import com.netflix.eureka.util.StatusInfo; import org.junit.After; import org.junit.Before; import org.junit.Test; -import com.netflix.eureka.util.StatusInfo; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.springframework.cloud.netflix.eureka.server.EurekaControllerTests.setInstance; public class EurekaControllerReplicasTests { String noAuthList1 = "http://test1.com"; + String noAuthList2 = noAuthList1 + ",http://test2.com"; String authList1 = "http://user:pwd@test1.com"; + String authList2 = authList1 + ",http://user2:pwd2@test2.com"; String combinationAuthList1 = "http://test1.com,http://user2:pwd2@test2.com"; + String combinationAuthList2 = "http://test3.com,http://user4:pwd4@test4.com"; String combinationNoAuthList1 = "http://test1.com,http://test2.com"; + String combinationNoAuthList2 = "http://test3.com,http://test4.com"; String totalAutoList = combinationAuthList1 + "," + combinationAuthList2; + String totalNoAutoList = combinationNoAuthList1 + "," + combinationNoAuthList2; String empty = new String(); private ApplicationInfoManager original; + private InstanceInfo instanceInfo; @Before @@ -54,8 +75,7 @@ public class EurekaControllerReplicasTests { public void testFilterReplicasNoAuth() throws Exception { Map model = new HashMap<>(); StatusInfo statusInfo = StatusInfo.Builder.newBuilder() - .add("registered-replicas", empty) - .add("available-replicas", noAuthList1) + .add("registered-replicas", empty).add("available-replicas", noAuthList1) .add("unavailable-replicas", noAuthList2) .withInstanceInfo(this.instanceInfo).build(); EurekaController controller = new EurekaController(null); @@ -64,9 +84,9 @@ public class EurekaControllerReplicasTests { @SuppressWarnings("unchecked") Map results = (Map) model.get("applicationStats"); - assertEquals(empty, results.get("registered-replicas")); - assertEquals(noAuthList1, results.get("available-replicas")); - assertEquals(noAuthList2, results.get("unavailable-replicas")); + assertThat(results.get("registered-replicas")).isEqualTo(empty); + assertThat(results.get("available-replicas")).isEqualTo(noAuthList1); + assertThat(results.get("unavailable-replicas")).isEqualTo(noAuthList2); } @@ -75,8 +95,7 @@ public class EurekaControllerReplicasTests { Map model = new HashMap<>(); StatusInfo statusInfo = StatusInfo.Builder.newBuilder() .add("registered-replicas", authList2) - .add("available-replicas", authList1) - .add("unavailable-replicas", empty) + .add("available-replicas", authList1).add("unavailable-replicas", empty) .withInstanceInfo(instanceInfo).build(); EurekaController controller = new EurekaController(null); @@ -84,9 +103,9 @@ public class EurekaControllerReplicasTests { @SuppressWarnings("unchecked") Map results = (Map) model.get("applicationStats"); - assertEquals(empty, results.get("unavailable-replicas")); - assertEquals(noAuthList1, results.get("available-replicas")); - assertEquals(noAuthList2, results.get("registered-replicas")); + assertThat(results.get("unavailable-replicas")).isEqualTo(empty); + assertThat(results.get("available-replicas")).isEqualTo(noAuthList1); + assertThat(results.get("registered-replicas")).isEqualTo(noAuthList2); } @@ -94,20 +113,19 @@ public class EurekaControllerReplicasTests { public void testFilterReplicasAuthWithCombinationList() throws Exception { Map model = new HashMap<>(); StatusInfo statusInfo = StatusInfo.Builder.newBuilder() - .add("registered-replicas", totalAutoList) - .add("available-replicas", combinationAuthList1) - .add("unavailable-replicas", combinationAuthList2) - .withInstanceInfo(instanceInfo).build(); + .add("registered-replicas", totalAutoList) + .add("available-replicas", combinationAuthList1) + .add("unavailable-replicas", combinationAuthList2) + .withInstanceInfo(instanceInfo).build(); EurekaController controller = new EurekaController(null); controller.filterReplicas(model, statusInfo); @SuppressWarnings("unchecked") Map results = (Map) model.get("applicationStats"); - assertEquals(totalNoAutoList, results.get("registered-replicas")); - assertEquals(combinationNoAuthList1, results.get("available-replicas")); - assertEquals(combinationNoAuthList2, results.get("unavailable-replicas")); - + assertThat(results.get("registered-replicas")).isEqualTo(totalNoAutoList); + assertThat(results.get("available-replicas")).isEqualTo(combinationNoAuthList1); + assertThat(results.get("unavailable-replicas")).isEqualTo(combinationNoAuthList2); } } diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/EurekaControllerTests.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/EurekaControllerTests.java index 62e740225..27fdc55a0 100644 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/EurekaControllerTests.java +++ b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/EurekaControllerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.eureka.server; @@ -24,12 +23,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.util.ReflectionUtils; - import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.InstanceInfo; @@ -40,27 +33,30 @@ import com.netflix.eureka.EurekaServerContextHolder; import com.netflix.eureka.cluster.PeerEurekaNode; import com.netflix.eureka.cluster.PeerEurekaNodes; import com.netflix.eureka.registry.PeerAwareInstanceRegistry; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.util.ReflectionUtils; + +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class EurekaControllerTests { private ApplicationInfoManager infoManager; + private ApplicationInfoManager original; @Before public void setup() throws Exception { PeerEurekaNodes peerEurekaNodes = mock(PeerEurekaNodes.class); - when(peerEurekaNodes.getPeerNodesView()).thenReturn(Collections.emptyList()); + when(peerEurekaNodes.getPeerNodesView()) + .thenReturn(Collections.emptyList()); - InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder() - .setAppName("test") + InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder().setAppName("test") .setDataCenterInfo(new MyDataCenterInfo(DataCenterInfo.Name.MyOwn)) .build(); @@ -70,11 +66,9 @@ public class EurekaControllerTests { when(this.infoManager.getInfo()).thenReturn(instanceInfo); Application myapp = new Application("myapp"); - myapp.addInstance(InstanceInfo.Builder.newBuilder() - .setAppName("myapp") + myapp.addInstance(InstanceInfo.Builder.newBuilder().setAppName("myapp") .setDataCenterInfo(new MyDataCenterInfo(DataCenterInfo.Name.MyOwn)) - .setInstanceId("myapp:1") - .build()); + .setInstanceId("myapp:1").build()); ArrayList applications = new ArrayList<>(); applications.add(myapp); @@ -95,8 +89,10 @@ public class EurekaControllerTests { setInstance(this.original); } - static void setInstance(ApplicationInfoManager infoManager) throws IllegalAccessException { - Field instance = ReflectionUtils.findField(ApplicationInfoManager.class, "instance"); + static void setInstance(ApplicationInfoManager infoManager) + throws IllegalAccessException { + Field instance = ReflectionUtils.findField(ApplicationInfoManager.class, + "instance"); ReflectionUtils.makeAccessible(instance); instance.set(null, infoManager); } @@ -113,15 +109,15 @@ public class EurekaControllerTests { Map instanceInfo = getFirst(app, "instanceInfos"); Map instance = getFirst(instanceInfo, "instances"); - assertThat("id was wrong", (String)instance.get("id"), is(equalTo("myapp:1"))); - assertThat("url was not null", instance.get("url"), is(nullValue())); - assertThat("isHref was wrong", (Boolean)instance.get("isHref"), is(false)); + assertThat((String) instance.get("id")).as("id was wrong").isEqualTo("myapp:1"); + assertThat(instance.get("url")).as("url was not null").isNull(); + assertThat((Boolean) instance.get("isHref")).as("isHref was wrong").isFalse(); } @SuppressWarnings("unchecked") Map getFirst(Map model, String key) { List> apps = (List>) model.get(key); - assertThat(key +" was wrong size", apps, is(hasSize(1))); + assertThat(apps).as(key + " was wrong size").hasSize(1); return apps.get(0); } diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/EurekaCustomPeerNodesTests.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/EurekaCustomPeerNodesTests.java index dc69ead86..c771078f1 100644 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/EurekaCustomPeerNodesTests.java +++ b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/EurekaCustomPeerNodesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,28 +12,27 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.eureka.server; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.junit4.SpringRunner; - import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.discovery.EurekaClientConfig; import com.netflix.eureka.EurekaServerConfig; import com.netflix.eureka.cluster.PeerEurekaNodes; import com.netflix.eureka.registry.PeerAwareInstanceRegistry; import com.netflix.eureka.resources.ServerCodecs; +import org.junit.Test; +import org.junit.runner.RunWith; -import static org.junit.Assert.assertTrue; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @SpringBootTest(classes = EurekaCustomPeerNodesTests.Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, value = { @@ -41,13 +40,13 @@ import static org.junit.Assert.assertTrue; "management.security.enabled=false" }) public class EurekaCustomPeerNodesTests { - @Autowired - private PeerEurekaNodes peerEurekaNodes; + @Autowired + private PeerEurekaNodes peerEurekaNodes; @Test public void testCustomPeerNodesShouldTakePrecedenceOverDefault() { - assertTrue("PeerEurekaNodes should be the user created one", - peerEurekaNodes instanceof CustomEurekaPeerNodes); + assertThat(peerEurekaNodes instanceof CustomEurekaPeerNodes) + .as("PeerEurekaNodes should be the user created one").isTrue(); } @Configuration @@ -68,13 +67,14 @@ public class EurekaCustomPeerNodesTests { private static class CustomEurekaPeerNodes extends PeerEurekaNodes { - public CustomEurekaPeerNodes(PeerAwareInstanceRegistry registry, + CustomEurekaPeerNodes(PeerAwareInstanceRegistry registry, EurekaServerConfig serverConfig, EurekaClientConfig clientConfig, ServerCodecs serverCodecs, ApplicationInfoManager applicationInfoManager) { super(registry, serverConfig, clientConfig, serverCodecs, applicationInfoManager); } + } } diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/InstanceRegistryTests.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/InstanceRegistryTests.java index 19a3ce559..ef3da450a 100644 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/InstanceRegistryTests.java +++ b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/InstanceRegistryTests.java @@ -1,3 +1,19 @@ +/* + * Copyright 2016-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.springframework.cloud.netflix.eureka.server; import java.util.ArrayList; @@ -27,24 +43,24 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.event.SmartApplicationListener; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doReturn; /** * @author Bartlomiej Slota */ @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = TestApplication.class, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - value = {"spring.application.name=eureka", "logging.level.org.springframework." - + "cloud.netflix.eureka.server.InstanceRegistry=DEBUG"}) +@SpringBootTest(classes = TestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, value = { + "spring.application.name=eureka", "logging.level.org.springframework." + + "cloud.netflix.eureka.server.InstanceRegistry=DEBUG" }) public class InstanceRegistryTests { private static final String APP_NAME = "MY-APP-NAME"; + private static final String HOST_NAME = "my-host-name"; + private static final String INSTANCE_ID = "my-host-name:8008"; + private static final int PORT = 8008; @SpyBean(PeerAwareInstanceRegistry.class) @@ -62,32 +78,36 @@ public class InstanceRegistryTests { public void testRegister() throws Exception { // creating instance info final LeaseInfo leaseInfo = getLeaseInfo(); - final InstanceInfo instanceInfo = getInstanceInfo(APP_NAME, HOST_NAME, INSTANCE_ID, PORT, leaseInfo); + final InstanceInfo instanceInfo = getInstanceInfo(APP_NAME, HOST_NAME, + INSTANCE_ID, PORT, leaseInfo); // calling tested method instanceRegistry.register(instanceInfo, false); // event of proper type is registered - assertEquals(1, this.testEvents.applicationEvents.size()); - assertTrue(this.testEvents.applicationEvents.get(0) instanceof EurekaInstanceRegisteredEvent); + assertThat(this.testEvents.applicationEvents.size()).isEqualTo(1); + assertThat(this.testEvents.applicationEvents + .get(0) instanceof EurekaInstanceRegisteredEvent).isTrue(); // event details are correct - final EurekaInstanceRegisteredEvent registeredEvent = - (EurekaInstanceRegisteredEvent) (this.testEvents.applicationEvents.get(0)); - assertEquals(instanceInfo, registeredEvent.getInstanceInfo()); - assertEquals(leaseInfo.getDurationInSecs(), registeredEvent.getLeaseDuration()); - assertEquals(instanceRegistry, registeredEvent.getSource()); - assertFalse(registeredEvent.isReplication()); + final EurekaInstanceRegisteredEvent registeredEvent = (EurekaInstanceRegisteredEvent) (this.testEvents.applicationEvents + .get(0)); + assertThat(registeredEvent.getInstanceInfo()).isEqualTo(instanceInfo); + assertThat(registeredEvent.getLeaseDuration()) + .isEqualTo(leaseInfo.getDurationInSecs()); + assertThat(registeredEvent.getSource()).isEqualTo(instanceRegistry); + assertThat(registeredEvent.isReplication()).isFalse(); } @Test public void testDefaultLeaseDurationRegisterEvent() throws Exception { // creating instance info - final InstanceInfo instanceInfo = getInstanceInfo(APP_NAME, HOST_NAME, INSTANCE_ID, PORT, null); + final InstanceInfo instanceInfo = getInstanceInfo(APP_NAME, HOST_NAME, + INSTANCE_ID, PORT, null); // calling tested method instanceRegistry.register(instanceInfo, false); // instance info duration is set to default - final EurekaInstanceRegisteredEvent registeredEvent = - (EurekaInstanceRegisteredEvent) (this.testEvents.applicationEvents.get(0)); - assertEquals(LeaseInfo.DEFAULT_LEASE_DURATION, - registeredEvent.getLeaseDuration()); + final EurekaInstanceRegisteredEvent registeredEvent = (EurekaInstanceRegisteredEvent) (this.testEvents.applicationEvents + .get(0)); + assertThat(registeredEvent.getLeaseDuration()) + .isEqualTo(LeaseInfo.DEFAULT_LEASE_DURATION); } @Test @@ -95,24 +115,28 @@ public class InstanceRegistryTests { // calling tested method instanceRegistry.internalCancel(APP_NAME, HOST_NAME, false); // event of proper type is registered - assertEquals(1, this.testEvents.applicationEvents.size()); - assertTrue(this.testEvents.applicationEvents.get(0) instanceof EurekaInstanceCanceledEvent); + assertThat(this.testEvents.applicationEvents.size()).isEqualTo(1); + assertThat(this.testEvents.applicationEvents + .get(0) instanceof EurekaInstanceCanceledEvent).isTrue(); // event details are correct - final EurekaInstanceCanceledEvent registeredEvent = - (EurekaInstanceCanceledEvent) (this.testEvents.applicationEvents.get(0)); - assertEquals(APP_NAME, registeredEvent.getAppName()); - assertEquals(HOST_NAME, registeredEvent.getServerId()); - assertEquals(instanceRegistry, registeredEvent.getSource()); - assertFalse(registeredEvent.isReplication()); + final EurekaInstanceCanceledEvent registeredEvent = (EurekaInstanceCanceledEvent) (this.testEvents.applicationEvents + .get(0)); + assertThat(registeredEvent.getAppName()).isEqualTo(APP_NAME); + assertThat(registeredEvent.getServerId()).isEqualTo(HOST_NAME); + assertThat(registeredEvent.getSource()).isEqualTo(instanceRegistry); + assertThat(registeredEvent.isReplication()).isFalse(); } @Test public void testRenew() throws Exception { - //Creating two instances of the app - final InstanceInfo instanceInfo1 = getInstanceInfo(APP_NAME, HOST_NAME, INSTANCE_ID, PORT, null); - final InstanceInfo instanceInfo2 = getInstanceInfo(APP_NAME, HOST_NAME, "my-host-name:8009", 8009, null); + // Creating two instances of the app + final InstanceInfo instanceInfo1 = getInstanceInfo(APP_NAME, HOST_NAME, + INSTANCE_ID, PORT, null); + final InstanceInfo instanceInfo2 = getInstanceInfo(APP_NAME, HOST_NAME, + "my-host-name:8009", 8009, null); // creating application list with an app having two instances - final Application application = new Application(APP_NAME, Arrays.asList(instanceInfo1, instanceInfo2)); + final Application application = new Application(APP_NAME, + Arrays.asList(instanceInfo1, instanceInfo2)); final List applications = new ArrayList<>(); applications.add(application); // stubbing applications list @@ -121,48 +145,23 @@ public class InstanceRegistryTests { instanceRegistry.renew(APP_NAME, INSTANCE_ID, false); instanceRegistry.renew(APP_NAME, "my-host-name:8009", false); // event of proper type is registered - assertEquals(2, this.testEvents.applicationEvents.size()); - assertTrue(this.testEvents.applicationEvents.get(0) instanceof EurekaInstanceRenewedEvent); - assertTrue(this.testEvents.applicationEvents.get(1) instanceof EurekaInstanceRenewedEvent); + assertThat(this.testEvents.applicationEvents.size()).isEqualTo(2); + assertThat(this.testEvents.applicationEvents + .get(0) instanceof EurekaInstanceRenewedEvent).isTrue(); + assertThat(this.testEvents.applicationEvents + .get(1) instanceof EurekaInstanceRenewedEvent).isTrue(); // event details are correct - final EurekaInstanceRenewedEvent event1 = (EurekaInstanceRenewedEvent) - (this.testEvents.applicationEvents.get(0)); - assertEquals(APP_NAME, event1.getAppName()); - assertEquals(INSTANCE_ID, event1.getServerId()); - assertEquals(instanceRegistry, event1.getSource()); - assertEquals(instanceInfo1, event1.getInstanceInfo()); - assertFalse(event1.isReplication()); - - final EurekaInstanceRenewedEvent event2 = (EurekaInstanceRenewedEvent) - (this.testEvents.applicationEvents.get(1)); - assertEquals(instanceInfo2, event2.getInstanceInfo()); - } - - @Configuration - @EnableAutoConfiguration - @EnableEurekaServer - protected static class TestApplication { - @Bean - public TestEvents testEvents() { - return new TestEvents(); - } - } - - protected static class TestEvents implements SmartApplicationListener { - public final List applicationEvents = new LinkedList<>(); - - @Override - public boolean supportsEventType(Class eventType) { - return EurekaInstanceRegisteredEvent.class.isAssignableFrom(eventType) - || EurekaInstanceCanceledEvent.class.isAssignableFrom(eventType) - || EurekaInstanceRenewedEvent.class.isAssignableFrom(eventType); - } - - @Override - public void onApplicationEvent(ApplicationEvent event) { - this.applicationEvents.add(event); - } + final EurekaInstanceRenewedEvent event1 = (EurekaInstanceRenewedEvent) (this.testEvents.applicationEvents + .get(0)); + assertThat(event1.getAppName()).isEqualTo(APP_NAME); + assertThat(event1.getServerId()).isEqualTo(INSTANCE_ID); + assertThat(event1.getSource()).isEqualTo(instanceRegistry); + assertThat(event1.getInstanceInfo()).isEqualTo(instanceInfo1); + assertThat(event1.isReplication()).isFalse(); + final EurekaInstanceRenewedEvent event2 = (EurekaInstanceRenewedEvent) (this.testEvents.applicationEvents + .get(1)); + assertThat(event2.getInstanceInfo()).isEqualTo(instanceInfo2); } private LeaseInfo getLeaseInfo() { @@ -182,4 +181,35 @@ public class InstanceRegistryTests { builder.setLeaseInfo(leaseInfo); return builder.build(); } + + @Configuration + @EnableAutoConfiguration + @EnableEurekaServer + protected static class TestApplication { + + @Bean + public TestEvents testEvents() { + return new TestEvents(); + } + + } + + protected static class TestEvents implements SmartApplicationListener { + + public final List applicationEvents = new LinkedList<>(); + + @Override + public boolean supportsEventType(Class eventType) { + return EurekaInstanceRegisteredEvent.class.isAssignableFrom(eventType) + || EurekaInstanceCanceledEvent.class.isAssignableFrom(eventType) + || EurekaInstanceRenewedEvent.class.isAssignableFrom(eventType); + } + + @Override + public void onApplicationEvent(ApplicationEvent event) { + this.applicationEvents.add(event); + } + + } + } diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/RefreshablePeerEurekaNodesTests.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/RefreshablePeerEurekaNodesTests.java index 56502735b..c22becb3a 100644 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/RefreshablePeerEurekaNodesTests.java +++ b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/RefreshablePeerEurekaNodesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.eureka.server; @@ -22,9 +21,15 @@ import java.util.Collections; import java.util.HashSet; import java.util.List; -import org.junit.Ignore; +import com.netflix.appinfo.ApplicationInfoManager; +import com.netflix.discovery.EurekaClientConfig; +import com.netflix.eureka.EurekaServerConfig; +import com.netflix.eureka.cluster.PeerEurekaNodes; +import com.netflix.eureka.registry.PeerAwareInstanceRegistry; +import com.netflix.eureka.resources.ServerCodecs; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -41,19 +46,7 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; -import com.netflix.appinfo.ApplicationInfoManager; -import com.netflix.discovery.EurekaClientConfig; -import com.netflix.eureka.EurekaServerConfig; -import com.netflix.eureka.cluster.PeerEurekaNodes; -import com.netflix.eureka.registry.PeerAwareInstanceRegistry; -import com.netflix.eureka.resources.ServerCodecs; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.anyListOf; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -65,169 +58,178 @@ import static org.mockito.Mockito.when; * @author Fahim Farook */ @RunWith(SpringRunner.class) -@SpringBootTest( - classes = RefreshablePeerEurekaNodesTests.Application.class, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - value = { +@SpringBootTest(classes = RefreshablePeerEurekaNodesTests.Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, value = { "spring.application.name=eureka-server", - "eureka.client.service-url.defaultZone=http://localhost:8678/eureka/" - }) + "eureka.client.service-url.defaultZone=http://localhost:8678/eureka/" }) public class RefreshablePeerEurekaNodesTests { @Autowired private ConfigurableApplicationContext context; - + @Autowired private PeerEurekaNodes peerEurekaNodes; - + @Value("${local.server.port}") private int port = 0; - - private static final String DEFAULT_ZONE = "eureka.client.service-url.defaultZone"; - private static final String REGION = "eureka.client.region"; - private static final String USE_DNS = "eureka.client.use-dns-for-fetching-service-urls"; - + + private static final String DEFAULT_ZONE = "eureka.client.service-url.defaultZone"; + + private static final String REGION = "eureka.client.region"; + + private static final String USE_DNS = "eureka.client.use-dns-for-fetching-service-urls"; + @Test - public void notUpdatedWhenDnsIsTrue() { - changeProperty( - "eureka.client.use-dns-for-fetching-service-urls=true", - "eureka.client.region=unavailable-region", // to force defaultZone + public void notUpdatedWhenDnsIsTrue() { + changeProperty("eureka.client.use-dns-for-fetching-service-urls=true", + "eureka.client.region=unavailable-region", // to force defaultZone "eureka.client.service-url.defaultZone=http://default-host1:8678/eureka/"); - this.context.publishEvent(new EnvironmentChangeEvent(new HashSet(Arrays.asList(USE_DNS, DEFAULT_ZONE)))); - - assertFalse("PeerEurekaNodes' are updated when eureka.client.use-dns-for-fetching-service-urls is true", - serviceUrlMatches("http://default-host1:8678/eureka/")); + this.context.publishEvent(new EnvironmentChangeEvent( + new HashSet(Arrays.asList(USE_DNS, DEFAULT_ZONE)))); + + assertThat(serviceUrlMatches("http://default-host1:8678/eureka/")).as( + "PeerEurekaNodes' are updated when eureka.client.use-dns-for-fetching-service-urls is true") + .isFalse(); } - + @Test public void updatedWhenDnsIsFalse() { - changeProperty( - "eureka.client.use-dns-for-fetching-service-urls=false", + changeProperty("eureka.client.use-dns-for-fetching-service-urls=false", "eureka.client.region=unavailable-region", // to force defaultZone "eureka.client.service-url.defaultZone=http://default-host2:8678/eureka/"); - this.context.publishEvent(new EnvironmentChangeEvent(new HashSet(Arrays.asList(USE_DNS, DEFAULT_ZONE)))); - - assertTrue("PeerEurekaNodes' are not updated when eureka.client.use-dns-for-fetching-service-urls is false", - serviceUrlMatches("http://default-host2:8678/eureka/")); + this.context.publishEvent(new EnvironmentChangeEvent( + new HashSet(Arrays.asList(USE_DNS, DEFAULT_ZONE)))); + + assertThat(serviceUrlMatches("http://default-host2:8678/eureka/")).as( + "PeerEurekaNodes' are not updated when eureka.client.use-dns-for-fetching-service-urls is false") + .isTrue(); } - - + @Test public void updatedWhenRegionChanged() { - changeProperty( - "eureka.client.use-dns-for-fetching-service-urls=false", + changeProperty("eureka.client.use-dns-for-fetching-service-urls=false", "eureka.client.region=region1", "eureka.client.availability-zones.region1=region1-zone", "eureka.client.availability-zones.region2=region2-zone", "eureka.client.service-url.region1-zone=http://region1-zone-host:8678/eureka/", "eureka.client.service-url.region2-zone=http://region2-zone-host:8678/eureka/"); - this.context.publishEvent(new EnvironmentChangeEvent(Collections.singleton(REGION))); - assertTrue("PeerEurekaNodes' are not updated when eureka.client.region is changed", - serviceUrlMatches("http://region1-zone-host:8678/eureka/")); - + this.context + .publishEvent(new EnvironmentChangeEvent(Collections.singleton(REGION))); + assertThat(serviceUrlMatches("http://region1-zone-host:8678/eureka/")).as( + "PeerEurekaNodes' are not updated when eureka.client.region is changed") + .isTrue(); + changeProperty("eureka.client.region=region2"); - this.context.publishEvent(new EnvironmentChangeEvent(Collections.singleton(REGION))); - assertTrue("PeerEurekaNodes' are not updated when eureka.client.region is changed", - serviceUrlMatches("http://region2-zone-host:8678/eureka/")); + this.context + .publishEvent(new EnvironmentChangeEvent(Collections.singleton(REGION))); + assertThat(serviceUrlMatches("http://region2-zone-host:8678/eureka/")).as( + "PeerEurekaNodes' are not updated when eureka.client.region is changed") + .isTrue(); } - + @Test public void updatedWhenAvailabilityZoneChanged() { - changeProperty( - "eureka.client.use-dns-for-fetching-service-urls=false", + changeProperty("eureka.client.use-dns-for-fetching-service-urls=false", "eureka.client.region=region4", "eureka.client.availability-zones.region3=region3-zone", "eureka.client.service-url.region4-zone=http://region4-zone-host:8678/eureka/", "eureka.client.service-url.defaultZone=http://default-host3:8678/eureka/"); - this.context.publishEvent(new EnvironmentChangeEvent(Collections.singleton("eureka.client.availability-zones.region3"))); - assertTrue(this.peerEurekaNodes.getPeerEurekaNodes().get(0).getServiceUrl().equals("http://default-host3:8678/eureka/")); - + this.context.publishEvent(new EnvironmentChangeEvent( + Collections.singleton("eureka.client.availability-zones.region3"))); + assertThat(this.peerEurekaNodes.getPeerEurekaNodes().get(0).getServiceUrl() + .equals("http://default-host3:8678/eureka/")).isTrue(); + changeProperty("eureka.client.availability-zones.region4=region4-zone"); - this.context.publishEvent(new EnvironmentChangeEvent(Collections.singleton("eureka.client.availability-zones.region4"))); - assertTrue("PeerEurekaNodes' are not updated when eureka.client.availability-zones are changed", - serviceUrlMatches("http://region4-zone-host:8678/eureka/")); + this.context.publishEvent(new EnvironmentChangeEvent( + Collections.singleton("eureka.client.availability-zones.region4"))); + assertThat(serviceUrlMatches("http://region4-zone-host:8678/eureka/")).as( + "PeerEurekaNodes' are not updated when eureka.client.availability-zones are changed") + .isTrue(); } - + @Test public void notUpdatedWhenIrrelevantPropertiesChanged() { // Only way to test this is verifying whether updatePeerEurekaNodes() is invoked. - - // PeerEurekaNodes.updatePeerEurekaNodes() is not public, hence cannot verify with Mockito. + + // PeerEurekaNodes.updatePeerEurekaNodes() is not public, hence cannot verify with + // Mockito. class VerifyablePeerEurekNode extends RefreshablePeerEurekaNodes { - public VerifyablePeerEurekNode(PeerAwareInstanceRegistry registry, EurekaServerConfig serverConfig, - EurekaClientConfig clientConfig, ServerCodecs serverCodecs, - ApplicationInfoManager applicationInfoManager) { - super(registry, serverConfig, clientConfig, serverCodecs, applicationInfoManager); + + VerifyablePeerEurekNode(PeerAwareInstanceRegistry registry, + EurekaServerConfig serverConfig, EurekaClientConfig clientConfig, + ServerCodecs serverCodecs, + ApplicationInfoManager applicationInfoManager) { + super(registry, serverConfig, clientConfig, serverCodecs, + applicationInfoManager); } protected void updatePeerEurekaNodes(List newPeerUrls) { super.updatePeerEurekaNodes(newPeerUrls); } + } - + // Create stubs. - final EurekaClientConfigBean configClientBean = mock(EurekaClientConfigBean.class); + final EurekaClientConfigBean configClientBean = mock( + EurekaClientConfigBean.class); when(configClientBean.isUseDnsForFetchingServiceUrls()).thenReturn(false); - final VerifyablePeerEurekNode mock = spy(new VerifyablePeerEurekNode(null, null, configClientBean, null, null)); - - mock.onApplicationEvent(new EnvironmentChangeEvent(Collections.singleton("some.irrelevant.property"))); + final VerifyablePeerEurekNode mock = spy( + new VerifyablePeerEurekNode(null, null, configClientBean, null, null)); + + mock.onApplicationEvent(new EnvironmentChangeEvent( + Collections.singleton("some.irrelevant.property"))); verify(mock, never()).updatePeerEurekaNodes(anyListOf(String.class)); } - + @Test public void peerEurekaNodesIsRefreshablePeerEurekaNodes() { - assertNotNull(this.peerEurekaNodes); - assertTrue("PeerEurekaNodes should be an instance of RefreshablePeerEurekaNodes", - this.peerEurekaNodes instanceof RefreshablePeerEurekaNodes); + assertThat(this.peerEurekaNodes).isNotNull(); + assertThat(this.peerEurekaNodes instanceof RefreshablePeerEurekaNodes) + .as("PeerEurekaNodes should be an instance of RefreshablePeerEurekaNodes") + .isTrue(); } - - + @Test public void serviceUrlsCountAsSoonAsRefreshed() { - changeProperty("eureka.client.service-url.defaultZone=http://defaul-host3:8678/eureka/,http://defaul-host4:8678/eureka/"); + changeProperty( + "eureka.client.service-url.defaultZone=http://defaul-host3:8678/eureka/,http://defaul-host4:8678/eureka/"); forceUpdate(); - assertThat("PeerEurekaNodes' peer count is incorrect.", - this.peerEurekaNodes.getPeerEurekaNodes().size(), is(2)); + assertThat(this.peerEurekaNodes.getPeerEurekaNodes().size()) + .as("PeerEurekaNodes' peer count is incorrect.").isEqualTo(2); } - - + @Test public void serviceUrlsValueAsSoonAsRefreshed() { - changeProperty("eureka.client.service-url.defaultZone=http://defaul-host4:8678/eureka/"); + changeProperty( + "eureka.client.service-url.defaultZone=http://defaul-host4:8678/eureka/"); forceUpdate(); - assertTrue("PeerEurekaNodes' new peer[0] is incorrect", - serviceUrlMatches("http://defaul-host4:8678/eureka/")); + assertThat(serviceUrlMatches("http://defaul-host4:8678/eureka/")) + .as("PeerEurekaNodes' new peer[0] is incorrect").isTrue(); } - + @Test public void dashboardUpdatedAsSoonAsRefreshed() { - changeProperty("eureka.client.service-url.defaultZone=http://defaul-host5:8678/eureka/"); + changeProperty( + "eureka.client.service-url.defaultZone=http://defaul-host5:8678/eureka/"); forceUpdate(); final ResponseEntity entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port + "/", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); final String body = entity.getBody(); - assertNotNull(body); - assertTrue("DS Replicas not updated in the Eureka Server dashboard", - body.contains("http://defaul-host5:8678/eureka/")); + assertThat(body).isNotNull(); + assertThat(body.contains("http://defaul-host5:8678/eureka/")) + .as("DS Replicas not updated in the Eureka Server dashboard").isTrue(); } - + @Test public void notUpdatedForRelaxedKeys() { - changeProperty( - "eureka.client.use-dns-for-fetching-service-urls=false", + changeProperty("eureka.client.use-dns-for-fetching-service-urls=false", "eureka.client.region=unavailable-region", // to force defaultZone "eureka.client.service-url.defaultZone=http://defaul-host6:8678/eureka/"); - this.context.publishEvent(new EnvironmentChangeEvent(Collections.singleton("eureka.client.serviceUrl.defaultZone"))); - assertFalse("PeerEurekaNodes' are updated for keys with relaxed binding", - serviceUrlMatches("http://defaul-host6:8678/eureka/")); - } - - @EnableEurekaServer - @Configuration - @EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class - }) - protected static class Application { + this.context.publishEvent(new EnvironmentChangeEvent( + Collections.singleton("eureka.client.serviceUrl.defaultZone"))); + assertThat(serviceUrlMatches("http://defaul-host6:8678/eureka/")) + .as("PeerEurekaNodes' are updated for keys with relaxed binding") + .isFalse(); } /* @@ -241,17 +243,25 @@ public class RefreshablePeerEurekaNodesTests { * Refreshes the context with properties satisfying to invoke update. */ private void forceUpdate() { - changeProperty( - "eureka.client.use-dns-for-fetching-service-urls=false", + changeProperty("eureka.client.use-dns-for-fetching-service-urls=false", "eureka.client.region=unavailable-region"); // to force defaultZone - this.context.publishEvent( - new EnvironmentChangeEvent(Collections.singleton("eureka.client.service-url.defaultZone"))); + this.context.publishEvent(new EnvironmentChangeEvent( + Collections.singleton("eureka.client.service-url.defaultZone"))); } - + /* * Whether the first element in PeerEurekaNodes matches the given url. */ private boolean serviceUrlMatches(final String serviceUrl) { - return this.peerEurekaNodes.getPeerEurekaNodes().get(0).getServiceUrl().equals(serviceUrl); + return this.peerEurekaNodes.getPeerEurekaNodes().get(0).getServiceUrl() + .equals(serviceUrl); } + + @EnableEurekaServer + @Configuration + @EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class }) + protected static class Application { + + } + } diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/AbstractDocumentationTests.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/AbstractDocumentationTests.java index b666ac095..6c9c3e513 100644 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/AbstractDocumentationTests.java +++ b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/AbstractDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,9 +18,17 @@ package org.springframework.cloud.netflix.eureka.server.doc; import java.util.UUID; +import com.netflix.appinfo.ApplicationInfoManager; +import com.netflix.appinfo.InstanceInfo; +import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl; +import io.restassured.RestAssured; +import io.restassured.builder.RequestSpecBuilder; +import io.restassured.filter.Filter; +import io.restassured.specification.RequestSpecification; import org.junit.After; import org.junit.Rule; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -38,15 +46,6 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.util.ReflectionTestUtils; -import com.netflix.appinfo.ApplicationInfoManager; -import com.netflix.appinfo.InstanceInfo; -import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl; - -import io.restassured.RestAssured; -import io.restassured.builder.RequestSpecBuilder; -import io.restassured.filter.Filter; -import io.restassured.specification.RequestSpecification; - import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest; import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse; import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; @@ -157,6 +156,7 @@ public abstract class AbstractDocumentationTests { @EnableAutoConfiguration @EnableEurekaServer protected static class Application { + } } diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/EurekaObjectMapper.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/EurekaObjectMapper.java index 412194f21..16c269a94 100644 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/EurekaObjectMapper.java +++ b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/EurekaObjectMapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,8 +12,8 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ + package org.springframework.cloud.netflix.eureka.server.doc; import java.io.ByteArrayOutputStream; @@ -25,8 +25,8 @@ import com.netflix.discovery.converters.EntityBodyConverter; import io.restassured.mapper.ObjectMapperDeserializationContext; import io.restassured.mapper.ObjectMapperSerializationContext; -final class EurekaObjectMapper - implements io.restassured.mapper.ObjectMapper { +final class EurekaObjectMapper implements io.restassured.mapper.ObjectMapper { + private EntityBodyConverter converter = new EntityBodyConverter(); @Override @@ -43,15 +43,14 @@ final class EurekaObjectMapper } @Override - public Object deserialize( - ObjectMapperDeserializationContext context) { + public Object deserialize(ObjectMapperDeserializationContext context) { try { - return converter.read( - context.getDataToDeserialize().asInputStream(), - (Class)context.getType(), MediaType.APPLICATION_JSON_TYPE); + return converter.read(context.getDataToDeserialize().asInputStream(), + (Class) context.getType(), MediaType.APPLICATION_JSON_TYPE); } catch (IOException e) { throw new IllegalStateException("Cannot deserialize", e); } } -} \ No newline at end of file + +} diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/EurekaServerTests.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/EurekaServerTests.java index 91d3e44fd..d5e123b0e 100644 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/EurekaServerTests.java +++ b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/EurekaServerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,7 +30,9 @@ import static org.hamcrest.Matchers.notNullValue; @RunWith(SpringJUnit4ClassRunner.class) // TODO: maybe this should be the default (the test fails without it because the JSON is // invalid) -@TestPropertySource(properties = {"eureka.server.minAvailableInstancesForPeerReplication=0", "spring.jmx.enabled=false"}) +@TestPropertySource(properties = { + "eureka.server.minAvailableInstancesForPeerReplication=0", + "spring.jmx.enabled=false" }) public class EurekaServerTests extends AbstractDocumentationTests { @Test diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/RequestVerifierFilter.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/RequestVerifierFilter.java index 361ebcd4d..cfc364e0a 100644 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/RequestVerifierFilter.java +++ b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/RequestVerifierFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2017 the original author or authors. + * Copyright 2016-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.netflix.eureka.server.doc; import java.util.ArrayList; @@ -43,12 +44,12 @@ import io.restassured.http.Header; import io.restassured.response.Response; import io.restassured.specification.FilterableRequestSpecification; import io.restassured.specification.FilterableResponseSpecification; +import wiremock.com.google.common.base.Optional; import org.springframework.util.Base64Utils; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; import org.springframework.web.util.UriComponentsBuilder; -import wiremock.com.google.common.base.Optional; import static org.assertj.core.api.Assertions.assertThat; @@ -56,10 +57,13 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer * */ + public class RequestVerifierFilter implements Filter { static final String CONTEXT_KEY_CONFIGURATION = "org.springframework.restdocs.configuration"; + private Map jsonPaths = new LinkedHashMap<>(); + private MappingBuilder builder; public static RequestVerifierFilter verify(String path) { @@ -136,12 +140,15 @@ public class RequestVerifierFilter implements Filter { .>getValue(CONTEXT_KEY_CONFIGURATION); return configuration; } + } class JsonPathValue { private final JsonPath jsonPath; + private final String expression; + private final CharSequence actual; JsonPathValue(JsonPath jsonPath, CharSequence actual) { @@ -201,7 +208,7 @@ class WireMockRestAssuredRequestAdapter implements Request { private FilterableRequestSpecification request; - public WireMockRestAssuredRequestAdapter(FilterableRequestSpecification request) { + WireMockRestAssuredRequestAdapter(FilterableRequestSpecification request) { this.request = request; } diff --git a/spring-cloud-netflix-eureka-server/src/test/resources/application.properties b/spring-cloud-netflix-eureka-server/src/test/resources/application.properties index 52c10d896..37328a3aa 100644 --- a/spring-cloud-netflix-eureka-server/src/test/resources/application.properties +++ b/spring-cloud-netflix-eureka-server/src/test/resources/application.properties @@ -3,4 +3,5 @@ spring.application.name=eureka eureka.client.registerWithEureka=false eureka.client.fetchRegistry=false logging.level.org.springframework.web.client=DEBUG -logging.level.com.netflix.discovery=DEBUG \ No newline at end of file +logging.level.com.netflix.discovery=DEBUG + diff --git a/spring-cloud-netflix-hystrix-contract/src/main/java/org/springframework/cloud/netflix/hystrix/contract/HystrixContractUtils.java b/spring-cloud-netflix-hystrix-contract/src/main/java/org/springframework/cloud/netflix/hystrix/contract/HystrixContractUtils.java index 156750dd6..94e42a0f2 100644 --- a/spring-cloud-netflix-hystrix-contract/src/main/java/org/springframework/cloud/netflix/hystrix/contract/HystrixContractUtils.java +++ b/spring-cloud-netflix-hystrix-contract/src/main/java/org/springframework/cloud/netflix/hystrix/contract/HystrixContractUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2017 the original author or authors. + * Copyright 2016-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,9 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.cloud.netflix.hystrix.contract; -import static org.assertj.core.api.Assertions.assertThat; +package org.springframework.cloud.netflix.hystrix.contract; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -24,12 +23,19 @@ import java.util.Map; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.util.StreamUtils; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Dave Syer * @author Daniel Lavoie * */ -public class HystrixContractUtils { +public final class HystrixContractUtils { + + private HystrixContractUtils() { + throw new AssertionError("Must not instantiate utility class."); + } + public static String simpleBody() { try { diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardConfiguration.java b/spring-cloud-netflix-hystrix-dashboard/src/main/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardConfiguration.java index 75dc7551b..4abdf70c5 100644 --- a/spring-cloud-netflix-hystrix-dashboard/src/main/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardConfiguration.java +++ b/spring-cloud-netflix-hystrix-dashboard/src/main/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,7 +67,8 @@ public class HystrixDashboardConfiguration { @Bean public HasFeatures hystrixDashboardFeature() { - return HasFeatures.namedFeature("Hystrix Dashboard", HystrixDashboardConfiguration.class); + return HasFeatures.namedFeature("Hystrix Dashboard", + HystrixDashboardConfiguration.class); } /** @@ -136,9 +137,8 @@ public class HystrixDashboardConfiguration { String origin = request.getParameter("origin"); if (origin == null) { response.setStatus(500); - response.getWriter() - .println( - "Required parameter 'origin' missing. Example: 107.20.175.135:7001"); + response.getWriter().println( + "Required parameter 'origin' missing. Example: 107.20.175.135:7001"); return; } origin = origin.trim(); @@ -204,7 +204,8 @@ public class HystrixDashboardConfiguration { .equalsIgnoreCase("ClientAbortException")) { // don't throw an exception as this means the user closed // the connection - log.debug("Connection closed by client. Will stop proxying ..."); + log.debug( + "Connection closed by client. Will stop proxying ..."); // break out of the while loop break; } @@ -262,7 +263,8 @@ public class HystrixDashboardConfiguration { && CONNECTION_CLOSE_VALUE.equalsIgnoreCase(header.getValue())) { log.warn("Ignoring 'Connection: close' header from stream response"); } - else if (!HttpHeaders.TRANSFER_ENCODING.equalsIgnoreCase(header.getName())) { + else if (!HttpHeaders.TRANSFER_ENCODING + .equalsIgnoreCase(header.getName())) { response.addHeader(header.getName(), header.getValue()); } } @@ -291,4 +293,5 @@ public class HystrixDashboardConfiguration { } } + } diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardController.java b/spring-cloud-netflix-hystrix-dashboard/src/main/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardController.java index 9c4ca3160..d9fefef33 100644 --- a/spring-cloud-netflix-hystrix-dashboard/src/main/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardController.java +++ b/spring-cloud-netflix-hystrix-dashboard/src/main/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardController.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,10 +43,10 @@ public class HystrixDashboardController { } private String extractPath(WebRequest request) { - String path = request.getContextPath() - + request.getAttribute("org.springframework." + String path = request.getContextPath() + request.getAttribute( + "org.springframework." + "web.servlet.HandlerMapping.pathWithinHandlerMapping", - RequestAttributes.SCOPE_REQUEST); + RequestAttributes.SCOPE_REQUEST); return path; } diff --git a/spring-cloud-netflix-hystrix-dashboard/src/main/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardProperties.java b/spring-cloud-netflix-hystrix-dashboard/src/main/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardProperties.java index 4223204d1..3f4a6d2a7 100644 --- a/spring-cloud-netflix-hystrix-dashboard/src/main/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardProperties.java +++ b/spring-cloud-netflix-hystrix-dashboard/src/main/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.netflix.hystrix.dashboard; import java.util.HashMap; @@ -29,10 +30,10 @@ public class HystrixDashboardProperties { /** * Directs the Hystrix dashboard to ignore 'Connection:close' headers if present in - * the Hystrix response stream + * the Hystrix response stream. */ private boolean enableIgnoreConnectionCloseHeader = false; - + /** * Initialization parameters for {@link ProxyStreamServlet}. ProxyStreamServlet itself * is not dependent on any initialization parameters, but could be used for adding web @@ -52,4 +53,5 @@ public class HystrixDashboardProperties { public Map getInitParameters() { return this.initParameters; } + } diff --git a/spring-cloud-netflix-hystrix-dashboard/src/test/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardConfigurationTests.java b/spring-cloud-netflix-hystrix-dashboard/src/test/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardConfigurationTests.java index 33d8a6444..946e5d9a3 100644 --- a/spring-cloud-netflix-hystrix-dashboard/src/test/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardConfigurationTests.java +++ b/spring-cloud-netflix-hystrix-dashboard/src/test/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,15 +21,13 @@ import java.util.Map; import org.apache.http.Header; import org.apache.http.message.BasicHeader; import org.junit.Test; + import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.util.ReflectionTestUtils; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Roy Clarkson @@ -45,9 +43,9 @@ public class HystrixDashboardConfigurationTests { headers[0] = new BasicHeader("Content-Type", "text/proxy.stream"); HystrixDashboardConfiguration.ProxyStreamServlet proxyStreamServlet = new HystrixDashboardConfiguration.ProxyStreamServlet(); ReflectionTestUtils.invokeMethod(proxyStreamServlet, - "copyHeadersToServletResponse", headers, response); - assertThat(response.getHeaderNames().size(), is(1)); - assertThat(response.getHeader("Content-Type"), is("text/proxy.stream")); + "copyHeadersToServletResponse", headers, response); + assertThat(response.getHeaderNames().size()).isEqualTo(1); + assertThat(response.getHeader("Content-Type")).isEqualTo("text/proxy.stream"); } @Test @@ -58,10 +56,10 @@ public class HystrixDashboardConfigurationTests { headers[1] = new BasicHeader("Connection", "close"); HystrixDashboardConfiguration.ProxyStreamServlet proxyStreamServlet = new HystrixDashboardConfiguration.ProxyStreamServlet(); ReflectionTestUtils.invokeMethod(proxyStreamServlet, - "copyHeadersToServletResponse", headers, response); - assertThat(response.getHeaderNames().size(), is(2)); - assertThat(response.getHeader("Content-Type"), is("text/proxy.stream")); - assertThat(response.getHeader("Connection"), is("close")); + "copyHeadersToServletResponse", headers, response); + assertThat(response.getHeaderNames().size()).isEqualTo(2); + assertThat(response.getHeader("Content-Type")).isEqualTo("text/proxy.stream"); + assertThat(response.getHeader("Connection")).isEqualTo("close"); } @Test @@ -73,10 +71,10 @@ public class HystrixDashboardConfigurationTests { HystrixDashboardConfiguration.ProxyStreamServlet proxyStreamServlet = new HystrixDashboardConfiguration.ProxyStreamServlet(); proxyStreamServlet.setEnableIgnoreConnectionCloseHeader(true); ReflectionTestUtils.invokeMethod(proxyStreamServlet, - "copyHeadersToServletResponse", headers, response); - assertThat(response.getHeaderNames().size(), is(1)); - assertThat(response.getHeader("Content-Type"), is("text/proxy.stream")); - assertNull(response.getHeader("Connection")); + "copyHeadersToServletResponse", headers, response); + assertThat(response.getHeaderNames().size()).isEqualTo(1); + assertThat(response.getHeader("Content-Type")).isEqualTo("text/proxy.stream"); + assertThat(response.getHeader("Connection")).isNull(); } @Test @@ -88,28 +86,29 @@ public class HystrixDashboardConfigurationTests { HystrixDashboardConfiguration.ProxyStreamServlet proxyStreamServlet = new HystrixDashboardConfiguration.ProxyStreamServlet(); proxyStreamServlet.setEnableIgnoreConnectionCloseHeader(false); ReflectionTestUtils.invokeMethod(proxyStreamServlet, - "copyHeadersToServletResponse", headers, response); - assertThat(response.getHeaderNames().size(), is(2)); - assertThat(response.getHeader("Content-Type"), is("text/proxy.stream")); - assertThat(response.getHeader("Connection"), is("close")); + "copyHeadersToServletResponse", headers, response); + assertThat(response.getHeaderNames().size()).isEqualTo(2); + assertThat(response.getHeader("Content-Type")).isEqualTo("text/proxy.stream"); + assertThat(response.getHeader("Connection")).isEqualTo("close"); } @Test public void initParameters() { new ApplicationContextRunner() - .withUserConfiguration(HystrixDashboardConfiguration.class) - .withPropertyValues( - "hystrix.dashboard.init-parameters.wl-dispatch-polixy=work-manager-hystrix") - .run(context -> { - final ServletRegistrationBean registration = context - .getBean(ServletRegistrationBean.class); - assertNotNull(registration); + .withUserConfiguration(HystrixDashboardConfiguration.class) + .withPropertyValues( + "hystrix.dashboard.init-parameters.wl-dispatch-polixy=work-manager-hystrix") + .run(context -> { + final ServletRegistrationBean registration = context + .getBean(ServletRegistrationBean.class); + assertThat(registration).isNotNull(); - final Map initParameters = registration - .getInitParameters(); - assertNotNull(initParameters); - assertThat(initParameters.get("wl-dispatch-polixy"), - is("work-manager-hystrix")); - }); + final Map initParameters = registration + .getInitParameters(); + assertThat(initParameters).isNotNull(); + assertThat(initParameters.get("wl-dispatch-polixy")) + .isEqualTo("work-manager-hystrix"); + }); } -} \ No newline at end of file + +} diff --git a/spring-cloud-netflix-hystrix-dashboard/src/test/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardContextTests.java b/spring-cloud-netflix-hystrix-dashboard/src/test/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardContextTests.java index fe8724d6c..12954aa98 100644 --- a/spring-cloud-netflix-hystrix-dashboard/src/test/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardContextTests.java +++ b/spring-cloud-netflix-hystrix-dashboard/src/test/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,13 +12,13 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.hystrix.dashboard; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; @@ -30,20 +30,20 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer * */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT, - properties = { "spring.application.name=hystrix-dashboard", +@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT, properties = { + "spring.application.name=hystrix-dashboard", "server.servlet.context-path=/context" }) public class HystrixDashboardContextTests { public static final String JQUERY_PATH = "/context/webjars/jquery/2.1.1/jquery.min.js"; + @LocalServerPort private int port = 0; @@ -51,20 +51,20 @@ public class HystrixDashboardContextTests { public void homePage() { ResponseEntity entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/context/hystrix", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); String body = entity.getBody(); - assertTrue("wrong base path rendered in template", - body.contains("base href=\"/context/hystrix\"")); + assertThat(body.contains("base href=\"/context/hystrix\"")) + .as("wrong base path rendered in template").isTrue(); } @Test public void correctJavascriptLink() { ResponseEntity entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/context/hystrix", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); String body = entity.getBody(); - assertTrue("wrong jquery path rendered in template", - body.contains("src=\""+JQUERY_PATH+"\"")); + assertThat(body.contains("src=\"" + JQUERY_PATH + "\"")) + .as("wrong jquery path rendered in template").isTrue(); } @Test @@ -72,14 +72,14 @@ public class HystrixDashboardContextTests { ResponseEntity entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/context/hystrix/css/global.css", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void webjarsAvailable() { ResponseEntity entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + JQUERY_PATH, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test @@ -87,16 +87,17 @@ public class HystrixDashboardContextTests { ResponseEntity entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/context/hystrix/monitor", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); String body = entity.getBody(); - assertTrue("wrong base path rendered in template", - body.contains("base href=\"/context/hystrix/monitor\"")); + assertThat(body.contains("base href=\"/context/hystrix/monitor\"")) + .as("wrong base path rendered in template").isTrue(); } @Configuration @EnableAutoConfiguration @EnableHystrixDashboard protected static class Application { + } } diff --git a/spring-cloud-netflix-hystrix-dashboard/src/test/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardHomePageTests.java b/spring-cloud-netflix-hystrix-dashboard/src/test/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardHomePageTests.java index 5e6c38b89..3bb99eb5e 100644 --- a/spring-cloud-netflix-hystrix-dashboard/src/test/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardHomePageTests.java +++ b/spring-cloud-netflix-hystrix-dashboard/src/test/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardHomePageTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,6 +18,7 @@ package org.springframework.cloud.netflix.hystrix.dashboard; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -31,7 +32,7 @@ import org.springframework.stereotype.Controller; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.bind.annotation.RequestMapping; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -49,7 +50,7 @@ public class HystrixDashboardHomePageTests { public void homePage() { ResponseEntity entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); entity.getBody().contains(""); } @@ -58,14 +59,14 @@ public class HystrixDashboardHomePageTests { ResponseEntity entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/hystrix/css/global.css", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void monitorPage() { ResponseEntity entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/hystrix/monitor", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Configuration diff --git a/spring-cloud-netflix-hystrix-dashboard/src/test/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardTests.java b/spring-cloud-netflix-hystrix-dashboard/src/test/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardTests.java index c1f003026..5d47687f8 100644 --- a/spring-cloud-netflix-hystrix-dashboard/src/test/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardTests.java +++ b/spring-cloud-netflix-hystrix-dashboard/src/test/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,6 +18,7 @@ package org.springframework.cloud.netflix.hystrix.dashboard; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -29,8 +30,7 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -47,11 +47,11 @@ public class HystrixDashboardTests { public void homePage() { ResponseEntity entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port + "/hystrix", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); String body = entity.getBody(); - assertTrue(body.contains("")); - assertTrue(body.contains("\"/webjars")); - assertTrue(body.contains("= \"/hystrix/monitor")); + assertThat(body.contains("")).isTrue(); + assertThat(body.contains("\"/webjars")).isTrue(); + assertThat(body.contains("= \"/hystrix/monitor")).isTrue(); } @Test @@ -59,22 +59,23 @@ public class HystrixDashboardTests { ResponseEntity entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/hystrix/css/global.css", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void monitorPage() { ResponseEntity entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/hystrix/monitor", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); String body = entity.getBody(); - assertTrue(body.contains("")); + assertThat(body.contains("")).isTrue(); } @Configuration @EnableAutoConfiguration @EnableHystrixDashboard protected static class Application { + } } diff --git a/spring-cloud-netflix-hystrix-stream/src/main/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamAutoConfiguration.java b/spring-cloud-netflix-hystrix-stream/src/main/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamAutoConfiguration.java index ad062aa55..e742b7867 100644 --- a/spring-cloud-netflix-hystrix-stream/src/main/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamAutoConfiguration.java +++ b/spring-cloud-netflix-hystrix-stream/src/main/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,6 +18,8 @@ package org.springframework.cloud.netflix.hystrix.stream; import javax.annotation.PostConstruct; +import com.netflix.hystrix.HystrixCircuitBreaker; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; @@ -37,8 +39,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.messaging.MessageChannel; import org.springframework.scheduling.annotation.EnableScheduling; -import com.netflix.hystrix.HystrixCircuitBreaker; - /** * Autoconfiguration for a Spring Cloud Hystrix on Spring Cloud Stream. Enabled by default * if spring-cloud-stream is on the classpath, and can be switched off with @@ -56,7 +56,8 @@ import com.netflix.hystrix.HystrixCircuitBreaker; @EnableConfigurationProperties @EnableScheduling @EnableBinding(HystrixStreamClient.class) -@AutoConfigureBefore(BindingServiceConfiguration.class) // Needed for bindings done in auto config +@AutoConfigureBefore(BindingServiceConfiguration.class) // Needed for bindings done in +// auto config public class HystrixStreamAutoConfiguration { @Autowired @@ -102,7 +103,8 @@ public class HystrixStreamAutoConfiguration { } @Bean - public HystrixStreamTask hystrixStreamTask(SimpleDiscoveryProperties simpleDiscoveryProperties) { + public HystrixStreamTask hystrixStreamTask( + SimpleDiscoveryProperties simpleDiscoveryProperties) { ServiceInstance serviceInstance = this.registration; if (serviceInstance == null) { serviceInstance = simpleDiscoveryProperties.getLocal(); diff --git a/spring-cloud-netflix-hystrix-stream/src/main/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamClient.java b/spring-cloud-netflix-hystrix-stream/src/main/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamClient.java index 107053fbc..a00d3704d 100644 --- a/spring-cloud-netflix-hystrix-stream/src/main/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamClient.java +++ b/spring-cloud-netflix-hystrix-stream/src/main/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamClient.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,13 +20,22 @@ import org.springframework.cloud.stream.annotation.Output; import org.springframework.messaging.MessageChannel; /** - * @author Dave Syer + * Store Hystrix Stream Client output information. * + * @author Dave Syer */ public interface HystrixStreamClient { + /** + * Hystrix Stream Output channel name. + */ String OUTPUT = "hystrixStreamOutput"; + /** + * Provides Hystrix Stream Output setup. + * @return corresponding {@link MessageChannel} instance + */ @Output(OUTPUT) MessageChannel hystrixStreamOutput(); + } diff --git a/spring-cloud-netflix-hystrix-stream/src/main/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamProperties.java b/spring-cloud-netflix-hystrix-stream/src/main/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamProperties.java index 86db29d8d..862c20576 100644 --- a/spring-cloud-netflix-hystrix-stream/src/main/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamProperties.java +++ b/spring-cloud-netflix-hystrix-stream/src/main/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,7 +34,10 @@ public class HystrixStreamProperties { /** Flag to indicate to send the id field in the metrics. Default is true */ private boolean sendId = true; - /** The destination of the stream. Destination as defined by Spring Cloud Stream. Defaults to springCloudHystrixStream */ + /** + * The destination of the stream. Destination as defined by Spring Cloud Stream. + * Defaults to springCloudHystrixStream + */ private String destination = HystrixConstants.HYSTRIX_STREAM_DESTINATION; /** The content type of the messages. Defaults to application/json */ @@ -43,10 +46,15 @@ public class HystrixStreamProperties { /** How often (in ms) to send messages to the stream. Defaults to 500. */ private long sendRate = 500; - /** How often to put messages in the queue. This queue drains to the stream. Defaults to 500. */ + /** + * How often to put messages in the queue. This queue drains to the stream. Defaults + * to 500. + */ private long gatherRate = 500; - /** The size of the metrics queue. This queue drains to the stream. Defaults to 1000. */ + /** + * The size of the metrics queue. This queue drains to the stream. Defaults to 1000. + */ private int size = 1000; public boolean isEnabled() { diff --git a/spring-cloud-netflix-hystrix-stream/src/main/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamTask.java b/spring-cloud-netflix-hystrix-stream/src/main/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamTask.java index 32cbba0c7..b7090cadc 100644 --- a/spring-cloud-netflix-hystrix-stream/src/main/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamTask.java +++ b/spring-cloud-netflix-hystrix-stream/src/main/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamTask.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,8 +22,18 @@ import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.LinkedBlockingQueue; +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.JsonGenerator; +import com.netflix.hystrix.HystrixCircuitBreaker; +import com.netflix.hystrix.HystrixCommandKey; +import com.netflix.hystrix.HystrixCommandMetrics; +import com.netflix.hystrix.HystrixCommandProperties; +import com.netflix.hystrix.HystrixThreadPoolKey; +import com.netflix.hystrix.HystrixThreadPoolMetrics; +import com.netflix.hystrix.util.HystrixRollingNumberEvent; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.beans.BeansException; import org.springframework.cloud.client.ServiceInstance; import org.springframework.context.ApplicationContext; @@ -34,19 +44,8 @@ import org.springframework.messaging.support.MessageBuilder; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.util.Assert; -import com.fasterxml.jackson.core.JsonFactory; -import com.fasterxml.jackson.core.JsonGenerator; -import com.netflix.hystrix.HystrixCircuitBreaker; -import com.netflix.hystrix.HystrixCommandKey; -import com.netflix.hystrix.HystrixCommandMetrics; -import com.netflix.hystrix.HystrixCommandProperties; -import com.netflix.hystrix.HystrixThreadPoolKey; -import com.netflix.hystrix.HystrixThreadPoolMetrics; -import com.netflix.hystrix.util.HystrixRollingNumberEvent; - /** * @author Spencer Gibb - * * @see com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsPoller (nested * private class MetricsPoller) */ @@ -67,8 +66,8 @@ public class HystrixStreamTask implements ApplicationContextAware { private final JsonFactory jsonFactory = new JsonFactory(); - public HystrixStreamTask(MessageChannel outboundChannel, - ServiceInstance registration, HystrixStreamProperties properties) { + public HystrixStreamTask(MessageChannel outboundChannel, ServiceInstance registration, + HystrixStreamProperties properties) { Assert.notNull(outboundChannel, "outboundChannel may not be null"); Assert.notNull(registration, "registration may not be null"); Assert.notNull(properties, "properties may not be null"); diff --git a/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamAutoConfigurationNoRegistrationTests.java b/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamAutoConfigurationNoRegistrationTests.java index 416373f9d..e05d093c5 100644 --- a/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamAutoConfigurationNoRegistrationTests.java +++ b/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamAutoConfigurationNoRegistrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.hystrix.stream; @@ -35,7 +34,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Spencer Gibb */ @RunWith(SpringRunner.class) -@SpringBootTest({"eureka.client.enabled=false"}) +@SpringBootTest({ "eureka.client.enabled=false" }) @DirtiesContext public class HystrixStreamAutoConfigurationNoRegistrationTests { @@ -52,12 +51,14 @@ public class HystrixStreamAutoConfigurationNoRegistrationTests { public void withoutRegistrationWorks() throws Exception { assertThat(this.registration).isNull(); assertThat(this.simpleDiscoveryProperties).isNotNull(); - assertThat(task.getRegistration()).isEqualTo(this.simpleDiscoveryProperties.getLocal()); + assertThat(task.getRegistration()) + .isEqualTo(this.simpleDiscoveryProperties.getLocal()); } @EnableAutoConfiguration @SpringBootConfiguration protected static class Config { + } } diff --git a/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamAutoConfigurationTests.java b/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamAutoConfigurationTests.java index 92a3aabe0..f648ef266 100644 --- a/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamAutoConfigurationTests.java +++ b/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.hystrix.stream; @@ -50,6 +49,7 @@ public class HystrixStreamAutoConfigurationTests { @EnableAutoConfiguration @SpringBootConfiguration protected static class Config { + } } diff --git a/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamTaskTests.java b/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamTaskTests.java index 7a98c4ec1..b27f17c07 100644 --- a/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamTaskTests.java +++ b/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamTaskTests.java @@ -1,25 +1,40 @@ -package org.springframework.cloud.netflix.hystrix.stream; +/* + * Copyright 2016-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Spy; -import org.mockito.runners.MockitoJUnitRunner; -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.cloud.client.serviceregistry.Registration; -import org.springframework.context.ApplicationContext; -import org.springframework.messaging.Message; -import org.springframework.messaging.MessageChannel; +package org.springframework.cloud.netflix.hystrix.stream; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixCommandMetrics; import com.netflix.hystrix.HystrixCommandProperties; import com.netflix.hystrix.strategy.properties.HystrixPropertiesCommandDefault; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.runners.MockitoJUnitRunner; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; +import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.cloud.client.serviceregistry.Registration; +import org.springframework.context.ApplicationContext; +import org.springframework.messaging.Message; +import org.springframework.messaging.MessageChannel; + +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.then; import static org.mockito.Matchers.any; import static org.mockito.Mockito.verifyZeroInteractions; @@ -29,12 +44,24 @@ import static org.mockito.Mockito.verifyZeroInteractions; */ @RunWith(MockitoJUnitRunner.class) public class HystrixStreamTaskTests { - @Mock MessageChannel outboundChannel; - @Mock DiscoveryClient discoveryClient; - @Mock ApplicationContext context; - @Spy HystrixStreamProperties properties; - @Mock Registration registration; - @InjectMocks HystrixStreamTask hystrixStreamTask; + + @Mock + MessageChannel outboundChannel; + + @Mock + DiscoveryClient discoveryClient; + + @Mock + ApplicationContext context; + + @Spy + HystrixStreamProperties properties; + + @Mock + Registration registration; + + @InjectMocks + HystrixStreamTask hystrixStreamTask; @Test public void should_not_send_metrics_when_they_are_empty() throws Exception { @@ -54,14 +81,17 @@ public class HystrixStreamTaskTests { @Test public void should_gather_json_metrics() throws Exception { - HystrixCommandKey hystrixCommandKey = HystrixCommandKey.Factory.asKey("commandKey"); + HystrixCommandKey hystrixCommandKey = HystrixCommandKey.Factory + .asKey("commandKey"); HystrixCommandMetrics.getInstance(hystrixCommandKey, HystrixCommandGroupKey.Factory.asKey("commandGroupKey"), - new HystrixPropertiesCommandDefault(hystrixCommandKey, HystrixCommandProperties.defaultSetter())); + new HystrixPropertiesCommandDefault(hystrixCommandKey, + HystrixCommandProperties.defaultSetter())); this.hystrixStreamTask.setApplicationContext(this.context); this.hystrixStreamTask.gatherMetrics(); - assertThat(this.hystrixStreamTask.jsonMetrics.isEmpty(), is(false)); + assertThat(this.hystrixStreamTask.jsonMetrics.isEmpty()).isFalse(); } + } diff --git a/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamTests.java b/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamTests.java index 251343913..587d10a3b 100644 --- a/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamTests.java +++ b/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/HystrixStreamTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.hystrix.stream; @@ -46,8 +45,8 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Daniel Lavoie */ @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { - "debug=true", "spring.jmx.enabled=true", "spring.application.name=mytestapp" }) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "debug=true", + "spring.jmx.enabled=true", "spring.application.name=mytestapp" }) @DirtiesContext public class HystrixStreamTests { @@ -70,6 +69,22 @@ public class HystrixStreamTests { @Qualifier(HystrixStreamClient.OUTPUT) private MessageChannel output; + @Test + public void contextLoads() throws Exception { + this.application.hello(); + // It is important that local service instance resolves for metrics + // origin details to be populated + assertThat(this.registration).isNotNull(); + assertThat(this.registration.getServiceId()).isEqualTo("mytestapp"); + this.task.gatherMetrics(); + Message message = this.collector.forChannel(output).take(); + JsonNode tree = mapper.readTree((String) message.getPayload()); + assertThat(tree.hasNonNull("origin")).isTrue(); + assertThat(tree.hasNonNull("data")).isTrue(); + assertThat(tree.hasNonNull("event")).isTrue(); + assertThat(tree.findValue("event").asText()).isEqualTo("message"); + } + @EnableAutoConfiguration @EnableCircuitBreaker @RestController @@ -81,22 +96,7 @@ public class HystrixStreamTests { public String hello() { return "Hello World"; } - } - @Test - public void contextLoads() throws Exception { - this.application.hello(); - // It is important that local service instance resolves for metrics - // origin details to be populated - assertThat(this.registration).isNotNull(); - assertThat(this.registration.getServiceId()).isEqualTo("mytestapp"); - this.task.gatherMetrics(); - Message message = this.collector.forChannel(output).take(); - JsonNode tree = mapper.readTree((String)message.getPayload()); - assertThat(tree.hasNonNull("origin")).isTrue(); - assertThat(tree.hasNonNull("data")).isTrue(); - assertThat(tree.hasNonNull("event")).isTrue(); - assertThat(tree.findValue("event").asText()).isEqualTo("message"); } } diff --git a/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/StreamSourceTestBase.java b/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/StreamSourceTestBase.java index 9d7e68642..0da71648a 100644 --- a/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/StreamSourceTestBase.java +++ b/spring-cloud-netflix-hystrix-stream/src/test/java/org/springframework/cloud/netflix/hystrix/stream/StreamSourceTestBase.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.hystrix.stream; @@ -22,7 +21,6 @@ import java.util.concurrent.TimeUnit; import com.fasterxml.jackson.databind.ObjectMapper; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; - import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -62,7 +60,8 @@ import org.springframework.web.bind.annotation.RestController; * @author Marius Bogoevici */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = TestApplication.class, properties = {"spring.application.name=application"}) +@SpringBootTest(classes = TestApplication.class, properties = { + "spring.application.name=application" }) @AutoConfigureMessageVerifier public abstract class StreamSourceTestBase { @@ -113,6 +112,7 @@ public abstract class StreamSourceTestBase { ApplicationContext applicationContext) { return new PatchedStubMessages(applicationContext); } + } static class PatchedStubMessages implements MessageVerifier> { @@ -121,10 +121,12 @@ public abstract class StreamSourceTestBase { .getLogger(StreamStubMessages.class); private final ApplicationContext context; + private final MessageCollector messageCollector; + private final ContractVerifierStreamMessageBuilder builder = new ContractVerifierStreamMessageBuilder(); - public PatchedStubMessages(ApplicationContext context) { + PatchedStubMessages(ApplicationContext context) { this.context = context; this.messageCollector = context.getBean(MessageCollector.class); } @@ -160,7 +162,8 @@ public abstract class StreamSourceTestBase { if (message == null) { return message; } - return MessageBuilder.createMessage(message.getPayload(), message.getHeaders()); + return MessageBuilder.createMessage(message.getPayload(), + message.getHeaders()); } catch (Exception e) { log.error("Exception occurred while trying to read a message from " @@ -235,4 +238,5 @@ public abstract class StreamSourceTestBase { } } + } diff --git a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixAutoConfiguration.java b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixAutoConfiguration.java index d7f6f01d1..6664d031a 100644 --- a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixAutoConfiguration.java +++ b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.hystrix; @@ -52,7 +51,8 @@ import static org.springframework.boot.autoconfigure.condition.ConditionalOnWebA * @author Dave Syer */ @Configuration -@ConditionalOnClass({ Hystrix.class, HealthIndicator.class, HealthIndicatorAutoConfiguration.class }) +@ConditionalOnClass({ Hystrix.class, HealthIndicator.class, + HealthIndicatorAutoConfiguration.class }) @AutoConfigureAfter({ HealthIndicatorAutoConfiguration.class }) public class HystrixAutoConfiguration { @@ -66,14 +66,17 @@ public class HystrixAutoConfiguration { @ConditionalOnProperty(value = "management.metrics.binders.hystrix.enabled", matchIfMissing = true) @ConditionalOnClass({ HystrixMetricsBinder.class }) protected static class HystrixMetricsConfiguration { + @Bean public HystrixMetricsBinder hystrixMetricsBinder() { return new HystrixMetricsBinder(); } + } /** - * See original {@link org.springframework.boot.actuate.autoconfigure.jolokia.JolokiaEndpointAutoConfiguration} + * See original + * {@link org.springframework.boot.actuate.autoconfigure.jolokia.JolokiaEndpointAutoConfiguration}. */ @Configuration @ConditionalOnWebApplication(type = SERVLET) @@ -90,8 +93,10 @@ public class HystrixAutoConfiguration { @Bean public HasFeatures hystrixStreamFeature() { - return HasFeatures.namedFeature("Hystrix Stream Servlet", HystrixMetricsStreamServlet.class); + return HasFeatures.namedFeature("Hystrix Stream Servlet", + HystrixMetricsStreamServlet.class); } + } @Configuration @@ -104,15 +109,21 @@ public class HystrixAutoConfiguration { @Bean @ConditionalOnEnabledEndpoint public HystrixWebfluxEndpoint hystrixWebfluxController() { - Observable serializedDashboardData = HystrixDashboardStream.getInstance().observe() - .concatMap(dashboardData -> Observable.from(SerialHystrixDashboardData.toMultipleJsonStrings(dashboardData))); - Publisher publisher = RxReactiveStreams.toPublisher(serializedDashboardData); + Observable serializedDashboardData = HystrixDashboardStream + .getInstance().observe() + .concatMap(dashboardData -> Observable.from(SerialHystrixDashboardData + .toMultipleJsonStrings(dashboardData))); + Publisher publisher = RxReactiveStreams + .toPublisher(serializedDashboardData); return new HystrixWebfluxEndpoint(publisher); } @Bean public HasFeatures hystrixStreamFeature() { - return HasFeatures.namedFeature("Hystrix Stream Webflux", HystrixWebfluxEndpoint.class); + return HasFeatures.namedFeature("Hystrix Stream Webflux", + HystrixWebfluxEndpoint.class); } + } + } diff --git a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixCircuitBreakerConfiguration.java b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixCircuitBreakerConfiguration.java index 8a15c1cc6..75d7eb291 100644 --- a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixCircuitBreakerConfiguration.java +++ b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixCircuitBreakerConfiguration.java @@ -1,11 +1,11 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,16 +16,16 @@ package org.springframework.cloud.netflix.hystrix; +import com.netflix.hystrix.Hystrix; +import com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect; import org.apache.catalina.core.ApplicationContext; + import org.springframework.beans.factory.DisposableBean; import org.springframework.cloud.client.actuator.HasFeatures; import org.springframework.cloud.client.actuator.NamedFeature; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import com.netflix.hystrix.Hystrix; -import com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect; - /** * @author Spencer Gibb * @author Christian Dupuis @@ -46,7 +46,8 @@ public class HystrixCircuitBreakerConfiguration { @Bean public HasFeatures hystrixFeature() { - return HasFeatures.namedFeatures(new NamedFeature("Hystrix", HystrixCommandAspect.class)); + return HasFeatures + .namedFeatures(new NamedFeature("Hystrix", HystrixCommandAspect.class)); } /** diff --git a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixCommands.java b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixCommands.java index 8d94a7722..1dc048ffa 100644 --- a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixCommands.java +++ b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixCommands.java @@ -1,11 +1,11 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -18,40 +18,63 @@ package org.springframework.cloud.netflix.hystrix; import java.util.function.Function; -import org.reactivestreams.Publisher; -import org.springframework.util.StringUtils; - import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixCommandProperties; import com.netflix.hystrix.HystrixObservableCommand; import com.netflix.hystrix.HystrixObservableCommand.Setter; - +import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import rx.Observable; import rx.RxReactiveStreams; +import org.springframework.util.StringUtils; + /** * Utility class to wrap a {@see Publisher} in a {@see HystrixObservableCommand}. Good for * use in a Spring WebFlux application. Allows more flexibility than the @HystrixCommand * annotation. + * * @author Spencer Gibb */ -public class HystrixCommands { +public final class HystrixCommands { + private HystrixCommands() { + throw new AssertionError("Must not instantiate utility class."); + } + + /** + * @param publisher A {@link Publisher} to pass to the new + * {@link PublisherHystrixCommand} + * @param type of the {@link Publisher}s to be built by the returned builder + * @return a builder for Hystrix-command-specific {@link Publisher}s + */ public static PublisherBuilder from(Publisher publisher) { return new PublisherBuilder<>(publisher); } + /** + * A builder class for building Hystrix-command-specific {@link Publisher}s. + * + * @param type of the {@link Publisher}s to be built + */ public static class PublisherBuilder { + private final Publisher publisher; + private String commandName; + private String groupName; + private Function> fallback; + private Setter setter; + private HystrixCommandProperties.Setter commandProperties; + private boolean eager = false; + private Function, Observable> toObservable; public PublisherBuilder(Publisher publisher) { @@ -104,18 +127,21 @@ public class HystrixCommands { return this; } - public PublisherBuilder toObservable(Function, Observable> toObservable) { + public PublisherBuilder toObservable( + Function, Observable> toObservable) { this.toObservable = toObservable; return this; } public Publisher build() { if (!StringUtils.hasText(commandName) && setter == null) { - throw new IllegalStateException("commandName and setter can not both be empty"); + throw new IllegalStateException( + "commandName and setter can not both be empty"); } Setter setterToUse = getSetter(); - PublisherHystrixCommand command = new PublisherHystrixCommand<>(setterToUse, this.publisher, this.fallback); + PublisherHystrixCommand command = new PublisherHystrixCommand<>( + setterToUse, this.publisher, this.fallback); Observable observable = getObservableFunction().apply(command); @@ -127,9 +153,11 @@ public class HystrixCommands { if (this.toObservable != null) { observableFunc = this.toObservable; - } else if (this.eager) { + } + else if (this.eager) { observableFunc = cmd -> cmd.observe(); - } else { // apply a default onBackpressureBuffer if not eager + } + else { // apply a default onBackpressureBuffer if not eager observableFunc = cmd -> cmd.toObservable().onBackpressureBuffer(); } return observableFunc; @@ -139,19 +167,22 @@ public class HystrixCommands { Setter setterToUse; if (this.setter != null) { setterToUse = this.setter; - } else { + } + else { String groupNameToUse; if (StringUtils.hasText(this.groupName)) { groupNameToUse = this.groupName; - } else { + } + else { groupNameToUse = commandName + "group"; } - HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey(groupNameToUse); - HystrixCommandKey commandKey = HystrixCommandKey.Factory.asKey(this.commandName); + HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory + .asKey(groupNameToUse); + HystrixCommandKey commandKey = HystrixCommandKey.Factory + .asKey(this.commandName); HystrixCommandProperties.Setter commandProperties = this.commandProperties != null - ? this.commandProperties - : HystrixCommandProperties.Setter(); + ? this.commandProperties : HystrixCommandProperties.Setter(); setterToUse = Setter.withGroupKey(groupKey).andCommandKey(commandKey) .andCommandPropertiesDefaults(commandProperties); } @@ -171,6 +202,7 @@ public class HystrixCommands { private static class PublisherHystrixCommand extends HystrixObservableCommand { private Publisher publisher; + private Function> fallback; protected PublisherHystrixCommand(Setter setter, Publisher publisher, @@ -193,5 +225,7 @@ public class HystrixCommands { } return super.resumeWithFallback(); } + } + } diff --git a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixConstants.java b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixConstants.java index 073eec025..a1e167b2c 100644 --- a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixConstants.java +++ b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixConstants.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,11 @@ package org.springframework.cloud.netflix.hystrix; /** * @author Spencer Gibb */ -public class HystrixConstants { +public final class HystrixConstants { + /** + * Hystrix stream destination name. + */ public static final String HYSTRIX_STREAM_DESTINATION = "springCloudHystrixStream"; private HystrixConstants() { diff --git a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixHealthIndicator.java b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixHealthIndicator.java index fb1a8bfe5..e95946d16 100644 --- a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixHealthIndicator.java +++ b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,18 +19,18 @@ package org.springframework.cloud.netflix.hystrix; import java.util.ArrayList; import java.util.List; +import com.netflix.hystrix.HystrixCircuitBreaker; +import com.netflix.hystrix.HystrixCommandMetrics; + import org.springframework.boot.actuate.health.AbstractHealthIndicator; import org.springframework.boot.actuate.health.Health.Builder; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.boot.actuate.health.Status; -import com.netflix.hystrix.HystrixCircuitBreaker; -import com.netflix.hystrix.HystrixCommandMetrics; - /** * A {@link HealthIndicator} implementation for Hystrix circuit breakers. *

- * This default implementation will not change the system state (e.g. OK) but + * This default implementation will not change the system state (e.g. OK) but * includes all open circuits by name. * * @author Christian Dupuis diff --git a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixMetricsProperties.java b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixMetricsProperties.java index 5501efd6a..1deea322d 100644 --- a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixMetricsProperties.java +++ b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixMetricsProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,10 +16,10 @@ package org.springframework.cloud.netflix.hystrix; -import org.springframework.boot.context.properties.ConfigurationProperties; - import java.util.Objects; +import org.springframework.boot.context.properties.ConfigurationProperties; + /** * @author Venil Noronha * @author Gregor Zurowski @@ -51,11 +51,15 @@ public class HystrixMetricsProperties { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } HystrixMetricsProperties that = (HystrixMetricsProperties) o; - return enabled == that.enabled && - Objects.equals(pollingIntervalMs, that.pollingIntervalMs); + return enabled == that.enabled + && Objects.equals(pollingIntervalMs, that.pollingIntervalMs); } @Override @@ -65,9 +69,9 @@ public class HystrixMetricsProperties { @Override public String toString() { - return new StringBuilder("HystrixMetricsProperties{") - .append("enabled=").append(enabled).append(", ") - .append("pollingIntervalMs=").append(pollingIntervalMs) - .append("}").toString(); + return new StringBuilder("HystrixMetricsProperties{").append("enabled=") + .append(enabled).append(", ").append("pollingIntervalMs=") + .append(pollingIntervalMs).append("}").toString(); } + } diff --git a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixProperties.java b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixProperties.java index 2039c62c1..620ff2f50 100644 --- a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixProperties.java +++ b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.hystrix; @@ -42,4 +41,3 @@ public class HystrixProperties { } } - diff --git a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixStreamEndpoint.java b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixStreamEndpoint.java index af2d870b9..5fb241e5a 100644 --- a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixStreamEndpoint.java +++ b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixStreamEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,20 +12,21 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.hystrix; -import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet; -import org.springframework.boot.actuate.endpoint.web.EndpointServlet; -import org.springframework.boot.actuate.endpoint.web.annotation.ServletEndpoint; - import java.util.Map; import java.util.function.Supplier; +import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet; + +import org.springframework.boot.actuate.endpoint.web.EndpointServlet; +import org.springframework.boot.actuate.endpoint.web.annotation.ServletEndpoint; + /** - * {@link org.springframework.boot.actuate.endpoint.annotation.Endpoint} to expose a Jolokia {@link HystrixMetricsStreamServlet}. + * {@link org.springframework.boot.actuate.endpoint.annotation.Endpoint} to expose a + * Jolokia {@link HystrixMetricsStreamServlet}. * * @author Phillip Webb * @since 2.0.0 @@ -33,15 +34,16 @@ import java.util.function.Supplier; @ServletEndpoint(id = "hystrix.stream") public class HystrixStreamEndpoint implements Supplier { - private final Map initParameters; + private final Map initParameters; - public HystrixStreamEndpoint(Map initParameters) { - this.initParameters = initParameters; - } + public HystrixStreamEndpoint(Map initParameters) { + this.initParameters = initParameters; + } + + @Override + public EndpointServlet get() { + return new EndpointServlet(HystrixMetricsStreamServlet.class) + .withInitParameters(this.initParameters); + } - @Override - public EndpointServlet get() { - return new EndpointServlet(HystrixMetricsStreamServlet.class) - .withInitParameters(this.initParameters); - } } diff --git a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixWebfluxEndpoint.java b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixWebfluxEndpoint.java index a9f4f220d..88eff84ea 100644 --- a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixWebfluxEndpoint.java +++ b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixWebfluxEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.hystrix; @@ -20,28 +19,29 @@ package org.springframework.cloud.netflix.hystrix; import java.time.Duration; import org.reactivestreams.Publisher; +import reactor.core.publisher.Flux; + import org.springframework.boot.actuate.endpoint.web.annotation.RestControllerEndpoint; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; -import reactor.core.publisher.Flux; - /** * @author Spencer Gibb */ @RestControllerEndpoint(id = "hystrix.stream") public class HystrixWebfluxEndpoint { - private final Flux stream; + private final Flux stream; - public HystrixWebfluxEndpoint(Publisher dashboardData) { - stream = Flux.interval(Duration.ofMillis(500)).map(aLong -> "{\"type\":\"ping\"}") - .mergeWith(dashboardData).share(); - } + public HystrixWebfluxEndpoint(Publisher dashboardData) { + stream = Flux.interval(Duration.ofMillis(500)).map(aLong -> "{\"type\":\"ping\"}") + .mergeWith(dashboardData).share(); + } + + // path needs to be empty, so it registers correct as /actuator/hystrix.stream + @GetMapping(path = "", produces = MediaType.TEXT_EVENT_STREAM_VALUE) + public Flux hystrixStream() { + return stream; + } - // path needs to be empty, so it registers correct as /actuator/hystrix.stream - @GetMapping(path = "", produces = MediaType.TEXT_EVENT_STREAM_VALUE) - public Flux hystrixStream() { - return stream; - } } diff --git a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityAutoConfiguration.java b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityAutoConfiguration.java index d2eddf08f..3e2f4a6a6 100644 --- a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityAutoConfiguration.java +++ b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,9 +18,17 @@ package org.springframework.cloud.netflix.hystrix.security; import javax.annotation.PostConstruct; +import com.netflix.hystrix.Hystrix; +import com.netflix.hystrix.strategy.HystrixPlugins; +import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy; import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategyDefault; +import com.netflix.hystrix.strategy.eventnotifier.HystrixEventNotifier; +import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook; +import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisher; +import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.AllNestedConditions; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; @@ -30,14 +38,6 @@ import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import org.springframework.security.core.context.SecurityContext; -import com.netflix.hystrix.Hystrix; -import com.netflix.hystrix.strategy.HystrixPlugins; -import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy; -import com.netflix.hystrix.strategy.eventnotifier.HystrixEventNotifier; -import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook; -import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisher; -import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy; - /** * @author Daniel Lavoie */ @@ -45,7 +45,10 @@ import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy; @Conditional(HystrixSecurityCondition.class) @ConditionalOnClass({ Hystrix.class, SecurityContext.class }) public class HystrixSecurityAutoConfiguration { - private static final Log LOGGER = LogFactory.getLog(HystrixSecurityAutoConfiguration.class); + + private static final Log LOGGER = LogFactory + .getLog(HystrixSecurityAutoConfiguration.class); + @Autowired(required = false) private HystrixConcurrencyStrategy existingConcurrencyStrategy; @@ -79,20 +82,22 @@ public class HystrixSecurityAutoConfiguration { if (existingConcurrencyStrategy == null) { return registeredStrategy; } - //Hystrix registered a default Strategy. - if (registeredStrategy instanceof HystrixConcurrencyStrategyDefault){ + // Hystrix registered a default Strategy. + if (registeredStrategy instanceof HystrixConcurrencyStrategyDefault) { return existingConcurrencyStrategy; } - //If registeredStrategy not the default and not some use bean of existingConcurrencyStrategy. - if (!existingConcurrencyStrategy.equals(registeredStrategy)){ - LOGGER.warn("Multiple HystrixConcurrencyStrategy detected. Bean of HystrixConcurrencyStrategy was used."); + // If registeredStrategy not the default and not some use bean of + // existingConcurrencyStrategy. + if (!existingConcurrencyStrategy.equals(registeredStrategy)) { + LOGGER.warn( + "Multiple HystrixConcurrencyStrategy detected. Bean of HystrixConcurrencyStrategy was used."); } return existingConcurrencyStrategy; } static class HystrixSecurityCondition extends AllNestedConditions { - public HystrixSecurityCondition() { + HystrixSecurityCondition() { super(ConfigurationPhase.REGISTER_BEAN); } @@ -100,5 +105,7 @@ public class HystrixSecurityAutoConfiguration { static class ShareSecurityContext { } + } + } diff --git a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/security/SecurityContextConcurrencyStrategy.java b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/security/SecurityContextConcurrencyStrategy.java index a438882c8..2d35a8a5b 100644 --- a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/security/SecurityContextConcurrencyStrategy.java +++ b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/security/SecurityContextConcurrencyStrategy.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,19 +21,20 @@ import java.util.concurrent.Callable; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; -import com.netflix.hystrix.HystrixThreadPoolProperties; -import org.springframework.security.concurrent.DelegatingSecurityContextCallable; - import com.netflix.hystrix.HystrixThreadPoolKey; +import com.netflix.hystrix.HystrixThreadPoolProperties; import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy; import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariable; import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariableLifecycle; import com.netflix.hystrix.strategy.properties.HystrixProperty; +import org.springframework.security.concurrent.DelegatingSecurityContextCallable; + /** - * @author daniellavoie + * @author Daniel Lavoie */ public class SecurityContextConcurrencyStrategy extends HystrixConcurrencyStrategy { + private HystrixConcurrencyStrategy existingConcurrencyStrategy; public SecurityContextConcurrencyStrategy( @@ -70,9 +71,11 @@ public class SecurityContextConcurrencyStrategy extends HystrixConcurrencyStrate } @Override - public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolProperties threadPoolProperties) { + public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey, + HystrixThreadPoolProperties threadPoolProperties) { return existingConcurrencyStrategy != null - ? existingConcurrencyStrategy.getThreadPool(threadPoolKey, threadPoolProperties) + ? existingConcurrencyStrategy.getThreadPool(threadPoolKey, + threadPoolProperties) : super.getThreadPool(threadPoolKey, threadPoolProperties); } @@ -83,4 +86,5 @@ public class SecurityContextConcurrencyStrategy extends HystrixConcurrencyStrate .wrapCallable(new DelegatingSecurityContextCallable(callable)) : super.wrapCallable(new DelegatingSecurityContextCallable(callable)); } + } diff --git a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixAutoConfigurationTests.java b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixAutoConfigurationTests.java index 094ef8c75..c8d12d10a 100644 --- a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixAutoConfigurationTests.java +++ b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.hystrix; @@ -38,14 +37,15 @@ import static org.assertj.core.api.Assertions.fail; public class HystrixAutoConfigurationTests { @Test - @Ignore //TODO: why does this test fail in maven, but not in IDE? + @Ignore // TODO: why does this test fail in maven, but not in IDE? public void contextStarts() { try (ConfigurableApplicationContext context = new SpringApplicationBuilder() .web(WebApplicationType.NONE).sources(TestApp.class).run()) { try { context.getBean("hystrixMetricsBinder"); fail("HystrixMetricsBinder class should not be found"); - } catch (NoSuchBeanDefinitionException e) { + } + catch (NoSuchBeanDefinitionException e) { // this is the correct case } } @@ -54,5 +54,8 @@ public class HystrixAutoConfigurationTests { @EnableCircuitBreaker @SpringBootConfiguration @EnableAutoConfiguration - protected static class TestApp {} -} \ No newline at end of file + protected static class TestApp { + + } + +} diff --git a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixCommandsTests.java b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixCommandsTests.java index 616a4fc4d..3e5d1b0aa 100644 --- a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixCommandsTests.java +++ b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixCommandsTests.java @@ -1,11 +1,11 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -18,10 +18,8 @@ package org.springframework.cloud.netflix.hystrix; import java.time.Duration; -import org.junit.Test; - import com.netflix.hystrix.exception.HystrixRuntimeException; - +import org.junit.Test; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; @@ -31,20 +29,15 @@ public class HystrixCommandsTests { @Test public void monoWorks() { StepVerifier.create(HystrixCommands.from(Flux.just("works")) - .commandName("testworks") - .toMono()) - .expectNext("works") - .verifyComplete(); + .commandName("testworks").toMono()).expectNext("works").verifyComplete(); } @Test public void eagerMonoWorks() { - StepVerifier.create(HystrixCommands.from(Mono.just("works")) - .eager() - .commandName("testworks") - .toMono()) - .expectNext("works") - .verifyComplete(); + StepVerifier + .create(HystrixCommands.from(Mono.just("works")).eager() + .commandName("testworks").toMono()) + .expectNext("works").verifyComplete(); } @Test @@ -52,101 +45,81 @@ public class HystrixCommandsTests { StepVerifier.create(HystrixCommands.from(Mono.fromCallable(() -> { Thread.sleep(1500); return "timeout"; - })).commandName("failcmd").toMono()) - .verifyError(HystrixRuntimeException.class); + })).commandName("failcmd").toMono()).verifyError(HystrixRuntimeException.class); } @Test public void monoFallbackWorks() { - StepVerifier.create(HystrixCommands.from(Mono.error(new Exception())) - .commandName("failcmd") - .fallback(Mono.just("fallback")) - .toMono()) - .expectNext("fallback") - .verifyComplete(); + StepVerifier + .create(HystrixCommands.from(Mono.error(new Exception())) + .commandName("failcmd").fallback(Mono.just("fallback")).toMono()) + .expectNext("fallback").verifyComplete(); } @Test public void monoFallbackWithExceptionWorks() { - StepVerifier.create(HystrixCommands.from(Mono.error(new IllegalStateException())) - .commandName("failcmd") - .fallback(throwable -> { - if (throwable instanceof IllegalStateException) { - return Mono.just("specificfallback"); - } - return Mono.just("genericfallback"); - }) - .toMono()) - .expectNext("specificfallback") - .verifyComplete(); + StepVerifier.create( + HystrixCommands.from(Mono.error(new IllegalStateException())) + .commandName("failcmd").fallback(throwable -> { + if (throwable instanceof IllegalStateException) { + return Mono.just("specificfallback"); + } + return Mono.just("genericfallback"); + }).toMono()) + .expectNext("specificfallback").verifyComplete(); } @Test public void fluxWorks() { - StepVerifier.create(HystrixCommands.from( Flux.just("1", "2")) - .commandName("multiflux") - .toFlux()) - .expectNext("1") - .expectNext("2") + StepVerifier.create(HystrixCommands.from(Flux.just("1", "2")) + .commandName("multiflux").toFlux()).expectNext("1").expectNext("2") .verifyComplete(); } @Test public void fluxWorksDeferredRequest() { - StepVerifier.create(HystrixCommands.from(Flux.just("1", "2")) - .commandName("multiflux") - .build(), 1) - .expectNext("1") - .thenAwait(Duration.ofSeconds(1)) - .thenRequest(1) - .expectNext("2") - .verifyComplete(); + StepVerifier + .create(HystrixCommands.from(Flux.just("1", "2")).commandName("multiflux") + .build(), 1) + .expectNext("1").thenAwait(Duration.ofSeconds(1)).thenRequest(1) + .expectNext("2").verifyComplete(); } @Test public void toObservableFunctionWorks() { - StepVerifier.create(HystrixCommands.from(Flux.just("1", "2")) - .commandName("multiflux") - .toObservable(cmd -> cmd.toObservable()) - .build(), 1) - .expectNext("1") - .thenAwait(Duration.ofSeconds(1)) - .thenRequest(1) + StepVerifier + .create(HystrixCommands.from(Flux.just("1", "2")).commandName("multiflux") + .toObservable(cmd -> cmd.toObservable()).build(), 1) + .expectNext("1").thenAwait(Duration.ofSeconds(1)).thenRequest(1) .verifyError(); } @Test public void eagerFluxWorks() { - StepVerifier.create(HystrixCommands.from( Flux.just("1", "2")) - .commandName("multiflux") - .eager() - .toFlux()) - .expectNext("1") - .expectNext("2") - .verifyComplete(); + StepVerifier + .create(HystrixCommands.from(Flux.just("1", "2")).commandName("multiflux") + .eager().toFlux()) + .expectNext("1").expectNext("2").verifyComplete(); } @Test public void fluxTimesOut() { - StepVerifier.create(HystrixCommands.from( Flux.from(s -> { + StepVerifier.create(HystrixCommands.from(Flux.from(s -> { try { Thread.sleep(1500); - } catch (InterruptedException e) { + } + catch (InterruptedException e) { throw new RuntimeException(e); } - })).commandName("failcmd").toFlux()) - .verifyError(HystrixRuntimeException.class); + })).commandName("failcmd").toFlux()).verifyError(HystrixRuntimeException.class); } @Test public void fluxFallbackWorks() { - StepVerifier.create(HystrixCommands.from(Flux.error(new Exception())) - .commandName("multiflux") - .fallback(Flux.just("a", "b")) - .toFlux()) - .expectNext("a") - .expectNext("b") - .verifyComplete(); + StepVerifier + .create(HystrixCommands.from(Flux.error(new Exception())) + .commandName("multiflux").fallback(Flux.just("a", "b")).toFlux()) + .expectNext("a").expectNext("b").verifyComplete(); } @Test @@ -157,9 +130,7 @@ public class HystrixCommandsTests { })).commandName("extendTimeout") .commandProperties( setter -> setter.withExecutionTimeoutInMilliseconds(2000)) - .toMono()) - .expectNext("works") - .verifyComplete(); + .toMono()).expectNext("works").verifyComplete(); } } diff --git a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixConfigurationTests.java b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixConfigurationTests.java index dcdab7b01..b2e5b4a31 100644 --- a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixConfigurationTests.java +++ b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,23 +37,24 @@ public class HystrixConfigurationTests { @Test public void nonWebAppStartsUp() { new ApplicationContextRunner() - .withUserConfiguration(HystrixCircuitBreakerConfiguration.class) - .run(c -> { - assertThat(c).hasSingleBean(HystrixCommandAspect.class); - }); + .withUserConfiguration(HystrixCircuitBreakerConfiguration.class) + .run(c -> { + assertThat(c).hasSingleBean(HystrixCommandAspect.class); + }); } @Test public void hystrixMetricsConfigured() { - new WebApplicationContextRunner() - .withUserConfiguration(TestApp.class) - .run(c -> { - assertThat(c.getBeansOfType(MeterBinder.class).values()) - .hasAtLeastOneElementOfType(HystrixMetricsBinder.class); - }); + new WebApplicationContextRunner().withUserConfiguration(TestApp.class).run(c -> { + assertThat(c.getBeansOfType(MeterBinder.class).values()) + .hasAtLeastOneElementOfType(HystrixMetricsBinder.class); + }); } @SpringBootConfiguration @EnableAutoConfiguration - protected static class TestApp {} -} \ No newline at end of file + protected static class TestApp { + + } + +} diff --git a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixOnlyTests.java b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixOnlyTests.java index 9f1b59915..3bacb4bed 100644 --- a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixOnlyTests.java +++ b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixOnlyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.hystrix; @@ -22,7 +21,6 @@ import java.util.List; import java.util.Map; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; -import org.assertj.core.api.Assertions; import org.junit.Test; import org.junit.runner.RunWith; @@ -49,9 +47,6 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; import static org.springframework.cloud.netflix.test.TestAutoConfiguration.PASSWORD; import static org.springframework.cloud.netflix.test.TestAutoConfiguration.USER; @@ -60,11 +55,12 @@ import static org.springframework.cloud.netflix.test.TestAutoConfiguration.USER; * @author Spencer Gibb */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = HystrixOnlyApplication.class, webEnvironment = RANDOM_PORT, - properties = {"management.endpoint.health.show-details=ALWAYS"}) +@SpringBootTest(classes = HystrixOnlyApplication.class, webEnvironment = RANDOM_PORT, properties = { + "management.endpoint.health.show-details=ALWAYS" }) @DirtiesContext @ActiveProfiles("proxysecurity") public class HystrixOnlyTests { + private static final String BASE_PATH = new WebEndpointProperties().getBasePath(); @LocalServerPort @@ -74,14 +70,15 @@ public class HystrixOnlyTests { public void testNormalExecution() { ResponseEntity res = new TestRestTemplate() .getForEntity("http://localhost:" + this.port + "/", String.class); - assertEquals("incorrect response", "Hello world", res.getBody()); + assertThat(res.getBody()).as("incorrect response").isEqualTo("Hello world"); } @Test public void testFailureFallback() { ResponseEntity res = new TestRestTemplate() .getForEntity("http://localhost:" + this.port + "/fail", String.class); - assertEquals("incorrect fallback", "Fallback Hello world", res.getBody()); + assertThat(res.getBody()).as("incorrect fallback") + .isEqualTo("Fallback Hello world"); } @Test @@ -99,8 +96,8 @@ public class HystrixOnlyTests { public void testNoDiscoveryHealth() { Map map = getHealth(); // There is explicitly no discovery, so there should be no discovery health key - assertFalse("Incorrect existing discovery health key", - map.containsKey("discovery")); + assertThat(map.containsKey("discovery")) + .as("Incorrect existing discovery health key").isFalse(); } @Test @@ -109,22 +106,24 @@ public class HystrixOnlyTests { String url = "http://localhost:" + this.port; ResponseEntity response = new TestRestTemplate().getForEntity(url, String.class); - assertEquals("bad response code", HttpStatus.OK, response.getStatusCode()); + assertThat(response.getStatusCode()).as("bad response code") + .isEqualTo(HttpStatus.OK); // Poller takes some time to realize for new metrics try { Thread.sleep(2000); - } catch (InterruptedException e) {} + } + catch (InterruptedException e) { + } Map> map = (Map>) getMetrics(); - assertTrue("There is no latencyTotal group key specified", - map.get("names").contains("hystrix.latency.total")); - assertTrue("There is no latencyExecute group key specified", - map.get("names").contains("hystrix.latency.execution")); + assertThat(map.get("names").contains("hystrix.latency.total")) + .as("There is no latencyTotal group key specified").isTrue(); + assertThat(map.get("names").contains("hystrix.latency.execution")) + .as("There is no latencyExecute group key specified").isTrue(); } - private Map getMetrics() { return getAuthenticatedEndpoint("/metrics"); } @@ -136,12 +135,12 @@ public class HystrixOnlyTests { private Map getAuthenticatedEndpoint(String endpoint) { return new TestRestTemplate().exchange( "http://localhost:" + this.port + BASE_PATH + endpoint, HttpMethod.GET, - new HttpEntity(createBasicAuthHeader(USER, PASSWORD)), - Map.class).getBody(); + new HttpEntity(createBasicAuthHeader(USER, PASSWORD)), Map.class) + .getBody(); } public static HttpHeaders createBasicAuthHeader(final String username, - final String password) { + final String password) { return new HttpHeaders() { private static final long serialVersionUID = 1766341693637204893L; @@ -153,9 +152,11 @@ public class HystrixOnlyTests { } }; } + } class Service { + @HystrixCommand public String hello() { return "Hello world"; @@ -169,6 +170,7 @@ class Service { public String fallback() { return "Fallback Hello world"; } + } // Don't use @SpringBootApplication because we don't want to component scan diff --git a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixStreamEndpointTests.java b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixStreamEndpointTests.java index f3d567ca2..1c425f997 100644 --- a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixStreamEndpointTests.java +++ b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixStreamEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.hystrix; @@ -22,10 +21,12 @@ import java.net.URL; import java.util.ArrayList; import java.util.List; +import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -45,22 +46,21 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; /** * @author Dave Syer * @author Spencer Gibb */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = HystrixStreamEndpointTests.Application.class, - webEnvironment = WebEnvironment.RANDOM_PORT, value = { +@SpringBootTest(classes = HystrixStreamEndpointTests.Application.class, webEnvironment = WebEnvironment.RANDOM_PORT, value = { "spring.application.name=hystrixstreamtest" }) @DirtiesContext public class HystrixStreamEndpointTests { + private static final String BASE_PATH = new WebEndpointProperties().getBasePath(); + private static final Log log = LogFactory.getLog(HystrixStreamEndpointTests.class); @LocalServerPort @@ -72,7 +72,8 @@ public class HystrixStreamEndpointTests { // you have to hit a Hystrix circuit breaker before the stream sends anything ResponseEntity response = new TestRestTemplate().getForEntity(url, String.class); - assertEquals("bad response code", HttpStatus.OK, response.getStatusCode()); + assertThat(response.getStatusCode()).as("bad response code") + .isEqualTo(HttpStatus.OK); URL hystrixUrl = new URL(url + BASE_PATH + "/hystrix.stream"); @@ -82,7 +83,8 @@ public class HystrixStreamEndpointTests { byte[] buffer = new byte[1024]; in.read(buffer); data.add(new String(buffer)); - } catch (Exception e) { + } + catch (Exception e) { log.error("Error getting hystrix stream, try " + i, e); } } @@ -101,6 +103,7 @@ public class HystrixStreamEndpointTests { @EnableCircuitBreaker @Import(NoSecurityConfiguration.class) protected static class Application { + @Autowired Service service; @@ -113,12 +116,16 @@ public class HystrixStreamEndpointTests { public String hello() { return service.hello(); } + } protected static class Service { + @HystrixCommand public String hello() { return "Hello World"; } + } + } diff --git a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixWebfluxEndpointTests.java b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixWebfluxEndpointTests.java index 95f5514f4..ffea005e5 100644 --- a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixWebfluxEndpointTests.java +++ b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixWebfluxEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.hystrix; @@ -49,12 +48,14 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Spencer Gibb */ @RunWith(SpringRunner.class) -@SpringBootTest( webEnvironment = RANDOM_PORT, properties = { +@SpringBootTest(webEnvironment = RANDOM_PORT, properties = { "spring.main.web-application-type=reactive", - "spring.application.name=hystrixstreamwebfluxtest", /*"debug=true"*/ }) + "spring.application.name=hystrixstreamwebfluxtest" /* "debug=true" */ }) @DirtiesContext public class HystrixWebfluxEndpointTests { + private static final String BASE_PATH = new WebEndpointProperties().getBasePath(); + private static final Log log = LogFactory.getLog(HystrixWebfluxEndpointTests.class); @LocalServerPort @@ -70,31 +71,29 @@ public class HystrixWebfluxEndpointTests { WebClient client = WebClient.create(url); Flux result = client.get().uri(BASE_PATH + "/hystrix.stream") - .accept(MediaType.TEXT_EVENT_STREAM) - .exchange() - .flatMapMany(res -> res.bodyToFlux(Map.class)) - .take(5) + .accept(MediaType.TEXT_EVENT_STREAM).exchange() + .flatMapMany(res -> res.bodyToFlux(Map.class)).take(5) .filter(map -> "HystrixCommand".equals(map.get("type"))) - .map(map -> (String)map.get("type")); + .map(map -> (String) map.get("type")); - StepVerifier.create(result) - .expectNext("HystrixCommand") - .thenCancel() - .verify(); + StepVerifier.create(result).expectNext("HystrixCommand").thenCancel().verify(); } @RestController @EnableCircuitBreaker - @EnableAutoConfiguration(exclude = TestAutoConfiguration.class, - excludeName = {"org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration", + @EnableAutoConfiguration(exclude = TestAutoConfiguration.class, excludeName = { + "org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration", "org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration", - "org.springframework.boot.actuate.autoconfigure.security.reactive.ReactiveManagementWebSecurityAutoConfiguration"}) + "org.springframework.boot.actuate.autoconfigure.security.reactive.ReactiveManagementWebSecurityAutoConfiguration" }) @SpringBootConfiguration protected static class Config { + @HystrixCommand @RequestMapping("/") public String hi() { return "hi"; } + } + } diff --git a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityAutoConfigurationTest.java b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityAutoConfigurationTest.java index 70a78e70d..f4d42c89f 100644 --- a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityAutoConfigurationTest.java +++ b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityAutoConfigurationTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,11 +12,12 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.hystrix.security; +import java.lang.reflect.Field; + import com.netflix.hystrix.strategy.HystrixPlugins; import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy; import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategyDefault; @@ -27,84 +28,98 @@ import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy; import org.junit.Test; import org.mockito.internal.util.reflection.FieldSetter; -import java.lang.reflect.Field; - -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author : ailin.zhou */ public class HystrixSecurityAutoConfigurationTest { - @Test - public void testInit() throws NoSuchFieldException, IllegalAccessException { + @Test + public void testInit() throws NoSuchFieldException, IllegalAccessException { - //save test context - HystrixEventNotifier eventNotifier = HystrixPlugins.getInstance() - .getEventNotifier(); - HystrixMetricsPublisher metricsPublisher = HystrixPlugins.getInstance() - .getMetricsPublisher(); - HystrixPropertiesStrategy propertiesStrategy = HystrixPlugins.getInstance() - .getPropertiesStrategy(); - HystrixCommandExecutionHook commandExecutionHook = HystrixPlugins.getInstance() - .getCommandExecutionHook(); - HystrixConcurrencyStrategy concurrencyStrategy = HystrixPlugins.getInstance().getConcurrencyStrategy(); + // save test context + HystrixEventNotifier eventNotifier = HystrixPlugins.getInstance() + .getEventNotifier(); + HystrixMetricsPublisher metricsPublisher = HystrixPlugins.getInstance() + .getMetricsPublisher(); + HystrixPropertiesStrategy propertiesStrategy = HystrixPlugins.getInstance() + .getPropertiesStrategy(); + HystrixCommandExecutionHook commandExecutionHook = HystrixPlugins.getInstance() + .getCommandExecutionHook(); + HystrixConcurrencyStrategy concurrencyStrategy = HystrixPlugins.getInstance() + .getConcurrencyStrategy(); - //test - testForMultiConcurrentStrategy(); + // test + testForMultiConcurrentStrategy(); - //recover test context - HystrixPlugins.reset(); - HystrixPlugins.getInstance().registerConcurrencyStrategy(concurrencyStrategy); - HystrixPlugins.getInstance().registerEventNotifier(eventNotifier); - HystrixPlugins.getInstance().registerMetricsPublisher(metricsPublisher); - HystrixPlugins.getInstance().registerPropertiesStrategy(propertiesStrategy); - HystrixPlugins.getInstance().registerCommandExecutionHook(commandExecutionHook); + // recover test context + HystrixPlugins.reset(); + HystrixPlugins.getInstance().registerConcurrencyStrategy(concurrencyStrategy); + HystrixPlugins.getInstance().registerEventNotifier(eventNotifier); + HystrixPlugins.getInstance().registerMetricsPublisher(metricsPublisher); + HystrixPlugins.getInstance().registerPropertiesStrategy(propertiesStrategy); + HystrixPlugins.getInstance().registerCommandExecutionHook(commandExecutionHook); + } - } + private void testForMultiConcurrentStrategy() + throws IllegalAccessException, NoSuchFieldException { + HystrixSecurityAutoConfiguration securityStrategy = new HystrixSecurityAutoConfiguration(); - private void testForMultiConcurrentStrategy() throws IllegalAccessException, NoSuchFieldException { - HystrixSecurityAutoConfiguration securityStrategy = new HystrixSecurityAutoConfiguration(); + // 1.existingConcurrencyStrategy is null, registeredStrategy is default + HystrixPlugins.reset(); + securityStrategy.init(); + // result is default + assertThat(getOriginalInSecurityConcurrencyStrategy()) + .isEqualTo(HystrixConcurrencyStrategyDefault.getInstance()); - //1.existingConcurrencyStrategy is null, registeredStrategy is default - HystrixPlugins.reset(); - securityStrategy.init(); - //result is default - assertEquals(HystrixConcurrencyStrategyDefault.getInstance(), getOriginalInSecurityConcurrencyStrategy()); + // 2.existingConcurrencyStrategy is null, registered strategy is customized + HystrixPlugins.reset(); + HystrixConcurrencyStrategy customized = new HystrixConcurrencyStrategy() { + }; + HystrixPlugins.getInstance().registerConcurrencyStrategy(customized); + securityStrategy.init(); + // result is customized + assertThat(getOriginalInSecurityConcurrencyStrategy()).isEqualTo(customized); - //2.existingConcurrencyStrategy is null, registered strategy is customized - HystrixPlugins.reset(); - HystrixConcurrencyStrategy customized = new HystrixConcurrencyStrategy() { - }; - HystrixPlugins.getInstance().registerConcurrencyStrategy(customized); - securityStrategy.init(); - //result is customized - assertEquals(customized, getOriginalInSecurityConcurrencyStrategy()); + // 3.existingConcurrencyStrategy is not null, registeredStrategy is default. + HystrixPlugins.reset(); + HystrixConcurrencyStrategy existingConcurrencyStrategy = new HystrixConcurrencyStrategy() { + }; + FieldSetter + .setField(securityStrategy, + securityStrategy.getClass() + .getDeclaredField("existingConcurrencyStrategy"), + existingConcurrencyStrategy); + securityStrategy.init(); + // result is existingConcurrencyStrategy + assertThat(getOriginalInSecurityConcurrencyStrategy()) + .isEqualTo(existingConcurrencyStrategy); - //3.existingConcurrencyStrategy is not null, registeredStrategy is default. - HystrixPlugins.reset(); - HystrixConcurrencyStrategy existingConcurrencyStrategy = new HystrixConcurrencyStrategy() { - }; - FieldSetter.setField(securityStrategy, securityStrategy.getClass().getDeclaredField("existingConcurrencyStrategy"), existingConcurrencyStrategy); - securityStrategy.init(); - //result is existingConcurrencyStrategy - assertEquals(existingConcurrencyStrategy, getOriginalInSecurityConcurrencyStrategy()); + // 4.existingConcurrencyStrategy is not null, registeredStrategy is customized. + HystrixPlugins.reset(); + HystrixPlugins.getInstance().registerConcurrencyStrategy(customized); + FieldSetter + .setField(securityStrategy, + securityStrategy.getClass() + .getDeclaredField("existingConcurrencyStrategy"), + existingConcurrencyStrategy); + securityStrategy.init(); + assertThat(getOriginalInSecurityConcurrencyStrategy()) + .isEqualTo(existingConcurrencyStrategy); + } - //4.existingConcurrencyStrategy is not null, registeredStrategy is customized. - HystrixPlugins.reset(); - HystrixPlugins.getInstance().registerConcurrencyStrategy(customized); - FieldSetter.setField(securityStrategy, securityStrategy.getClass().getDeclaredField("existingConcurrencyStrategy"), existingConcurrencyStrategy); - securityStrategy.init(); - assertEquals(existingConcurrencyStrategy, getOriginalInSecurityConcurrencyStrategy()); - } + private HystrixConcurrencyStrategy getOriginalInSecurityConcurrencyStrategy() + throws IllegalAccessException, NoSuchFieldException { + HystrixConcurrencyStrategy concurrencyStrategy = HystrixPlugins.getInstance() + .getConcurrencyStrategy(); + Field existingConcurrencyStrategy = concurrencyStrategy.getClass() + .getDeclaredField("existingConcurrencyStrategy"); + existingConcurrencyStrategy.setAccessible(true); + HystrixConcurrencyStrategy strategyInSecurityStrategy = (HystrixConcurrencyStrategy) existingConcurrencyStrategy + .get(concurrencyStrategy); + return strategyInSecurityStrategy; + } - private HystrixConcurrencyStrategy getOriginalInSecurityConcurrencyStrategy() throws IllegalAccessException, NoSuchFieldException { - HystrixConcurrencyStrategy concurrencyStrategy = HystrixPlugins.getInstance().getConcurrencyStrategy(); - Field existingConcurrencyStrategy = concurrencyStrategy.getClass().getDeclaredField("existingConcurrencyStrategy"); - existingConcurrencyStrategy.setAccessible(true); - HystrixConcurrencyStrategy strategyInSecurityStrategy = (HystrixConcurrencyStrategy) existingConcurrencyStrategy.get(concurrencyStrategy); - return strategyInSecurityStrategy; - } - -} \ No newline at end of file +} diff --git a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityNoFeignTests.java b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityNoFeignTests.java index e9a36fd36..621d4881d 100644 --- a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityNoFeignTests.java +++ b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityNoFeignTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,20 +12,19 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.hystrix.security; +import com.netflix.hystrix.strategy.HystrixPlugins; +import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; -import com.netflix.hystrix.strategy.HystrixPlugins; -import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy; - import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @@ -35,8 +34,10 @@ public class HystrixSecurityNoFeignTests { @Test public void testSecurityConcurrencyStrategyInstalled() { - HystrixConcurrencyStrategy concurrencyStrategy = HystrixPlugins.getInstance().getConcurrencyStrategy(); - assertThat(concurrencyStrategy).isInstanceOf(SecurityContextConcurrencyStrategy.class); + HystrixConcurrencyStrategy concurrencyStrategy = HystrixPlugins.getInstance() + .getConcurrencyStrategy(); + assertThat(concurrencyStrategy) + .isInstanceOf(SecurityContextConcurrencyStrategy.class); } } diff --git a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/app/CustomConcurrenyStrategy.java b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/app/CustomConcurrenyStrategy.java index 674adf671..535101535 100644 --- a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/app/CustomConcurrenyStrategy.java +++ b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/app/CustomConcurrenyStrategy.java @@ -1,13 +1,30 @@ +/* + * Copyright 2016-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.springframework.cloud.netflix.hystrix.security.app; import java.util.concurrent.Callable; -import org.springframework.stereotype.Component; - import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy; +import org.springframework.stereotype.Component; + @Component public class CustomConcurrenyStrategy extends HystrixConcurrencyStrategy { + private boolean hookCalled; @Override @@ -20,4 +37,5 @@ public class CustomConcurrenyStrategy extends HystrixConcurrencyStrategy { public boolean isHookCalled() { return hookCalled; } + } diff --git a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/app/UsernameController.java b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/app/UsernameController.java index 54605b8e4..5e516326d 100644 --- a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/app/UsernameController.java +++ b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/app/UsernameController.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,8 +26,10 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/username") public class UsernameController { + @RequestMapping - public String getUsername(@RequestHeader String username){ + public String getUsername(@RequestHeader String username) { return username; } + } diff --git a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/resttemplate/RestTemplateRetryTests.java b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/resttemplate/RestTemplateRetryTests.java index 84ea0d0bc..065ecff68 100644 --- a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/resttemplate/RestTemplateRetryTests.java +++ b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/resttemplate/RestTemplateRetryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.resttemplate; @@ -21,11 +20,25 @@ import java.net.UnknownHostException; import java.util.Arrays; import java.util.concurrent.atomic.AtomicInteger; +import com.netflix.client.RetryHandler; +import com.netflix.client.config.IClientConfig; +import com.netflix.loadbalancer.AvailabilityFilteringRule; +import com.netflix.loadbalancer.BaseLoadBalancer; +import com.netflix.loadbalancer.ILoadBalancer; +import com.netflix.loadbalancer.IPing; +import com.netflix.loadbalancer.IRule; +import com.netflix.loadbalancer.LoadBalancerBuilder; +import com.netflix.loadbalancer.LoadBalancerStats; +import com.netflix.loadbalancer.Server; +import com.netflix.loadbalancer.ServerList; +import com.netflix.loadbalancer.ServerStats; +import com.netflix.niws.client.http.HttpClientLoadBalancerErrorHandler; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -44,30 +57,15 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; -import com.netflix.client.RetryHandler; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.AvailabilityFilteringRule; -import com.netflix.loadbalancer.BaseLoadBalancer; -import com.netflix.loadbalancer.ILoadBalancer; -import com.netflix.loadbalancer.IPing; -import com.netflix.loadbalancer.IRule; -import com.netflix.loadbalancer.LoadBalancerBuilder; -import com.netflix.loadbalancer.LoadBalancerStats; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerList; -import com.netflix.loadbalancer.ServerStats; -import com.netflix.niws.client.http.HttpClientLoadBalancerErrorHandler; - import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertTrue; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; @RunWith(SpringRunner.class) -@SpringBootTest(classes = RestTemplateRetryTests.Application.class, webEnvironment = RANDOM_PORT, - properties = { "spring.application.name=resttemplatetest", "logging.level.com.netflix=DEBUG", - "logging.level.org.springframework.cloud.netflix.resttemplate=DEBUG", - "logging.level.com.netflix=DEBUG", "badClients.ribbon.MaxAutoRetries=25", - "badClients.ribbon.OkToRetryOnAllOperations=true", "ribbon.http.client.enabled" }) +@SpringBootTest(classes = RestTemplateRetryTests.Application.class, webEnvironment = RANDOM_PORT, properties = { + "spring.application.name=resttemplatetest", "logging.level.com.netflix=DEBUG", + "logging.level.org.springframework.cloud.netflix.resttemplate=DEBUG", + "logging.level.com.netflix=DEBUG", "badClients.ribbon.MaxAutoRetries=25", + "badClients.ribbon.OkToRetryOnAllOperations=true", "ribbon.http.client.enabled" }) @DirtiesContext public class RestTemplateRetryTests { @@ -111,9 +109,10 @@ public class RestTemplateRetryTests { logServerStats(LocalBadClientConfiguration.badServer2); logServerStats(LocalBadClientConfiguration.goodServer); - assertTrue(badServer1Stats.isCircuitBreakerTripped()); - assertTrue(badServer2Stats.isCircuitBreakerTripped()); - assertThat(targetConnectionCount).isLessThanOrEqualTo(goodServerStats.getTotalRequestsCount()); + assertThat(badServer1Stats.isCircuitBreakerTripped()).isTrue(); + assertThat(badServer2Stats.isCircuitBreakerTripped()).isTrue(); + assertThat(targetConnectionCount) + .isLessThanOrEqualTo(goodServerStats.getTotalRequestsCount()); // Wait for any timeout thread to finish. @@ -157,9 +156,10 @@ public class RestTemplateRetryTests { logServerStats(LocalBadClientConfiguration.badServer2); logServerStats(LocalBadClientConfiguration.goodServer); - assertTrue(badServer1Stats.isCircuitBreakerTripped()); - assertTrue(badServer2Stats.isCircuitBreakerTripped()); - assertThat(targetConnectionCount).isLessThanOrEqualTo(goodServerStats.getTotalRequestsCount()); + assertThat(badServer1Stats.isCircuitBreakerTripped()).isTrue(); + assertThat(badServer2Stats.isCircuitBreakerTripped()).isTrue(); + assertThat(targetConnectionCount) + .isLessThanOrEqualTo(goodServerStats.getTotalRequestsCount()); assertThat(hits).isGreaterThanOrEqualTo(numCalls); logger.debug("Retry Hits: " + hits); } @@ -178,8 +178,8 @@ public class RestTemplateRetryTests { badServer1Stats.clearSuccessiveConnectionFailureCount(); badServer2Stats.clearSuccessiveConnectionFailureCount(); - assertTrue(!badServer1Stats.isCircuitBreakerTripped()); - assertTrue(!badServer2Stats.isCircuitBreakerTripped()); + assertThat(!badServer1Stats.isCircuitBreakerTripped()).isTrue(); + assertThat(!badServer2Stats.isCircuitBreakerTripped()).isTrue(); int hits = 0; @@ -192,9 +192,9 @@ public class RestTemplateRetryTests { logServerStats(LocalBadClientConfiguration.badServer2); logServerStats(LocalBadClientConfiguration.goodServer); - assertTrue(badServer1Stats.isCircuitBreakerTripped()); - assertTrue(badServer2Stats.isCircuitBreakerTripped()); - assertTrue(!goodServerStats.isCircuitBreakerTripped()); + assertThat(badServer1Stats.isCircuitBreakerTripped()).isTrue(); + assertThat(badServer2Stats.isCircuitBreakerTripped()).isTrue(); + assertThat(!goodServerStats.isCircuitBreakerTripped()).isTrue(); // 15 + 4 timeouts. See the endpoint for timeout conditions. assertThat(hits).isGreaterThanOrEqualTo(numCalls + 4); @@ -212,6 +212,7 @@ public class RestTemplateRetryTests { public static class Application { private AtomicInteger hits = new AtomicInteger(1); + private AtomicInteger retryHits = new AtomicInteger(1); @RequestMapping(method = RequestMethod.GET, value = "/ping") @@ -246,8 +247,8 @@ public class RestTemplateRetryTests { RestTemplate restTemplate() { return new RestTemplate(); } - } + } // Load balancer with fixed server list for "local" pointing to localhost // and some bogus servers are thrown in to test retry @@ -259,7 +260,7 @@ public class RestTemplateRetryTests { static Server badServer; static Server badServer2; - public LocalBadClientConfiguration() { + LocalBadClientConfiguration() { } @Value("${local.server.port}") @@ -267,7 +268,8 @@ public class RestTemplateRetryTests { @Bean public IRule loadBalancerRule() { - // This is a good place to try different load balancing rules and how those rules + // This is a good place to try different load balancing rules and how those + // rules // behave in failure states: BestAvailableRule, WeightedResponseTimeRule, etc // This rule just uses a round robin and will skip servers that are in circuit @@ -296,11 +298,14 @@ public class RestTemplateRetryTests { } static class OverrideRetryHandler extends HttpClientLoadBalancerErrorHandler { - public OverrideRetryHandler() { + + OverrideRetryHandler() { this.circuitRelated.add(UnknownHostException.class); this.retriable.add(UnknownHostException.class); } + } } + } diff --git a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientStatusCodeExceptionTest.java b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientStatusCodeExceptionTest.java index ac00fc64a..6ecde8ceb 100644 --- a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientStatusCodeExceptionTest.java +++ b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientStatusCodeExceptionTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,11 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.netflix.ribbon.apache; import java.io.ByteArrayInputStream; import java.net.URI; import java.util.Locale; + import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.ProtocolVersion; @@ -31,8 +33,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -49,7 +50,7 @@ public class HttpClientStatusCodeExceptionTest { CloseableHttpResponse response = mock(CloseableHttpResponse.class); doReturn(new Locale("en")).when(response).getLocale(); Header foo = new BasicHeader("foo", "bar"); - Header[] headers = new Header[]{foo}; + Header[] headers = new Header[] { foo }; doReturn(headers).when(response).getAllHeaders(); StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("http", 1, 1), 200, "Success"); @@ -59,16 +60,21 @@ public class HttpClientStatusCodeExceptionTest { entity.setContentLength(3); doReturn(entity).when(response).getEntity(); HttpEntity copiedEntity = HttpClientUtils.createEntity(response); - HttpClientStatusCodeException ex = new HttpClientStatusCodeException("service", response, copiedEntity, - new URI("http://service.com")); - assertEquals("en", ex.getResponse().getLocale().toString()); - assertArrayEquals(headers, ex.getResponse().getAllHeaders()); - assertEquals("Success", ex.getResponse().getStatusLine().getReasonPhrase()); - assertEquals(200, ex.getResponse().getStatusLine().getStatusCode()); - assertEquals("http", ex.getResponse().getStatusLine().getProtocolVersion().getProtocol()); - assertEquals(1, ex.getResponse().getStatusLine().getProtocolVersion().getMajor()); - assertEquals(1, ex.getResponse().getStatusLine().getProtocolVersion().getMinor()); - assertEquals("foo", EntityUtils.toString(ex.getResponse().getEntity())); + HttpClientStatusCodeException ex = new HttpClientStatusCodeException("service", + response, copiedEntity, new URI("http://service.com")); + assertThat(ex.getResponse().getLocale().toString()).isEqualTo("en"); + assertThat(ex.getResponse().getAllHeaders()).isEqualTo(headers); + assertThat(ex.getResponse().getStatusLine().getReasonPhrase()) + .isEqualTo("Success"); + assertThat(ex.getResponse().getStatusLine().getStatusCode()).isEqualTo(200); + assertThat(ex.getResponse().getStatusLine().getProtocolVersion().getProtocol()) + .isEqualTo("http"); + assertThat(ex.getResponse().getStatusLine().getProtocolVersion().getMajor()) + .isEqualTo(1); + assertThat(ex.getResponse().getStatusLine().getProtocolVersion().getMinor()) + .isEqualTo(1); + assertThat(EntityUtils.toString(ex.getResponse().getEntity())).isEqualTo("foo"); verify(response, times(1)).close(); } -} \ No newline at end of file + +} diff --git a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpStatusCodeExceptionTest.java b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpStatusCodeExceptionTest.java index af8320a5c..71cf55e77 100644 --- a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpStatusCodeExceptionTest.java +++ b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpStatusCodeExceptionTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,22 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.netflix.ribbon.okhttp; +import java.net.URI; + import okhttp3.Headers; import okhttp3.MediaType; import okhttp3.Protocol; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; - -import java.net.URI; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; -import static org.junit.Assert.assertEquals; - +import static org.assertj.core.api.Assertions.assertThat; /** * @author Ryan Baxter @@ -39,15 +39,19 @@ public class OkHttpStatusCodeExceptionTest { @Test public void getResponse() throws Exception { Headers headers = new Headers.Builder().add("foo", "bar").build(); - Response response = new Response.Builder().code(200).headers(headers).code(200).message("Success") - .body(ResponseBody.create(MediaType.parse("text/plain"), "foo")).protocol(Protocol.HTTP_1_1) + Response response = new Response.Builder().code(200).headers(headers).code(200) + .message("Success") + .body(ResponseBody.create(MediaType.parse("text/plain"), "foo")) + .protocol(Protocol.HTTP_1_1) .request(new Request.Builder().url("http://service.com").build()).build(); ResponseBody body = response.peekBody(Integer.MAX_VALUE); - OkHttpStatusCodeException ex = new OkHttpStatusCodeException("service", response, body, new URI("http://service.com")); - assertEquals(headers, ex.getResponse().headers()); - assertEquals(200, ex.getResponse().code()); - assertEquals("Success", ex.getResponse().message()); - assertEquals("foo", ex.getResponse().body().string()); - assertEquals(Protocol.HTTP_1_1, ex.getResponse().protocol()); + OkHttpStatusCodeException ex = new OkHttpStatusCodeException("service", response, + body, new URI("http://service.com")); + assertThat(ex.getResponse().headers()).isEqualTo(headers); + assertThat(ex.getResponse().code()).isEqualTo(200); + assertThat(ex.getResponse().message()).isEqualTo("Success"); + assertThat(ex.getResponse().body().string()).isEqualTo("foo"); + assertThat(ex.getResponse().protocol()).isEqualTo(Protocol.HTTP_1_1); } -} \ No newline at end of file + +} diff --git a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/test/NoSecurityConfiguration.java b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/test/NoSecurityConfiguration.java index 44e71946e..f93e0563e 100644 --- a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/test/NoSecurityConfiguration.java +++ b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/test/NoSecurityConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.test; @@ -23,11 +22,10 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur @Configuration public class NoSecurityConfiguration extends WebSecurityConfigurerAdapter { + @Override protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests() - .anyRequest().permitAll() - .and() - .csrf().disable(); + http.authorizeRequests().anyRequest().permitAll().and().csrf().disable(); } + } diff --git a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/test/TestAutoConfiguration.java b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/test/TestAutoConfiguration.java index 33b671e70..6be271a05 100644 --- a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/test/TestAutoConfiguration.java +++ b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/test/TestAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,17 +34,18 @@ import org.springframework.security.provisioning.InMemoryUserDetailsManager; * @author Spencer Gibb */ @Configuration -@Import({NoopDiscoveryClientAutoConfiguration.class}) +@Import({ NoopDiscoveryClientAutoConfiguration.class }) @AutoConfigureBefore(SecurityAutoConfiguration.class) public class TestAutoConfiguration { public static final String USER = "user"; + public static final String PASSWORD = "{noop}password"; @Configuration @Order(Ordered.HIGHEST_PRECEDENCE) - protected static class TestSecurityConfiguration extends WebSecurityConfigurerAdapter { - + protected static class TestSecurityConfiguration + extends WebSecurityConfigurerAdapter { TestSecurityConfiguration() { super(true); @@ -53,18 +54,18 @@ public class TestAutoConfiguration { @Bean public UserDetailsService userDetailsService() { InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); - manager.createUser(User.withUsername(USER).password(PASSWORD).roles("USER").build()); + manager.createUser( + User.withUsername(USER).password(PASSWORD).roles("USER").build()); return manager; } @Override protected void configure(HttpSecurity http) throws Exception { // super.configure(http); - http.antMatcher("/proxy-username") - .httpBasic() - .and() - .authorizeRequests().antMatchers("/**").permitAll(); + http.antMatcher("/proxy-username").httpBasic().and().authorizeRequests() + .antMatchers("/**").permitAll(); } } + } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/DefaultServerIntrospector.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/DefaultServerIntrospector.java index c1dfcb1dc..b2a185343 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/DefaultServerIntrospector.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/DefaultServerIntrospector.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,10 +19,10 @@ package org.springframework.cloud.netflix.ribbon; import java.util.Collections; import java.util.Map; -import org.springframework.beans.factory.annotation.Autowired; - import com.netflix.loadbalancer.Server; +import org.springframework.beans.factory.annotation.Autowired; + /** * @author Spencer Gibb */ @@ -31,7 +31,8 @@ public class DefaultServerIntrospector implements ServerIntrospector { private ServerIntrospectorProperties serverIntrospectorProperties = new ServerIntrospectorProperties(); @Autowired(required = false) - public void setServerIntrospectorProperties(ServerIntrospectorProperties serverIntrospectorProperties){ + public void setServerIntrospectorProperties( + ServerIntrospectorProperties serverIntrospectorProperties) { this.serverIntrospectorProperties = serverIntrospectorProperties; } @@ -44,4 +45,5 @@ public class DefaultServerIntrospector implements ServerIntrospector { public Map getMetadata(Server server) { return Collections.emptyMap(); } + } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/PropertiesFactory.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/PropertiesFactory.java index 3e26ee31f..09072b7ec 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/PropertiesFactory.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/PropertiesFactory.java @@ -1,10 +1,24 @@ +/* + * Copyright 2016-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.springframework.cloud.netflix.ribbon; import java.util.HashMap; import java.util.Map; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; -import org.springframework.util.StringUtils; + import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.loadbalancer.IPing; @@ -12,12 +26,17 @@ import com.netflix.loadbalancer.IRule; import com.netflix.loadbalancer.ServerList; import com.netflix.loadbalancer.ServerListFilter; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.util.StringUtils; + import static org.springframework.cloud.netflix.ribbon.SpringClientFactory.NAMESPACE; /** * @author Spencer Gibb */ public class PropertiesFactory { + @Autowired private Environment environment; @@ -38,7 +57,8 @@ public class PropertiesFactory { public String getClassName(Class clazz, String name) { if (this.classToProperty.containsKey(clazz)) { String classNameProperty = this.classToProperty.get(clazz); - String className = environment.getProperty(name + "." + NAMESPACE + "." + classNameProperty); + String className = environment + .getProperty(name + "." + NAMESPACE + "." + classNameProperty); return className; } return null; @@ -50,11 +70,15 @@ public class PropertiesFactory { if (StringUtils.hasText(className)) { try { Class toInstantiate = Class.forName(className); - return (C) SpringClientFactory.instantiateWithConfig(toInstantiate, config); - } catch (ClassNotFoundException e) { - throw new IllegalArgumentException("Unknown class to load "+className+" for class " + clazz + " named " + name); + return (C) SpringClientFactory.instantiateWithConfig(toInstantiate, + config); + } + catch (ClassNotFoundException e) { + throw new IllegalArgumentException("Unknown class to load " + className + + " for class " + clazz + " named " + name); } } return null; } + } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RestClientRibbonConfiguration.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RestClientRibbonConfiguration.java index 61076e51a..884e2347d 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RestClientRibbonConfiguration.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RestClientRibbonConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,22 +12,20 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.ribbon; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Lazy; - import com.netflix.client.AbstractLoadBalancerAwareClient; import com.netflix.client.RetryHandler; import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.niws.client.http.RestClient; -import com.netflix.servo.monitor.Monitors; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Lazy; /** * @author Spencer Gibb @@ -36,6 +34,7 @@ import com.netflix.servo.monitor.Monitors; @Configuration @RibbonAutoConfiguration.ConditionalOnRibbonRestClient class RestClientRibbonConfiguration { + @RibbonClientName private String name = "client"; @@ -43,21 +42,23 @@ class RestClientRibbonConfiguration { * Create a Netflix {@link RestClient} integrated with Ribbon if none already exists * in the application context. It is not required for Ribbon to work properly and is * therefore created lazily if ever another component requires it. - * - * @param config the configuration to use by the underlying Ribbon instance - * @param loadBalancer the load balancer to use by the underlying Ribbon instance - * @param serverIntrospector server introspector to use by the underlying Ribbon instance - * @param retryHandler retry handler to use by the underlying Ribbon instance + * @param config the configuration to use by the underlying Ribbon instance + * @param loadBalancer the load balancer to use by the underlying Ribbon instance + * @param serverIntrospector server introspector to use by the underlying Ribbon + * instance + * @param retryHandler retry handler to use by the underlying Ribbon instance * @return a {@link RestClient} instances backed by Ribbon */ @Bean @Lazy @ConditionalOnMissingBean(AbstractLoadBalancerAwareClient.class) public RestClient ribbonRestClient(IClientConfig config, ILoadBalancer loadBalancer, - ServerIntrospector serverIntrospector, RetryHandler retryHandler) { - RestClient client = new RibbonClientConfiguration.OverrideRestClient(config, serverIntrospector); + ServerIntrospector serverIntrospector, RetryHandler retryHandler) { + RestClient client = new RibbonClientConfiguration.OverrideRestClient(config, + serverIntrospector); client.setLoadBalancer(loadBalancer); client.setRetryHandler(retryHandler); return client; } + } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonApplicationContextInitializer.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonApplicationContextInitializer.java index 3051bb495..cf77fd4fb 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonApplicationContextInitializer.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonApplicationContextInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,12 +17,13 @@ package org.springframework.cloud.netflix.ribbon; import java.util.List; + import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.ApplicationListener; /** * Responsible for eagerly creating the child application context holding the Ribbon - * related configuration + * related configuration. * * @author Biju Kunjummen */ @@ -30,8 +31,8 @@ public class RibbonApplicationContextInitializer implements ApplicationListener { private final SpringClientFactory springClientFactory; - - //List of Ribbon client names + + // List of Ribbon client names private final List clientNames; public RibbonApplicationContextInitializer(SpringClientFactory springClientFactory, @@ -52,4 +53,5 @@ public class RibbonApplicationContextInitializer public void onApplicationEvent(ApplicationReadyEvent event) { initialize(); } + } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonAutoConfiguration.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonAutoConfiguration.java index 1e71032c0..94378cba0 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonAutoConfiguration.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,8 +60,10 @@ import org.springframework.web.client.RestTemplate; @Conditional(RibbonAutoConfiguration.RibbonClassesConditions.class) @RibbonClients @AutoConfigureAfter(name = "org.springframework.cloud.netflix.eureka.EurekaClientAutoConfiguration") -@AutoConfigureBefore({LoadBalancerAutoConfiguration.class, AsyncLoadBalancerAutoConfiguration.class}) -@EnableConfigurationProperties({RibbonEagerLoadProperties.class, ServerIntrospectorProperties.class}) +@AutoConfigureBefore({ LoadBalancerAutoConfiguration.class, + AsyncLoadBalancerAutoConfiguration.class }) +@EnableConfigurationProperties({ RibbonEagerLoadProperties.class, + ServerIntrospectorProperties.class }) public class RibbonAutoConfiguration { @Autowired(required = false) @@ -91,7 +93,8 @@ public class RibbonAutoConfiguration { @Bean @ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate") @ConditionalOnMissingBean - public LoadBalancedRetryFactory loadBalancedRetryPolicyFactory(final SpringClientFactory clientFactory) { + public LoadBalancedRetryFactory loadBalancedRetryPolicyFactory( + final SpringClientFactory clientFactory) { return new RibbonLoadBalancedRetryFactory(clientFactory); } @@ -102,7 +105,7 @@ public class RibbonAutoConfiguration { } @Bean - @ConditionalOnProperty(value = "ribbon.eager-load.enabled") + @ConditionalOnProperty("ribbon.eager-load.enabled") public RibbonApplicationContextInitializer ribbonApplicationContextInitializer() { return new RibbonApplicationContextInitializer(springClientFactory(), ribbonEagerLoadProperties.getClients()); @@ -119,38 +122,48 @@ public class RibbonAutoConfiguration { @Bean public RestTemplateCustomizer restTemplateCustomizer( final RibbonClientHttpRequestFactory ribbonClientHttpRequestFactory) { - return restTemplate -> restTemplate.setRequestFactory(ribbonClientHttpRequestFactory); + return restTemplate -> restTemplate + .setRequestFactory(ribbonClientHttpRequestFactory); } @Bean public RibbonClientHttpRequestFactory ribbonClientHttpRequestFactory() { return new RibbonClientHttpRequestFactory(this.springClientFactory); } + } - //TODO: support for autoconfiguring restemplate to use apache http client or okhttp + // TODO: support for autoconfiguring restemplate to use apache http client or okhttp @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Documented @Conditional(OnRibbonRestClientCondition.class) - @interface ConditionalOnRibbonRestClient { } + @interface ConditionalOnRibbonRestClient { + + } private static class OnRibbonRestClientCondition extends AnyNestedCondition { - public OnRibbonRestClientCondition() { + + OnRibbonRestClientCondition() { super(ConfigurationPhase.REGISTER_BEAN); } - @Deprecated //remove in Edgware" + @Deprecated // remove in Edgware" @ConditionalOnProperty("ribbon.http.client.enabled") - static class ZuulProperty {} + static class ZuulProperty { + + } @ConditionalOnProperty("ribbon.restclient.enabled") - static class RibbonProperty {} + static class RibbonProperty { + + } + } /** - * {@link AllNestedConditions} that checks that either multiple classes are present + * {@link AllNestedConditions} that checks that either multiple classes are present. */ static class RibbonClassesConditions extends AllNestedConditions { @@ -179,4 +192,5 @@ public class RibbonAutoConfiguration { } } + } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClient.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClient.java index 1b6e017b4..69ca1ecac 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClient.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClient.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,12 +21,14 @@ import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; + import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.loadbalancer.IRule; import com.netflix.loadbalancer.ServerListFilter; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; + /** * Declarative configuration for a ribbon client. Add this annotation to any * @Configuration and then inject a {@link SpringClientFactory} to access the @@ -42,15 +44,17 @@ import com.netflix.loadbalancer.ServerListFilter; public @interface RibbonClient { /** - * Synonym for name (the name of the client) + * Synonym for name (the name of the client). * * @see #name() + * @return name of the Ribbon client */ String value() default ""; /** * The name of the ribbon client, uniquely identifying a set of client resources, * including a load balancer. + * @return name of the Ribbon client */ String name() default ""; @@ -60,6 +64,7 @@ public @interface RibbonClient { * {@link ILoadBalancer}, {@link ServerListFilter}, {@link IRule}. * * @see RibbonClientConfiguration for the defaults + * @return the custom Ribbon client configuration */ Class[] configuration() default {}; diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfiguration.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfiguration.java index 9d1de9d8f..dc489e956 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfiguration.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,18 +17,9 @@ package org.springframework.cloud.netflix.ribbon; import java.net.URI; + import javax.annotation.PostConstruct; -import org.apache.http.client.params.ClientPNames; -import org.apache.http.client.params.CookiePolicy; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.cloud.commons.httpclient.HttpClientConfiguration; -import org.springframework.cloud.netflix.ribbon.apache.HttpClientRibbonConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.cloud.netflix.ribbon.okhttp.OkHttpRibbonConfiguration; + import com.netflix.client.DefaultLoadBalancerRetryHandler; import com.netflix.client.RetryHandler; import com.netflix.client.config.CommonClientConfigKey; @@ -49,6 +40,18 @@ import com.netflix.loadbalancer.ZoneAwareLoadBalancer; import com.netflix.niws.client.http.RestClient; import com.sun.jersey.api.client.Client; import com.sun.jersey.client.apache4.ApacheHttpClient4; +import org.apache.http.client.params.ClientPNames; +import org.apache.http.client.params.CookiePolicy; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.cloud.commons.httpclient.HttpClientConfiguration; +import org.springframework.cloud.netflix.ribbon.apache.HttpClientRibbonConfiguration; +import org.springframework.cloud.netflix.ribbon.okhttp.OkHttpRibbonConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; import static com.netflix.client.config.CommonClientConfigKey.DeploymentContextBasedVipAddresses; import static org.springframework.cloud.netflix.ribbon.RibbonUtils.setRibbonProperty; @@ -61,13 +64,26 @@ import static org.springframework.cloud.netflix.ribbon.RibbonUtils.updateToSecur @SuppressWarnings("deprecation") @Configuration @EnableConfigurationProperties -//Order is important here, last should be the default, first should be optional -// see https://github.com/spring-cloud/spring-cloud-netflix/issues/2086#issuecomment-316281653 -@Import({HttpClientConfiguration.class, OkHttpRibbonConfiguration.class, RestClientRibbonConfiguration.class, HttpClientRibbonConfiguration.class}) +// Order is important here, last should be the default, first should be optional +// see +// https://github.com/spring-cloud/spring-cloud-netflix/issues/2086#issuecomment-316281653 +@Import({ HttpClientConfiguration.class, OkHttpRibbonConfiguration.class, + RestClientRibbonConfiguration.class, HttpClientRibbonConfiguration.class }) public class RibbonClientConfiguration { + /** + * Ribbon client default connect timeout. + */ public static final int DEFAULT_CONNECT_TIMEOUT = 1000; + + /** + * Ribbon client default read timeout. + */ public static final int DEFAULT_READ_TIMEOUT = 1000; + + /** + * Ribbon client default Gzip Payload flag. + */ public static final boolean DEFAULT_GZIP_PAYLOAD = true; @RibbonClientName @@ -155,7 +171,7 @@ public class RibbonClientConfiguration { @Bean @ConditionalOnMissingBean public RibbonLoadBalancerContext ribbonLoadBalancerContext(ILoadBalancer loadBalancer, - IClientConfig config, RetryHandler retryHandler) { + IClientConfig config, RetryHandler retryHandler) { return new RibbonLoadBalancerContext(loadBalancer, config, retryHandler); } @@ -179,6 +195,7 @@ public class RibbonClientConfiguration { static class OverrideRestClient extends RestClient { private IClientConfig config; + private ServerIntrospector serverIntrospector; protected OverrideRestClient(IClientConfig config, diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfigurationRegistrar.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfigurationRegistrar.java index b72841caa..cc03ed8ac 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfigurationRegistrar.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfigurationRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ package org.springframework.cloud.netflix.ribbon; import java.util.Map; + import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; @@ -32,8 +33,8 @@ public class RibbonClientConfigurationRegistrar implements ImportBeanDefinitionR @Override public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { - Map attrs = metadata.getAnnotationAttributes( - RibbonClients.class.getName(), true); + Map attrs = metadata + .getAnnotationAttributes(RibbonClients.class.getName(), true); if (attrs != null && attrs.containsKey("value")) { AnnotationAttributes[] clients = (AnnotationAttributes[]) attrs.get("value"); for (AnnotationAttributes client : clients) { @@ -45,14 +46,15 @@ public class RibbonClientConfigurationRegistrar implements ImportBeanDefinitionR String name; if (metadata.hasEnclosingClass()) { name = "default." + metadata.getEnclosingClassName(); - } else { + } + else { name = "default." + metadata.getClassName(); } registerClientConfiguration(registry, name, attrs.get("defaultConfiguration")); } - Map client = metadata.getAnnotationAttributes( - RibbonClient.class.getName(), true); + Map client = metadata + .getAnnotationAttributes(RibbonClient.class.getName(), true); String name = getClientName(client); if (name != null) { registerClientConfiguration(registry, name, client.get("configuration")); @@ -74,8 +76,8 @@ public class RibbonClientConfigurationRegistrar implements ImportBeanDefinitionR "Either 'name' or 'value' must be provided in @RibbonClient"); } - private void registerClientConfiguration(BeanDefinitionRegistry registry, - Object name, Object configuration) { + private void registerClientConfiguration(BeanDefinitionRegistry registry, Object name, + Object configuration) { BeanDefinitionBuilder builder = BeanDefinitionBuilder .genericBeanDefinition(RibbonClientSpecification.class); builder.addConstructorArgValue(name); diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientHttpRequestFactory.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientHttpRequestFactory.java index 910206b4d..8abc3b265 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientHttpRequestFactory.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientHttpRequestFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,13 +18,15 @@ package org.springframework.cloud.netflix.ribbon; import java.io.IOException; import java.net.URI; -import org.springframework.http.HttpMethod; -import org.springframework.http.client.ClientHttpRequest; -import org.springframework.http.client.ClientHttpRequestFactory; + import com.netflix.client.config.IClientConfig; import com.netflix.client.http.HttpRequest; import com.netflix.niws.client.http.RestClient; +import org.springframework.http.HttpMethod; +import org.springframework.http.client.ClientHttpRequest; +import org.springframework.http.client.ClientHttpRequestFactory; + /** * @author Spencer Gibb */ diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientName.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientName.java index 122edb624..0a441a349 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientName.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientName.java @@ -1,6 +1,20 @@ -package org.springframework.cloud.netflix.ribbon; +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ -import org.springframework.beans.factory.annotation.Value; +package org.springframework.cloud.netflix.ribbon; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; @@ -8,16 +22,18 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.springframework.beans.factory.annotation.Value; + /** - * Annotation at the field or method/constructor parameter level that injects the - * Ribbon Client Name that got allocated at runtime. Provides a convenient - * alternative for @Value("${ribbon.client.name}"). + * Annotation at the field or method/constructor parameter level that injects the Ribbon + * Client Name that got allocated at runtime. Provides a convenient alternative for + * @Value("${ribbon.client.name}"). * * @author Spencer Gibb * @since 2.0.0 */ @Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, - ElementType.ANNOTATION_TYPE }) + ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @Value("${ribbon.client.name}") diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientSpecification.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientSpecification.java index ad1827fe6..aaf7f6c94 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientSpecification.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientSpecification.java @@ -18,6 +18,7 @@ package org.springframework.cloud.netflix.ribbon; import java.util.Arrays; import java.util.Objects; + import org.springframework.cloud.context.named.NamedContextFactory; /** @@ -55,11 +56,15 @@ public class RibbonClientSpecification implements NamedContextFactory.Specificat @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } RibbonClientSpecification that = (RibbonClientSpecification) o; - return Arrays.equals(configuration, that.configuration) && - Objects.equals(name, that.name); + return Arrays.equals(configuration, that.configuration) + && Objects.equals(name, that.name); } @Override @@ -69,10 +74,9 @@ public class RibbonClientSpecification implements NamedContextFactory.Specificat @Override public String toString() { - return new StringBuilder("RibbonClientSpecification{") - .append("name='").append(name).append("', ") - .append("configuration=").append(Arrays.toString(configuration)) - .append("}").toString(); + return new StringBuilder("RibbonClientSpecification{").append("name='") + .append(name).append("', ").append("configuration=") + .append(Arrays.toString(configuration)).append("}").toString(); } } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClients.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClients.java index 32e88cc22..cee741b6f 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClients.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClients.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,7 @@ import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; + import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonEagerLoadProperties.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonEagerLoadProperties.java index f27b6b48d..b648ff8f7 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonEagerLoadProperties.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonEagerLoadProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,17 +17,20 @@ package org.springframework.cloud.netflix.ribbon; import java.util.List; + import org.springframework.boot.context.properties.ConfigurationProperties; -/* - * Configuration Properties to indicate which Ribbon configurations - * should be eagerly loaded up - * +/** + * Configuration Properties to indicate which Ribbon configurations should be eagerly + * loaded up. + * * @author Biju Kunjummen */ @ConfigurationProperties(prefix = "ribbon.eager-load") public class RibbonEagerLoadProperties { + private boolean enabled = false; + private List clients; public boolean isEnabled() { @@ -45,4 +48,5 @@ public class RibbonEagerLoadProperties { public void setClients(List clients) { this.clients = clients; } + } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonHttpRequest.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonHttpRequest.java index 803f2cb76..0f612606e 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonHttpRequest.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonHttpRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,15 +21,17 @@ import java.io.IOException; import java.io.OutputStream; import java.net.URI; import java.util.List; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.client.AbstractClientHttpRequest; -import org.springframework.http.client.ClientHttpResponse; + import com.netflix.client.config.IClientConfig; import com.netflix.client.http.HttpRequest; import com.netflix.client.http.HttpResponse; import com.netflix.niws.client.http.RestClient; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.client.AbstractClientHttpRequest; +import org.springframework.http.client.ClientHttpResponse; + /** * @author Spencer Gibb */ @@ -37,14 +39,19 @@ import com.netflix.niws.client.http.RestClient; public class RibbonHttpRequest extends AbstractClientHttpRequest { private HttpRequest.Builder builder; + private URI uri; + private HttpRequest.Verb verb; + private RestClient client; + private IClientConfig config; + private ByteArrayOutputStream outputStream = null; public RibbonHttpRequest(URI uri, HttpRequest.Verb verb, RestClient client, - IClientConfig config) { + IClientConfig config) { this.uri = uri; this.verb = verb; this.client = client; @@ -76,8 +83,7 @@ public class RibbonHttpRequest extends AbstractClientHttpRequest { } @Override - protected ClientHttpResponse executeInternal(HttpHeaders headers) - throws IOException { + protected ClientHttpResponse executeInternal(HttpHeaders headers) throws IOException { try { addHeaders(headers); if (outputStream != null) { @@ -87,19 +93,21 @@ public class RibbonHttpRequest extends AbstractClientHttpRequest { HttpRequest request = builder.build(); HttpResponse response = client.executeWithLoadBalancer(request, config); return new RibbonHttpResponse(response); - } catch (Exception e) { + } + catch (Exception e) { throw new IOException(e); } } private void addHeaders(HttpHeaders headers) { for (String name : headers.keySet()) { - // apache http RequestContent pukes if there is a body and - // the dynamic headers are already present + // apache http RequestContent pukes if there is a body and + // the dynamic headers are already present if (isDynamic(name) && outputStream != null) { continue; } - //Don't add content-length if the output stream is null. The RibbonClient does this for us. + // Don't add content-length if the output stream is null. The RibbonClient + // does this for us. if (name.equals("Content-Length") && outputStream == null) { continue; } @@ -111,6 +119,8 @@ public class RibbonHttpRequest extends AbstractClientHttpRequest { } private boolean isDynamic(String name) { - return "Content-Length".equalsIgnoreCase(name) || "Transfer-Encoding".equalsIgnoreCase(name); + return "Content-Length".equalsIgnoreCase(name) + || "Transfer-Encoding".equalsIgnoreCase(name); } + } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonHttpResponse.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonHttpResponse.java index 12a6e1929..d704cdbfd 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonHttpResponse.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonHttpResponse.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,10 +20,12 @@ import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; + +import com.netflix.client.http.HttpResponse; + import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.client.AbstractClientHttpResponse; -import com.netflix.client.http.HttpResponse; /** * @author Spencer Gibb @@ -31,6 +33,7 @@ import com.netflix.client.http.HttpResponse; public class RibbonHttpResponse extends AbstractClientHttpResponse { private HttpResponse response; + private HttpHeaders httpHeaders; public RibbonHttpResponse(HttpResponse response) { diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancedRetryFactory.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancedRetryFactory.java index de307a9d1..b544b7ec1 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancedRetryFactory.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancedRetryFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.netflix.ribbon; import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory; @@ -33,10 +34,12 @@ public class RibbonLoadBalancedRetryFactory implements LoadBalancedRetryFactory } @Override - public LoadBalancedRetryPolicy createRetryPolicy(String service, ServiceInstanceChooser serviceInstanceChooser) { + public LoadBalancedRetryPolicy createRetryPolicy(String service, + ServiceInstanceChooser serviceInstanceChooser) { RibbonLoadBalancerContext lbContext = this.clientFactory .getLoadBalancerContext(service); - return new RibbonLoadBalancedRetryPolicy(service, lbContext, serviceInstanceChooser, clientFactory.getClientConfig(service)); + return new RibbonLoadBalancedRetryPolicy(service, lbContext, + serviceInstanceChooser, clientFactory.getClientConfig(service)); } @Override @@ -48,5 +51,5 @@ public class RibbonLoadBalancedRetryFactory implements LoadBalancedRetryFactory public BackOffPolicy createBackOffPolicy(String service) { return null; } -} +} diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancedRetryPolicy.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancedRetryPolicy.java index 05fd0abec..9047cf2c7 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancedRetryPolicy.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancedRetryPolicy.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,14 @@ package org.springframework.cloud.netflix.ribbon; import java.util.ArrayList; import java.util.List; +import com.netflix.client.config.CommonClientConfigKey; +import com.netflix.client.config.IClientConfig; +import com.netflix.client.config.IClientConfigKey; +import com.netflix.loadbalancer.Server; +import com.netflix.loadbalancer.ServerStats; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryContext; import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicy; @@ -29,48 +35,62 @@ import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient.RibbonS import org.springframework.http.HttpMethod; import org.springframework.util.StringUtils; -import com.netflix.client.config.CommonClientConfigKey; -import com.netflix.client.config.IClientConfig; -import com.netflix.client.config.IClientConfigKey; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerStats; - /** * {@link LoadBalancedRetryPolicy} for Ribbon clients. + * * @author Ryan Baxter */ public class RibbonLoadBalancedRetryPolicy implements LoadBalancedRetryPolicy { - public static final IClientConfigKey RETRYABLE_STATUS_CODES = new CommonClientConfigKey("retryableStatusCodes") {}; - private static final Log log = LogFactory.getLog(RibbonLoadBalancedRetryPolicy.class); - private int sameServerCount = 0; - private int nextServerCount = 0; - private String serviceId; - private RibbonLoadBalancerContext lbContext; - private ServiceInstanceChooser loadBalanceChooser; - List retryableStatusCodes = new ArrayList<>(); - - private static final Log LOGGER = LogFactory.getLog(RibbonLoadBalancedRetryPolicy.class); + /** + * Retrayable status codes config key. + */ + public static final IClientConfigKey RETRYABLE_STATUS_CODES = new CommonClientConfigKey( + "retryableStatusCodes") { + }; - public RibbonLoadBalancedRetryPolicy(String serviceId, RibbonLoadBalancerContext context, ServiceInstanceChooser loadBalanceChooser) { + private static final Log log = LogFactory.getLog(RibbonLoadBalancedRetryPolicy.class); + + private int sameServerCount = 0; + + private int nextServerCount = 0; + + private String serviceId; + + private RibbonLoadBalancerContext lbContext; + + private ServiceInstanceChooser loadBalanceChooser; + + List retryableStatusCodes = new ArrayList<>(); + + private static final Log LOGGER = LogFactory + .getLog(RibbonLoadBalancedRetryPolicy.class); + + public RibbonLoadBalancedRetryPolicy(String serviceId, + RibbonLoadBalancerContext context, + ServiceInstanceChooser loadBalanceChooser) { this.serviceId = serviceId; this.lbContext = context; this.loadBalanceChooser = loadBalanceChooser; } - public RibbonLoadBalancedRetryPolicy(String serviceId, RibbonLoadBalancerContext context, ServiceInstanceChooser loadBalanceChooser, - IClientConfig clientConfig) { + public RibbonLoadBalancedRetryPolicy(String serviceId, + RibbonLoadBalancerContext context, ServiceInstanceChooser loadBalanceChooser, + IClientConfig clientConfig) { this.serviceId = serviceId; this.lbContext = context; this.loadBalanceChooser = loadBalanceChooser; - String retryableStatusCodesProp = clientConfig.getPropertyAsString(RETRYABLE_STATUS_CODES, ""); + String retryableStatusCodesProp = clientConfig + .getPropertyAsString(RETRYABLE_STATUS_CODES, ""); String[] retryableStatusCodesArray = retryableStatusCodesProp.split(","); - for(String code : retryableStatusCodesArray) { - if(!StringUtils.isEmpty(code)) { + for (String code : retryableStatusCodesArray) { + if (!StringUtils.isEmpty(code)) { try { retryableStatusCodes.add(Integer.valueOf(code.trim())); - } catch (NumberFormatException e) { - log.warn("We cant add the status code because the code [ " + code + " ] could not be converted to an integer. ", e); + } + catch (NumberFormatException e) { + log.warn("We cant add the status code because the code [ " + code + + " ] could not be converted to an integer. ", e); } } } @@ -83,15 +103,17 @@ public class RibbonLoadBalancedRetryPolicy implements LoadBalancedRetryPolicy { @Override public boolean canRetrySameServer(LoadBalancedRetryContext context) { - return sameServerCount < lbContext.getRetryHandler().getMaxRetriesOnSameServer() && canRetry(context); + return sameServerCount < lbContext.getRetryHandler().getMaxRetriesOnSameServer() + && canRetry(context); } @Override public boolean canRetryNextServer(LoadBalancedRetryContext context) { - //this will be called after a failure occurs and we increment the counter - //so we check that the count is less than or equals to too make sure - //we try the next server the right number of times - return nextServerCount <= lbContext.getRetryHandler().getMaxRetriesOnNextServer() && canRetry(context); + // this will be called after a failure occurs and we increment the counter + // so we check that the count is less than or equals to too make sure + // we try the next server the right number of times + return nextServerCount <= lbContext.getRetryHandler().getMaxRetriesOnNextServer() + && canRetry(context); } @Override @@ -101,44 +123,50 @@ public class RibbonLoadBalancedRetryPolicy implements LoadBalancedRetryPolicy { @Override public void registerThrowable(LoadBalancedRetryContext context, Throwable throwable) { - //if this is a circuit tripping exception then notify the load balancer + // if this is a circuit tripping exception then notify the load balancer if (lbContext.getRetryHandler().isCircuitTrippingException(throwable)) { updateServerInstanceStats(context); } - - //Check if we need to ask the load balancer for a new server. - //Do this before we increment the counters because the first call to this method - //is not a retry it is just an initial failure. - if(!canRetrySameServer(context) && canRetryNextServer(context)) { + + // Check if we need to ask the load balancer for a new server. + // Do this before we increment the counters because the first call to this method + // is not a retry it is just an initial failure. + if (!canRetrySameServer(context) && canRetryNextServer(context)) { context.setServiceInstance(loadBalanceChooser.choose(serviceId)); } - //This method is called regardless of whether we are retrying or making the first request. - //Since we do not count the initial request in the retry count we don't reset the counter - //until we actually equal the same server count limit. This will allow us to make the initial - //request plus the right number of retries. - if(sameServerCount >= lbContext.getRetryHandler().getMaxRetriesOnSameServer() && canRetry(context)) { - //reset same server since we are moving to a new server + // This method is called regardless of whether we are retrying or making the first + // request. + // Since we do not count the initial request in the retry count we don't reset the + // counter + // until we actually equal the same server count limit. This will allow us to make + // the initial + // request plus the right number of retries. + if (sameServerCount >= lbContext.getRetryHandler().getMaxRetriesOnSameServer() + && canRetry(context)) { + // reset same server since we are moving to a new server sameServerCount = 0; nextServerCount++; - if(!canRetryNextServer(context)) { + if (!canRetryNextServer(context)) { context.setExhaustedOnly(); } - } else { + } + else { sameServerCount++; } } - + private void updateServerInstanceStats(LoadBalancedRetryContext context) { ServiceInstance serviceInstance = context.getServiceInstance(); if (serviceInstance instanceof RibbonServer) { - Server lbServer = ((RibbonServer)serviceInstance).getServer(); + Server lbServer = ((RibbonServer) serviceInstance).getServer(); ServerStats serverStats = lbContext.getServerStats(lbServer); serverStats.incrementSuccessiveConnectionFailureCount(); - serverStats.addToFailureCount(); - LOGGER.debug(lbServer.getHostPort() + " RetryCount: " + context.getRetryCount() - + " Successive Failures: " + serverStats.getSuccessiveConnectionFailureCount() - + " CircuitBreakerTripped:" + serverStats.isCircuitBreakerTripped()); + serverStats.addToFailureCount(); + LOGGER.debug(lbServer.getHostPort() + " RetryCount: " + + context.getRetryCount() + " Successive Failures: " + + serverStats.getSuccessiveConnectionFailureCount() + + " CircuitBreakerTripped:" + serverStats.isCircuitBreakerTripped()); } } @@ -146,4 +174,5 @@ public class RibbonLoadBalancedRetryPolicy implements LoadBalancedRetryPolicy { public boolean retryableStatusCode(int statusCode) { return retryableStatusCodes.contains(statusCode); } + } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancerClient.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancerClient.java index 34b053fae..fb51fbadd 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancerClient.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancerClient.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,8 +61,10 @@ public class RibbonLoadBalancerClient implements LoadBalancerClient { RibbonServer ribbonServer = (RibbonServer) instance; server = ribbonServer.getServer(); uri = updateToSecureConnectionIfNeeded(original, ribbonServer); - } else { - server = new Server(instance.getScheme(), instance.getHost(), instance.getPort()); + } + else { + server = new Server(instance.getScheme(), instance.getHost(), + instance.getPort()); IClientConfig clientConfig = clientFactory.getClientConfig(serviceId); ServerIntrospector serverIntrospector = serverIntrospector(serviceId); uri = updateToSecureConnectionIfNeeded(original, clientConfig, @@ -73,11 +75,14 @@ public class RibbonLoadBalancerClient implements LoadBalancerClient { @Override public ServiceInstance choose(String serviceId) { - return choose(serviceId, null); + return choose(serviceId, null); } /** * New: Select a server using a 'key'. + * @param serviceId of the service to choose an instance for + * @param hint to specify the service instance + * @return the selected {@link ServiceInstance} */ public ServiceInstance choose(String serviceId, Object hint) { Server server = getServer(getLoadBalancer(serviceId), hint); @@ -89,32 +94,43 @@ public class RibbonLoadBalancerClient implements LoadBalancerClient { } @Override - public T execute(String serviceId, LoadBalancerRequest request) throws IOException { - return execute(serviceId, request, null); + public T execute(String serviceId, LoadBalancerRequest request) + throws IOException { + return execute(serviceId, request, null); } /** - * New: Execute a request by selecting server using a 'key'. - * The hint will have to be the last parameter to not mess with the `execute(serviceId, ServiceInstance, request)` - * method. This somewhat breaks the fluent coding style when using a lambda to define the LoadBalancerRequest. + * New: Execute a request by selecting server using a 'key'. The hint will have to be + * the last parameter to not mess with the `execute(serviceId, ServiceInstance, + * request)` method. This somewhat breaks the fluent coding style when using a lambda + * to define the LoadBalancerRequest. + * @param returned request execution result type + * @param serviceId id of the service to execute the request to + * @param request to be executed + * @param hint used to choose appropriate {@link Server} instance + * @return request execution result + * @throws IOException executing the request may result in an {@link IOException} */ - public T execute(String serviceId, LoadBalancerRequest request, Object hint) throws IOException { + public T execute(String serviceId, LoadBalancerRequest request, Object hint) + throws IOException { ILoadBalancer loadBalancer = getLoadBalancer(serviceId); Server server = getServer(loadBalancer, hint); if (server == null) { throw new IllegalStateException("No instances available for " + serviceId); } - RibbonServer ribbonServer = new RibbonServer(serviceId, server, isSecure(server, - serviceId), serverIntrospector(serviceId).getMetadata(server)); + RibbonServer ribbonServer = new RibbonServer(serviceId, server, + isSecure(server, serviceId), + serverIntrospector(serviceId).getMetadata(server)); return execute(serviceId, ribbonServer, request); } @Override - public T execute(String serviceId, ServiceInstance serviceInstance, LoadBalancerRequest request) throws IOException { + public T execute(String serviceId, ServiceInstance serviceInstance, + LoadBalancerRequest request) throws IOException { Server server = null; - if(serviceInstance instanceof RibbonServer) { - server = ((RibbonServer)serviceInstance).getServer(); + if (serviceInstance instanceof RibbonServer) { + server = ((RibbonServer) serviceInstance).getServer(); } if (server == null) { throw new IllegalStateException("No instances available for " + serviceId); @@ -156,15 +172,13 @@ public class RibbonLoadBalancerClient implements LoadBalancerClient { return RibbonUtils.isSecure(config, serverIntrospector, server); } - /** - * Note: This method could be removed? - */ + // Note: This method could be removed? protected Server getServer(String serviceId) { return getServer(getLoadBalancer(serviceId), null); } protected Server getServer(ILoadBalancer loadBalancer) { - return getServer(loadBalancer, null); + return getServer(loadBalancer, null); } protected Server getServer(ILoadBalancer loadBalancer, Object hint) { @@ -179,10 +193,17 @@ public class RibbonLoadBalancerClient implements LoadBalancerClient { return this.clientFactory.getLoadBalancer(serviceId); } + /** + * Ribbon-server-specific {@link ServiceInstance} implementation. + */ public static class RibbonServer implements ServiceInstance { + private final String serviceId; + private final Server server; + private final boolean secure; + private Map metadata; public RibbonServer(String serviceId, Server server) { @@ -251,6 +272,7 @@ public class RibbonLoadBalancerClient implements LoadBalancerClient { sb.append('}'); return sb.toString(); } + } } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancerContext.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancerContext.java index 72eb2471b..e837b9bab 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancerContext.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancerContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,6 +27,7 @@ import com.netflix.servo.monitor.Timer; * @author Spencer Gibb */ public class RibbonLoadBalancerContext extends LoadBalancerContext { + public RibbonLoadBalancerContext(ILoadBalancer lb) { super(lb); } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonProperties.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonProperties.java index 57737041b..4d47dd37b 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonProperties.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonProperties.java @@ -1,3 +1,19 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.springframework.cloud.netflix.ribbon; import java.util.concurrent.TimeUnit; @@ -21,7 +37,14 @@ import static com.netflix.client.config.DefaultClientConfigImpl.DEFAULT_POOL_KEE import static com.netflix.client.config.DefaultClientConfigImpl.DEFAULT_PORT; import static com.netflix.client.config.DefaultClientConfigImpl.DEFAULT_READ_TIMEOUT; +/** + * Stores and allows the access to Ribbon {@link IClientConfig}. + * + * @author Spencer Gibb + * @author Tomasz Juchniewicz + */ public class RibbonProperties { + private final IClientConfig config; public static RibbonProperties from(IClientConfig config) { @@ -111,16 +134,17 @@ public class RibbonProperties { Object property = this.config.getProperty(PoolKeepAliveTime); if (property instanceof Long) { return (Long) property; - } else if (property instanceof String) { - return Long.valueOf((String) property); + } + else if (property instanceof String) { + return Long.valueOf((String) property); } return null; } public long poolKeepAliveTime() { - Long poolKeepAliveTime = getPoolKeepAliveTime(); - if (poolKeepAliveTime != null) { - return poolKeepAliveTime; + Long poolKeepAliveTime = getPoolKeepAliveTime(); + if (poolKeepAliveTime != null) { + return poolKeepAliveTime; } return DEFAULT_POOL_KEEP_ALIVE_TIME; @@ -194,4 +218,5 @@ public class RibbonProperties { public T get(IClientConfigKey key, T defaultValue) { return this.config.get(key, defaultValue); } + } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonStatsRecorder.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonStatsRecorder.java index 4f01100f9..ef70db101 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonStatsRecorder.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonStatsRecorder.java @@ -1,6 +1,23 @@ +/* + * Copyright 2016-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.springframework.cloud.netflix.ribbon; import java.util.concurrent.TimeUnit; + import com.netflix.loadbalancer.Server; import com.netflix.loadbalancer.ServerStats; import com.netflix.servo.monitor.Stopwatch; @@ -11,7 +28,9 @@ import com.netflix.servo.monitor.Stopwatch; public class RibbonStatsRecorder { private RibbonLoadBalancerContext context; + private ServerStats serverStats; + private Stopwatch tracer; public RibbonStatsRecorder(RibbonLoadBalancerContext context, Server server) { @@ -35,7 +54,9 @@ public class RibbonStatsRecorder { if (this.tracer != null && this.serverStats != null) { this.tracer.stop(); long duration = this.tracer.getDuration(TimeUnit.MILLISECONDS); - this.context.noteRequestCompletion(serverStats, entity, exception, duration, null/* errorHandler */); + this.context.noteRequestCompletion(serverStats, entity, exception, duration, + null/* errorHandler */); } } + } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonUtils.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonUtils.java index 54fac1348..a8182da0b 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonUtils.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonUtils.java @@ -1,3 +1,19 @@ +/* + * Copyright 2016-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.springframework.cloud.netflix.ribbon; import java.net.URI; @@ -23,22 +39,32 @@ import static com.netflix.client.config.CommonClientConfigKey.EnableZoneAffinity * @author Jacques-Etienne Beaudet * @author Tim Ysewyn */ -public class RibbonUtils { +public final class RibbonUtils { + /** + * Used to verify if property value is set. + */ public static final String VALUE_NOT_SET = "__not__set__"; + + /** + * Default Ribbon namespace. + */ public static final String DEFAULT_NAMESPACE = "ribbon"; private static final Map unsecureSchemeMapping; - static - { + + static { unsecureSchemeMapping = new HashMap<>(); unsecureSchemeMapping.put("http", "https"); unsecureSchemeMapping.put("ws", "wss"); } + private RibbonUtils() { + throw new AssertionError("Must not instantiate utility class."); + } + public static void initializeRibbonDefaults(String serviceId) { - setRibbonProperty(serviceId, DeploymentContextBasedVipAddresses.key(), - serviceId); + setRibbonProperty(serviceId, DeploymentContextBasedVipAddresses.key(), serviceId); setRibbonProperty(serviceId, EnableZoneAffinity.key(), "true"); } @@ -60,14 +86,16 @@ public class RibbonUtils { } /** - * Determine if client is secure. If the supplied {@link IClientConfig} has the {@link CommonClientConfigKey#IsSecure} - * set, return that value. Otherwise, query the supplied {@link ServerIntrospector}. + * Determine if client is secure. If the supplied {@link IClientConfig} has the + * {@link CommonClientConfigKey#IsSecure} set, return that value. Otherwise, query the + * supplied {@link ServerIntrospector}. * @param config the supplied client configuration. - * @param serverIntrospector - * @param server + * @param serverIntrospector used to verify if the server provides secure connections + * @param server to verify * @return true if the client is secure */ - public static boolean isSecure(IClientConfig config, ServerIntrospector serverIntrospector, Server server) { + public static boolean isSecure(IClientConfig config, + ServerIntrospector serverIntrospector, Server server) { if (config != null) { Boolean isSecure = config.get(CommonClientConfigKey.IsSecure); if (isSecure != null) { @@ -80,30 +108,28 @@ public class RibbonUtils { /** * Replace the scheme to https if needed. If the uri doesn't start with https and - * {@link #isSecure(IClientConfig, ServerIntrospector, Server)} is true, update the scheme. - * This assumes the uri is already encoded to avoid double encoding. - * - * @param uri - * @param config - * @param serverIntrospector - * @param server - * @return - * + * {@link #isSecure(IClientConfig, ServerIntrospector, Server)} is true, update the + * scheme. This assumes the uri is already encoded to avoid double encoding. + * @param uri to modify if required + * @param config Ribbon {@link IClientConfig} configuration + * @param serverIntrospector used to verify if the server provides secure connections + * @param server to verify + * @return {@link URI} updated to https if necessary * @deprecated use {@link #updateToSecureConnectionIfNeeded} */ - public static URI updateToHttpsIfNeeded(URI uri, IClientConfig config, ServerIntrospector serverIntrospector, - Server server) { + public static URI updateToHttpsIfNeeded(URI uri, IClientConfig config, + ServerIntrospector serverIntrospector, Server server) { return updateToSecureConnectionIfNeeded(uri, config, serverIntrospector, server); } /** - * Replace the scheme to the secure variant if needed. If the {@link #unsecureSchemeMapping} map contains the uri - * scheme and {@link #isSecure(IClientConfig, ServerIntrospector, Server)} is true, update the scheme. - * This assumes the uri is already encoded to avoid double encoding. - * - * @param uri - * @param ribbonServer - * @return + * Replace the scheme to the secure variant if needed. If the + * {@link #unsecureSchemeMapping} map contains the uri scheme and + * {@link #isSecure(IClientConfig, ServerIntrospector, Server)} is true, update the + * scheme. This assumes the uri is already encoded to avoid double encoding. + * @param uri to modify if required + * @param ribbonServer to verify if it provides secure connections + * @return {@link URI} updated if required */ static URI updateToSecureConnectionIfNeeded(URI uri, ServiceInstance ribbonServer) { String scheme = uri.getScheme(); @@ -113,26 +139,25 @@ public class RibbonUtils { } if (!StringUtils.isEmpty(uri.toString()) - && unsecureSchemeMapping.containsKey(scheme) - && ribbonServer.isSecure()) { + && unsecureSchemeMapping.containsKey(scheme) && ribbonServer.isSecure()) { return upgradeConnection(uri, unsecureSchemeMapping.get(scheme)); } return uri; } /** - * Replace the scheme to the secure variant if needed. If the {@link #unsecureSchemeMapping} map contains the uri - * scheme and {@link #isSecure(IClientConfig, ServerIntrospector, Server)} is true, update the scheme. - * This assumes the uri is already encoded to avoid double encoding. - * - * @param uri - * @param config - * @param serverIntrospector - * @param server - * @return + * Replace the scheme to the secure variant if needed. If the + * {@link #unsecureSchemeMapping} map contains the uri scheme and + * {@link #isSecure(IClientConfig, ServerIntrospector, Server)} is true, update the + * scheme. This assumes the uri is already encoded to avoid double encoding. + * @param uri to modify if required + * @param config the supplied client configuration + * @param serverIntrospector used to verify if the server provides secure connections + * @param server to verify + * @return {@link URI} updated if required */ public static URI updateToSecureConnectionIfNeeded(URI uri, IClientConfig config, - ServerIntrospector serverIntrospector, Server server) { + ServerIntrospector serverIntrospector, Server server) { String scheme = uri.getScheme(); if (StringUtils.isEmpty(scheme)) { @@ -148,13 +173,16 @@ public class RibbonUtils { } private static URI upgradeConnection(URI uri, String scheme) { - UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUri(uri).scheme(scheme); + UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUri(uri) + .scheme(scheme); if (uri.getRawQuery() != null) { - // When building the URI, UriComponentsBuilder verify the allowed characters and does not + // When building the URI, UriComponentsBuilder verify the allowed characters + // and does not // support the '+' so we replace it for its equivalent '%20'. // See issue https://jira.spring.io/browse/SPR-10172 uriComponentsBuilder.replaceQuery(uri.getRawQuery().replace("+", "%20")); } return uriComponentsBuilder.build(true).toUri(); } + } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ServerIntrospector.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ServerIntrospector.java index d63641784..cfa2c5ea0 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ServerIntrospector.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ServerIntrospector.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ package org.springframework.cloud.netflix.ribbon; import java.util.Map; + import com.netflix.loadbalancer.Server; /** @@ -27,4 +28,5 @@ public interface ServerIntrospector { boolean isSecure(Server server); Map getMetadata(Server server); + } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ServerIntrospectorProperties.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ServerIntrospectorProperties.java index ce8633457..1250e2fe3 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ServerIntrospectorProperties.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ServerIntrospectorProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ package org.springframework.cloud.netflix.ribbon; import java.util.Arrays; import java.util.List; import java.util.Objects; + import org.springframework.boot.context.properties.ConfigurationProperties; /** @@ -28,7 +29,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties("ribbon") public class ServerIntrospectorProperties { - private List securePorts = Arrays.asList(443,8443); + private List securePorts = Arrays.asList(443, 8443); public List getSecurePorts() { return securePorts; @@ -40,8 +41,12 @@ public class ServerIntrospectorProperties { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } ServerIntrospectorProperties that = (ServerIntrospectorProperties) o; return Objects.equals(securePorts, that.securePorts); } @@ -53,9 +58,8 @@ public class ServerIntrospectorProperties { @Override public String toString() { - return new StringBuilder("ServerIntrospectorProperties{") - .append("securePorts=").append(securePorts) - .append("}").toString(); + return new StringBuilder("ServerIntrospectorProperties{").append("securePorts=") + .append(securePorts).append("}").toString(); } } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/SpringClientFactory.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/SpringClientFactory.java index d23408743..15121f7da 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/SpringClientFactory.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/SpringClientFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,14 +17,16 @@ package org.springframework.cloud.netflix.ribbon; import java.lang.reflect.Constructor; -import org.springframework.beans.BeanUtils; -import org.springframework.cloud.context.named.NamedContextFactory; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; + import com.netflix.client.IClient; import com.netflix.client.IClientConfigAware; import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.ILoadBalancer; +import org.springframework.beans.BeanUtils; +import org.springframework.cloud.context.named.NamedContextFactory; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + /** * A factory that creates client, load balancer and client configuration instances. It * creates a Spring ApplicationContext per client name, and extracts the beans that it @@ -43,6 +45,10 @@ public class SpringClientFactory extends NamedContextFactory {@link IClient} subtype + * @return {@link IClient} instance * @throws RuntimeException if any error occurs */ public > C getClient(String name, Class clientClass) { @@ -51,6 +57,8 @@ public class SpringClientFactory extends NamedContextFactory C instantiateWithConfig(AnnotationConfigApplicationContext context, - Class clazz, IClientConfig config) { + Class clazz, IClientConfig config) { C result = null; - + try { Constructor constructor = clazz.getConstructor(IClientConfig.class); result = constructor.newInstance(config); - } catch (Throwable e) { + } + catch (Throwable e) { // Ignored } - + if (result == null) { result = BeanUtils.instantiate(clazz); - + if (result instanceof IClientConfigAware) { ((IClientConfigAware) result).initWithNiwsConfig(config); } - + if (context != null) { context.getAutowireCapableBeanFactory().autowireBean(result); } } - + return result; } @@ -119,4 +132,3 @@ public class SpringClientFactory extends NamedContextFactory {@link Server} subtype * @author Spencer Gibb */ public class StaticServerList implements ServerList { @@ -41,4 +45,5 @@ public class StaticServerList implements ServerList { public List getUpdatedListOfServers() { return servers; } + } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ZonePreferenceServerListFilter.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ZonePreferenceServerListFilter.java index b0defeaa4..d4f86b35f 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ZonePreferenceServerListFilter.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ZonePreferenceServerListFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ package org.springframework.cloud.netflix.ribbon; import java.util.ArrayList; import java.util.List; import java.util.Objects; + import com.netflix.client.config.IClientConfig; import com.netflix.config.ConfigurationManager; import com.netflix.config.DeploymentContext.ContextKey; @@ -39,8 +40,8 @@ public class ZonePreferenceServerListFilter extends ZoneAffinityServerListFilter public void initWithNiwsConfig(IClientConfig niwsClientConfig) { super.initWithNiwsConfig(niwsClientConfig); if (ConfigurationManager.getDeploymentContext() != null) { - this.zone = ConfigurationManager.getDeploymentContext().getValue( - ContextKey.zone); + this.zone = ConfigurationManager.getDeploymentContext() + .getValue(ContextKey.zone); } } @@ -71,8 +72,12 @@ public class ZonePreferenceServerListFilter extends ZoneAffinityServerListFilter @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } ZonePreferenceServerListFilter that = (ZonePreferenceServerListFilter) o; return Objects.equals(zone, that.zone); } @@ -84,9 +89,8 @@ public class ZonePreferenceServerListFilter extends ZoneAffinityServerListFilter @Override public String toString() { - return new StringBuilder("ZonePreferenceServerListFilter{") - .append("zone='").append(zone).append("'") - .append("}").toString(); + return new StringBuilder("ZonePreferenceServerListFilter{").append("zone='") + .append(zone).append("'").append("}").toString(); } } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientRibbonConfiguration.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientRibbonConfiguration.java index a02b4b1ae..5da66d9a6 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientRibbonConfiguration.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientRibbonConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.ribbon.apache; @@ -23,10 +22,16 @@ import java.util.concurrent.TimeUnit; import javax.annotation.PreDestroy; +import com.netflix.client.AbstractLoadBalancerAwareClient; +import com.netflix.client.RetryHandler; +import com.netflix.client.config.IClientConfig; +import com.netflix.loadbalancer.ILoadBalancer; +import com.netflix.servo.monitor.Monitors; import org.apache.http.client.config.RequestConfig; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.impl.client.CloseableHttpClient; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; @@ -42,12 +47,6 @@ import org.springframework.cloud.netflix.ribbon.ServerIntrospector; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import com.netflix.client.AbstractLoadBalancerAwareClient; -import com.netflix.client.RetryHandler; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.ILoadBalancer; -import com.netflix.servo.monitor.Monitors; - /** * @author Spencer Gibb */ @@ -55,13 +54,49 @@ import com.netflix.servo.monitor.Monitors; @ConditionalOnClass(name = "org.apache.http.client.HttpClient") @ConditionalOnProperty(name = "ribbon.httpclient.enabled", matchIfMissing = true) public class HttpClientRibbonConfiguration { + @RibbonClientName private String name = "client"; + @Bean + @ConditionalOnMissingBean(AbstractLoadBalancerAwareClient.class) + @ConditionalOnMissingClass("org.springframework.retry.support.RetryTemplate") + public RibbonLoadBalancingHttpClient ribbonLoadBalancingHttpClient( + IClientConfig config, ServerIntrospector serverIntrospector, + ILoadBalancer loadBalancer, RetryHandler retryHandler, + CloseableHttpClient httpClient) { + RibbonLoadBalancingHttpClient client = new RibbonLoadBalancingHttpClient( + httpClient, config, serverIntrospector); + client.setLoadBalancer(loadBalancer); + client.setRetryHandler(retryHandler); + Monitors.registerObject("Client_" + this.name, client); + return client; + } + + @Bean + @ConditionalOnMissingBean(AbstractLoadBalancerAwareClient.class) + @ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate") + public RetryableRibbonLoadBalancingHttpClient retryableRibbonLoadBalancingHttpClient( + IClientConfig config, ServerIntrospector serverIntrospector, + ILoadBalancer loadBalancer, RetryHandler retryHandler, + LoadBalancedRetryFactory loadBalancedRetryFactory, + CloseableHttpClient httpClient, + RibbonLoadBalancerContext ribbonLoadBalancerContext) { + RetryableRibbonLoadBalancingHttpClient client = new RetryableRibbonLoadBalancingHttpClient( + httpClient, config, serverIntrospector, loadBalancedRetryFactory); + client.setLoadBalancer(loadBalancer); + client.setRetryHandler(retryHandler); + client.setRibbonLoadBalancerContext(ribbonLoadBalancerContext); + Monitors.registerObject("Client_" + this.name, client); + return client; + } + @Configuration protected static class ApacheHttpClientConfiguration { + private final Timer connectionManagerTimer = new Timer( "RibbonApacheHttpClientConfiguration.connectionManagerTimer", true); + private CloseableHttpClient httpClient; @Autowired(required = false) @@ -93,55 +128,27 @@ public class HttpClientRibbonConfiguration { @Bean @ConditionalOnMissingBean(CloseableHttpClient.class) public CloseableHttpClient httpClient(ApacheHttpClientFactory httpClientFactory, - HttpClientConnectionManager connectionManager, IClientConfig config) { + HttpClientConnectionManager connectionManager, IClientConfig config) { RibbonProperties ribbon = RibbonProperties.from(config); Boolean followRedirects = ribbon.isFollowRedirects(); Integer connectTimeout = ribbon.connectTimeout(); RequestConfig defaultRequestConfig = RequestConfig.custom() .setConnectTimeout(connectTimeout) .setRedirectsEnabled(followRedirects).build(); - this.httpClient = httpClientFactory.createBuilder(). - setDefaultRequestConfig(defaultRequestConfig). - setConnectionManager(connectionManager).build(); + this.httpClient = httpClientFactory.createBuilder() + .setDefaultRequestConfig(defaultRequestConfig) + .setConnectionManager(connectionManager).build(); return httpClient; } @PreDestroy public void destroy() throws Exception { connectionManagerTimer.cancel(); - if(httpClient != null) { + if (httpClient != null) { httpClient.close(); } } + } - @Bean - @ConditionalOnMissingBean(AbstractLoadBalancerAwareClient.class) - @ConditionalOnMissingClass(value = "org.springframework.retry.support.RetryTemplate") - public RibbonLoadBalancingHttpClient ribbonLoadBalancingHttpClient( - IClientConfig config, ServerIntrospector serverIntrospector, - ILoadBalancer loadBalancer, RetryHandler retryHandler, CloseableHttpClient httpClient) { - RibbonLoadBalancingHttpClient client = new RibbonLoadBalancingHttpClient(httpClient, config, serverIntrospector); - client.setLoadBalancer(loadBalancer); - client.setRetryHandler(retryHandler); - Monitors.registerObject("Client_" + this.name, client); - return client; - } - - @Bean - @ConditionalOnMissingBean(AbstractLoadBalancerAwareClient.class) - @ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate") - public RetryableRibbonLoadBalancingHttpClient retryableRibbonLoadBalancingHttpClient( - IClientConfig config, ServerIntrospector serverIntrospector, - ILoadBalancer loadBalancer, RetryHandler retryHandler, - LoadBalancedRetryFactory loadBalancedRetryFactory, CloseableHttpClient httpClient, - RibbonLoadBalancerContext ribbonLoadBalancerContext) { - RetryableRibbonLoadBalancingHttpClient client = new RetryableRibbonLoadBalancingHttpClient( - httpClient, config, serverIntrospector, loadBalancedRetryFactory); - client.setLoadBalancer(loadBalancer); - client.setRetryHandler(retryHandler); - client.setRibbonLoadBalancerContext(ribbonLoadBalancerContext); - Monitors.registerObject("Client_" + this.name, client); - return client; - } } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientStatusCodeException.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientStatusCodeException.java index 8e53719ba..d770a8271 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientStatusCodeException.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientStatusCodeException.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,28 +13,30 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.netflix.ribbon.apache; -import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.URI; + import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.entity.BasicHttpEntity; import org.apache.http.message.BasicHttpResponse; import org.apache.http.util.EntityUtils; + import org.springframework.cloud.client.loadbalancer.RetryableStatusCodeException; /** - * A {@link RetryableStatusCodeException} for {@link HttpResponse}s + * A {@link RetryableStatusCodeException} for {@link HttpResponse}s. + * * @author Ryan Baxter */ public class HttpClientStatusCodeException extends RetryableStatusCodeException { - private BasicHttpResponse response; + private final BasicHttpResponse response; - public HttpClientStatusCodeException(String serviceId, HttpResponse response, HttpEntity entity, URI uri) throws IOException { + public HttpClientStatusCodeException(String serviceId, HttpResponse response, + HttpEntity entity, URI uri) throws IOException { super(serviceId, response.getStatusLine().getStatusCode(), response, uri); this.response = new BasicHttpResponse(response.getStatusLine()); this.response.setLocale(response.getLocale()); @@ -48,4 +50,5 @@ public class HttpClientStatusCodeException extends RetryableStatusCodeException public HttpResponse getResponse() { return this.response; } + } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientUtils.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientUtils.java index 67c70612d..bfdb07843 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientUtils.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,10 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.netflix.ribbon.apache; import java.io.ByteArrayInputStream; import java.io.IOException; + import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.CloseableHttpResponse; @@ -24,14 +26,19 @@ import org.apache.http.entity.BasicHttpEntity; import org.apache.http.util.EntityUtils; /** - * Provides basic utilities for {@link org.apache.http.client.HttpClient} + * Provides basic utilities for {@link org.apache.http.client.HttpClient}. + * * @author Ryan Baxter */ -public class HttpClientUtils { +public final class HttpClientUtils { + + private HttpClientUtils() { + throw new AssertionError("Must not instantiate utility class."); + } /** - * Creates an new {@link HttpEntity} by copying the {@link HttpEntity} from the {@link HttpResponse}. - * This method will close the response after copying the entity. + * Creates an new {@link HttpEntity} by copying the {@link HttpEntity} from the + * {@link HttpResponse}. This method will close the response after copying the entity. * @param response The response to create the {@link HttpEntity} from * @return A new {@link HttpEntity} * @throws IOException thrown if there is a problem closing the response. @@ -42,9 +49,10 @@ public class HttpClientUtils { BasicHttpEntity entity = new BasicHttpEntity(); entity.setContent(is); entity.setContentLength(response.getEntity().getContentLength()); - if(CloseableHttpResponse.class.isInstance(response)) { - ((CloseableHttpResponse)response).close(); + if (CloseableHttpResponse.class.isInstance(response)) { + ((CloseableHttpResponse) response).close(); } return entity; } + } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RetryableRibbonLoadBalancingHttpClient.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RetryableRibbonLoadBalancingHttpClient.java index 021395ba3..2138abe10 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RetryableRibbonLoadBalancingHttpClient.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RetryableRibbonLoadBalancingHttpClient.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,28 +13,33 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.netflix.ribbon.apache; import java.net.URI; +import com.netflix.client.RequestSpecificRetryHandler; +import com.netflix.client.RetryHandler; +import com.netflix.client.config.IClientConfig; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpResponse; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.CloseableHttpClient; + import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.loadbalancer.InterceptorRetryPolicy; import org.springframework.cloud.client.loadbalancer.LoadBalancedRecoveryCallback; import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryContext; import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory; import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicy; import org.springframework.cloud.client.loadbalancer.ServiceInstanceChooser; -import org.springframework.cloud.client.loadbalancer.InterceptorRetryPolicy; +import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient.RibbonServer; +import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerContext; import org.springframework.cloud.netflix.ribbon.RibbonProperties; import org.springframework.cloud.netflix.ribbon.RibbonStatsRecorder; import org.springframework.cloud.netflix.ribbon.ServerIntrospector; -import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient.RibbonServer; -import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerContext; import org.springframework.cloud.netflix.ribbon.support.ContextAwareRequest; import org.springframework.http.HttpRequest; import org.springframework.retry.RecoveryCallback; @@ -46,30 +51,32 @@ import org.springframework.retry.policy.NeverRetryPolicy; import org.springframework.retry.support.RetryTemplate; import org.springframework.web.util.UriComponentsBuilder; -import com.netflix.client.RequestSpecificRetryHandler; -import com.netflix.client.RetryHandler; -import com.netflix.client.config.IClientConfig; - /** * An Apache HTTP client which leverages Spring Retry to retry failed requests. + * * @author Ryan Baxter * @author Gang Li */ -public class RetryableRibbonLoadBalancingHttpClient extends RibbonLoadBalancingHttpClient { - private static final Log LOGGER = LogFactory.getLog(RetryableRibbonLoadBalancingHttpClient.class); +public class RetryableRibbonLoadBalancingHttpClient + extends RibbonLoadBalancingHttpClient { + + private static final Log LOGGER = LogFactory + .getLog(RetryableRibbonLoadBalancingHttpClient.class); private LoadBalancedRetryFactory loadBalancedRetryFactory; + private RibbonLoadBalancerContext ribbonLoadBalancerContext; public RetryableRibbonLoadBalancingHttpClient(CloseableHttpClient delegate, - IClientConfig config, ServerIntrospector serverIntrospector, - LoadBalancedRetryFactory loadBalancedRetryFactory) { + IClientConfig config, ServerIntrospector serverIntrospector, + LoadBalancedRetryFactory loadBalancedRetryFactory) { super(delegate, config, serverIntrospector); this.loadBalancedRetryFactory = loadBalancedRetryFactory; } @Override - public RibbonApacheHttpResponse execute(final RibbonApacheHttpRequest request, final IClientConfig configOverride) throws Exception { + public RibbonApacheHttpResponse execute(final RibbonApacheHttpRequest request, + final IClientConfig configOverride) throws Exception { final RequestConfig.Builder builder = RequestConfig.custom(); IClientConfig config = configOverride != null ? configOverride : this.config; RibbonProperties ribbon = RibbonProperties.from(config); @@ -79,37 +86,49 @@ public class RetryableRibbonLoadBalancingHttpClient extends RibbonLoadBalancingH builder.setContentCompressionEnabled(ribbon.isGZipPayload(this.gzipPayload)); final RequestConfig requestConfig = builder.build(); - final LoadBalancedRetryPolicy retryPolicy = loadBalancedRetryFactory.createRetryPolicy(this.getClientName(), this); + final LoadBalancedRetryPolicy retryPolicy = loadBalancedRetryFactory + .createRetryPolicy(this.getClientName(), this); RetryCallback retryCallback = context -> { - //on retries the policy will choose the server and set it in the context - //extract the server and update the request being made + // on retries the policy will choose the server and set it in the context + // extract the server and update the request being made RibbonApacheHttpRequest newRequest = request; RibbonStatsRecorder statsRecorder = null; if (context instanceof LoadBalancedRetryContext) { - ServiceInstance service = ((LoadBalancedRetryContext) context).getServiceInstance(); + ServiceInstance service = ((LoadBalancedRetryContext) context) + .getServiceInstance(); validateServiceInstance(service); if (service != null) { - //Reconstruct the request URI using the host and port set in the retry context - newRequest = newRequest.withNewUri(UriComponentsBuilder.newInstance().host(service.getHost()) - .scheme(service.getUri().getScheme()).userInfo(newRequest.getURI().getUserInfo()) + // Reconstruct the request URI using the host and port set in the + // retry context + newRequest = newRequest.withNewUri(UriComponentsBuilder.newInstance() + .host(service.getHost()).scheme(service.getUri().getScheme()) + .userInfo(newRequest.getURI().getUserInfo()) .port(service.getPort()).path(newRequest.getURI().getPath()) - .query(newRequest.getURI().getQuery()).fragment(newRequest.getURI().getFragment()) - .build().encode().toUri()); - + .query(newRequest.getURI().getQuery()) + .fragment(newRequest.getURI().getFragment()).build().encode() + .toUri()); + if (ribbonLoadBalancerContext == null) { - LOGGER.error("RibbonLoadBalancerContext is null. Unable to update load balancer stats"); - } else if (service instanceof RibbonServer) { - statsRecorder = new RibbonStatsRecorder(ribbonLoadBalancerContext, ((RibbonServer)service).getServer()); + LOGGER.error( + "RibbonLoadBalancerContext is null. Unable to update load balancer stats"); + } + else if (service instanceof RibbonServer) { + statsRecorder = new RibbonStatsRecorder(ribbonLoadBalancerContext, + ((RibbonServer) service).getServer()); } } } newRequest = getSecureRequest(newRequest, configOverride); HttpUriRequest httpUriRequest = newRequest.toRequest(requestConfig); - final HttpResponse httpResponse = RetryableRibbonLoadBalancingHttpClient.this.delegate.execute(httpUriRequest); - if (retryPolicy.retryableStatusCode(httpResponse.getStatusLine().getStatusCode())) { - throw new HttpClientStatusCodeException(RetryableRibbonLoadBalancingHttpClient.this.clientName, - httpResponse, HttpClientUtils.createEntity(httpResponse), httpUriRequest.getURI()); + final HttpResponse httpResponse = RetryableRibbonLoadBalancingHttpClient.this.delegate + .execute(httpUriRequest); + if (retryPolicy + .retryableStatusCode(httpResponse.getStatusLine().getStatusCode())) { + throw new HttpClientStatusCodeException( + RetryableRibbonLoadBalancingHttpClient.this.clientName, + httpResponse, HttpClientUtils.createEntity(httpResponse), + httpUriRequest.getURI()); } if (statsRecorder != null) { statsRecorder.recordStats(httpResponse); @@ -118,16 +137,18 @@ public class RetryableRibbonLoadBalancingHttpClient extends RibbonLoadBalancingH }; LoadBalancedRecoveryCallback recoveryCallback = new LoadBalancedRecoveryCallback() { @Override - protected RibbonApacheHttpResponse createResponse(HttpResponse response, URI uri) { + protected RibbonApacheHttpResponse createResponse(HttpResponse response, + URI uri) { return new RibbonApacheHttpResponse(response, uri); } }; - return this.executeWithRetry(request, retryPolicy, retryCallback, recoveryCallback); + return this.executeWithRetry(request, retryPolicy, retryCallback, + recoveryCallback); } - + @Override public boolean isClientRetryable(ContextAwareRequest request) { - return request!= null && isRequestRetryable(request); + return request != null && isRequestRetryable(request); } private boolean isRequestRetryable(ContextAwareRequest request) { @@ -137,16 +158,22 @@ public class RetryableRibbonLoadBalancingHttpClient extends RibbonLoadBalancingH return request.getContext().getRetryable(); } - private RibbonApacheHttpResponse executeWithRetry(RibbonApacheHttpRequest request, LoadBalancedRetryPolicy retryPolicy, - RetryCallback callback, - RecoveryCallback recoveryCallback) throws Exception { + private RibbonApacheHttpResponse executeWithRetry(RibbonApacheHttpRequest request, + LoadBalancedRetryPolicy retryPolicy, + RetryCallback callback, + RecoveryCallback recoveryCallback) + throws Exception { RetryTemplate retryTemplate = new RetryTemplate(); boolean retryable = isRequestRetryable(request); - retryTemplate.setRetryPolicy(retryPolicy == null || !retryable ? new NeverRetryPolicy() + retryTemplate.setRetryPolicy(retryPolicy == null || !retryable + ? new NeverRetryPolicy() : new RetryPolicy(request, retryPolicy, this, this.getClientName())); - BackOffPolicy backOffPolicy = loadBalancedRetryFactory.createBackOffPolicy(this.getClientName()); - retryTemplate.setBackOffPolicy(backOffPolicy == null ? new NoBackOffPolicy() : backOffPolicy); - RetryListener[] retryListeners = this.loadBalancedRetryFactory.createRetryListeners(this.getClientName()); + BackOffPolicy backOffPolicy = loadBalancedRetryFactory + .createBackOffPolicy(this.getClientName()); + retryTemplate.setBackOffPolicy( + backOffPolicy == null ? new NoBackOffPolicy() : backOffPolicy); + RetryListener[] retryListeners = this.loadBalancedRetryFactory + .createRetryListeners(this.getClientName()); if (retryListeners != null && retryListeners.length != 0) { retryTemplate.setListeners(retryListeners); } @@ -154,19 +181,23 @@ public class RetryableRibbonLoadBalancingHttpClient extends RibbonLoadBalancingH } @Override - public RequestSpecificRetryHandler getRequestSpecificRetryHandler(RibbonApacheHttpRequest request, IClientConfig requestConfig) { + public RequestSpecificRetryHandler getRequestSpecificRetryHandler( + RibbonApacheHttpRequest request, IClientConfig requestConfig) { return new RequestSpecificRetryHandler(false, false, RetryHandler.DEFAULT, null); } + public void setRibbonLoadBalancerContext( + RibbonLoadBalancerContext ribbonLoadBalancerContext) { + this.ribbonLoadBalancerContext = ribbonLoadBalancerContext; + } + static class RetryPolicy extends InterceptorRetryPolicy { - public RetryPolicy(HttpRequest request, LoadBalancedRetryPolicy policy, + + RetryPolicy(HttpRequest request, LoadBalancedRetryPolicy policy, ServiceInstanceChooser serviceInstanceChooser, String serviceName) { super(request, policy, serviceInstanceChooser, serviceName); } + } - public void setRibbonLoadBalancerContext(RibbonLoadBalancerContext ribbonLoadBalancerContext) { - this.ribbonLoadBalancerContext = ribbonLoadBalancerContext; - } - } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpRequest.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpRequest.java index ed11f8f68..d8db563ac 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpRequest.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,12 +18,14 @@ package org.springframework.cloud.netflix.ribbon.apache; import java.net.URI; import java.util.List; + import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.entity.BasicHttpEntity; -import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; + import org.springframework.cloud.netflix.ribbon.support.ContextAwareRequest; +import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; import static org.springframework.cloud.netflix.ribbon.support.RibbonRequestCustomizer.Runner.customize; @@ -60,9 +62,11 @@ public class RibbonApacheHttpRequest extends ContextAwareRequest implements Clon // if the entity contentLength isn't set, transfer-encoding will be set // to chunked in org.apache.http.protocol.RequestContent. See gh-1042 Long contentLength = this.context.getContentLength(); - if ("GET".equals(this.context.getMethod()) && (contentLength == null || contentLength < 0)) { + if ("GET".equals(this.context.getMethod()) + && (contentLength == null || contentLength < 0)) { entity.setContentLength(0); - } else if (contentLength != null) { + } + else if (contentLength != null) { entity.setContentLength(contentLength); } builder.setEntity(entity); diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpResponse.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpResponse.java index 689fff082..f09730739 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpResponse.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpResponse.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,14 +25,16 @@ import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.apache.http.Header; -import org.apache.http.HttpResponse; -import org.springframework.http.HttpStatus; -import org.springframework.util.Assert; + import com.google.common.reflect.TypeToken; import com.netflix.client.ClientException; import com.netflix.client.http.CaseInsensitiveMultiMap; import com.netflix.client.http.HttpHeaders; +import org.apache.http.Header; +import org.apache.http.HttpResponse; + +import org.springframework.http.HttpStatus; +import org.springframework.util.Assert; /** * @author Christian Lohmann @@ -40,6 +42,7 @@ import com.netflix.client.http.HttpHeaders; public class RibbonApacheHttpResponse implements com.netflix.client.http.HttpResponse { private HttpResponse httpResponse; + private URI uri; public RibbonApacheHttpResponse(final HttpResponse httpResponse, final URI uri) { @@ -68,7 +71,8 @@ public class RibbonApacheHttpResponse implements com.netflix.client.http.HttpRes @Override public boolean isSuccess() { - return HttpStatus.valueOf(this.httpResponse.getStatusLine().getStatusCode()).is2xxSuccessful(); + return HttpStatus.valueOf(this.httpResponse.getStatusLine().getStatusCode()) + .is2xxSuccessful(); } @Override @@ -143,7 +147,7 @@ public class RibbonApacheHttpResponse implements com.netflix.client.http.HttpRes } /** - * Not used + * Not used. */ @Override public T getEntity(final Class type) throws Exception { @@ -151,7 +155,7 @@ public class RibbonApacheHttpResponse implements com.netflix.client.http.HttpRes } /** - * Not used + * Not used. */ @Override public T getEntity(final Type type) throws Exception { @@ -159,10 +163,11 @@ public class RibbonApacheHttpResponse implements com.netflix.client.http.HttpRes } /** - * Not used + * Not used. */ @Override public T getEntity(final TypeToken type) throws Exception { return null; } + } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonLoadBalancingHttpClient.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonLoadBalancingHttpClient.java index 21f688931..6f67826a7 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonLoadBalancingHttpClient.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonLoadBalancingHttpClient.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,21 +18,21 @@ package org.springframework.cloud.netflix.ribbon.apache; import java.net.URI; +import com.netflix.client.RequestSpecificRetryHandler; +import com.netflix.client.RetryHandler; +import com.netflix.client.config.IClientConfig; +import com.netflix.loadbalancer.Server; import org.apache.http.HttpResponse; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; + import org.springframework.cloud.netflix.ribbon.RibbonProperties; import org.springframework.cloud.netflix.ribbon.ServerIntrospector; import org.springframework.cloud.netflix.ribbon.support.AbstractLoadBalancingClient; import org.springframework.web.util.UriComponentsBuilder; -import com.netflix.client.RequestSpecificRetryHandler; -import com.netflix.client.RetryHandler; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.Server; - import static org.springframework.cloud.netflix.ribbon.RibbonUtils.updateToSecureConnectionIfNeeded; /** @@ -40,7 +40,8 @@ import static org.springframework.cloud.netflix.ribbon.RibbonUtils.updateToSecur * @author Ryan Baxter * @author Tim Ysewyn */ -// TODO: rename (ie new class that extends this in Dalston) to ApacheHttpLoadBalancingClient +// TODO: rename (ie new class that extends this in Dalston) to +// ApacheHttpLoadBalancingClient public class RibbonLoadBalancingHttpClient extends AbstractLoadBalancingClient { @@ -67,7 +68,7 @@ public class RibbonLoadBalancingHttpClient extends @Override public RibbonApacheHttpResponse execute(RibbonApacheHttpRequest request, - final IClientConfig configOverride) throws Exception { + final IClientConfig configOverride) throws Exception { IClientConfig config = configOverride != null ? configOverride : this.config; RibbonProperties ribbon = RibbonProperties.from(config); RequestConfig requestConfig = RequestConfig.custom() @@ -85,8 +86,8 @@ public class RibbonLoadBalancingHttpClient extends @Override public URI reconstructURIWithServer(Server server, URI original) { - URI uri = updateToSecureConnectionIfNeeded(original, this.config, this.serverIntrospector, - server); + URI uri = updateToSecureConnectionIfNeeded(original, this.config, + this.serverIntrospector, server); return super.reconstructURIWithServer(server, uri); } @@ -97,7 +98,8 @@ public class RibbonLoadBalancingHttpClient extends requestConfig); } - protected RibbonApacheHttpRequest getSecureRequest(RibbonApacheHttpRequest request, IClientConfig configOverride) { + protected RibbonApacheHttpRequest getSecureRequest(RibbonApacheHttpRequest request, + IClientConfig configOverride) { if (isSecure(configOverride)) { final URI secureUri = UriComponentsBuilder.fromUri(request.getUri()) .scheme("https").build(true).toUri(); @@ -105,4 +107,5 @@ public class RibbonLoadBalancingHttpClient extends } return request; } + } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpLoadBalancingClient.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpLoadBalancingClient.java index b488f8e11..2cc3196b0 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpLoadBalancingClient.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpLoadBalancingClient.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,27 +19,26 @@ package org.springframework.cloud.netflix.ribbon.okhttp; import java.net.URI; import java.util.concurrent.TimeUnit; +import com.netflix.client.config.IClientConfig; +import com.netflix.loadbalancer.Server; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; + import org.springframework.cloud.netflix.ribbon.RibbonProperties; import org.springframework.cloud.netflix.ribbon.ServerIntrospector; import org.springframework.cloud.netflix.ribbon.support.AbstractLoadBalancingClient; import org.springframework.web.util.UriComponentsBuilder; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.Server; - import static org.springframework.cloud.netflix.ribbon.RibbonUtils.updateToSecureConnectionIfNeeded; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; - /** * @author Spencer Gibb * @author Ryan Baxter * @author Tim Ysewyn */ -public class OkHttpLoadBalancingClient - extends AbstractLoadBalancingClient { +public class OkHttpLoadBalancingClient extends + AbstractLoadBalancingClient { public OkHttpLoadBalancingClient(IClientConfig config, ServerIntrospector serverIntrospector) { @@ -47,7 +46,7 @@ public class OkHttpLoadBalancingClient } public OkHttpLoadBalancingClient(OkHttpClient delegate, IClientConfig config, - ServerIntrospector serverIntrospector) { + ServerIntrospector serverIntrospector) { super(delegate, config, serverIntrospector); } @@ -58,7 +57,7 @@ public class OkHttpLoadBalancingClient @Override public OkHttpRibbonResponse execute(OkHttpRibbonRequest ribbonRequest, - final IClientConfig configOverride) throws Exception { + final IClientConfig configOverride) throws Exception { boolean secure = isSecure(configOverride); if (secure) { final URI secureUri = UriComponentsBuilder.fromUri(ribbonRequest.getUri()) @@ -76,7 +75,8 @@ public class OkHttpLoadBalancingClient IClientConfig config = configOverride != null ? configOverride : this.config; RibbonProperties ribbon = RibbonProperties.from(config); OkHttpClient.Builder builder = this.delegate.newBuilder() - .connectTimeout(ribbon.connectTimeout(this.connectTimeout), TimeUnit.MILLISECONDS) + .connectTimeout(ribbon.connectTimeout(this.connectTimeout), + TimeUnit.MILLISECONDS) .readTimeout(ribbon.readTimeout(this.readTimeout), TimeUnit.MILLISECONDS) .followRedirects(ribbon.isFollowRedirects(this.followRedirects)); if (secure) { @@ -88,8 +88,9 @@ public class OkHttpLoadBalancingClient @Override public URI reconstructURIWithServer(Server server, URI original) { - URI uri = updateToSecureConnectionIfNeeded(original, this.config, this.serverIntrospector, - server); + URI uri = updateToSecureConnectionIfNeeded(original, this.config, + this.serverIntrospector, server); return super.reconstructURIWithServer(server, uri); } + } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonConfiguration.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonConfiguration.java index 51b6edb2a..28a6ffb9d 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonConfiguration.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.ribbon.okhttp; @@ -21,6 +20,14 @@ import java.util.concurrent.TimeUnit; import javax.annotation.PreDestroy; +import com.netflix.client.AbstractLoadBalancerAwareClient; +import com.netflix.client.RetryHandler; +import com.netflix.client.config.IClientConfig; +import com.netflix.loadbalancer.ILoadBalancer; +import com.netflix.servo.monitor.Monitors; +import okhttp3.ConnectionPool; +import okhttp3.OkHttpClient; + import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; @@ -29,21 +36,12 @@ import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory; import org.springframework.cloud.commons.httpclient.OkHttpClientConnectionPoolFactory; import org.springframework.cloud.commons.httpclient.OkHttpClientFactory; import org.springframework.cloud.netflix.ribbon.RibbonClientName; -import org.springframework.cloud.netflix.ribbon.RibbonProperties; import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerContext; +import org.springframework.cloud.netflix.ribbon.RibbonProperties; import org.springframework.cloud.netflix.ribbon.ServerIntrospector; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import com.netflix.client.AbstractLoadBalancerAwareClient; -import com.netflix.client.RetryHandler; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.ILoadBalancer; -import com.netflix.servo.monitor.Monitors; - -import okhttp3.ConnectionPool; -import okhttp3.OkHttpClient; - /** * @author Spencer Gibb */ @@ -51,17 +49,50 @@ import okhttp3.OkHttpClient; @ConditionalOnProperty("ribbon.okhttp.enabled") @ConditionalOnClass(name = "okhttp3.OkHttpClient") public class OkHttpRibbonConfiguration { + @RibbonClientName private String name = "client"; + @Bean + @ConditionalOnMissingBean(AbstractLoadBalancerAwareClient.class) + @ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate") + public RetryableOkHttpLoadBalancingClient retryableOkHttpLoadBalancingClient( + IClientConfig config, ServerIntrospector serverIntrospector, + ILoadBalancer loadBalancer, RetryHandler retryHandler, + LoadBalancedRetryFactory loadBalancedRetryFactory, OkHttpClient delegate, + RibbonLoadBalancerContext ribbonLoadBalancerContext) { + RetryableOkHttpLoadBalancingClient client = new RetryableOkHttpLoadBalancingClient( + delegate, config, serverIntrospector, loadBalancedRetryFactory); + client.setLoadBalancer(loadBalancer); + client.setRetryHandler(retryHandler); + client.setRibbonLoadBalancerContext(ribbonLoadBalancerContext); + Monitors.registerObject("Client_" + this.name, client); + return client; + } + + @Bean + @ConditionalOnMissingBean(AbstractLoadBalancerAwareClient.class) + @ConditionalOnMissingClass("org.springframework.retry.support.RetryTemplate") + public OkHttpLoadBalancingClient okHttpLoadBalancingClient(IClientConfig config, + ServerIntrospector serverIntrospector, ILoadBalancer loadBalancer, + RetryHandler retryHandler, OkHttpClient delegate) { + OkHttpLoadBalancingClient client = new OkHttpLoadBalancingClient(delegate, config, + serverIntrospector); + client.setLoadBalancer(loadBalancer); + client.setRetryHandler(retryHandler); + Monitors.registerObject("Client_" + this.name, client); + return client; + } + @Configuration protected static class OkHttpClientConfiguration { + private OkHttpClient httpClient; @Bean @ConditionalOnMissingBean(ConnectionPool.class) public ConnectionPool httpClientConnectionPool(IClientConfig config, - OkHttpClientConnectionPoolFactory connectionPoolFactory) { + OkHttpClientConnectionPoolFactory connectionPoolFactory) { RibbonProperties ribbon = RibbonProperties.from(config); int maxTotalConnections = ribbon.maxTotalConnections(); long timeToLive = ribbon.poolKeepAliveTime(); @@ -72,57 +103,24 @@ public class OkHttpRibbonConfiguration { @Bean @ConditionalOnMissingBean(OkHttpClient.class) public OkHttpClient client(OkHttpClientFactory httpClientFactory, - ConnectionPool connectionPool, IClientConfig config) { + ConnectionPool connectionPool, IClientConfig config) { RibbonProperties ribbon = RibbonProperties.from(config); this.httpClient = httpClientFactory.createBuilder(false) .connectTimeout(ribbon.connectTimeout(), TimeUnit.MILLISECONDS) .readTimeout(ribbon.readTimeout(), TimeUnit.MILLISECONDS) .followRedirects(ribbon.isFollowRedirects()) - .connectionPool(connectionPool) - .build(); + .connectionPool(connectionPool).build(); return this.httpClient; } @PreDestroy public void destroy() { - if(httpClient != null) { + if (httpClient != null) { httpClient.dispatcher().executorService().shutdown(); httpClient.connectionPool().evictAll(); } } + } - @Bean - @ConditionalOnMissingBean(AbstractLoadBalancerAwareClient.class) - @ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate") - public RetryableOkHttpLoadBalancingClient retryableOkHttpLoadBalancingClient( - IClientConfig config, - ServerIntrospector serverIntrospector, - ILoadBalancer loadBalancer, - RetryHandler retryHandler, - LoadBalancedRetryFactory loadBalancedRetryFactory, - OkHttpClient delegate, RibbonLoadBalancerContext ribbonLoadBalancerContext) { - RetryableOkHttpLoadBalancingClient client = new RetryableOkHttpLoadBalancingClient(delegate, config, - serverIntrospector, loadBalancedRetryFactory); - client.setLoadBalancer(loadBalancer); - client.setRetryHandler(retryHandler); - client.setRibbonLoadBalancerContext(ribbonLoadBalancerContext); - Monitors.registerObject("Client_" + this.name, client); - return client; - } - - @Bean - @ConditionalOnMissingBean(AbstractLoadBalancerAwareClient.class) - @ConditionalOnMissingClass(value = "org.springframework.retry.support.RetryTemplate") - public OkHttpLoadBalancingClient okHttpLoadBalancingClient( - IClientConfig config, - ServerIntrospector serverIntrospector, ILoadBalancer loadBalancer, - RetryHandler retryHandler, OkHttpClient delegate) { - OkHttpLoadBalancingClient client = new OkHttpLoadBalancingClient(delegate, config, - serverIntrospector); - client.setLoadBalancer(loadBalancer); - client.setRetryHandler(retryHandler); - Monitors.registerObject("Client_" + this.name, client); - return client; - } } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonRequest.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonRequest.java index 7df4c8a53..917641720 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonRequest.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,11 @@ package org.springframework.cloud.netflix.ribbon.okhttp; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.util.List; + import okhttp3.Headers; import okhttp3.HttpUrl; import okhttp3.MediaType; @@ -26,10 +31,6 @@ import okio.BufferedSink; import okio.Okio; import okio.Source; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.util.List; import org.springframework.cloud.netflix.ribbon.support.ContextAwareRequest; import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; @@ -63,18 +64,18 @@ public class OkHttpRibbonRequest extends ContextAwareRequest implements Cloneabl RequestBody requestBody = null; - if (this.context.getRequestEntity() != null && HttpMethod.permitsRequestBody(this.context.getMethod())) { + if (this.context.getRequestEntity() != null + && HttpMethod.permitsRequestBody(this.context.getMethod())) { MediaType mediaType = null; if (headers.get("Content-Type") != null) { mediaType = MediaType.parse(headers.get("Content-Type")); } - requestBody = new InputStreamRequestBody(this.context.getRequestEntity(), mediaType, this.context.getContentLength()); + requestBody = new InputStreamRequestBody(this.context.getRequestEntity(), + mediaType, this.context.getContentLength()); } - Request.Builder builder = new Request.Builder() - .url(url.build()) - .headers(headers.build()) - .method(this.context.getMethod(), requestBody); + Request.Builder builder = new Request.Builder().url(url.build()) + .headers(headers.build()).method(this.context.getMethod(), requestBody); customize(this.context.getRequestCustomizers(), builder); @@ -88,10 +89,13 @@ public class OkHttpRibbonRequest extends ContextAwareRequest implements Cloneabl static class InputStreamRequestBody extends RequestBody { private InputStream inputStream; + private MediaType mediaType; + private Long contentLength; - InputStreamRequestBody(InputStream inputStream, MediaType mediaType, Long contentLength) { + InputStreamRequestBody(InputStream inputStream, MediaType mediaType, + Long contentLength) { this.inputStream = inputStream; this.mediaType = mediaType; this.contentLength = contentLength; @@ -109,7 +113,8 @@ public class OkHttpRibbonRequest extends ContextAwareRequest implements Cloneabl } try { return inputStream.available(); - } catch (IOException e) { + } + catch (IOException e) { return 0; } } @@ -120,11 +125,14 @@ public class OkHttpRibbonRequest extends ContextAwareRequest implements Cloneabl try { source = Okio.source(inputStream); sink.writeAll(source); - } finally { + } + finally { if (source != null) { source.close(); } } } + } + } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonResponse.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonResponse.java index 6fcfdc15f..f984fc4c6 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonResponse.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonResponse.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,9 +16,6 @@ package org.springframework.cloud.netflix.ribbon.okhttp; -import okhttp3.Response; -import okhttp3.ResponseBody; - import java.io.InputStream; import java.lang.reflect.Type; import java.net.URI; @@ -27,11 +24,15 @@ import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.springframework.util.Assert; + import com.google.common.reflect.TypeToken; import com.netflix.client.ClientException; import com.netflix.client.http.CaseInsensitiveMultiMap; import com.netflix.client.http.HttpHeaders; +import okhttp3.Response; +import okhttp3.ResponseBody; + +import org.springframework.util.Assert; /** * @author Spencer Gibb @@ -39,7 +40,9 @@ import com.netflix.client.http.HttpHeaders; public class OkHttpRibbonResponse implements com.netflix.client.http.HttpResponse { private final ResponseBody body; + private URI uri; + private Response response; public OkHttpRibbonResponse(Response response, URI uri) { @@ -49,7 +52,6 @@ public class OkHttpRibbonResponse implements com.netflix.client.http.HttpRespons this.uri = uri; } - @Override public int getStatus() { return this.response.code(); @@ -86,12 +88,14 @@ public class OkHttpRibbonResponse implements com.netflix.client.http.HttpRespons @Override public Map> getHeaders() { final Map> headers = new HashMap<>(); - for (Map.Entry> entry : this.response.headers().toMultimap().entrySet()) { + for (Map.Entry> entry : this.response.headers().toMultimap() + .entrySet()) { String name = entry.getKey(); for (String value : entry.getValue()) { if (headers.containsKey(name)) { headers.get(name).add(value); - } else { + } + else { final List values = new ArrayList<>(); values.add(value); headers.put(name, values); @@ -105,7 +109,8 @@ public class OkHttpRibbonResponse implements com.netflix.client.http.HttpRespons @Override public HttpHeaders getHttpHeaders() { final CaseInsensitiveMultiMap headers = new CaseInsensitiveMultiMap(); - for (Map.Entry> entry : this.response.headers().toMultimap().entrySet()) { + for (Map.Entry> entry : this.response.headers().toMultimap() + .entrySet()) { for (String value : entry.getValue()) { headers.addHeader(entry.getKey(), value); } @@ -146,4 +151,5 @@ public class OkHttpRibbonResponse implements com.netflix.client.http.HttpRespons public T getEntity(TypeToken type) throws Exception { return null; } + } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpStatusCodeException.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpStatusCodeException.java index a5341fa6c..654e959ad 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpStatusCodeException.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpStatusCodeException.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,33 +13,41 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.netflix.ribbon.okhttp; +import java.net.URI; + import okhttp3.Response; import okhttp3.ResponseBody; -import java.io.IOException; -import java.net.URI; import org.springframework.cloud.client.loadbalancer.RetryableStatusCodeException; /** - * An {@link RetryableStatusCodeException} that captures a {@link Response} + * An {@link RetryableStatusCodeException} that captures a {@link Response}. + * * @author Ryan Baxter */ public class OkHttpStatusCodeException extends RetryableStatusCodeException { - private Response response; - public OkHttpStatusCodeException(String serviceId, Response response, ResponseBody responseBody, URI uri) { + private final Response response; + + public OkHttpStatusCodeException(String serviceId, Response response, + ResponseBody responseBody, URI uri) { super(serviceId, response.code(), response, uri); - this.response = new Response.Builder().code(response.code()).message(response.message()).protocol(response.protocol()) - .request(response.request()).headers(response.headers()).handshake(response.handshake()) - .cacheResponse(response.cacheResponse()).networkResponse(response.networkResponse()) - .priorResponse(response.priorResponse()).sentRequestAtMillis(response.sentRequestAtMillis()) - .body(responseBody).build(); + this.response = new Response.Builder().code(response.code()) + .message(response.message()).protocol(response.protocol()) + .request(response.request()).headers(response.headers()) + .handshake(response.handshake()).cacheResponse(response.cacheResponse()) + .networkResponse(response.networkResponse()) + .priorResponse(response.priorResponse()) + .sentRequestAtMillis(response.sentRequestAtMillis()).body(responseBody) + .build(); } @Override public Response getResponse() { return response; } + } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/RetryableOkHttpLoadBalancingClient.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/RetryableOkHttpLoadBalancingClient.java index 825024320..42ffd3da6 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/RetryableOkHttpLoadBalancingClient.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/RetryableOkHttpLoadBalancingClient.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,16 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.netflix.ribbon.okhttp; +import java.net.URI; + +import com.netflix.client.RequestSpecificRetryHandler; +import com.netflix.client.RetryHandler; +import com.netflix.client.config.IClientConfig; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; - -import java.net.URI; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.loadbalancer.InterceptorRetryPolicy; import org.springframework.cloud.client.loadbalancer.LoadBalancedRecoveryCallback; @@ -30,10 +35,10 @@ import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryContext; import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory; import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicy; import org.springframework.cloud.client.loadbalancer.ServiceInstanceChooser; +import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient.RibbonServer; import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerContext; import org.springframework.cloud.netflix.ribbon.RibbonStatsRecorder; import org.springframework.cloud.netflix.ribbon.ServerIntrospector; -import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient.RibbonServer; import org.springframework.cloud.netflix.ribbon.support.ContextAwareRequest; import org.springframework.http.HttpRequest; import org.springframework.retry.RecoveryCallback; @@ -46,96 +51,112 @@ import org.springframework.retry.policy.NeverRetryPolicy; import org.springframework.retry.support.RetryTemplate; import org.springframework.web.util.UriComponentsBuilder; -import com.netflix.client.RequestSpecificRetryHandler; -import com.netflix.client.RetryHandler; -import com.netflix.client.config.IClientConfig; - /** * An OK HTTP client which leverages Spring Retry to retry failed request. + * * @author Ryan Baxter * @author Gang Li */ public class RetryableOkHttpLoadBalancingClient extends OkHttpLoadBalancingClient { - private static final Log LOGGER = LogFactory.getLog(RetryableOkHttpLoadBalancingClient.class); + + private static final Log LOGGER = LogFactory + .getLog(RetryableOkHttpLoadBalancingClient.class); private LoadBalancedRetryFactory loadBalancedRetryFactory; + private RibbonLoadBalancerContext ribbonLoadBalancerContext; - public RetryableOkHttpLoadBalancingClient(OkHttpClient delegate, IClientConfig config, ServerIntrospector serverIntrospector, - LoadBalancedRetryFactory loadBalancedRetryPolicyFactory) { + public RetryableOkHttpLoadBalancingClient(OkHttpClient delegate, IClientConfig config, + ServerIntrospector serverIntrospector, + LoadBalancedRetryFactory loadBalancedRetryPolicyFactory) { super(delegate, config, serverIntrospector); this.loadBalancedRetryFactory = loadBalancedRetryPolicyFactory; } @Override public boolean isClientRetryable(ContextAwareRequest request) { - return request!= null && isRequestRetryable(request); + return request != null && isRequestRetryable(request); } - + private boolean isRequestRetryable(ContextAwareRequest request) { - if (request.getContext() == null || request.getContext().getRetryable() == null) { - return true; + if (request.getContext() == null || request.getContext().getRetryable() == null) { + return true; } return request.getContext().getRetryable(); } - - private OkHttpRibbonResponse executeWithRetry(OkHttpRibbonRequest request, LoadBalancedRetryPolicy retryPolicy, - RetryCallback callback, - RecoveryCallback recoveryCallback) throws Exception { + + private OkHttpRibbonResponse executeWithRetry(OkHttpRibbonRequest request, + LoadBalancedRetryPolicy retryPolicy, + RetryCallback callback, + RecoveryCallback recoveryCallback) throws Exception { RetryTemplate retryTemplate = new RetryTemplate(); - BackOffPolicy backOffPolicy = loadBalancedRetryFactory.createBackOffPolicy(this.getClientName()); - retryTemplate.setBackOffPolicy(backOffPolicy == null ? new NoBackOffPolicy() : backOffPolicy); - RetryListener[] retryListeners = this.loadBalancedRetryFactory.createRetryListeners(this.getClientName()); + BackOffPolicy backOffPolicy = loadBalancedRetryFactory + .createBackOffPolicy(this.getClientName()); + retryTemplate.setBackOffPolicy( + backOffPolicy == null ? new NoBackOffPolicy() : backOffPolicy); + RetryListener[] retryListeners = this.loadBalancedRetryFactory + .createRetryListeners(this.getClientName()); if (retryListeners != null && retryListeners.length != 0) { retryTemplate.setListeners(retryListeners); } boolean retryable = isRequestRetryable(request); - retryTemplate.setRetryPolicy(retryPolicy == null || !retryable ? new NeverRetryPolicy() + retryTemplate.setRetryPolicy(retryPolicy == null || !retryable + ? new NeverRetryPolicy() : new RetryPolicy(request, retryPolicy, this, this.getClientName())); return retryTemplate.execute(callback, recoveryCallback); } @Override public OkHttpRibbonResponse execute(final OkHttpRibbonRequest ribbonRequest, - final IClientConfig configOverride) throws Exception { - final LoadBalancedRetryPolicy retryPolicy = loadBalancedRetryFactory.createRetryPolicy(this.getClientName(), this); - RetryCallback retryCallback = new RetryCallback() { + final IClientConfig configOverride) throws Exception { + final LoadBalancedRetryPolicy retryPolicy = loadBalancedRetryFactory + .createRetryPolicy(this.getClientName(), this); + RetryCallback retryCallback = new RetryCallback() { @Override - public OkHttpRibbonResponse doWithRetry(RetryContext context) throws Exception { - //on retries the policy will choose the server and set it in the context - //extract the server and update the request being made + public OkHttpRibbonResponse doWithRetry(RetryContext context) + throws Exception { + // on retries the policy will choose the server and set it in the context + // extract the server and update the request being made OkHttpRibbonRequest newRequest = ribbonRequest; RibbonStatsRecorder statsRecorder = null; - - if(context instanceof LoadBalancedRetryContext) { - ServiceInstance service = ((LoadBalancedRetryContext)context).getServiceInstance(); + + if (context instanceof LoadBalancedRetryContext) { + ServiceInstance service = ((LoadBalancedRetryContext) context) + .getServiceInstance(); validateServiceInstance(service); - //Reconstruct the request URI using the host and port set in the retry context - newRequest = newRequest.withNewUri(new URI(service.getUri().getScheme(), - newRequest.getURI().getUserInfo(), service.getHost(), service.getPort(), - newRequest.getURI().getPath(), newRequest.getURI().getQuery(), - newRequest.getURI().getFragment())); - + // Reconstruct the request URI using the host and port set in the + // retry context + newRequest = newRequest + .withNewUri(new URI(service.getUri().getScheme(), + newRequest.getURI().getUserInfo(), service.getHost(), + service.getPort(), newRequest.getURI().getPath(), + newRequest.getURI().getQuery(), + newRequest.getURI().getFragment())); + if (ribbonLoadBalancerContext == null) { - LOGGER.error("RibbonLoadBalancerContext is null. Unable to update load balancer stats"); - } else if (service instanceof RibbonServer) { - statsRecorder = new RibbonStatsRecorder(ribbonLoadBalancerContext, ((RibbonServer)service).getServer()); + LOGGER.error( + "RibbonLoadBalancerContext is null. Unable to update load balancer stats"); + } + else if (service instanceof RibbonServer) { + statsRecorder = new RibbonStatsRecorder(ribbonLoadBalancerContext, + ((RibbonServer) service).getServer()); } } if (isSecure(configOverride)) { - final URI secureUri = UriComponentsBuilder.fromUri(newRequest.getUri()) - .scheme("https").build().toUri(); + final URI secureUri = UriComponentsBuilder + .fromUri(newRequest.getUri()).scheme("https").build().toUri(); newRequest = newRequest.withNewUri(secureUri); } OkHttpClient httpClient = getOkHttpClient(configOverride, secure); final Request request = newRequest.toRequest(); Response response = httpClient.newCall(request).execute(); - if(retryPolicy.retryableStatusCode(response.code())) { + if (retryPolicy.retryableStatusCode(response.code())) { ResponseBody responseBody = response.peekBody(Integer.MAX_VALUE); response.close(); - throw new OkHttpStatusCodeException(RetryableOkHttpLoadBalancingClient.this.clientName, - response, responseBody, newRequest.getURI()); + throw new OkHttpStatusCodeException( + RetryableOkHttpLoadBalancingClient.this.clientName, response, + responseBody, newRequest.getURI()); } if (statsRecorder != null) { statsRecorder.recordStats(response); @@ -143,27 +164,35 @@ public class RetryableOkHttpLoadBalancingClient extends OkHttpLoadBalancingClien return new OkHttpRibbonResponse(response, newRequest.getUri()); } }; - return this.executeWithRetry(ribbonRequest, retryPolicy, retryCallback, new LoadBalancedRecoveryCallback(){ + return this.executeWithRetry(ribbonRequest, retryPolicy, retryCallback, + new LoadBalancedRecoveryCallback() { - @Override - protected OkHttpRibbonResponse createResponse(Response response, URI uri) { - return new OkHttpRibbonResponse(response, uri); - } - }); + @Override + protected OkHttpRibbonResponse createResponse(Response response, + URI uri) { + return new OkHttpRibbonResponse(response, uri); + } + }); } @Override - public RequestSpecificRetryHandler getRequestSpecificRetryHandler(OkHttpRibbonRequest request, IClientConfig requestConfig) { + public RequestSpecificRetryHandler getRequestSpecificRetryHandler( + OkHttpRibbonRequest request, IClientConfig requestConfig) { return new RequestSpecificRetryHandler(false, false, RetryHandler.DEFAULT, null); } - - public void setRibbonLoadBalancerContext(RibbonLoadBalancerContext ribbonLoadBalancerContext) { + + public void setRibbonLoadBalancerContext( + RibbonLoadBalancerContext ribbonLoadBalancerContext) { this.ribbonLoadBalancerContext = ribbonLoadBalancerContext; } static class RetryPolicy extends InterceptorRetryPolicy { - public RetryPolicy(HttpRequest request, LoadBalancedRetryPolicy policy, ServiceInstanceChooser serviceInstanceChooser, String serviceName) { + + RetryPolicy(HttpRequest request, LoadBalancedRetryPolicy policy, + ServiceInstanceChooser serviceInstanceChooser, String serviceName) { super(request, policy, serviceInstanceChooser, serviceName); } + } + } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/AbstractLoadBalancingClient.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/AbstractLoadBalancingClient.java index 2e3106de7..b751133dd 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/AbstractLoadBalancingClient.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/AbstractLoadBalancingClient.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,16 +12,10 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.ribbon.support; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.loadbalancer.ServiceInstanceChooser; -import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient; -import org.springframework.cloud.netflix.ribbon.RibbonProperties; -import org.springframework.cloud.netflix.ribbon.ServerIntrospector; import com.netflix.client.AbstractLoadBalancerAwareClient; import com.netflix.client.ClientException; import com.netflix.client.IResponse; @@ -31,15 +25,25 @@ import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.Server; import com.netflix.loadbalancer.reactive.LoadBalancerCommand; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.loadbalancer.ServiceInstanceChooser; +import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient; +import org.springframework.cloud.netflix.ribbon.RibbonProperties; +import org.springframework.cloud.netflix.ribbon.ServerIntrospector; + import static org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration.DEFAULT_CONNECT_TIMEOUT; +import static org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration.DEFAULT_GZIP_PAYLOAD; import static org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration.DEFAULT_READ_TIMEOUT; -import static org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration.DEFAULT_GZIP_PAYLOAD;; /** + * @param delegate + * @param {@link ContextAwareRequest} subtype + * @param {@link ServiceInstanceChooser} subtype * @author Spencer Gibb + * */ -public abstract class AbstractLoadBalancingClient extends - AbstractLoadBalancerAwareClient implements ServiceInstanceChooser { +public abstract class AbstractLoadBalancingClient + extends AbstractLoadBalancerAwareClient implements ServiceInstanceChooser { protected int connectTimeout; @@ -54,14 +58,17 @@ public abstract class AbstractLoadBalancingClient builder) { + protected void customizeLoadBalancerCommandBuilder(S request, IClientConfig config, + LoadBalancerCommand.Builder builder) { if (request.getLoadBalancerKey() != null) { builder.withServerLocator(request.getLoadBalancerKey()); } } - + @Override public ServiceInstance choose(String serviceId) { Server server = this.getLoadBalancer().chooseServer(serviceId); @@ -137,12 +146,18 @@ public abstract class AbstractLoadBalancingClient headers = context.getHeaders(); this.httpHeaders = new HttpHeaders(); - for(String key : headers.keySet()) { + for (String key : headers.keySet()) { this.httpHeaders.put(key, headers.get(key)); } this.uri = context.uri(); @@ -69,11 +72,13 @@ public abstract class ContextAwareRequest extends ClientRequest implements HttpR } protected RibbonCommandContext newContext(URI uri) { - RibbonCommandContext commandContext = new RibbonCommandContext(this.context.getServiceId(), - this.context.getMethod(), uri.toString(), this.context.getRetryable(), - this.context.getHeaders(), this.context.getParams(), this.context.getRequestEntity(), + RibbonCommandContext commandContext = new RibbonCommandContext( + this.context.getServiceId(), this.context.getMethod(), uri.toString(), + this.context.getRetryable(), this.context.getHeaders(), + this.context.getParams(), this.context.getRequestEntity(), this.context.getRequestCustomizers(), this.context.getContentLength(), this.context.getLoadBalancerKey()); return commandContext; } + } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/ResettableServletInputStreamWrapper.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/ResettableServletInputStreamWrapper.java index 11d5b93cd..628c26271 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/ResettableServletInputStreamWrapper.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/ResettableServletInputStreamWrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,14 +13,24 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.netflix.ribbon.support; import java.io.ByteArrayInputStream; import java.io.IOException; + import javax.servlet.ReadListener; import javax.servlet.ServletInputStream; +/** + * A wrapper for {@link ServletInputStream} providing additional capabilities to allow for + * resetting. + * + * @author Arne Dörnbrack + * @author Spencer Gibb + */ public class ResettableServletInputStreamWrapper extends ServletInputStream { + private final ByteArrayInputStream input; public ResettableServletInputStreamWrapper(byte[] data) { @@ -50,4 +60,5 @@ public class ResettableServletInputStreamWrapper extends ServletInputStream { public synchronized void reset() throws IOException { input.reset(); } + } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonCommandContext.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonCommandContext.java index 3d548e831..113a19e10 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonCommandContext.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonCommandContext.java @@ -1,11 +1,11 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -22,6 +22,7 @@ import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Objects; + import org.springframework.util.Assert; import org.springframework.util.MultiValueMap; import org.springframework.util.ReflectionUtils; @@ -32,49 +33,66 @@ import org.springframework.util.StreamUtils; * @author Yongsung Yoon */ public class RibbonCommandContext { + private final String serviceId; + private final String method; + private final String uri; + private final Boolean retryable; + private final MultiValueMap headers; + private final MultiValueMap params; + private final List requestCustomizers; + private InputStream requestEntity; + private Long contentLength; + private Object loadBalancerKey; /** - * Kept for backwards compatibility with Spring Cloud Sleuth 1.x versions + * Kept for backwards compatibility with Spring Cloud Sleuth 1.x versions. + * @param serviceId to be used with Ribbon request + * @param method to be used with Ribbon request + * @param uri {@link String} value of the uri to be used with Ribbon request + * @param retryable determines whether the requests should be retried + * @param headers to pass to the Ribbon request + * @param params parameters to pass to the Ribbon request + * @param requestEntity request content {@link InputStream} */ @Deprecated - public RibbonCommandContext(String serviceId, String method, - String uri, Boolean retryable, MultiValueMap headers, - MultiValueMap params, InputStream requestEntity) { + public RibbonCommandContext(String serviceId, String method, String uri, + Boolean retryable, MultiValueMap headers, + MultiValueMap params, InputStream requestEntity) { this(serviceId, method, uri, retryable, headers, params, requestEntity, - new ArrayList(), null, null); + new ArrayList(), null, null); } public RibbonCommandContext(String serviceId, String method, String uri, - Boolean retryable, MultiValueMap headers, - MultiValueMap params, InputStream requestEntity, - List requestCustomizers) { + Boolean retryable, MultiValueMap headers, + MultiValueMap params, InputStream requestEntity, + List requestCustomizers) { this(serviceId, method, uri, retryable, headers, params, requestEntity, - requestCustomizers, null, null); + requestCustomizers, null, null); } public RibbonCommandContext(String serviceId, String method, String uri, - Boolean retryable, MultiValueMap headers, - MultiValueMap params, InputStream requestEntity, - List requestCustomizers, Long contentLength) { + Boolean retryable, MultiValueMap headers, + MultiValueMap params, InputStream requestEntity, + List requestCustomizers, Long contentLength) { this(serviceId, method, uri, retryable, headers, params, requestEntity, - requestCustomizers, contentLength, null); + requestCustomizers, contentLength, null); } public RibbonCommandContext(String serviceId, String method, String uri, - Boolean retryable, MultiValueMap headers, - MultiValueMap params, InputStream requestEntity, - List requestCustomizers, Long contentLength, - Object loadBalancerKey) { + Boolean retryable, MultiValueMap headers, + MultiValueMap params, InputStream requestEntity, + List requestCustomizers, Long contentLength, + Object loadBalancerKey) { Assert.notNull(serviceId, "serviceId may not be null"); Assert.notNull(method, "method may not be null"); Assert.notNull(uri, "uri may not be null"); @@ -96,16 +114,16 @@ public class RibbonCommandContext { public URI uri() { try { return new URI(this.uri); - } catch (URISyntaxException e) { + } + catch (URISyntaxException e) { ReflectionUtils.rethrowRuntimeException(e); } return null; } /** - * Use getMethod() - * - * @return + * Use {@link #getMethod()}. + * @return request method */ @Deprecated public String getVerb() { @@ -140,20 +158,23 @@ public class RibbonCommandContext { if (requestEntity == null) { return null; } - //If the route is not retryable there is no point in copying the RequestEntity. This - //has memory implications in all cases but especially when uploading large files through - //Zuul - if(!retryable) { + // If the route is not retryable there is no point in copying the RequestEntity. + // This + // has memory implications in all cases but especially when uploading large files + // through + // Zuul + if (!retryable) { return requestEntity; } try { if (!(requestEntity instanceof ResettableServletInputStreamWrapper)) { requestEntity = new ResettableServletInputStreamWrapper( - StreamUtils.copyToByteArray(requestEntity)); + StreamUtils.copyToByteArray(requestEntity)); } requestEntity.reset(); - } finally { + } + finally { return requestEntity; } } @@ -180,26 +201,28 @@ public class RibbonCommandContext { @Override public boolean equals(Object o) { - if (this == o) + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } RibbonCommandContext that = (RibbonCommandContext) o; - return Objects.equals(serviceId, that.serviceId) && Objects - .equals(method, that.method) && Objects.equals(uri, that.uri) - && Objects.equals(retryable, that.retryable) && Objects - .equals(headers, that.headers) && Objects - .equals(params, that.params) && Objects - .equals(requestEntity, that.requestEntity) && Objects - .equals(requestCustomizers, that.requestCustomizers) && Objects - .equals(contentLength, that.contentLength) && Objects - .equals(loadBalancerKey, that.loadBalancerKey); + return Objects.equals(serviceId, that.serviceId) + && Objects.equals(method, that.method) && Objects.equals(uri, that.uri) + && Objects.equals(retryable, that.retryable) + && Objects.equals(headers, that.headers) + && Objects.equals(params, that.params) + && Objects.equals(requestEntity, that.requestEntity) + && Objects.equals(requestCustomizers, that.requestCustomizers) + && Objects.equals(contentLength, that.contentLength) + && Objects.equals(loadBalancerKey, that.loadBalancerKey); } @Override public int hashCode() { return Objects.hash(serviceId, method, uri, retryable, headers, params, - requestEntity, requestCustomizers, contentLength, loadBalancerKey); + requestEntity, requestCustomizers, contentLength, loadBalancerKey); } @Override @@ -218,4 +241,5 @@ public class RibbonCommandContext { sb.append('}'); return sb.toString(); } + } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonRequestCustomizer.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonRequestCustomizer.java index 4e416a1b9..3546932bf 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonRequestCustomizer.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonRequestCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.ribbon.support; @@ -20,21 +19,33 @@ package org.springframework.cloud.netflix.ribbon.support; import java.util.List; /** + * Interface providing methods for customizing Ribbon requests. + * + * @param Request builder type * @author Spencer Gibb */ public interface RibbonRequestCustomizer { + boolean accepts(Class builderClass); + void customize(B builder); class Runner { + private Runner() { + throw new AssertionError("Must not instantiate utility class."); + } + @SuppressWarnings("unchecked") - public static void customize(List customizers, Object builder) { + public static void customize(List customizers, + Object builder) { for (RibbonRequestCustomizer customizer : customizers) { if (customizer.accepts(builder.getClass())) { customizer.customize(builder); } } } + } + } diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonRetryPolicy.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonRetryPolicy.java index 157ce5013..7f5ce20ec 100644 --- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonRetryPolicy.java +++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonRetryPolicy.java @@ -1,8 +1,25 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.springframework.cloud.netflix.ribbon.support; import java.net.URI; import java.util.HashMap; import java.util.Map; + import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.loadbalancer.InterceptorRetryPolicy; import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryContext; @@ -15,9 +32,13 @@ import org.springframework.retry.RetryContext; * @author Ryan Baxter */ public class RibbonRetryPolicy extends InterceptorRetryPolicy { + private HttpRequest request; + private String serviceId; - public RibbonRetryPolicy(HttpRequest request, LoadBalancedRetryPolicy policy, ServiceInstanceChooser serviceInstanceChooser, String serviceName) { + + public RibbonRetryPolicy(HttpRequest request, LoadBalancedRetryPolicy policy, + ServiceInstanceChooser serviceInstanceChooser, String serviceName) { super(request, policy, serviceInstanceChooser, serviceName); this.request = request; this.serviceId = serviceName; @@ -26,13 +47,14 @@ public class RibbonRetryPolicy extends InterceptorRetryPolicy { @Override public boolean canRetry(RetryContext context) { /* - * In InterceptorRetryPolicy.canRetry we ask the LoadBalancer to choose a server if one is not - * set in the retry context and then return true. RetryTemplat calls the canRetry method of - * the policy even on its first execution. So the fact that we didnt have a service instance set - * in the RetryContext signaled that it was the first execution and we should return true. + * In InterceptorRetryPolicy.canRetry we ask the LoadBalancer to choose a server + * if one is not set in the retry context and then return true. RetryTemplat calls + * the canRetry method of the policy even on its first execution. So the fact that + * we didnt have a service instance set in the RetryContext signaled that it was + * the first execution and we should return true. * */ - if(context.getRetryCount() == 0) { + if (context.getRetryCount() == 0) { return true; } return super.canRetry(context); @@ -40,15 +62,19 @@ public class RibbonRetryPolicy extends InterceptorRetryPolicy { @Override public RetryContext open(RetryContext parent) { - LoadBalancedRetryContext context = new LoadBalancedRetryContext(parent, this.request); - context.setServiceInstance(new RibbonRetryPolicyServiceInstance(serviceId, request)); + LoadBalancedRetryContext context = new LoadBalancedRetryContext(parent, + this.request); + context.setServiceInstance( + new RibbonRetryPolicyServiceInstance(serviceId, request)); return context; } class RibbonRetryPolicyServiceInstance implements ServiceInstance { private String serviceId; + private HttpRequest request; + private Map metadata; RibbonRetryPolicyServiceInstance(String serviceId, HttpRequest request) { @@ -86,5 +112,7 @@ public class RibbonRetryPolicy extends InterceptorRetryPolicy { public Map getMetadata() { return metadata; } + } + } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/DefaultServerIntrospectorDefaultTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/DefaultServerIntrospectorDefaultTests.java index caa1f9156..3d0445b66 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/DefaultServerIntrospectorDefaultTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/DefaultServerIntrospectorDefaultTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,17 +16,18 @@ package org.springframework.cloud.netflix.ribbon; -import org.junit.Assert; +import com.netflix.loadbalancer.Server; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.netflix.loadbalancer.Server; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -41,23 +42,26 @@ public class DefaultServerIntrospectorDefaultTests { private ServerIntrospector serverIntrospector; @Test - public void testDefaultSslPorts(){ + public void testDefaultSslPorts() { Server serverMock = mock(Server.class); when(serverMock.getPort()).thenReturn(443); - Assert.assertTrue(serverIntrospector.isSecure(serverMock)); + assertThat(serverIntrospector.isSecure(serverMock)).isTrue(); when(serverMock.getPort()).thenReturn(8443); - Assert.assertTrue(serverIntrospector.isSecure(serverMock)); + assertThat(serverIntrospector.isSecure(serverMock)).isTrue(); when(serverMock.getPort()).thenReturn(16443); - Assert.assertFalse(serverIntrospector.isSecure(serverMock)); + assertThat(serverIntrospector.isSecure(serverMock)).isFalse(); } @Configuration @EnableConfigurationProperties(ServerIntrospectorProperties.class) protected static class TestConfiguration { + @Bean - public DefaultServerIntrospector defaultServerIntrospector(){ + public DefaultServerIntrospector defaultServerIntrospector() { return new DefaultServerIntrospector(); } + } + } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/DefaultServerIntrospectorTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/DefaultServerIntrospectorTests.java index 4e614df68..e728635e0 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/DefaultServerIntrospectorTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/DefaultServerIntrospectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,9 +16,10 @@ package org.springframework.cloud.netflix.ribbon; -import org.junit.Assert; +import com.netflix.loadbalancer.Server; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.context.SpringBootTest; @@ -26,8 +27,8 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.netflix.loadbalancer.Server; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -43,22 +44,25 @@ public class DefaultServerIntrospectorTests { private ServerIntrospector serverIntrospector; @Test - public void testSecurePortConfiguration(){ + public void testSecurePortConfiguration() { Server serverMock = mock(Server.class); when(serverMock.getPort()).thenReturn(12345); - Assert.assertTrue(serverIntrospector.isSecure(serverMock)); + assertThat(serverIntrospector.isSecure(serverMock)).isTrue(); when(serverMock.getPort()).thenReturn(556); - Assert.assertTrue(serverIntrospector.isSecure(serverMock)); + assertThat(serverIntrospector.isSecure(serverMock)).isTrue(); when(serverMock.getPort()).thenReturn(443); - Assert.assertFalse(serverIntrospector.isSecure(serverMock)); + assertThat(serverIntrospector.isSecure(serverMock)).isFalse(); } @Configuration @EnableConfigurationProperties(ServerIntrospectorProperties.class) protected static class TestConfiguration { + @Bean - public DefaultServerIntrospector defaultServerIntrospector(){ + public DefaultServerIntrospector defaultServerIntrospector() { return new DefaultServerIntrospector(); } + } + } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/PlainRibbonClientPreprocessorIntegrationTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/PlainRibbonClientPreprocessorIntegrationTests.java index 14e396029..a2c2de05d 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/PlainRibbonClientPreprocessorIntegrationTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/PlainRibbonClientPreprocessorIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,13 +12,16 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.ribbon; +import com.netflix.loadbalancer.ConfigurationBasedServerList; +import com.netflix.loadbalancer.Server; +import com.netflix.loadbalancer.ZoneAwareLoadBalancer; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -28,9 +31,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.netflix.loadbalancer.ConfigurationBasedServerList; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ZoneAwareLoadBalancer; /** * @author Dave Syer @@ -53,9 +53,10 @@ public class PlainRibbonClientPreprocessorIntegrationTests { @Configuration @RibbonClient("foo") - @Import({ PropertyPlaceholderAutoConfiguration.class, - ArchaiusAutoConfiguration.class, RibbonAutoConfiguration.class}) + @Import({ PropertyPlaceholderAutoConfiguration.class, ArchaiusAutoConfiguration.class, + RibbonAutoConfiguration.class }) protected static class TestConfiguration { + } } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonApplicationContextInitializerTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonApplicationContextInitializerTests.java index 690cbc7a2..cc5649af8 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonApplicationContextInitializerTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonApplicationContextInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,8 +18,10 @@ package org.springframework.cloud.netflix.ribbon; import java.util.Arrays; import java.util.concurrent.atomic.AtomicInteger; + import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.netflix.archaius.ArchaiusAutoConfiguration; @@ -36,8 +38,9 @@ import static org.assertj.core.api.Assertions.assertThat; */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = {RibbonAutoConfiguration.class, - ArchaiusAutoConfiguration.class, RibbonApplicationContextInitializerTests.RibbonInitializerConfig.class}) +@SpringBootTest(classes = { RibbonAutoConfiguration.class, + ArchaiusAutoConfiguration.class, + RibbonApplicationContextInitializerTests.RibbonInitializerConfig.class }) @DirtiesContext public class RibbonApplicationContextInitializerTests { @@ -66,7 +69,7 @@ public class RibbonApplicationContextInitializerTests { } @Configuration - @RibbonClient(name="testspec", configuration = FooConfig.class) + @RibbonClient(name = "testspec", configuration = FooConfig.class) static class RibbonInitializerConfig { @Bean @@ -79,14 +82,17 @@ public class RibbonApplicationContextInitializerTests { } static class Foo { + private static final AtomicInteger INSTANCE_COUNT = new AtomicInteger(); - public Foo() { + Foo() { INSTANCE_COUNT.incrementAndGet(); } public static int getInstanceCount() { return INSTANCE_COUNT.get(); } + } + } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonAutoConfigurationIntegrationTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonAutoConfigurationIntegrationTests.java index e16998397..a798f8bb2 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonAutoConfigurationIntegrationTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,13 +12,15 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.ribbon; +import com.netflix.client.config.CommonClientConfigKey; +import com.netflix.client.config.IClientConfig; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -28,16 +30,15 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.netflix.client.config.CommonClientConfigKey; -import com.netflix.client.config.IClientConfig; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer */ @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = TestConfiguration.class, value = {"ribbon.ConnectTimeout=25000"}) +@SpringBootTest(classes = TestConfiguration.class, value = { + "ribbon.ConnectTimeout=25000" }) @DirtiesContext public class RibbonAutoConfigurationIntegrationTests { @@ -47,8 +48,9 @@ public class RibbonAutoConfigurationIntegrationTests { @Test public void serverListIsConfigured() throws Exception { IClientConfig config = this.factory.getClientConfig("client"); - assertEquals(25000, - config.getPropertyAsInteger(CommonClientConfigKey.ConnectTimeout, 3000)); + assertThat( + config.getPropertyAsInteger(CommonClientConfigKey.ConnectTimeout, 3000)) + .isEqualTo(25000); } @Configuration @@ -56,6 +58,7 @@ public class RibbonAutoConfigurationIntegrationTests { @Import({ PropertyPlaceholderAutoConfiguration.class, ArchaiusAutoConfiguration.class, RibbonAutoConfiguration.class }) protected static class TestConfiguration { + } } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfigurationIntegrationTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfigurationIntegrationTests.java index f4c16a3d4..9f2a40967 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfigurationIntegrationTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,13 +12,17 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.ribbon; +import com.netflix.loadbalancer.ILoadBalancer; +import com.netflix.loadbalancer.PollingServerListUpdater; +import com.netflix.loadbalancer.ServerListUpdater; +import com.netflix.loadbalancer.ZoneAwareLoadBalancer; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -26,22 +30,14 @@ import org.springframework.context.annotation.Configuration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.util.ReflectionTestUtils; -import com.netflix.loadbalancer.ILoadBalancer; -import com.netflix.loadbalancer.PollingServerListUpdater; -import com.netflix.loadbalancer.ServerListUpdater; -import com.netflix.loadbalancer.ZoneAwareLoadBalancer; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.sameInstance; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = RibbonClientConfigurationIntegrationTests.TestLBConfig.class, - properties = "test.ribbon.ServerListRefreshInterval=999") +@SpringBootTest(classes = RibbonClientConfigurationIntegrationTests.TestLBConfig.class, properties = "test.ribbon.ServerListRefreshInterval=999") @DirtiesContext public class RibbonClientConfigurationIntegrationTests { @@ -50,19 +46,25 @@ public class RibbonClientConfigurationIntegrationTests { @Test public void testLoadBalancerConstruction() { - ILoadBalancer loadBalancer = clientFactory.getInstance("test", ILoadBalancer.class); - assertThat(loadBalancer, is(instanceOf(ZoneAwareLoadBalancer.class))); + ILoadBalancer loadBalancer = clientFactory.getInstance("test", + ILoadBalancer.class); + assertThat(loadBalancer).isInstanceOf(ZoneAwareLoadBalancer.class); ZoneAwareLoadBalancer lb = (ZoneAwareLoadBalancer) loadBalancer; - ServerListUpdater serverListUpdater = (PollingServerListUpdater) ReflectionTestUtils.getField(loadBalancer, "serverListUpdater"); - Long refreshIntervalMs = (Long) ReflectionTestUtils.getField(serverListUpdater, "refreshIntervalMs"); + ServerListUpdater serverListUpdater = (PollingServerListUpdater) ReflectionTestUtils + .getField(loadBalancer, "serverListUpdater"); + Long refreshIntervalMs = (Long) ReflectionTestUtils.getField(serverListUpdater, + "refreshIntervalMs"); // assertThat(refreshIntervalMs, equalTo(999L)); - ServerListUpdater updater = clientFactory.getInstance("test", ServerListUpdater.class); - assertThat(updater, is(sameInstance(serverListUpdater))); + ServerListUpdater updater = clientFactory.getInstance("test", + ServerListUpdater.class); + assertThat(updater).isSameAs(serverListUpdater); } @Configuration @EnableAutoConfiguration - protected static class TestLBConfig { } + protected static class TestLBConfig { + + } } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfigurationTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfigurationTests.java index 9c7eb8700..44a0bd199 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfigurationTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.ribbon; @@ -20,10 +19,18 @@ package org.springframework.cloud.netflix.ribbon; import java.net.URI; import java.util.ArrayList; import java.util.List; + +import com.netflix.client.AbstractLoadBalancerAwareClient; +import com.netflix.client.config.CommonClientConfigKey; +import com.netflix.client.config.DefaultClientConfigImpl; +import com.netflix.client.config.IClientConfig; +import com.netflix.loadbalancer.Server; +import com.netflix.niws.client.http.RestClient; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; + import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -34,15 +41,8 @@ import org.springframework.cloud.netflix.ribbon.apache.RibbonLoadBalancingHttpCl import org.springframework.cloud.netflix.ribbon.okhttp.OkHttpLoadBalancingClient; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Configuration; -import com.netflix.client.AbstractLoadBalancerAwareClient; -import com.netflix.client.config.CommonClientConfigKey; -import com.netflix.client.config.DefaultClientConfigImpl; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.Server; -import com.netflix.niws.client.http.RestClient; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; /** @@ -68,7 +68,7 @@ public class RibbonClientConfigurationTests { @Test public void restClientInitCalledOnce() { new TestRestClient(this.config); - assertThat(this.config.count, is(1)); + assertThat(this.config.count).isEqualTo(1); } @Test @@ -81,12 +81,8 @@ public class RibbonClientConfigurationTests { Server server = new Server("example.com", 443); URI uri = new TestRestClient(config).reconstructURIWithServer(server, new URI("/foo")); - assertThat(uri.getScheme(), is("https")); - assertThat(uri.getHost(), is("example.com")); - } - - static class CountingConfig extends DefaultClientConfigImpl { - int count = 0; + assertThat(uri.getScheme()).isEqualTo("https"); + assertThat(uri.getHost()).isEqualTo("example.com"); } @Test @@ -95,9 +91,8 @@ public class RibbonClientConfigurationTests { when(this.inspector.isSecure(server)).thenReturn(true); for (AbstractLoadBalancerAwareClient client : clients()) { - URI uri = client.reconstructURIWithServer(server, - new URI("http://foo/")); - assertThat(getReason(client), uri, is(new URI("https://foo:7777/"))); + URI uri = client.reconstructURIWithServer(server, new URI("http://foo/")); + assertThat(uri).as(getReason(client)).isEqualTo(new URI("https://foo:7777/")); } } @@ -107,14 +102,13 @@ public class RibbonClientConfigurationTests { when(this.inspector.isSecure(server)).thenReturn(false); for (AbstractLoadBalancerAwareClient client : clients()) { - URI uri = client.reconstructURIWithServer(server, - new URI("http://foo/")); - assertThat(getReason(client), uri, is(new URI("http://foo:7777/"))); + URI uri = client.reconstructURIWithServer(server, new URI("http://foo/")); + assertThat(uri).as(getReason(client)).isEqualTo(new URI("http://foo:7777/")); } } String getReason(AbstractLoadBalancerAwareClient client) { - return client.getClass().getSimpleName()+" failed"; + return client.getClass().getSimpleName() + " failed"; } @Test @@ -125,7 +119,8 @@ public class RibbonClientConfigurationTests { for (AbstractLoadBalancerAwareClient client : clients()) { URI uri = client.reconstructURIWithServer(server, new URI("http://foo/%20bar")); - assertThat(getReason(client), uri, is(new URI("https://foo:7777/%20bar"))); + assertThat(uri).as(getReason(client)) + .isEqualTo(new URI("https://foo:7777/%20bar")); } } @@ -135,8 +130,9 @@ public class RibbonClientConfigurationTests { when(this.inspector.isSecure(server)).thenReturn(true); for (AbstractLoadBalancerAwareClient client : clients()) { - URI uri = client.reconstructURIWithServer(server, new URI("http://foo/%20bar?hello=1+2")); - assertThat(uri, is(new URI("https://foo:7777/%20bar?hello=1%202"))); + URI uri = client.reconstructURIWithServer(server, + new URI("http://foo/%20bar?hello=1+2")); + assertThat(uri).isEqualTo(new URI("https://foo:7777/%20bar?hello=1%202")); } } @@ -151,22 +147,26 @@ public class RibbonClientConfigurationTests { @SuppressWarnings("deprecation") @Test public void testDefaultsToApacheHttpClient() { - testClient(RibbonLoadBalancingHttpClient.class, null, RestClient.class, OkHttpLoadBalancingClient.class); - testClient(RibbonLoadBalancingHttpClient.class, new String[]{"ribbon.httpclient.enabled"}, RestClient.class, OkHttpLoadBalancingClient.class); - } - - @SuppressWarnings("deprecation") - @Test - public void testEnableRestClient() { - testClient(RestClient.class, new String[]{"ribbon.restclient.enabled"}, RibbonLoadBalancingHttpClient.class, + testClient(RibbonLoadBalancingHttpClient.class, null, RestClient.class, + OkHttpLoadBalancingClient.class); + testClient(RibbonLoadBalancingHttpClient.class, + new String[] { "ribbon.httpclient.enabled" }, RestClient.class, OkHttpLoadBalancingClient.class); } + @SuppressWarnings("deprecation") + @Test + public void testEnableRestClient() { + testClient(RestClient.class, new String[] { "ribbon.restclient.enabled" }, + RibbonLoadBalancingHttpClient.class, OkHttpLoadBalancingClient.class); + } + @SuppressWarnings("deprecation") @Test public void testEnableOkHttpClient() { - testClient(OkHttpLoadBalancingClient.class, new String[]{"ribbon.okhttp.enabled"}, RibbonLoadBalancingHttpClient.class, - RestClient.class); + testClient(OkHttpLoadBalancingClient.class, + new String[] { "ribbon.okhttp.enabled" }, + RibbonLoadBalancingHttpClient.class, RestClient.class); } void testClient(Class clientType, String[] properties, Class... excludedTypes) { @@ -179,7 +179,8 @@ public class RibbonClientConfigurationTests { context.refresh(); context.getBean(clientType); for (Class excludedType : excludedTypes) { - assertThat("has "+excludedType.getSimpleName()+ " instance", hasInstance(context, excludedType), is(false)); + assertThat(hasInstance(context, excludedType)) + .as("has " + excludedType.getSimpleName() + " instance").isFalse(); } context.close(); } @@ -191,9 +192,17 @@ public class RibbonClientConfigurationTests { @Configuration @EnableAutoConfiguration - protected static class TestLBConfig { } + protected static class TestLBConfig { - static class TestRestClient extends OverrideRestClient { + } + + static class CountingConfig extends DefaultClientConfigImpl { + + int count = 0; + + } + + static final class TestRestClient extends OverrideRestClient { private TestRestClient(IClientConfig ncc) { super(ncc, new DefaultServerIntrospector()); @@ -204,5 +213,7 @@ public class RibbonClientConfigurationTests { ((CountingConfig) clientConfig).count++; super.initWithNiwsConfig(clientConfig); } + } + } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientHttpRequestFactoryTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientHttpRequestFactoryTests.java index ce59f7b9f..1d6a078ba 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientHttpRequestFactoryTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientHttpRequestFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,16 +12,19 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.ribbon; import java.net.URI; + +import com.netflix.loadbalancer.Server; +import com.netflix.loadbalancer.ServerList; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -46,11 +49,8 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.ResourceAccessException; import org.springframework.web.client.RestTemplate; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerList; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; /** @@ -59,7 +59,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = RibbonClientHttpRequestFactoryTests.App.class, webEnvironment = RANDOM_PORT, value = { "spring.application.name=ribbonclienttest", "spring.jmx.enabled=true", - "spring.cloud.netflix.metrics.enabled=false", "ribbon.restclient.enabled=true", "debug=true" }) + "spring.cloud.netflix.metrics.enabled=false", "ribbon.restclient.enabled=true", + "debug=true" }) @DirtiesContext public class RibbonClientHttpRequestFactoryTests { @@ -80,49 +81,55 @@ public class RibbonClientHttpRequestFactoryTests { public void vanillaRequestWorks() { ResponseEntity response = this.restTemplate.getForEntity("http://simple/", String.class); - assertEquals("wrong response code", HttpStatus.OK, response.getStatusCode()); - assertEquals("wrong response body", "hello", response.getBody()); + assertThat(response.getStatusCode()).as("wrong response code") + .isEqualTo(HttpStatus.OK); + assertThat(response.getBody()).as("wrong response body").isEqualTo("hello"); } @Test public void requestWithPathParamWorks() { ResponseEntity response = this.restTemplate .getForEntity("http://simple/path/{param}", String.class, "world"); - assertEquals("wrong response code", HttpStatus.OK, response.getStatusCode()); - assertEquals("wrong response body", "hello world", response.getBody()); + assertThat(response.getStatusCode()).as("wrong response code") + .isEqualTo(HttpStatus.OK); + assertThat(response.getBody()).as("wrong response body").isEqualTo("hello world"); } @Test public void requestWithEncodedPathParamWorks() { ResponseEntity response = this.restTemplate.getForEntity( "http://simple/path/{param}", String.class, "world & everyone else"); - assertEquals("wrong response code", HttpStatus.OK, response.getStatusCode()); - assertEquals("wrong response body", "hello world & everyone else", - response.getBody()); + assertThat(response.getStatusCode()).as("wrong response code") + .isEqualTo(HttpStatus.OK); + assertThat(response.getBody()).as("wrong response body") + .isEqualTo("hello world & everyone else"); } @Test public void requestWithRequestParamWorks() { ResponseEntity response = this.restTemplate.getForEntity( "http://simple/request?param={param}", String.class, "world"); - assertEquals("wrong response code", HttpStatus.OK, response.getStatusCode()); - assertEquals("wrong response body", "hello world", response.getBody()); + assertThat(response.getStatusCode()).as("wrong response code") + .isEqualTo(HttpStatus.OK); + assertThat(response.getBody()).as("wrong response body").isEqualTo("hello world"); } @Test public void requestWithPostWorks() { ResponseEntity response = this.restTemplate .postForEntity("http://simple/post", "world", String.class); - assertEquals("wrong response code", HttpStatus.OK, response.getStatusCode()); - assertEquals("wrong response body", "hello world", response.getBody()); + assertThat(response.getStatusCode()).as("wrong response code") + .isEqualTo(HttpStatus.OK); + assertThat(response.getBody()).as("wrong response body").isEqualTo("hello world"); } @Test public void requestWithEmptyPostWorks() { ResponseEntity response = this.restTemplate .postForEntity("http://simple/emptypost", "", String.class); - assertEquals("wrong response code", HttpStatus.OK, response.getStatusCode()); - assertEquals("wrong response body", "hello empty", response.getBody()); + assertThat(response.getStatusCode()).as("wrong response code") + .isEqualTo(HttpStatus.OK); + assertThat(response.getBody()).as("wrong response body").isEqualTo("hello empty"); } @Test @@ -131,8 +138,9 @@ public class RibbonClientHttpRequestFactoryTests { .header("X-Param", "world").build(); ResponseEntity response = this.restTemplate.exchange(entity, String.class); - assertEquals("wrong response code", HttpStatus.OK, response.getStatusCode()); - assertEquals("wrong response body", "hello world", response.getBody()); + assertThat(response.getStatusCode()).as("wrong response code") + .isEqualTo(HttpStatus.OK); + assertThat(response.getBody()).as("wrong response body").isEqualTo("hello world"); } @Test @@ -150,10 +158,7 @@ public class RibbonClientHttpRequestFactoryTests { @Override protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests() - .anyRequest().permitAll() - .and() - .csrf().disable(); + http.authorizeRequests().anyRequest().permitAll().and().csrf().disable(); } @LoadBalanced @@ -191,6 +196,7 @@ public class RibbonClientHttpRequestFactoryTests { public String hiHeader(@RequestHeader("X-Param") String param) { return "hello " + param; } + } @Configuration @@ -205,4 +211,5 @@ public class RibbonClientHttpRequestFactoryTests { } } + } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientPreprocessorIntegrationTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientPreprocessorIntegrationTests.java index 26633866f..190cdee8c 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientPreprocessorIntegrationTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientPreprocessorIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,13 +12,18 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.ribbon; +import com.netflix.loadbalancer.ConfigurationBasedServerList; +import com.netflix.loadbalancer.DummyPing; +import com.netflix.loadbalancer.Server; +import com.netflix.loadbalancer.ZoneAvoidanceRule; +import com.netflix.loadbalancer.ZoneAwareLoadBalancer; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -28,11 +33,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.netflix.loadbalancer.ConfigurationBasedServerList; -import com.netflix.loadbalancer.DummyPing; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ZoneAvoidanceRule; -import com.netflix.loadbalancer.ZoneAwareLoadBalancer; /** * @author Dave Syer @@ -72,9 +72,10 @@ public class RibbonClientPreprocessorIntegrationTests { @Configuration @RibbonClient(name = "foo") - @Import({ PropertyPlaceholderAutoConfiguration.class, - ArchaiusAutoConfiguration.class, RibbonAutoConfiguration.class }) + @Import({ PropertyPlaceholderAutoConfiguration.class, ArchaiusAutoConfiguration.class, + RibbonAutoConfiguration.class }) protected static class PlainConfiguration { + } } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientPreprocessorOverridesIntegrationTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientPreprocessorOverridesIntegrationTests.java index 0fdf5734c..e642423f4 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientPreprocessorOverridesIntegrationTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientPreprocessorOverridesIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,23 +12,10 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.ribbon; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.commons.util.UtilAutoConfiguration; -import org.springframework.cloud.netflix.archaius.ArchaiusAutoConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.ConfigurationBasedServerList; import com.netflix.loadbalancer.DummyPing; @@ -41,8 +28,21 @@ import com.netflix.loadbalancer.Server; import com.netflix.loadbalancer.ServerList; import com.netflix.loadbalancer.ServerListFilter; import com.netflix.loadbalancer.ZoneAwareLoadBalancer; +import org.junit.Test; +import org.junit.runner.RunWith; -import static org.junit.Assert.assertEquals; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.commons.util.UtilAutoConfiguration; +import org.springframework.cloud.netflix.archaius.ArchaiusAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -81,23 +81,22 @@ public class RibbonClientPreprocessorOverridesIntegrationTests { @Test public void serverListFilterOverride() throws Exception { ServerListFilter filter = getLoadBalancer("foo").getFilter(); - assertEquals("FooTestZone", - ZonePreferenceServerListFilter.class.cast(filter) - .getZone()); + assertThat(ZonePreferenceServerListFilter.class.cast(filter).getZone()) + .isEqualTo("FooTestZone"); } @Configuration - @RibbonClients({ - @RibbonClient(name = "foo", configuration = FooConfiguration.class), - @RibbonClient(name = "bar", configuration = BarConfiguration.class) - }) + @RibbonClients({ @RibbonClient(name = "foo", configuration = FooConfiguration.class), + @RibbonClient(name = "bar", configuration = BarConfiguration.class) }) @Import({ UtilAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, - ArchaiusAutoConfiguration.class, RibbonAutoConfiguration.class}) + ArchaiusAutoConfiguration.class, RibbonAutoConfiguration.class }) protected static class TestConfiguration { + } @Configuration public static class FooConfiguration { + @Bean public IRule ribbonRule() { return new RandomRule(); @@ -119,12 +118,15 @@ public class RibbonClientPreprocessorOverridesIntegrationTests { filter.setZone("FooTestZone"); return filter; } + } public static class FooServiceList extends ConfigurationBasedServerList { + public FooServiceList(IClientConfig config) { super.initWithNiwsConfig(config); } + } @Configuration @@ -151,11 +153,15 @@ public class RibbonClientPreprocessorOverridesIntegrationTests { filter.setZone("BarTestZone"); return filter; } + } public static class BarServiceList extends ConfigurationBasedServerList { + public BarServiceList(IClientConfig config) { super.initWithNiwsConfig(config); } + } + } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientPreprocessorOverridesRetryTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientPreprocessorOverridesRetryTests.java index 9fa5f1370..f90062052 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientPreprocessorOverridesRetryTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientPreprocessorOverridesRetryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.ribbon; @@ -23,8 +22,13 @@ import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; + +import com.netflix.client.DefaultLoadBalancerRetryHandler; +import com.netflix.client.RetryHandler; +import com.netflix.client.config.IClientConfig; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -35,9 +39,6 @@ import org.springframework.context.annotation.Import; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.Assert; -import com.netflix.client.DefaultLoadBalancerRetryHandler; -import com.netflix.client.RetryHandler; -import com.netflix.client.config.IClientConfig; /** * @author Tyler Van Gorder @@ -70,12 +71,14 @@ public class RibbonClientPreprocessorOverridesRetryTests { @Import({ PropertyPlaceholderAutoConfiguration.class, ArchaiusAutoConfiguration.class, RibbonAutoConfiguration.class }) protected static class TestConfiguration { + } } @Configuration class RetryRibbonConfiguration { + @Bean public RetryHandler retryHandler(IClientConfig config) { return new CustomRetryHandler(config); @@ -116,4 +119,5 @@ class RetryRibbonConfiguration { } } + } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientPreprocessorPropertiesOverridesIntegrationTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientPreprocessorPropertiesOverridesIntegrationTests.java index b894cc19c..f6d6dca8c 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientPreprocessorPropertiesOverridesIntegrationTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientPreprocessorPropertiesOverridesIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,13 +12,21 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.ribbon; +import com.netflix.loadbalancer.ConfigurationBasedServerList; +import com.netflix.loadbalancer.DummyPing; +import com.netflix.loadbalancer.NoOpPing; +import com.netflix.loadbalancer.RandomRule; +import com.netflix.loadbalancer.Server; +import com.netflix.loadbalancer.ServerListSubsetFilter; +import com.netflix.loadbalancer.ZoneAvoidanceRule; +import com.netflix.loadbalancer.ZoneAwareLoadBalancer; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -31,14 +39,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.netflix.loadbalancer.ConfigurationBasedServerList; -import com.netflix.loadbalancer.DummyPing; -import com.netflix.loadbalancer.NoOpPing; -import com.netflix.loadbalancer.RandomRule; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerListSubsetFilter; -import com.netflix.loadbalancer.ZoneAvoidanceRule; -import com.netflix.loadbalancer.ZoneAwareLoadBalancer; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; @@ -103,9 +103,11 @@ public class RibbonClientPreprocessorPropertiesOverridesIntegrationTests { @Configuration @RibbonClients - @Import({ UtilAutoConfiguration.class, HttpClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class, - ArchaiusAutoConfiguration.class, RibbonAutoConfiguration.class }) + @Import({ UtilAutoConfiguration.class, HttpClientConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, ArchaiusAutoConfiguration.class, + RibbonAutoConfiguration.class }) protected static class TestConfiguration { + } } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientsEagerInitializationTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientsEagerInitializationTests.java index 53ece37f4..6ba5fbbe7 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientsEagerInitializationTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientsEagerInitializationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,8 +17,10 @@ package org.springframework.cloud.netflix.ribbon; import java.util.concurrent.atomic.AtomicInteger; + import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; @@ -33,10 +35,8 @@ import static org.assertj.core.api.Assertions.assertThat; */ @RunWith(SpringRunner.class) -@SpringBootTest(properties = { - "ribbon.eager-load.enabled=true", - "ribbon.eager-load.clients=testspec1,testspec2" -}) +@SpringBootTest(properties = { "ribbon.eager-load.enabled=true", + "ribbon.eager-load.clients=testspec1,testspec2" }) @DirtiesContext public class RibbonClientsEagerInitializationTests { @@ -46,32 +46,35 @@ public class RibbonClientsEagerInitializationTests { } static class FooConfig { + @Bean public Foo1 foo() { return new Foo1(); } + } @Configuration @EnableAutoConfiguration - @RibbonClients( - value = { - @RibbonClient(name="testspec1", configuration = FooConfig.class), - @RibbonClient(name="testspec2", configuration = FooConfig.class), - @RibbonClient(name="testspec3", configuration = FooConfig.class), - }) + @RibbonClients({ @RibbonClient(name = "testspec1", configuration = FooConfig.class), + @RibbonClient(name = "testspec2", configuration = FooConfig.class), + @RibbonClient(name = "testspec3", configuration = FooConfig.class) }) static class RibbonConfig { + } static class Foo1 { + private static final AtomicInteger INSTANCE_COUNT = new AtomicInteger(); - public Foo1() { + Foo1() { INSTANCE_COUNT.incrementAndGet(); } public static int getInstanceCount() { return INSTANCE_COUNT.get(); } + } + } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientsPreprocessorIntegrationTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientsPreprocessorIntegrationTests.java index 2ac7a27ef..afa7caa95 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientsPreprocessorIntegrationTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonClientsPreprocessorIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,13 +12,18 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.ribbon; +import com.netflix.loadbalancer.IPing; +import com.netflix.loadbalancer.PingUrl; +import com.netflix.loadbalancer.Server; +import com.netflix.loadbalancer.ZoneAvoidanceRule; +import com.netflix.loadbalancer.ZoneAwareLoadBalancer; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -31,11 +36,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.netflix.loadbalancer.IPing; -import com.netflix.loadbalancer.PingUrl; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ZoneAvoidanceRule; -import com.netflix.loadbalancer.ZoneAwareLoadBalancer; import static org.assertj.core.api.Assertions.assertThat; @@ -74,13 +74,16 @@ public class RibbonClientsPreprocessorIntegrationTests { @Configuration @RibbonClients(@RibbonClient(name = "foo", configuration = FooConfiguration.class)) @Import({ UtilAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, - ArchaiusAutoConfiguration.class, RibbonAutoConfiguration.class, HttpClientConfiguration.class}) + ArchaiusAutoConfiguration.class, RibbonAutoConfiguration.class, + HttpClientConfiguration.class }) protected static class TestConfiguration { + } // tag::sample_override_ribbon_config[] @Configuration protected static class FooConfiguration { + @Bean public ZonePreferenceServerListFilter serverListFilter() { ZonePreferenceServerListFilter filter = new ZonePreferenceServerListFilter(); @@ -92,6 +95,7 @@ public class RibbonClientsPreprocessorIntegrationTests { public IPing ribbonPing() { return new PingUrl(); } + } // end::sample_override_ribbon_config[] diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonDisabledTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonDisabledTests.java index dcca01f6e..9ccfb8b5c 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonDisabledTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonDisabledTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,20 +12,19 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.ribbon; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.cloud.test.ClassPathExclusions; import org.springframework.cloud.test.ModifiedClassPathRunner; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * @author Ryan Baxter @@ -34,13 +33,15 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(ModifiedClassPathRunner.class) @ClassPathExclusions({ "ribbon-{version:\\d.*}.jar" }) public class RibbonDisabledTests { + @Test public void testRibbonDisabled() { new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RibbonAutoConfiguration.class)) - .run(context -> { - assertThat(context.getBeanNamesForType(SpringClientFactory.class)) - .hasSize(0); - }); + .withConfiguration(AutoConfigurations.of(RibbonAutoConfiguration.class)) + .run(context -> { + assertThat(context.getBeanNamesForType(SpringClientFactory.class)) + .hasSize(0); + }); } -} \ No newline at end of file + +} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonInterceptorTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonInterceptorTests.java index aa9bb89ea..ab4c7e799 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonInterceptorTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,11 +19,14 @@ package org.springframework.cloud.netflix.ribbon; import java.io.IOException; import java.net.URI; import java.net.URL; + +import com.netflix.loadbalancer.Server; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; + import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor; @@ -35,10 +38,8 @@ import org.springframework.http.client.ClientHttpResponse; import org.springframework.http.client.support.HttpRequestWrapper; import org.springframework.util.ReflectionUtils; import org.springframework.web.util.UriComponentsBuilder; -import com.netflix.loadbalancer.Server; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.verify; @@ -65,7 +66,8 @@ public class RibbonInterceptorTests { @Test public void testIntercept() throws Exception { RibbonServer server = new RibbonServer("myservice", new Server("myhost", 8080)); - LoadBalancerInterceptor interceptor = new LoadBalancerInterceptor(new MyClient(server)); + LoadBalancerInterceptor interceptor = new LoadBalancerInterceptor( + new MyClient(server)); given(this.request.getURI()).willReturn(new URL("http://myservice").toURI()); given(this.execution.execute(isA(HttpRequest.class), isA(byte[].class))) .willReturn(this.response); @@ -73,11 +75,11 @@ public class RibbonInterceptorTests { .forClass(HttpRequestWrapper.class); ClientHttpResponse response = interceptor.intercept(this.request, new byte[0], this.execution); - assertNotNull("response was null", response); + assertThat(response).as("response was null").isNotNull(); verify(this.execution).execute(argument.capture(), isA(byte[].class)); HttpRequestWrapper wrapper = argument.getValue(); - assertEquals("wrong constructed uri", new URL("http://myhost:8080").toURI(), - wrapper.getURI()); + assertThat(wrapper.getURI()).as("wrong constructed uri") + .isEqualTo(new URL("http://myhost:8080").toURI()); } protected static class MyClient implements LoadBalancerClient { @@ -105,7 +107,8 @@ public class RibbonInterceptorTests { } @Override - public T execute(String s, ServiceInstance serviceInstance, LoadBalancerRequest request) throws IOException { + public T execute(String s, ServiceInstance serviceInstance, + LoadBalancerRequest request) throws IOException { try { return request.apply(this.instance); } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancedRetryFactoryTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancedRetryFactoryTests.java index b032e24f7..36450299d 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancedRetryFactoryTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancedRetryFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,17 +20,7 @@ import java.io.IOException; import java.net.SocketException; import java.util.Collections; import java.util.Map; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryContext; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicy; -import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient.RibbonServer; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpRequest; + import com.netflix.client.DefaultLoadBalancerRetryHandler; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; @@ -38,9 +28,20 @@ import com.netflix.loadbalancer.BaseLoadBalancer; import com.netflix.loadbalancer.LoadBalancerStats; import com.netflix.loadbalancer.Server; import com.netflix.loadbalancer.ServerStats; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryContext; +import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicy; +import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient.RibbonServer; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpRequest; + +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyBoolean; @@ -74,8 +75,8 @@ public class RibbonLoadBalancedRetryFactoryTests { @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); - given(this.clientFactory.getLoadBalancerContext(anyString())).willReturn( - new RibbonLoadBalancerContext(this.loadBalancer)); + given(this.clientFactory.getLoadBalancerContext(anyString())) + .willReturn(new RibbonLoadBalancerContext(this.loadBalancer)); given(this.clientFactory.getInstance(anyString(), eq(ServerIntrospector.class))) .willReturn(new DefaultServerIntrospector() { @Override @@ -87,7 +88,8 @@ public class RibbonLoadBalancedRetryFactoryTests { } @After - public void tearDown() throws Exception {} + public void tearDown() throws Exception { + } @Test public void testGetRetryPolicyNoRetry() throws Exception { @@ -96,25 +98,35 @@ public class RibbonLoadBalancedRetryFactoryTests { boolean retryOnAllOps = false; RibbonServer server = getRibbonServer(); IClientConfig config = mock(IClientConfig.class); - doReturn(sameServer).when(config).get(eq(CommonClientConfigKey.MaxAutoRetries), anyInt()); - doReturn(sameServer).when(config).getPropertyAsInteger(eq(CommonClientConfigKey.MaxAutoRetries), anyInt()); - doReturn(nextServer).when(config).get(eq(CommonClientConfigKey.MaxAutoRetriesNextServer), anyInt()); - doReturn(nextServer).when(config).getPropertyAsInteger(eq(CommonClientConfigKey.MaxAutoRetriesNextServer), anyInt()); - doReturn(retryOnAllOps).when(config).get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), anyBoolean()); - doReturn(retryOnAllOps).when(config).getPropertyAsBoolean(eq(CommonClientConfigKey.OkToRetryOnAllOperations), anyBoolean()); - doReturn("").when(config).getPropertyAsString(eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES),eq("")); + doReturn(sameServer).when(config).get(eq(CommonClientConfigKey.MaxAutoRetries), + anyInt()); + doReturn(sameServer).when(config) + .getPropertyAsInteger(eq(CommonClientConfigKey.MaxAutoRetries), anyInt()); + doReturn(nextServer).when(config) + .get(eq(CommonClientConfigKey.MaxAutoRetriesNextServer), anyInt()); + doReturn(nextServer).when(config).getPropertyAsInteger( + eq(CommonClientConfigKey.MaxAutoRetriesNextServer), anyInt()); + doReturn(retryOnAllOps).when(config) + .get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), anyBoolean()); + doReturn(retryOnAllOps).when(config).getPropertyAsBoolean( + eq(CommonClientConfigKey.OkToRetryOnAllOperations), anyBoolean()); + doReturn("").when(config).getPropertyAsString( + eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES), eq("")); doReturn(server.getServiceId()).when(config).getClientName(); doReturn(config).when(clientFactory).getClientConfig(eq(server.getServiceId())); - clientFactory.getLoadBalancerContext(server.getServiceId()).setRetryHandler(new DefaultLoadBalancerRetryHandler(config)); + clientFactory.getLoadBalancerContext(server.getServiceId()) + .setRetryHandler(new DefaultLoadBalancerRetryHandler(config)); RibbonLoadBalancerClient client = getRibbonLoadBalancerClient(server); - RibbonLoadBalancedRetryFactory factory = new RibbonLoadBalancedRetryFactory(clientFactory); - LoadBalancedRetryPolicy policy = factory.createRetryPolicy(server.getServiceId(), client); + RibbonLoadBalancedRetryFactory factory = new RibbonLoadBalancedRetryFactory( + clientFactory); + LoadBalancedRetryPolicy policy = factory.createRetryPolicy(server.getServiceId(), + client); HttpRequest request = mock(HttpRequest.class); doReturn(HttpMethod.GET).when(request).getMethod(); LoadBalancedRetryContext context = new LoadBalancedRetryContext(null, request); - assertThat(policy.canRetryNextServer(context), is(true)); - assertThat(policy.canRetrySameServer(context), is(false)); - assertThat(policy.retryableStatusCode(400), is(false)); + assertThat(policy.canRetryNextServer(context)).isTrue(); + assertThat(policy.canRetrySameServer(context)).isFalse(); + assertThat(policy.retryableStatusCode(400)).isFalse(); } @Test @@ -124,25 +136,35 @@ public class RibbonLoadBalancedRetryFactoryTests { boolean retryOnAllOps = false; RibbonServer server = getRibbonServer(); IClientConfig config = mock(IClientConfig.class); - doReturn(sameServer).when(config).get(eq(CommonClientConfigKey.MaxAutoRetries), anyInt()); - doReturn(sameServer).when(config).getPropertyAsInteger(eq(CommonClientConfigKey.MaxAutoRetries), anyInt()); - doReturn(nextServer).when(config).get(eq(CommonClientConfigKey.MaxAutoRetriesNextServer), anyInt()); - doReturn(nextServer).when(config).getPropertyAsInteger(eq(CommonClientConfigKey.MaxAutoRetriesNextServer), anyInt()); - doReturn(retryOnAllOps).when(config).get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), anyBoolean()); - doReturn(retryOnAllOps).when(config).getPropertyAsBoolean(eq(CommonClientConfigKey.OkToRetryOnAllOperations), anyBoolean()); - doReturn("").when(config).getPropertyAsString(eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES),eq("")); + doReturn(sameServer).when(config).get(eq(CommonClientConfigKey.MaxAutoRetries), + anyInt()); + doReturn(sameServer).when(config) + .getPropertyAsInteger(eq(CommonClientConfigKey.MaxAutoRetries), anyInt()); + doReturn(nextServer).when(config) + .get(eq(CommonClientConfigKey.MaxAutoRetriesNextServer), anyInt()); + doReturn(nextServer).when(config).getPropertyAsInteger( + eq(CommonClientConfigKey.MaxAutoRetriesNextServer), anyInt()); + doReturn(retryOnAllOps).when(config) + .get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), anyBoolean()); + doReturn(retryOnAllOps).when(config).getPropertyAsBoolean( + eq(CommonClientConfigKey.OkToRetryOnAllOperations), anyBoolean()); + doReturn("").when(config).getPropertyAsString( + eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES), eq("")); doReturn(server.getServiceId()).when(config).getClientName(); doReturn(config).when(clientFactory).getClientConfig(eq(server.getServiceId())); - clientFactory.getLoadBalancerContext(server.getServiceId()).setRetryHandler(new DefaultLoadBalancerRetryHandler(config)); + clientFactory.getLoadBalancerContext(server.getServiceId()) + .setRetryHandler(new DefaultLoadBalancerRetryHandler(config)); RibbonLoadBalancerClient client = getRibbonLoadBalancerClient(server); - RibbonLoadBalancedRetryFactory factory = new RibbonLoadBalancedRetryFactory(clientFactory); - LoadBalancedRetryPolicy policy = factory.createRetryPolicy(server.getServiceId(), client); + RibbonLoadBalancedRetryFactory factory = new RibbonLoadBalancedRetryFactory( + clientFactory); + LoadBalancedRetryPolicy policy = factory.createRetryPolicy(server.getServiceId(), + client); HttpRequest request = mock(HttpRequest.class); doReturn(HttpMethod.POST).when(request).getMethod(); LoadBalancedRetryContext context = new LoadBalancedRetryContext(null, request); - assertThat(policy.canRetryNextServer(context), is(false)); - assertThat(policy.canRetrySameServer(context), is(false)); - assertThat(policy.retryableStatusCode(400), is(false)); + assertThat(policy.canRetryNextServer(context)).isFalse(); + assertThat(policy.canRetrySameServer(context)).isFalse(); + assertThat(policy.retryableStatusCode(400)).isFalse(); } @Test @@ -152,25 +174,35 @@ public class RibbonLoadBalancedRetryFactoryTests { boolean retryOnAllOps = true; RibbonServer server = getRibbonServer(); IClientConfig config = mock(IClientConfig.class); - doReturn(sameServer).when(config).get(eq(CommonClientConfigKey.MaxAutoRetries), anyInt()); - doReturn(sameServer).when(config).getPropertyAsInteger(eq(CommonClientConfigKey.MaxAutoRetries), anyInt()); - doReturn(nextServer).when(config).get(eq(CommonClientConfigKey.MaxAutoRetriesNextServer), anyInt()); - doReturn(nextServer).when(config).getPropertyAsInteger(eq(CommonClientConfigKey.MaxAutoRetriesNextServer), anyInt()); - doReturn(retryOnAllOps).when(config).get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), anyBoolean()); - doReturn(retryOnAllOps).when(config).getPropertyAsBoolean(eq(CommonClientConfigKey.OkToRetryOnAllOperations), anyBoolean()); - doReturn("").when(config).getPropertyAsString(eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES),eq("")); + doReturn(sameServer).when(config).get(eq(CommonClientConfigKey.MaxAutoRetries), + anyInt()); + doReturn(sameServer).when(config) + .getPropertyAsInteger(eq(CommonClientConfigKey.MaxAutoRetries), anyInt()); + doReturn(nextServer).when(config) + .get(eq(CommonClientConfigKey.MaxAutoRetriesNextServer), anyInt()); + doReturn(nextServer).when(config).getPropertyAsInteger( + eq(CommonClientConfigKey.MaxAutoRetriesNextServer), anyInt()); + doReturn(retryOnAllOps).when(config) + .get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), anyBoolean()); + doReturn(retryOnAllOps).when(config).getPropertyAsBoolean( + eq(CommonClientConfigKey.OkToRetryOnAllOperations), anyBoolean()); + doReturn("").when(config).getPropertyAsString( + eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES), eq("")); doReturn(server.getServiceId()).when(config).getClientName(); doReturn(config).when(clientFactory).getClientConfig(eq(server.getServiceId())); - clientFactory.getLoadBalancerContext(server.getServiceId()).initWithNiwsConfig(config); + clientFactory.getLoadBalancerContext(server.getServiceId()) + .initWithNiwsConfig(config); RibbonLoadBalancerClient client = getRibbonLoadBalancerClient(server); - RibbonLoadBalancedRetryFactory factory = new RibbonLoadBalancedRetryFactory(clientFactory); - LoadBalancedRetryPolicy policy = factory.createRetryPolicy(server.getServiceId(), client); + RibbonLoadBalancedRetryFactory factory = new RibbonLoadBalancedRetryFactory( + clientFactory); + LoadBalancedRetryPolicy policy = factory.createRetryPolicy(server.getServiceId(), + client); HttpRequest request = mock(HttpRequest.class); doReturn(HttpMethod.POST).when(request).getMethod(); LoadBalancedRetryContext context = new LoadBalancedRetryContext(null, request); - assertThat(policy.canRetryNextServer(context), is(true)); - assertThat(policy.canRetrySameServer(context), is(true)); - assertThat(policy.retryableStatusCode(400), is(false)); + assertThat(policy.canRetryNextServer(context)).isTrue(); + assertThat(policy.canRetrySameServer(context)).isTrue(); + assertThat(policy.retryableStatusCode(400)).isFalse(); } @Test @@ -179,40 +211,51 @@ public class RibbonLoadBalancedRetryFactoryTests { int nextServer = 3; RibbonServer server = getRibbonServer(); IClientConfig config = mock(IClientConfig.class); - doReturn(sameServer).when(config).get(eq(CommonClientConfigKey.MaxAutoRetries), anyInt()); - doReturn(nextServer).when(config).get(eq(CommonClientConfigKey.MaxAutoRetriesNextServer), anyInt()); - doReturn(false).when(config).get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), eq(false)); + doReturn(sameServer).when(config).get(eq(CommonClientConfigKey.MaxAutoRetries), + anyInt()); + doReturn(nextServer).when(config) + .get(eq(CommonClientConfigKey.MaxAutoRetriesNextServer), anyInt()); + doReturn(false).when(config) + .get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), eq(false)); doReturn(config).when(clientFactory).getClientConfig(eq(server.getServiceId())); - doReturn("").when(config).getPropertyAsString(eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES),eq("")); - clientFactory.getLoadBalancerContext(server.getServiceId()).setRetryHandler(new DefaultLoadBalancerRetryHandler(config)); + doReturn("").when(config).getPropertyAsString( + eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES), eq("")); + clientFactory.getLoadBalancerContext(server.getServiceId()) + .setRetryHandler(new DefaultLoadBalancerRetryHandler(config)); RibbonLoadBalancerClient client = getRibbonLoadBalancerClient(server); - RibbonLoadBalancedRetryFactory factory = new RibbonLoadBalancedRetryFactory(clientFactory); - LoadBalancedRetryPolicy policy = factory.createRetryPolicy(server.getServiceId(), client); + RibbonLoadBalancedRetryFactory factory = new RibbonLoadBalancedRetryFactory( + clientFactory); + LoadBalancedRetryPolicy policy = factory.createRetryPolicy(server.getServiceId(), + client); HttpRequest request = mock(HttpRequest.class); doReturn(HttpMethod.GET).when(request).getMethod(); - LoadBalancedRetryContext context = spy(new LoadBalancedRetryContext(null, request)); - //Loop through as if we are retrying a request until we exhaust the number of retries - //outer loop is for next server retries - //inner loop is for same server retries - for(int i = 0; i < nextServer + 1; i++) { - //iterate once time beyond the same server retry limit to cause us to reset - //the same sever counter and increment the next server counter - for(int j = 0; j < sameServer + 1; j++) { - if(j < 3) { - assertThat(policy.canRetrySameServer(context), is(true)); - } else { - assertThat(policy.canRetrySameServer(context), is(false)); + LoadBalancedRetryContext context = spy( + new LoadBalancedRetryContext(null, request)); + // Loop through as if we are retrying a request until we exhaust the number of + // retries + // outer loop is for next server retries + // inner loop is for same server retries + for (int i = 0; i < nextServer + 1; i++) { + // iterate once time beyond the same server retry limit to cause us to reset + // the same sever counter and increment the next server counter + for (int j = 0; j < sameServer + 1; j++) { + if (j < 3) { + assertThat(policy.canRetrySameServer(context)).isTrue(); + } + else { + assertThat(policy.canRetrySameServer(context)).isFalse(); } policy.registerThrowable(context, new IOException()); } - if(i < 3) { - assertThat(policy.canRetryNextServer(context), is(true)); - } else { - assertThat(policy.canRetryNextServer(context), is(false)); + if (i < 3) { + assertThat(policy.canRetryNextServer(context)).isTrue(); + } + else { + assertThat(policy.canRetryNextServer(context)).isFalse(); } } - assertThat(context.isExhaustedOnly(), is(true)); - assertThat(policy.retryableStatusCode(400), is(false)); + assertThat(context.isExhaustedOnly()).isTrue(); + assertThat(policy.retryableStatusCode(400)).isFalse(); verify(context, times(4)).setServiceInstance(any(ServiceInstance.class)); } @@ -220,28 +263,36 @@ public class RibbonLoadBalancedRetryFactoryTests { public void testCiruitRelatedExceptionsUpdateServerStats() throws Exception { int sameServer = 3; int nextServer = 3; - + RibbonServer server = getRibbonServer(); IClientConfig config = mock(IClientConfig.class); - - doReturn(sameServer).when(config).get(eq(CommonClientConfigKey.MaxAutoRetries), anyInt()); - doReturn(nextServer).when(config).get(eq(CommonClientConfigKey.MaxAutoRetriesNextServer), anyInt()); - doReturn(false).when(config).get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), eq(false)); + + doReturn(sameServer).when(config).get(eq(CommonClientConfigKey.MaxAutoRetries), + anyInt()); + doReturn(nextServer).when(config) + .get(eq(CommonClientConfigKey.MaxAutoRetriesNextServer), anyInt()); + doReturn(false).when(config) + .get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), eq(false)); doReturn(config).when(clientFactory).getClientConfig(eq(server.getServiceId())); - doReturn("").when(config).getPropertyAsString(eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES),eq("")); - clientFactory.getLoadBalancerContext(server.getServiceId()).setRetryHandler(new DefaultLoadBalancerRetryHandler(config)); + doReturn("").when(config).getPropertyAsString( + eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES), eq("")); + clientFactory.getLoadBalancerContext(server.getServiceId()) + .setRetryHandler(new DefaultLoadBalancerRetryHandler(config)); RibbonLoadBalancerClient client = getRibbonLoadBalancerClient(server); - - RibbonLoadBalancedRetryFactory factory = new RibbonLoadBalancedRetryFactory(clientFactory); - LoadBalancedRetryPolicy policy = factory.createRetryPolicy(server.getServiceId(), client); + + RibbonLoadBalancedRetryFactory factory = new RibbonLoadBalancedRetryFactory( + clientFactory); + LoadBalancedRetryPolicy policy = factory.createRetryPolicy(server.getServiceId(), + client); HttpRequest request = mock(HttpRequest.class); - - LoadBalancedRetryContext context = spy(new LoadBalancedRetryContext(null, request)); + + LoadBalancedRetryContext context = spy( + new LoadBalancedRetryContext(null, request)); doReturn(server).when(context).getServiceInstance(); - + policy.registerThrowable(context, new IOException()); verify(serverStats, times(0)).incrementSuccessiveConnectionFailureCount(); - + // Circuit Related should increment failure count policy.registerThrowable(context, new SocketException()); verify(serverStats, times(1)).incrementSuccessiveConnectionFailureCount(); @@ -253,28 +304,35 @@ public class RibbonLoadBalancedRetryFactoryTests { int nextServer = 3; RibbonServer server = getRibbonServer(); IClientConfig config = mock(IClientConfig.class); - doReturn(sameServer).when(config).get(eq(CommonClientConfigKey.MaxAutoRetries), anyInt()); - doReturn(nextServer).when(config).get(eq(CommonClientConfigKey.MaxAutoRetriesNextServer), anyInt()); - doReturn(false).when(config).get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), eq(false)); + doReturn(sameServer).when(config).get(eq(CommonClientConfigKey.MaxAutoRetries), + anyInt()); + doReturn(nextServer).when(config) + .get(eq(CommonClientConfigKey.MaxAutoRetriesNextServer), anyInt()); + doReturn(false).when(config) + .get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), eq(false)); doReturn(config).when(clientFactory).getClientConfig(eq(server.getServiceId())); - doReturn("404, 418,502,foo, ,").when(config).getPropertyAsString(eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES),eq("")); - clientFactory.getLoadBalancerContext(server.getServiceId()).setRetryHandler(new DefaultLoadBalancerRetryHandler(config)); + doReturn("404, 418,502,foo, ,").when(config).getPropertyAsString( + eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES), eq("")); + clientFactory.getLoadBalancerContext(server.getServiceId()) + .setRetryHandler(new DefaultLoadBalancerRetryHandler(config)); RibbonLoadBalancerClient client = getRibbonLoadBalancerClient(server); - RibbonLoadBalancedRetryFactory factory = new RibbonLoadBalancedRetryFactory(clientFactory); - LoadBalancedRetryPolicy policy = factory.createRetryPolicy(server.getServiceId(), client); + RibbonLoadBalancedRetryFactory factory = new RibbonLoadBalancedRetryFactory( + clientFactory); + LoadBalancedRetryPolicy policy = factory.createRetryPolicy(server.getServiceId(), + client); HttpRequest request = mock(HttpRequest.class); doReturn(HttpMethod.GET).when(request).getMethod(); - assertThat(policy.retryableStatusCode(400), is(false)); - assertThat(policy.retryableStatusCode(404), is(true)); - assertThat(policy.retryableStatusCode(418), is(true)); - assertThat(policy.retryableStatusCode(502), is(true)); + assertThat(policy.retryableStatusCode(400)).isFalse(); + assertThat(policy.retryableStatusCode(404)).isTrue(); + assertThat(policy.retryableStatusCode(418)).isTrue(); + assertThat(policy.retryableStatusCode(502)).isTrue(); } protected RibbonLoadBalancerClient getRibbonLoadBalancerClient( RibbonServer ribbonServer) { given(this.loadBalancer.getName()).willReturn(ribbonServer.getServiceId()); - given(this.loadBalancer.chooseServer(anyObject())).willReturn( - ribbonServer.getServer()); + given(this.loadBalancer.chooseServer(anyObject())) + .willReturn(ribbonServer.getServer()); given(this.loadBalancer.getLoadBalancerStats()) .willReturn(this.loadBalancerStats); given(this.loadBalancerStats.getSingleServerStat(ribbonServer.getServer())) @@ -289,4 +347,4 @@ public class RibbonLoadBalancedRetryFactoryTests { Collections.singletonMap("mykey", "myvalue")); } -} \ No newline at end of file +} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancerClientTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancerClientTests.java index bc4246f20..8008d2a49 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancerClientTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancerClientTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,10 +39,7 @@ import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient.RibbonS import org.springframework.web.util.DefaultUriBuilderFactory; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.same; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.anyDouble; @@ -77,8 +74,8 @@ public class RibbonLoadBalancerClientTests { public void init() { server = null; MockitoAnnotations.initMocks(this); - given(this.clientFactory.getLoadBalancerContext(anyString())).willReturn( - new RibbonLoadBalancerContext(this.loadBalancer)); + given(this.clientFactory.getLoadBalancerContext(anyString())) + .willReturn(new RibbonLoadBalancerContext(this.loadBalancer)); given(this.clientFactory.getInstance(anyString(), eq(ServerIntrospector.class))) .willReturn(new DefaultServerIntrospector() { @@ -111,11 +108,9 @@ public class RibbonLoadBalancerClientTests { ServiceInstance serviceInstance = client.choose(server.getServiceId()); URI uri = client.reconstructURI(serviceInstance, new URL(scheme + "://" + server.getServiceId()).toURI()); - assertThat(uri).hasScheme(scheme) - .hasHost(serviceInstance.getHost()) + assertThat(uri).hasScheme(scheme).hasHost(serviceInstance.getHost()) .hasPort(serviceInstance.getPort()); - assertThat(this.server).isNotNull() - .isInstanceOf(MyServer.class); + assertThat(this.server).isNotNull().isInstanceOf(MyServer.class); } @Test @@ -155,7 +150,8 @@ public class RibbonLoadBalancerClientTests { RibbonLoadBalancerClient client = getRibbonLoadBalancerClient(server); ServiceInstance serviceInstance = client.choose(server.getServiceId()); - URI uri = client.reconstructURI(serviceInstance, URI.create("http://testService")); + URI uri = client.reconstructURI(serviceInstance, + URI.create("http://testService")); assertThat(uri).hasScheme("ws").hasHost("myhost").hasPort(9080); } @@ -171,9 +167,9 @@ public class RibbonLoadBalancerClientTests { ServiceInstance serviceInstance = client.choose(server.getServiceId()); URI uri = client.reconstructURI(serviceInstance, new URL("http://" + server.getServiceId()).toURI()); - assertEquals(server.getHost(), uri.getHost()); - assertEquals(server.getPort(), uri.getPort()); - assertEquals("https", uri.getScheme()); + assertThat(uri.getHost()).isEqualTo(server.getHost()); + assertThat(uri.getPort()).isEqualTo(server.getPort()); + assertThat(uri.getScheme()).isEqualTo("https"); } @Test @@ -186,8 +182,8 @@ public class RibbonLoadBalancerClientTests { testReconstructSchemelessUriWithoutClientConfig(getRibbonServer(), "http"); } - public void testReconstructSchemelessUriWithoutClientConfig(RibbonServer server, String expectedScheme) - throws Exception { + public void testReconstructSchemelessUriWithoutClientConfig(RibbonServer server, + String expectedScheme) throws Exception { IClientConfig config = mock(IClientConfig.class); when(config.get(CommonClientConfigKey.IsSecure)).thenReturn(null); when(clientFactory.getClientConfig(server.getServiceId())).thenReturn(config); @@ -196,9 +192,9 @@ public class RibbonLoadBalancerClientTests { ServiceInstance serviceInstance = client.choose(server.getServiceId()); URI uri = client.reconstructURI(serviceInstance, new URI("//" + server.getServiceId())); - assertEquals(server.getHost(), uri.getHost()); - assertEquals(server.getPort(), uri.getPort()); - assertEquals(expectedScheme, uri.getScheme()); + assertThat(uri.getHost()).isEqualTo(server.getHost()); + assertThat(uri.getPort()).isEqualTo(server.getPort()); + assertThat(uri.getScheme()).isEqualTo(expectedScheme); } @Test @@ -225,9 +221,10 @@ public class RibbonLoadBalancerClientTests { given(this.clientFactory.getLoadBalancer(this.loadBalancer.getName())) .willReturn(null); given(this.loadBalancer.getName()).willReturn("missingservice"); - RibbonLoadBalancerClient client = new RibbonLoadBalancerClient(this.clientFactory); + RibbonLoadBalancerClient client = new RibbonLoadBalancerClient( + this.clientFactory); ServiceInstance instance = client.choose("missingservice"); - assertNull("instance wasn't null", instance); + assertThat(instance).as("instance wasn't null").isNull(); } @Test @@ -237,12 +234,12 @@ public class RibbonLoadBalancerClientTests { final String returnVal = "myval"; Object actualReturn = client.execute(server.getServiceId(), (LoadBalancerRequest) instance -> { - assertServiceInstance(server, instance); - return returnVal; - }); + assertServiceInstance(server, instance); + return returnVal; + }); verifyServerStats(); verify(this.loadBalancer).chooseServer(eq("default")); - assertEquals("retVal was wrong", returnVal, actualReturn); + assertThat(actualReturn).as("retVal was wrong").isEqualTo(returnVal); } @Test @@ -258,7 +255,7 @@ public class RibbonLoadBalancerClientTests { }, hint); verifyServerStats(); verify(this.loadBalancer).chooseServer(same(hint)); - assertEquals("retVal was wrong", returnVal, actualReturn); + assertThat(actualReturn).as("retVal was wrong").isEqualTo(returnVal); } @Test @@ -266,15 +263,14 @@ public class RibbonLoadBalancerClientTests { final RibbonServer ribbonServer = getRibbonServer(); RibbonLoadBalancerClient client = getRibbonLoadBalancerClient(ribbonServer); try { - client.execute(ribbonServer.getServiceId(), - instance -> { - assertServiceInstance(ribbonServer, instance); - throw new RuntimeException(); - }); + client.execute(ribbonServer.getServiceId(), instance -> { + assertServiceInstance(ribbonServer, instance); + throw new RuntimeException(); + }); fail("Should have thrown exception"); } catch (Exception ex) { - assertNotNull(ex); + assertThat(ex).isNotNull(); } verifyServerStats(); } @@ -284,15 +280,14 @@ public class RibbonLoadBalancerClientTests { final RibbonServer ribbonServer = getRibbonServer(); RibbonLoadBalancerClient client = getRibbonLoadBalancerClient(ribbonServer); try { - client.execute(ribbonServer.getServiceId(), - instance -> { - assertServiceInstance(ribbonServer, instance); - throw new IOException(); - }); + client.execute(ribbonServer.getServiceId(), instance -> { + assertServiceInstance(ribbonServer, instance); + throw new IOException(); + }); fail("Should have thrown exception"); } catch (Exception ex) { - assertThat(ex).isInstanceOf(IOException.class); + assertThat(ex).isInstanceOf(IOException.class); } verifyServerStats(); } @@ -307,14 +302,6 @@ public class RibbonLoadBalancerClientTests { Collections.singletonMap("mykey", "myvalue")); } - protected static class MyServer extends Server { - - public MyServer(String host, int port) { - super(host, port); - } - - } - protected void verifyServerStats() { verify(this.serverStats).incrementActiveRequestsCount(); verify(this.serverStats).decrementActiveRequestsCount(); @@ -324,22 +311,24 @@ public class RibbonLoadBalancerClientTests { protected void assertServiceInstance(RibbonServer ribbonServer, ServiceInstance instance) { - assertNotNull("instance was null", instance); - assertEquals("instanceId was wrong", ribbonServer.getInstanceId(), - instance.getInstanceId()); - assertEquals("serviceId was wrong", ribbonServer.getServiceId(), - instance.getServiceId()); - assertEquals("host was wrong", ribbonServer.getHost(), instance.getHost()); - assertEquals("port was wrong", ribbonServer.getPort(), instance.getPort()); - assertEquals("missing metadata", ribbonServer.getMetadata().get("mykey"), - instance.getMetadata().get("mykey")); + assertThat(instance).as("instance was null").isNotNull(); + assertThat(instance.getInstanceId()).as("instanceId was wrong") + .isEqualTo(ribbonServer.getInstanceId()); + assertThat(instance.getServiceId()).as("serviceId was wrong") + .isEqualTo(ribbonServer.getServiceId()); + assertThat(instance.getHost()).as("host was wrong") + .isEqualTo(ribbonServer.getHost()); + assertThat(instance.getPort()).as("port was wrong") + .isEqualTo(ribbonServer.getPort()); + assertThat(instance.getMetadata().get("mykey")).as("missing metadata") + .isEqualTo(ribbonServer.getMetadata().get("mykey")); } protected RibbonLoadBalancerClient getRibbonLoadBalancerClient( RibbonServer ribbonServer) { given(this.loadBalancer.getName()).willReturn(ribbonServer.getServiceId()); - given(this.loadBalancer.chooseServer(anyObject())).willReturn( - ribbonServer.getServer()); + given(this.loadBalancer.chooseServer(anyObject())) + .willReturn(ribbonServer.getServer()); given(this.loadBalancer.getLoadBalancerStats()) .willReturn(this.loadBalancerStats); given(this.loadBalancerStats.getSingleServerStat(ribbonServer.getServer())) @@ -348,4 +337,13 @@ public class RibbonLoadBalancerClientTests { .willReturn(this.loadBalancer); return new RibbonLoadBalancerClient(this.clientFactory); } + + protected static class MyServer extends Server { + + public MyServer(String host, int port) { + super(host, port); + } + + } + } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonPropertiesTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonPropertiesTests.java index eb414ace0..2a087dc27 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonPropertiesTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonPropertiesTests.java @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.ribbon; @@ -36,4 +35,5 @@ public class RibbonPropertiesTests { assertThat(properties.poolKeepAliveTime()).isEqualTo(714L); assertThat(properties.getPoolKeepAliveTime()).isEqualTo(714L); } + } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonUtilsTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonUtilsTests.java index 13051356b..6afb3d059 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonUtilsTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/RibbonUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.ribbon; @@ -20,13 +19,13 @@ package org.springframework.cloud.netflix.ribbon; import java.net.URI; import java.net.URISyntaxException; import java.util.Map; -import org.junit.Assert; -import org.junit.Test; + import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.loadbalancer.Server; +import org.junit.Test; -import static org.hamcrest.Matchers.is; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.cloud.netflix.ribbon.RibbonUtils.isSecure; import static org.springframework.cloud.netflix.ribbon.RibbonUtils.updateToSecureConnectionIfNeeded; @@ -37,91 +36,113 @@ import static org.springframework.cloud.netflix.ribbon.RibbonUtils.updateToSecur */ public class RibbonUtilsTests { - private static final ServerIntrospector NON_SECURE_INTROSPECTOR = new StaticServerIntrospector(false); - private static final ServerIntrospector SECURE_INTROSPECTOR = new StaticServerIntrospector(true); + private static final ServerIntrospector NON_SECURE_INTROSPECTOR = new StaticServerIntrospector( + false); + + private static final ServerIntrospector SECURE_INTROSPECTOR = new StaticServerIntrospector( + true); + private static final Server SERVER = new Server("localhost", 8080); + private static final DefaultClientConfigImpl SECURE_CONFIG = getConfig(true); + private static final DefaultClientConfigImpl NON_SECURE_CONFIG = getConfig(false); + private static final DefaultClientConfigImpl NO_IS_SECURE_CONFIG = new DefaultClientConfigImpl(); @Test public void noRibbonPropSecureIntrospector() { boolean secure = isSecure(NO_IS_SECURE_CONFIG, SECURE_INTROSPECTOR, SERVER); - Assert.assertThat("isSecure was wrong", secure, is(true)); + assertThat(secure).as("isSecure was wrong").isTrue(); } @Test public void noRibbonPropNonSecureIntrospector() { boolean secure = isSecure(NO_IS_SECURE_CONFIG, NON_SECURE_INTROSPECTOR, SERVER); - Assert.assertThat("isSecure was wrong", secure, is(false)); + assertThat(secure).as("isSecure was wrong").isFalse(); } @Test public void isSecureRibbonPropSecureIntrospector() { boolean secure = isSecure(SECURE_CONFIG, SECURE_INTROSPECTOR, SERVER); - Assert.assertThat("isSecure was wrong", secure, is(true)); + assertThat(secure).as("isSecure was wrong").isTrue(); } @Test public void nonSecureRibbonPropNonSecureIntrospector() { boolean secure = isSecure(NON_SECURE_CONFIG, NON_SECURE_INTROSPECTOR, SERVER); - Assert.assertThat("isSecure was wrong", secure, is(false)); + assertThat(secure).as("isSecure was wrong").isFalse(); } @Test public void isSecureRibbonPropNonSecureIntrospector() { boolean secure = isSecure(SECURE_CONFIG, NON_SECURE_INTROSPECTOR, SERVER); - Assert.assertThat("isSecure was wrong", secure, is(true)); + assertThat(secure).as("isSecure was wrong").isTrue(); } @Test public void nonSecureRibbonPropSecureIntrospector() { boolean secure = isSecure(NON_SECURE_CONFIG, SECURE_INTROSPECTOR, SERVER); - Assert.assertThat("isSecure was wrong", secure, is(false)); + assertThat(secure).as("isSecure was wrong").isFalse(); } @Test public void uriIsNotChangedWhenServerIsNotSecured() throws URISyntaxException { URI original = new URI("http://foo"); - URI updated = updateToSecureConnectionIfNeeded(original, NON_SECURE_CONFIG, NON_SECURE_INTROSPECTOR, SERVER); - Assert.assertThat("URI should not have been updated since server is not secured.", original, is(updated)); + URI updated = updateToSecureConnectionIfNeeded(original, NON_SECURE_CONFIG, + NON_SECURE_INTROSPECTOR, SERVER); + assertThat(original) + .as("URI should not have been updated since server is not secured.") + .isEqualTo(updated); } @Test - public void uriIsNotChangedWhenServerIsSecuredAndUriAlreadyInHttps() throws URISyntaxException { + public void uriIsNotChangedWhenServerIsSecuredAndUriAlreadyInHttps() + throws URISyntaxException { URI original = new URI("https://foo"); - URI updated = updateToSecureConnectionIfNeeded(original, SECURE_CONFIG, SECURE_INTROSPECTOR, SERVER); - Assert.assertThat("URI should not have been updated since uri is already in https.", original, is(updated)); + URI updated = updateToSecureConnectionIfNeeded(original, SECURE_CONFIG, + SECURE_INTROSPECTOR, SERVER); + assertThat(original) + .as("URI should not have been updated since uri is already in https.") + .isEqualTo(updated); } @Test - public void shouldUpgradeUriToHttpsWhenServerIsSecureAndUriNotInHttps() throws URISyntaxException { + public void shouldUpgradeUriToHttpsWhenServerIsSecureAndUriNotInHttps() + throws URISyntaxException { URI original = new URI("http://foo"); - URI updated = updateToSecureConnectionIfNeeded(original, SECURE_CONFIG, SECURE_INTROSPECTOR, SERVER); - Assert.assertThat("URI should have been updated to https.", updated, is(new URI("https://foo"))); + URI updated = updateToSecureConnectionIfNeeded(original, SECURE_CONFIG, + SECURE_INTROSPECTOR, SERVER); + assertThat(updated).as("URI should have been updated to https.") + .isEqualTo(new URI("https://foo")); } @Test - public void shouldUpgradeUriToWssWhenServerIsSecureAndUriNotInWss() throws URISyntaxException { + public void shouldUpgradeUriToWssWhenServerIsSecureAndUriNotInWss() + throws URISyntaxException { URI original = new URI("ws://foo"); - URI updated = updateToSecureConnectionIfNeeded(original, SECURE_CONFIG, SECURE_INTROSPECTOR, SERVER); - Assert.assertThat("URI should have been updated to wss.", updated, is(new URI("wss://foo"))); + URI updated = updateToSecureConnectionIfNeeded(original, SECURE_CONFIG, + SECURE_INTROSPECTOR, SERVER); + assertThat(updated).as("URI should have been updated to wss.") + .isEqualTo(new URI("wss://foo")); } @Test public void shouldSubstitutePlusInQueryParam() throws URISyntaxException { URI original = new URI("http://foo/%20bar?hello=1+2"); - URI updated = updateToSecureConnectionIfNeeded(original, SECURE_CONFIG, SECURE_INTROSPECTOR, SERVER); - Assert.assertThat("URI should have had its plus sign replaced in query string.", updated, is(new URI( - "https://foo/%20bar?hello=1%202"))); + URI updated = updateToSecureConnectionIfNeeded(original, SECURE_CONFIG, + SECURE_INTROSPECTOR, SERVER); + assertThat(updated) + .as("URI should have had its plus sign replaced in query string.") + .isEqualTo(new URI("https://foo/%20bar?hello=1%202")); } @Test public void emptyStringUri() throws URISyntaxException { URI original = new URI(""); - URI updated = updateToSecureConnectionIfNeeded(original, SECURE_CONFIG, SECURE_INTROSPECTOR, SERVER); - Assert.assertThat("URI should be the emptry string", updated, is(new URI( - ""))); + URI updated = updateToSecureConnectionIfNeeded(original, SECURE_CONFIG, + SECURE_INTROSPECTOR, SERVER); + assertThat(updated).as("URI should be the emptry string").isEqualTo(new URI("")); } static DefaultClientConfigImpl getConfig(boolean value) { @@ -134,7 +155,7 @@ public class RibbonUtilsTests { final boolean secure; - public StaticServerIntrospector(boolean secure) { + StaticServerIntrospector(boolean secure) { this.secure = secure; } @@ -147,5 +168,7 @@ public class RibbonUtilsTests { public Map getMetadata(Server server) { return null; } + } + } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/SpringClientFactoryTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/SpringClientFactoryTests.java index 4684a217f..1bb22dfb6 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/SpringClientFactoryTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/SpringClientFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,27 +12,26 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.ribbon; -import org.apache.http.client.params.ClientPNames; -import org.apache.http.client.params.CookiePolicy; -import org.junit.Test; -import org.springframework.boot.test.util.TestPropertyValues; -import org.springframework.cloud.commons.httpclient.HttpClientConfiguration; -import org.springframework.cloud.netflix.archaius.ArchaiusAutoConfiguration; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; import com.netflix.client.DefaultLoadBalancerRetryHandler; import com.netflix.client.IClientConfigAware; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.client.config.IClientConfig; import com.netflix.niws.client.http.RestClient; import com.sun.jersey.client.apache4.ApacheHttpClient4; +import org.apache.http.client.params.ClientPNames; +import org.apache.http.client.params.CookiePolicy; +import org.junit.Test; + +import org.springframework.boot.test.util.TestPropertyValues; +import org.springframework.cloud.commons.httpclient.HttpClientConfiguration; +import org.springframework.cloud.netflix.archaius.ArchaiusAutoConfiguration; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; /** * @author Dave Syer @@ -40,42 +39,17 @@ import static org.junit.Assert.assertEquals; */ public class SpringClientFactoryTests { - public static class ClientConfigInjectedByConstructor { - - private IClientConfig clientConfig; - - public ClientConfigInjectedByConstructor(IClientConfig clientConfig) { - this.clientConfig = clientConfig; - } - } - - public static class ClientConfigInjectedByInitMethod implements IClientConfigAware { - - private IClientConfig clientConfig; - - @Override - public void initWithNiwsConfig(IClientConfig clientConfig) { - this.clientConfig = clientConfig; - } - } - - public static class NoClientConfigAware { - - public NoClientConfigAware() { - // no client config - } - } - @Test public void testConfigureRetry() { SpringClientFactory factory = new SpringClientFactory(); AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext( - RibbonAutoConfiguration.class, ArchaiusAutoConfiguration.class, HttpClientConfiguration.class); + RibbonAutoConfiguration.class, ArchaiusAutoConfiguration.class, + HttpClientConfiguration.class); TestPropertyValues.of("foo.ribbon.MaxAutoRetries:2").applyTo(parent); factory.setApplicationContext(parent); DefaultLoadBalancerRetryHandler retryHandler = (DefaultLoadBalancerRetryHandler) factory .getLoadBalancerContext("foo").getRetryHandler(); - assertEquals(2, retryHandler.getMaxRetriesOnSameServer()); + assertThat(retryHandler.getMaxRetriesOnSameServer()).isEqualTo(2); parent.close(); factory.destroy(); } @@ -91,30 +65,66 @@ public class SpringClientFactoryTests { factory.setApplicationContext(parent); RestClient client = factory.getClient("foo", RestClient.class); ApacheHttpClient4 jerseyClient = (ApacheHttpClient4) client.getJerseyClient(); - assertEquals(CookiePolicy.IGNORE_COOKIES, jerseyClient.getClientHandler() - .getHttpClient().getParams().getParameter(ClientPNames.COOKIE_POLICY)); + assertThat(jerseyClient.getClientHandler().getHttpClient().getParams() + .getParameter(ClientPNames.COOKIE_POLICY)) + .isEqualTo(CookiePolicy.IGNORE_COOKIES); parent.close(); factory.destroy(); } - + @Test public void testInstantiateWithConfigInjectByConstructor() { IClientConfig clientConfig = new DefaultClientConfigImpl(); - ClientConfigInjectedByConstructor instance = SpringClientFactory.instantiateWithConfig(ClientConfigInjectedByConstructor.class, clientConfig); + ClientConfigInjectedByConstructor instance = SpringClientFactory + .instantiateWithConfig(ClientConfigInjectedByConstructor.class, + clientConfig); assertThat(instance.clientConfig).isSameAs(clientConfig); } - + @Test public void testInstantiateWithConfigInjectedByInitMethod() { IClientConfig clientConfig = new DefaultClientConfigImpl(); - ClientConfigInjectedByInitMethod instance = SpringClientFactory.instantiateWithConfig(ClientConfigInjectedByInitMethod.class, clientConfig); + ClientConfigInjectedByInitMethod instance = SpringClientFactory + .instantiateWithConfig(ClientConfigInjectedByInitMethod.class, + clientConfig); assertThat(instance.clientConfig).isSameAs(clientConfig); } - + @Test public void testInstantiateWithoutConfig() { IClientConfig clientConfig = new DefaultClientConfigImpl(); - NoClientConfigAware instance = SpringClientFactory.instantiateWithConfig(NoClientConfigAware.class, clientConfig); + NoClientConfigAware instance = SpringClientFactory + .instantiateWithConfig(NoClientConfigAware.class, clientConfig); assertThat(instance).isNotNull(); } + + public static class ClientConfigInjectedByConstructor { + + private IClientConfig clientConfig; + + public ClientConfigInjectedByConstructor(IClientConfig clientConfig) { + this.clientConfig = clientConfig; + } + + } + + public static class ClientConfigInjectedByInitMethod implements IClientConfigAware { + + private IClientConfig clientConfig; + + @Override + public void initWithNiwsConfig(IClientConfig clientConfig) { + this.clientConfig = clientConfig; + } + + } + + public static class NoClientConfigAware { + + public NoClientConfigAware() { + // no client config + } + + } + } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/SpringRetryDisabledTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/SpringRetryDisabledTests.java index c9f112c80..69c2a3756 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/SpringRetryDisabledTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/SpringRetryDisabledTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.ribbon; @@ -21,6 +20,7 @@ import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory; @@ -29,30 +29,32 @@ import org.springframework.cloud.netflix.ribbon.apache.RibbonLoadBalancingHttpCl import org.springframework.cloud.test.ClassPathExclusions; import org.springframework.cloud.test.ModifiedClassPathRunner; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.instanceOf; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Ryan Baxter * @author Biju Kunjummen */ @RunWith(ModifiedClassPathRunner.class) -@ClassPathExclusions({"spring-retry-*.jar", "spring-boot-starter-aop-*.jar"}) +@ClassPathExclusions({ "spring-retry-*.jar", "spring-boot-starter-aop-*.jar" }) public class SpringRetryDisabledTests { @Test public void testLoadBalancedRetryFactoryBean() { new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RibbonAutoConfiguration.class, - LoadBalancerAutoConfiguration.class, - RibbonClientConfiguration.class)) - .run(context -> { - Map factories = context.getBeansOfType(LoadBalancedRetryFactory.class); - assertThat(factories.values(), hasSize(0)); - Map clients = context.getBeansOfType(RibbonLoadBalancingHttpClient.class); - assertThat(clients.values(), hasSize(1)); - assertThat(clients.values().toArray()[0], instanceOf(RibbonLoadBalancingHttpClient.class)); - }); + .withConfiguration(AutoConfigurations.of(RibbonAutoConfiguration.class, + LoadBalancerAutoConfiguration.class, + RibbonClientConfiguration.class)) + .run(context -> { + Map factories = context + .getBeansOfType(LoadBalancedRetryFactory.class); + assertThat(factories.values()).hasSize(0); + Map clients = context + .getBeansOfType(RibbonLoadBalancingHttpClient.class); + assertThat(clients.values()).hasSize(1); + assertThat(clients.values().toArray()[0]) + .isInstanceOf(RibbonLoadBalancingHttpClient.class); + }); } + } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/SpringRetryEnabledTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/SpringRetryEnabledTests.java index 2854ad3f4..b5dbf5242 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/SpringRetryEnabledTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/SpringRetryEnabledTests.java @@ -1,6 +1,5 @@ /* - * - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,17 +12,17 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.ribbon; import java.util.Map; + import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.BeansException; import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory; -import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicy; import org.springframework.cloud.client.loadbalancer.LoadBalancerAutoConfiguration; import org.springframework.cloud.commons.httpclient.HttpClientConfiguration; import org.springframework.cloud.netflix.ribbon.apache.RetryableRibbonLoadBalancingHttpClient; @@ -33,32 +32,36 @@ import org.springframework.context.ApplicationContextAware; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.collection.IsCollectionWithSize.hasSize; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Ryan Baxter */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {RibbonAutoConfiguration.class, RibbonClientConfiguration.class, LoadBalancerAutoConfiguration.class, - HttpClientConfiguration.class}) +@ContextConfiguration(classes = { RibbonAutoConfiguration.class, + RibbonClientConfiguration.class, LoadBalancerAutoConfiguration.class, + HttpClientConfiguration.class }) public class SpringRetryEnabledTests implements ApplicationContextAware { private ApplicationContext context; @Test public void testLoadBalancedRetryFactoryBean() throws Exception { - Map factories = context.getBeansOfType(LoadBalancedRetryFactory.class); - assertThat(factories.values(), hasSize(1)); - assertThat(factories.values().toArray()[0], instanceOf(RibbonLoadBalancedRetryFactory.class)); - Map clients = context.getBeansOfType(RibbonLoadBalancingHttpClient.class); - assertThat(clients.values(), hasSize(1)); - assertThat(clients.values().toArray()[0], instanceOf(RetryableRibbonLoadBalancingHttpClient.class)); + Map factories = context + .getBeansOfType(LoadBalancedRetryFactory.class); + assertThat(factories.values()).hasSize(1); + assertThat(factories.values().toArray()[0]) + .isInstanceOf(RibbonLoadBalancedRetryFactory.class); + Map clients = context + .getBeansOfType(RibbonLoadBalancingHttpClient.class); + assertThat(clients.values()).hasSize(1); + assertThat(clients.values().toArray()[0]) + .isInstanceOf(RetryableRibbonLoadBalancingHttpClient.class); } @Override public void setApplicationContext(ApplicationContext context) throws BeansException { this.context = context; } + } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/ZonePreferenceServerListFilterTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/ZonePreferenceServerListFilterTests.java index 6dfefc593..a20827be8 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/ZonePreferenceServerListFilterTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/ZonePreferenceServerListFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,12 +18,14 @@ package org.springframework.cloud.netflix.ribbon; import java.util.Arrays; import java.util.List; + +import com.netflix.loadbalancer.Server; import org.junit.Before; import org.junit.Test; -import org.springframework.test.util.ReflectionTestUtils; -import com.netflix.loadbalancer.Server; -import static org.junit.Assert.assertEquals; +import org.springframework.test.util.ReflectionTestUtils; + +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -31,6 +33,7 @@ import static org.junit.Assert.assertEquals; public class ZonePreferenceServerListFilterTests { private Server dsyer = new Server("dsyer", 8080); + private Server localhost = new Server("localhost", 8080); @Before @@ -42,27 +45,27 @@ public class ZonePreferenceServerListFilterTests { @Test public void noZoneSet() { ZonePreferenceServerListFilter filter = new ZonePreferenceServerListFilter(); - List result = filter.getFilteredListOfServers(Arrays - .asList(this.localhost)); - assertEquals(1, result.size()); + List result = filter + .getFilteredListOfServers(Arrays.asList(this.localhost)); + assertThat(result.size()).isEqualTo(1); } @Test public void withZoneSetAndNoMatches() { ZonePreferenceServerListFilter filter = new ZonePreferenceServerListFilter(); ReflectionTestUtils.setField(filter, "zone", "dsyer"); - List result = filter.getFilteredListOfServers(Arrays - .asList(this.localhost)); - assertEquals(1, result.size()); + List result = filter + .getFilteredListOfServers(Arrays.asList(this.localhost)); + assertThat(result.size()).isEqualTo(1); } @Test public void withZoneSetAndMatches() { ZonePreferenceServerListFilter filter = new ZonePreferenceServerListFilter(); ReflectionTestUtils.setField(filter, "zone", "dsyer"); - List result = filter.getFilteredListOfServers(Arrays.asList(this.dsyer, - this.localhost)); - assertEquals(1, result.size()); + List result = filter + .getFilteredListOfServers(Arrays.asList(this.dsyer, this.localhost)); + assertThat(result.size()).isEqualTo(1); } } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpRequestTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpRequestTests.java index c16621266..f8dcd0b30 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpRequestTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpRequestTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.ribbon.apache; @@ -23,24 +22,20 @@ import java.net.URI; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collections; + import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.RequestBuilder; import org.junit.Test; + import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; import org.springframework.cloud.netflix.ribbon.support.RibbonRequestCustomizer; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.StreamUtils; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Spencer Gibb @@ -55,35 +50,44 @@ public class RibbonApacheHttpRequestTests { headers.add("content-length", "5192"); LinkedMultiValueMap params = new LinkedMultiValueMap<>(); params.add("myparam", "myparamval"); - RibbonApacheHttpRequest httpRequest = - new RibbonApacheHttpRequest( - new RibbonCommandContext("example", "GET", uri, false, headers, params, null, new ArrayList())); + RibbonApacheHttpRequest httpRequest = new RibbonApacheHttpRequest( + new RibbonCommandContext("example", "GET", uri, false, headers, params, + null, new ArrayList())); HttpUriRequest request = httpRequest.toRequest(RequestConfig.custom().build()); - assertThat("request is wrong type", request, is(not(instanceOf(HttpEntityEnclosingRequest.class)))); - assertThat("uri is wrong", request.getURI().toString(), startsWith(uri)); - assertThat("my-header is missing", request.getFirstHeader("my-header"), is(notNullValue())); - assertThat("my-header is wrong", request.getFirstHeader("my-header").getValue(), is(equalTo("my-value"))); - assertThat("Content-Length is wrong", request.getFirstHeader("content-length").getValue(), is(equalTo("5192"))); - assertThat("myparam is missing", request.getURI().getQuery(), is(equalTo("myparam=myparamval"))); - + assertThat(request).as("request is wrong type") + .isNotInstanceOf(HttpEntityEnclosingRequest.class); + assertThat(request.getURI().toString()).as("uri is wrong").startsWith(uri); + assertThat(request.getFirstHeader("my-header")).as("my-header is missing") + .isNotNull(); + assertThat(request.getFirstHeader("my-header").getValue()) + .as("my-header is wrong").isEqualTo("my-value"); + assertThat(request.getFirstHeader("content-length").getValue()) + .as("Content-Length is wrong").isEqualTo("5192"); + assertThat(request.getURI().getQuery()).as("myparam is missing") + .isEqualTo("myparam=myparamval"); + } @Test - // this situation happens, see https://github.com/spring-cloud/spring-cloud-netflix/issues/1042#issuecomment-227723877 + // this situation happens, see + // https://github.com/spring-cloud/spring-cloud-netflix/issues/1042#issuecomment-227723877 public void testEmptyEntityGet() throws Exception { String entityValue = ""; - testEntity(entityValue, new ByteArrayInputStream(entityValue.getBytes()), false, "GET"); + testEntity(entityValue, new ByteArrayInputStream(entityValue.getBytes()), false, + "GET"); } @Test public void testNonEmptyEntityPost() throws Exception { String entityValue = "abcd"; - testEntity(entityValue, new ByteArrayInputStream(entityValue.getBytes()), true, "POST"); + testEntity(entityValue, new ByteArrayInputStream(entityValue.getBytes()), true, + "POST"); } - void testEntity(String entityValue, ByteArrayInputStream requestEntity, boolean addContentLengthHeader, String method) throws IOException { + void testEntity(String entityValue, ByteArrayInputStream requestEntity, + boolean addContentLengthHeader, String method) throws IOException { String lengthString = String.valueOf(entityValue.length()); Long length = null; URI uri = URI.create("http://example.com"); @@ -112,24 +116,30 @@ public class RibbonApacheHttpRequestTests { HttpUriRequest request = httpRequest.toRequest(RequestConfig.custom().build()); - assertThat("request is wrong type", request, is(instanceOf(HttpEntityEnclosingRequest.class))); - assertThat("uri is wrong", request.getURI().toString(), startsWith(uri.toString())); + assertThat(request).as("request is wrong type") + .isInstanceOf(HttpEntityEnclosingRequest.class); + assertThat(request.getURI().toString()).as("uri is wrong") + .startsWith(uri.toString()); if (addContentLengthHeader) { - assertThat("Content-Length is missing", request.getFirstHeader("Content-Length"), is(notNullValue())); - assertThat("Content-Length is wrong", request.getFirstHeader("Content-Length").getValue(), - is(equalTo(lengthString))); + assertThat(request.getFirstHeader("Content-Length")) + .as("Content-Length is missing").isNotNull(); + assertThat(request.getFirstHeader("Content-Length").getValue()) + .as("Content-Length is wrong").isEqualTo(lengthString); } - assertThat("from-customizer is missing", request.getFirstHeader("from-customizer"), is(notNullValue())); - assertThat("from-customizer is wrong", request.getFirstHeader("from-customizer").getValue(), - is(equalTo("foo"))); + assertThat(request.getFirstHeader("from-customizer")) + .as("from-customizer is missing").isNotNull(); + assertThat(request.getFirstHeader("from-customizer").getValue()) + .as("from-customizer is wrong").isEqualTo("foo"); HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; - assertThat("entity is missing", entityRequest.getEntity(), is(notNullValue())); + assertThat(entityRequest.getEntity()).as("entity is missing").isNotNull(); HttpEntity entity = entityRequest.getEntity(); - assertThat("contentLength is wrong", entity.getContentLength(), is(equalTo((long)entityValue.length()))); - assertThat("content is missing", entity.getContent(), is(notNullValue())); - String string = StreamUtils.copyToString(entity.getContent(), Charset.forName("UTF-8")); - assertThat("content is wrong", string, is(equalTo(entityValue))); + assertThat(entity.getContentLength()).as("contentLength is wrong") + .isEqualTo((long) entityValue.length()); + assertThat(entity.getContent()).as("content is missing").isNotNull(); + String string = StreamUtils.copyToString(entity.getContent(), + Charset.forName("UTF-8")); + assertThat(string).as("content is wrong").isEqualTo(entityValue); } -} +} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpResponseTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpResponseTests.java index 0611dd0b8..899653418 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpResponseTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpResponseTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,15 +18,13 @@ package org.springframework.cloud.netflix.ribbon.apache; import java.io.ByteArrayInputStream; import java.net.URI; + import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.entity.BasicHttpEntity; import org.junit.Test; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.mock; @@ -42,15 +40,15 @@ public class RibbonApacheHttpResponseTests { HttpResponse response = mock(HttpResponse.class); given(response.getStatusLine()).willReturn(statusLine); - RibbonApacheHttpResponse httpResponse = new RibbonApacheHttpResponse(response, URI.create("http://example.com")); + RibbonApacheHttpResponse httpResponse = new RibbonApacheHttpResponse(response, + URI.create("http://example.com")); - assertThat(httpResponse.isSuccess(), is(true)); - assertThat(httpResponse.hasPayload(), is(false)); - assertThat(httpResponse.getPayload(), is(nullValue())); - assertThat(httpResponse.getInputStream(), is(nullValue())); + assertThat(httpResponse.isSuccess()).isTrue(); + assertThat(httpResponse.hasPayload()).isFalse(); + assertThat(httpResponse.getPayload()).isNull(); + assertThat(httpResponse.getInputStream()).isNull(); } - @Test public void testNotNullEntity() throws Exception { StatusLine statusLine = mock(StatusLine.class); @@ -61,11 +59,13 @@ public class RibbonApacheHttpResponseTests { entity.setContent(new ByteArrayInputStream(new byte[0])); given(response.getEntity()).willReturn(entity); - RibbonApacheHttpResponse httpResponse = new RibbonApacheHttpResponse(response, URI.create("http://example.com")); + RibbonApacheHttpResponse httpResponse = new RibbonApacheHttpResponse(response, + URI.create("http://example.com")); - assertThat(httpResponse.isSuccess(), is(true)); - assertThat(httpResponse.hasPayload(), is(true)); - assertThat(httpResponse.getPayload(), is(notNullValue())); - assertThat(httpResponse.getInputStream(), is(notNullValue())); + assertThat(httpResponse.isSuccess()).isTrue(); + assertThat(httpResponse.hasPayload()).isTrue(); + assertThat(httpResponse.getPayload()).isNotNull(); + assertThat(httpResponse.getInputStream()).isNotNull(); } + } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/apache/RibbonLoadBalancingHttpClientTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/apache/RibbonLoadBalancingHttpClientTests.java index 350e948c0..0592a98fc 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/apache/RibbonLoadBalancingHttpClientTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/apache/RibbonLoadBalancingHttpClientTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.ribbon.apache; @@ -25,6 +24,18 @@ import java.util.ArrayList; import java.util.Locale; import java.util.concurrent.TimeUnit; +import com.netflix.client.ClientException; +import com.netflix.client.DefaultLoadBalancerRetryHandler; +import com.netflix.client.RetryHandler; +import com.netflix.client.config.CommonClientConfigKey; +import com.netflix.client.config.DefaultClientConfigImpl; +import com.netflix.client.config.IClientConfig; +import com.netflix.loadbalancer.AbstractLoadBalancer; +import com.netflix.loadbalancer.ILoadBalancer; +import com.netflix.loadbalancer.LoadBalancerStats; +import com.netflix.loadbalancer.Server; +import com.netflix.loadbalancer.ServerStats; +import com.netflix.servo.monitor.Monitors; import org.apache.http.HttpEntity; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; @@ -41,11 +52,12 @@ import org.mockito.ArgumentCaptor; import org.mockito.ArgumentMatcher; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; + import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory; import org.springframework.cloud.commons.httpclient.HttpClientConfiguration; import org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration; -import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancedRetryPolicy; import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancedRetryFactory; +import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancedRetryPolicy; import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerContext; import org.springframework.cloud.netflix.ribbon.ServerIntrospector; import org.springframework.cloud.netflix.ribbon.SpringClientFactory; @@ -65,26 +77,8 @@ import org.springframework.retry.backoff.BackOffPolicy; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.util.LinkedMultiValueMap; -import com.netflix.client.ClientException; -import com.netflix.client.DefaultLoadBalancerRetryHandler; -import com.netflix.client.RetryHandler; -import com.netflix.client.config.CommonClientConfigKey; -import com.netflix.client.config.DefaultClientConfigImpl; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.AbstractLoadBalancer; -import com.netflix.loadbalancer.ILoadBalancer; -import com.netflix.loadbalancer.LoadBalancerStats; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerStats; -import com.netflix.servo.monitor.Monitors; - -import static org.hamcrest.Matchers.is; -import static org.hamcrest.CoreMatchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.any; import static org.mockito.Matchers.argThat; @@ -109,8 +103,10 @@ public class RibbonLoadBalancingHttpClientTests { @Before public void setup() { loadBalancer = mock(AbstractLoadBalancer.class); - doReturn(new Server("foo.com", 8000)).when(loadBalancer).chooseServer(eq("default")); - doReturn(new Server("foo.com", 8000)).when(loadBalancer).chooseServer(eq("service")); + doReturn(new Server("foo.com", 8000)).when(loadBalancer) + .chooseServer(eq("default")); + doReturn(new Server("foo.com", 8000)).when(loadBalancer) + .chooseServer(eq("service")); } @After @@ -122,50 +118,51 @@ public class RibbonLoadBalancingHttpClientTests { public void testRequestConfigUseDefaultsNoOverride() throws Exception { RequestConfig result = getBuiltRequestConfig(UseDefaults.class, null); - assertThat(result.isRedirectsEnabled(), is(false)); - + assertThat(result.isRedirectsEnabled()).isFalse(); + } @Test public void testRequestConfigDoNotFollowRedirectsNoOverride() throws Exception { RequestConfig result = getBuiltRequestConfig(DoNotFollowRedirects.class, null); - assertThat(result.isRedirectsEnabled(), is(false)); + assertThat(result.isRedirectsEnabled()).isFalse(); } @Test public void testRequestConfigFollowRedirectsNoOverride() throws Exception { RequestConfig result = getBuiltRequestConfig(FollowRedirects.class, null); - assertThat(result.isRedirectsEnabled(), is(true)); + assertThat(result.isRedirectsEnabled()).isTrue(); } @Test public void testTimeouts() throws Exception { RequestConfig result = getBuiltRequestConfig(Timeouts.class, null); - assertThat(result.getConnectTimeout(), is(60000)); - assertThat(result.getSocketTimeout(), is (50000)); + assertThat(result.getConnectTimeout()).isEqualTo(60000); + assertThat(result.getSocketTimeout()).isEqualTo(50000); } @Test public void testDefaultTimeouts() throws Exception { RequestConfig result = getBuiltRequestConfig(UseDefaults.class, null); - assertThat(result.getConnectTimeout(), is(1000)); - assertThat(result.getSocketTimeout(), is (1000)); + assertThat(result.getConnectTimeout()).isEqualTo(1000); + assertThat(result.getSocketTimeout()).isEqualTo(1000); } - + @Test public void testCompressionDefault() throws Exception { RequestConfig result = getBuiltRequestConfig(UseDefaults.class, null); - assertTrue(result.isContentCompressionEnabled()); + assertThat(result.isContentCompressionEnabled()).isTrue(); } - + @Test public void testCompressionDisabled() throws Exception { - IClientConfig configOverride = DefaultClientConfigImpl.getClientConfigWithDefaultValues(); + IClientConfig configOverride = DefaultClientConfigImpl + .getClientConfigWithDefaultValues(); configOverride.set(CommonClientConfigKey.GZipPayload, false); RequestConfig result = getBuiltRequestConfig(UseDefaults.class, configOverride); - assertFalse(result.isContentCompressionEnabled()); + assertThat(result.isContentCompressionEnabled()).isFalse(); } @Test @@ -177,9 +174,10 @@ public class RibbonLoadBalancingHttpClientTests { RetryableRibbonLoadBalancingHttpClient.class); HttpClient delegate = client.getDelegate(); - PoolingHttpClientConnectionManager connManager = (PoolingHttpClientConnectionManager) ReflectionTestUtils.getField(delegate, "connManager"); - assertThat(connManager.getMaxTotal(), is(101)); - assertThat(connManager.getDefaultMaxPerRoute(), is(201)); + PoolingHttpClientConnectionManager connManager = (PoolingHttpClientConnectionManager) ReflectionTestUtils + .getField(delegate, "connManager"); + assertThat(connManager.getMaxTotal()).isEqualTo(101); + assertThat(connManager.getDefaultMaxPerRoute()).isEqualTo(201); } @Test @@ -190,9 +188,10 @@ public class RibbonLoadBalancingHttpClientTests { override.set(CommonClientConfigKey.FollowRedirects, true); override.set(CommonClientConfigKey.IsSecure, false); - RequestConfig result = getBuiltRequestConfig(DoNotFollowRedirects.class, override); + RequestConfig result = getBuiltRequestConfig(DoNotFollowRedirects.class, + override); - assertThat(result.isRedirectsEnabled(), is(true)); + assertThat(result.isRedirectsEnabled()).isTrue(); } @Test @@ -205,39 +204,43 @@ public class RibbonLoadBalancingHttpClientTests { RequestConfig result = getBuiltRequestConfig(FollowRedirects.class, override); - assertThat(result.isRedirectsEnabled(), is(false)); + assertThat(result.isRedirectsEnabled()).isFalse(); } @Test - public void testUpdatedTimeouts() - throws Exception { + public void testUpdatedTimeouts() throws Exception { SpringClientFactory factory = new SpringClientFactory(); RequestConfig result = getBuiltRequestConfig(Timeouts.class, null, factory); - assertThat(result.getConnectTimeout(), is(60000)); - assertThat(result.getSocketTimeout(), is (50000)); + assertThat(result.getConnectTimeout()).isEqualTo(60000); + assertThat(result.getSocketTimeout()).isEqualTo(50000); IClientConfig config = factory.getClientConfig("service"); config.set(CommonClientConfigKey.ConnectTimeout, 60); config.set(CommonClientConfigKey.ReadTimeout, 50); result = getBuiltRequestConfig(Timeouts.class, null, factory); - assertThat(result.getConnectTimeout(), is(60)); - assertThat(result.getSocketTimeout(), is (50)); + assertThat(result.getConnectTimeout()).isEqualTo(60); + assertThat(result.getSocketTimeout()).isEqualTo(50); } @Test public void testNeverRetry() throws Exception { ServerIntrospector introspector = mock(ServerIntrospector.class); CloseableHttpClient delegate = mock(CloseableHttpClient.class); - doThrow(new IOException("boom")).when(delegate).execute(any(HttpUriRequest.class)); + doThrow(new IOException("boom")).when(delegate) + .execute(any(HttpUriRequest.class)); DefaultClientConfigImpl clientConfig = new DefaultClientConfigImpl(); clientConfig.setClientName("foo"); - RibbonLoadBalancingHttpClient client = new RibbonLoadBalancingHttpClient(delegate, clientConfig, - introspector); + RibbonLoadBalancingHttpClient client = new RibbonLoadBalancingHttpClient(delegate, + clientConfig, introspector); RibbonApacheHttpRequest request = mock(RibbonApacheHttpRequest.class); - when(request.toRequest(any(RequestConfig.class))).thenReturn(mock(HttpUriRequest.class)); + when(request.toRequest(any(RequestConfig.class))) + .thenReturn(mock(HttpUriRequest.class)); try { client.execute(request, null); fail("Expected IOException"); - } catch(IOException e) {} finally { + } + catch (IOException e) { + } + finally { verify(delegate, times(1)).execute(any(HttpUriRequest.class)); } } @@ -262,7 +265,8 @@ public class RibbonLoadBalancingHttpClientTests { @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { HttpEntity entity = mock(HttpEntity.class); - doReturn(new ByteArrayInputStream("test".getBytes())).when(entity).getContent(); + doReturn(new ByteArrayInputStream("test".getBytes())).when(entity) + .getContent(); return entity; } }).when(fourOFourResponse).getEntity(); @@ -271,9 +275,11 @@ public class RibbonLoadBalancingHttpClientTests { doReturn(locale).when(fourOFourResponse).getLocale(); doReturn(fourOFourResponse).when(delegate).execute(any(HttpUriRequest.class)); ILoadBalancer lb = mock(ILoadBalancer.class); - RibbonLoadBalancerContext ribbonLoadBalancerContext = new RibbonLoadBalancerContext(lb); + RibbonLoadBalancerContext ribbonLoadBalancerContext = new RibbonLoadBalancerContext( + lb); MyBackOffPolicy myBackOffPolicy = new MyBackOffPolicy(); - RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry(retriesNextServer, retriesSameServer, retryable, retryOnAllOps, + RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry( + retriesNextServer, retriesSameServer, retryable, retryOnAllOps, serviceName, host, port, delegate, lb, "404", myBackOffPolicy); client.setRibbonLoadBalancerContext(ribbonLoadBalancerContext); RibbonApacheHttpRequest request = mock(RibbonApacheHttpRequest.class); @@ -288,72 +294,82 @@ public class RibbonLoadBalancingHttpClientTests { byte[] buf = new byte[100]; InputStream inputStream = returnedResponse.getInputStream(); int read = inputStream.read(buf); - assertThat(new String(buf, 0, read), is("test")); + assertThat(new String(buf, 0, read)).isEqualTo("test"); } - private RetryableRibbonLoadBalancingHttpClient setupClientForRetry(int retriesNextServer, int retriesSameServer, - boolean retryable, boolean retryOnAllOps, - String serviceName, String host, int port, - CloseableHttpClient delegate, ILoadBalancer lb, String statusCodes, - BackOffPolicy backOffPolicy) throws Exception { - return setupClientForRetry(retriesNextServer, retriesSameServer, retryable, retryOnAllOps, serviceName, host, port, - delegate, lb, statusCodes, backOffPolicy, false); + private RetryableRibbonLoadBalancingHttpClient setupClientForRetry( + int retriesNextServer, int retriesSameServer, boolean retryable, + boolean retryOnAllOps, String serviceName, String host, int port, + CloseableHttpClient delegate, ILoadBalancer lb, String statusCodes, + BackOffPolicy backOffPolicy) throws Exception { + return setupClientForRetry(retriesNextServer, retriesSameServer, retryable, + retryOnAllOps, serviceName, host, port, delegate, lb, statusCodes, + backOffPolicy, false); } - private RetryableRibbonLoadBalancingHttpClient setupClientForRetry(int retriesNextServer, int retriesSameServer, - boolean retryable, boolean retryOnAllOps, - String serviceName, String host, int port, - CloseableHttpClient delegate, ILoadBalancer lb, String statusCodes, - BackOffPolicy backOffPolicy, - boolean isSecure) throws Exception { + private RetryableRibbonLoadBalancingHttpClient setupClientForRetry( + int retriesNextServer, int retriesSameServer, boolean retryable, + boolean retryOnAllOps, String serviceName, String host, int port, + CloseableHttpClient delegate, ILoadBalancer lb, String statusCodes, + BackOffPolicy backOffPolicy, boolean isSecure) throws Exception { ServerIntrospector introspector = mock(ServerIntrospector.class); - RetryHandler retryHandler = new DefaultLoadBalancerRetryHandler(retriesSameServer, retriesNextServer, retryable); + RetryHandler retryHandler = new DefaultLoadBalancerRetryHandler(retriesSameServer, + retriesNextServer, retryable); doReturn(new Server(host, port)).when(lb).chooseServer(eq(serviceName)); DefaultClientConfigImpl clientConfig = new DefaultClientConfigImpl(); clientConfig.set(CommonClientConfigKey.OkToRetryOnAllOperations, retryOnAllOps); - clientConfig.set(CommonClientConfigKey.MaxAutoRetriesNextServer, retriesNextServer); + clientConfig.set(CommonClientConfigKey.MaxAutoRetriesNextServer, + retriesNextServer); clientConfig.set(CommonClientConfigKey.MaxAutoRetries, retriesSameServer); - clientConfig.set(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES, statusCodes); + clientConfig.set(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES, + statusCodes); clientConfig.set(CommonClientConfigKey.IsSecure, isSecure); clientConfig.setClientName(serviceName); - RibbonLoadBalancerContext context = new RibbonLoadBalancerContext(lb, clientConfig, retryHandler); + RibbonLoadBalancerContext context = new RibbonLoadBalancerContext(lb, + clientConfig, retryHandler); SpringClientFactory clientFactory = mock(SpringClientFactory.class); doReturn(context).when(clientFactory).getLoadBalancerContext(eq(serviceName)); doReturn(clientConfig).when(clientFactory).getClientConfig(eq(serviceName)); - LoadBalancedRetryFactory factory = new RibbonLoadBalancedRetryFactory(clientFactory) { + LoadBalancedRetryFactory factory = new RibbonLoadBalancedRetryFactory( + clientFactory) { @Override public BackOffPolicy createBackOffPolicy(String service) { return backOffPolicy; } }; - RetryableRibbonLoadBalancingHttpClient client = new RetryableRibbonLoadBalancingHttpClient(delegate, clientConfig, - introspector, factory); + RetryableRibbonLoadBalancingHttpClient client = new RetryableRibbonLoadBalancingHttpClient( + delegate, clientConfig, introspector, factory); client.setLoadBalancer(lb); ReflectionTestUtils.setField(client, "delegate", delegate); return client; } - private RetryableRibbonLoadBalancingHttpClient setupClientForRetry(int retriesNextServer, int retriesSameServer, - boolean retryable, boolean retryOnAllOps, - String serviceName, String host, int port, - CloseableHttpClient delegate, ILoadBalancer lb, String statusCodes, - BackOffPolicy backOffPolicy, - boolean isSecure, RetryListener[] retryListeners) throws Exception { + private RetryableRibbonLoadBalancingHttpClient setupClientForRetry( + int retriesNextServer, int retriesSameServer, boolean retryable, + boolean retryOnAllOps, String serviceName, String host, int port, + CloseableHttpClient delegate, ILoadBalancer lb, String statusCodes, + BackOffPolicy backOffPolicy, boolean isSecure, RetryListener[] retryListeners) + throws Exception { ServerIntrospector introspector = mock(ServerIntrospector.class); - RetryHandler retryHandler = new DefaultLoadBalancerRetryHandler(retriesSameServer, retriesNextServer, retryable); + RetryHandler retryHandler = new DefaultLoadBalancerRetryHandler(retriesSameServer, + retriesNextServer, retryable); doReturn(new Server(host, port)).when(lb).chooseServer(eq(serviceName)); DefaultClientConfigImpl clientConfig = new DefaultClientConfigImpl(); clientConfig.set(CommonClientConfigKey.OkToRetryOnAllOperations, retryOnAllOps); - clientConfig.set(CommonClientConfigKey.MaxAutoRetriesNextServer, retriesNextServer); + clientConfig.set(CommonClientConfigKey.MaxAutoRetriesNextServer, + retriesNextServer); clientConfig.set(CommonClientConfigKey.MaxAutoRetries, retriesSameServer); - clientConfig.set(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES, statusCodes); + clientConfig.set(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES, + statusCodes); clientConfig.set(CommonClientConfigKey.IsSecure, isSecure); clientConfig.setClientName(serviceName); - RibbonLoadBalancerContext context = new RibbonLoadBalancerContext(lb, clientConfig, retryHandler); + RibbonLoadBalancerContext context = new RibbonLoadBalancerContext(lb, + clientConfig, retryHandler); SpringClientFactory clientFactory = mock(SpringClientFactory.class); doReturn(context).when(clientFactory).getLoadBalancerContext(eq(serviceName)); doReturn(clientConfig).when(clientFactory).getClientConfig(eq(serviceName)); - LoadBalancedRetryFactory factory = new RibbonLoadBalancedRetryFactory(clientFactory) { + LoadBalancedRetryFactory factory = new RibbonLoadBalancedRetryFactory( + clientFactory) { @Override public RetryListener[] createRetryListeners(String service) { return retryListeners; @@ -364,8 +380,8 @@ public class RibbonLoadBalancingHttpClientTests { return backOffPolicy; } }; - RetryableRibbonLoadBalancingHttpClient client = new RetryableRibbonLoadBalancingHttpClient(delegate, clientConfig, - introspector, factory); + RetryableRibbonLoadBalancingHttpClient client = new RetryableRibbonLoadBalancingHttpClient( + delegate, clientConfig, introspector, factory); client.setLoadBalancer(lb); ReflectionTestUtils.setField(client, "delegate", delegate); return client; @@ -387,16 +403,20 @@ public class RibbonLoadBalancingHttpClientTests { StatusLine statusLine = mock(StatusLine.class); doReturn(200).when(statusLine).getStatusCode(); doReturn(statusLine).when(response).getStatusLine(); - doThrow(new IOException("boom")).doReturn(response).when(delegate).execute(any(HttpUriRequest.class)); + doThrow(new IOException("boom")).doReturn(response).when(delegate) + .execute(any(HttpUriRequest.class)); AbstractLoadBalancer lb = mock(AbstractLoadBalancer.class); LoadBalancerStats lbStats = mock(LoadBalancerStats.class); doReturn(lbStats).when(lb).getLoadBalancerStats(); ServerStats serverStats = mock(ServerStats.class); doReturn(serverStats).when(lbStats).getSingleServerStat(any(Server.class)); - RibbonLoadBalancerContext ribbonLoadBalancerContext = mock(RibbonLoadBalancerContext.class); + RibbonLoadBalancerContext ribbonLoadBalancerContext = mock( + RibbonLoadBalancerContext.class); doReturn(lb).when(ribbonLoadBalancerContext).getLoadBalancer(); - doReturn(Monitors.newTimer("_LoadBalancerExecutionTimer", TimeUnit.MILLISECONDS)).when(ribbonLoadBalancerContext).getExecuteTracer(); - RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry(retriesNextServer, retriesSameServer, retryable, retryOnAllOps, + doReturn(Monitors.newTimer("_LoadBalancerExecutionTimer", TimeUnit.MILLISECONDS)) + .when(ribbonLoadBalancerContext).getExecuteTracer(); + RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry( + retriesNextServer, retriesSameServer, retryable, retryOnAllOps, serviceName, host, port, delegate, lb, "", null); client.setRibbonLoadBalancerContext(ribbonLoadBalancerContext); RibbonApacheHttpRequest request = mock(RibbonApacheHttpRequest.class); @@ -409,7 +429,8 @@ public class RibbonLoadBalancingHttpClientTests { RibbonApacheHttpResponse returnedResponse = client.execute(request, null); verify(delegate, times(2)).execute(any(HttpUriRequest.class)); verify(lb, times(1)).chooseServer(eq(serviceName)); - verify(ribbonLoadBalancerContext, times(1)).noteRequestCompletion(serverStats, response, null, 0, null); + verify(ribbonLoadBalancerContext, times(1)).noteRequestCompletion(serverStats, + response, null, 0, null); } @Test @@ -428,12 +449,14 @@ public class RibbonLoadBalancingHttpClientTests { StatusLine statusLine = mock(StatusLine.class); doReturn(200).when(statusLine).getStatusCode(); doReturn(statusLine).when(response).getStatusLine(); - doThrow(new IOException("boom")).doThrow(new IOException("boom again")).doReturn(response). - when(delegate).execute(any(HttpUriRequest.class)); + doThrow(new IOException("boom")).doThrow(new IOException("boom again")) + .doReturn(response).when(delegate).execute(any(HttpUriRequest.class)); ILoadBalancer lb = mock(ILoadBalancer.class); - RibbonLoadBalancerContext ribbonLoadBalancerContext = new RibbonLoadBalancerContext(lb); + RibbonLoadBalancerContext ribbonLoadBalancerContext = new RibbonLoadBalancerContext( + lb); MyBackOffPolicy myBackOffPolicy = new MyBackOffPolicy(); - RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry(retriesNextServer, retriesSameServer, retryable, retryOnAllOps, + RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry( + retriesNextServer, retriesSameServer, retryable, retryOnAllOps, serviceName, host, port, delegate, lb, "", myBackOffPolicy); client.setRibbonLoadBalancerContext(ribbonLoadBalancerContext); RibbonApacheHttpRequest request = mock(RibbonApacheHttpRequest.class); @@ -446,7 +469,7 @@ public class RibbonLoadBalancingHttpClientTests { client.execute(request, null); verify(delegate, times(3)).execute(any(HttpUriRequest.class)); verify(lb, times(2)).chooseServer(eq(serviceName)); - assertEquals(2, myBackOffPolicy.getCount()); + assertThat(myBackOffPolicy.getCount()).isEqualTo(2); } @Test @@ -465,12 +488,14 @@ public class RibbonLoadBalancingHttpClientTests { StatusLine statusLine = mock(StatusLine.class); doReturn(200).when(statusLine).getStatusCode(); doReturn(statusLine).when(response).getStatusLine(); - doThrow(new IOException("boom")).doThrow(new IOException("boom again")).doReturn(response). - when(delegate).execute(any(HttpUriRequest.class)); + doThrow(new IOException("boom")).doThrow(new IOException("boom again")) + .doReturn(response).when(delegate).execute(any(HttpUriRequest.class)); ILoadBalancer lb = mock(ILoadBalancer.class); - RibbonLoadBalancerContext ribbonLoadBalancerContext = new RibbonLoadBalancerContext(lb); + RibbonLoadBalancerContext ribbonLoadBalancerContext = new RibbonLoadBalancerContext( + lb); MyBackOffPolicy myBackOffPolicy = new MyBackOffPolicy(); - RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry(retriesNextServer, retriesSameServer, retryable, retryOnAllOps, + RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry( + retriesNextServer, retriesSameServer, retryable, retryOnAllOps, serviceName, host, port, delegate, lb, "", myBackOffPolicy); client.setRibbonLoadBalancerContext(ribbonLoadBalancerContext); RibbonApacheHttpRequest request = mock(RibbonApacheHttpRequest.class); @@ -483,7 +508,7 @@ public class RibbonLoadBalancingHttpClientTests { verify(response, times(0)).close(); verify(delegate, times(3)).execute(any(HttpUriRequest.class)); verify(lb, times(2)).chooseServer(eq(serviceName)); - assertEquals(2, myBackOffPolicy.getCount()); + assertThat(myBackOffPolicy.getCount()).isEqualTo(2); } @Test @@ -496,8 +521,10 @@ public class RibbonLoadBalancingHttpClientTests { DefaultClientConfigImpl clientConfig = new DefaultClientConfigImpl(); clientConfig.setClientName(serviceName); ServerIntrospector introspector = mock(ServerIntrospector.class); - RibbonCommandContext context = new RibbonCommandContext(serviceName, method.toString(), uri.toString(), false, - new LinkedMultiValueMap(), new LinkedMultiValueMap(), + RibbonCommandContext context = new RibbonCommandContext(serviceName, + method.toString(), uri.toString(), false, + new LinkedMultiValueMap(), + new LinkedMultiValueMap(), new ByteArrayInputStream("bar".getBytes()), new ArrayList()); RibbonApacheHttpRequest request = new RibbonApacheHttpRequest(context); @@ -506,16 +533,16 @@ public class RibbonLoadBalancingHttpClientTests { StatusLine statusLine = mock(StatusLine.class); doReturn(200).when(statusLine).getStatusCode(); doReturn(statusLine).when(response).getStatusLine(); - doReturn(response). - when(delegate).execute(any(HttpUriRequest.class)); - RibbonLoadBalancingHttpClient client = new RibbonLoadBalancingHttpClient(delegate, clientConfig, introspector); + doReturn(response).when(delegate).execute(any(HttpUriRequest.class)); + RibbonLoadBalancingHttpClient client = new RibbonLoadBalancingHttpClient(delegate, + clientConfig, introspector); client.execute(request, null); verify(response, times(0)).close(); verify(delegate, times(1)).execute(argThat(new ArgumentMatcher() { @Override public boolean matches(HttpUriRequest argument) { - if(argument instanceof HttpUriRequest) { - HttpUriRequest arg = (HttpUriRequest)argument; + if (argument instanceof HttpUriRequest) { + HttpUriRequest arg = (HttpUriRequest) argument; return arg.getURI().equals(uri); } return false; @@ -534,8 +561,10 @@ public class RibbonLoadBalancingHttpClientTests { int port = 80; HttpMethod method = HttpMethod.GET; final URI uri = new URI("https://" + host + ":" + port + "/a%20b"); - RibbonCommandContext context = new RibbonCommandContext(serviceName, method.toString(), uri.toString(), true, - new LinkedMultiValueMap(), new LinkedMultiValueMap(), + RibbonCommandContext context = new RibbonCommandContext(serviceName, + method.toString(), uri.toString(), true, + new LinkedMultiValueMap(), + new LinkedMultiValueMap(), new ByteArrayInputStream(new String("bar").getBytes()), new ArrayList()); RibbonApacheHttpRequest request = new RibbonApacheHttpRequest(context); @@ -544,20 +573,21 @@ public class RibbonLoadBalancingHttpClientTests { StatusLine statusLine = mock(StatusLine.class); doReturn(200).when(statusLine).getStatusCode(); doReturn(statusLine).when(response).getStatusLine(); - doReturn(response). - when(delegate).execute(any(HttpUriRequest.class)); + doReturn(response).when(delegate).execute(any(HttpUriRequest.class)); ILoadBalancer lb = mock(ILoadBalancer.class); - RibbonLoadBalancerContext ribbonLoadBalancerContext = new RibbonLoadBalancerContext(lb); - RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry(retriesNextServer, retriesSameServer, retryable, retryOnAllOps, - serviceName, host, port, delegate, lb, "", null,true); + RibbonLoadBalancerContext ribbonLoadBalancerContext = new RibbonLoadBalancerContext( + lb); + RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry( + retriesNextServer, retriesSameServer, retryable, retryOnAllOps, + serviceName, host, port, delegate, lb, "", null, true); client.setRibbonLoadBalancerContext(ribbonLoadBalancerContext); client.execute(request, null); verify(response, times(0)).close(); verify(delegate, times(1)).execute(argThat(new ArgumentMatcher() { @Override public boolean matches(HttpUriRequest argument) { - if(argument instanceof HttpUriRequest) { - HttpUriRequest arg = (HttpUriRequest)argument; + if (argument instanceof HttpUriRequest) { + HttpUriRequest arg = (HttpUriRequest) argument; return arg.getURI().equals(uri); } return false; @@ -578,11 +608,13 @@ public class RibbonLoadBalancingHttpClientTests { URI uri = new URI("http://" + host + ":" + port); CloseableHttpClient delegate = mock(CloseableHttpClient.class); final CloseableHttpResponse response = mock(CloseableHttpResponse.class); - doThrow(new IOException("boom")).doThrow(new IOException("boom again")).doReturn(response). - when(delegate).execute(any(HttpUriRequest.class)); + doThrow(new IOException("boom")).doThrow(new IOException("boom again")) + .doReturn(response).when(delegate).execute(any(HttpUriRequest.class)); ILoadBalancer lb = mock(ILoadBalancer.class); - RibbonLoadBalancerContext ribbonLoadBalancerContext = new RibbonLoadBalancerContext(lb); - RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry(retriesNextServer, retriesSameServer, retryable, retryOnAllOps, + RibbonLoadBalancerContext ribbonLoadBalancerContext = new RibbonLoadBalancerContext( + lb); + RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry( + retriesNextServer, retriesSameServer, retryable, retryOnAllOps, serviceName, host, port, delegate, lb, "", null); client.setRibbonLoadBalancerContext(ribbonLoadBalancerContext); RibbonApacheHttpRequest request = mock(RibbonApacheHttpRequest.class); @@ -595,7 +627,10 @@ public class RibbonLoadBalancingHttpClientTests { try { client.execute(request, null); fail("Expected IOException"); - } catch(IOException e) {} finally { + } + catch (IOException e) { + } + finally { verify(response, times(0)).close(); verify(delegate, times(1)).execute(any(HttpUriRequest.class)); verify(lb, times(1)).chooseServer(eq(serviceName)); @@ -629,11 +664,14 @@ public class RibbonLoadBalancingHttpClientTests { StatusLine fourOFourStatusLine = mock(StatusLine.class); doReturn(404).when(fourOFourStatusLine).getStatusCode(); doReturn(fourOFourStatusLine).when(fourOFourResponse).getStatusLine(); - doReturn(fourOFourResponse).doReturn(response).when(delegate).execute(any(HttpUriRequest.class)); + doReturn(fourOFourResponse).doReturn(response).when(delegate) + .execute(any(HttpUriRequest.class)); ILoadBalancer lb = mock(ILoadBalancer.class); - RibbonLoadBalancerContext ribbonLoadBalancerContext = new RibbonLoadBalancerContext(lb); + RibbonLoadBalancerContext ribbonLoadBalancerContext = new RibbonLoadBalancerContext( + lb); MyBackOffPolicy myBackOffPolicy = new MyBackOffPolicy(); - RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry(retriesNextServer, retriesSameServer, retryable, retryOnAllOps, + RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry( + retriesNextServer, retriesSameServer, retryable, retryOnAllOps, serviceName, host, port, delegate, lb, "404", myBackOffPolicy); client.setRibbonLoadBalancerContext(ribbonLoadBalancerContext); RibbonApacheHttpRequest request = mock(RibbonApacheHttpRequest.class); @@ -647,7 +685,7 @@ public class RibbonLoadBalancingHttpClientTests { verify(fourOFourResponse, times(1)).close(); verify(delegate, times(2)).execute(any(HttpUriRequest.class)); verify(lb, times(1)).chooseServer(eq(serviceName)); - assertEquals(1, myBackOffPolicy.getCount()); + assertThat(myBackOffPolicy.getCount()).isEqualTo(1); } @Test @@ -666,14 +704,17 @@ public class RibbonLoadBalancingHttpClientTests { StatusLine statusLine = mock(StatusLine.class); doReturn(200).when(statusLine).getStatusCode(); doReturn(statusLine).when(response).getStatusLine(); - doThrow(new IOException("boom")).doThrow(new IOException("boom again")).doReturn(response). - when(delegate).execute(any(HttpUriRequest.class)); + doThrow(new IOException("boom")).doThrow(new IOException("boom again")) + .doReturn(response).when(delegate).execute(any(HttpUriRequest.class)); ILoadBalancer lb = mock(ILoadBalancer.class); - RibbonLoadBalancerContext ribbonLoadBalancerContext = new RibbonLoadBalancerContext(lb); + RibbonLoadBalancerContext ribbonLoadBalancerContext = new RibbonLoadBalancerContext( + lb); MyBackOffPolicy myBackOffPolicy = new MyBackOffPolicy(); MyRetryListener myRetryListener = new MyRetryListener(); - RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry(retriesNextServer, retriesSameServer, retryable, retryOnAllOps, - serviceName, host, port, delegate, lb, "", myBackOffPolicy, false, new RetryListener[]{myRetryListener}); + RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry( + retriesNextServer, retriesSameServer, retryable, retryOnAllOps, + serviceName, host, port, delegate, lb, "", myBackOffPolicy, false, + new RetryListener[] { myRetryListener }); client.setRibbonLoadBalancerContext(ribbonLoadBalancerContext); RibbonApacheHttpRequest request = mock(RibbonApacheHttpRequest.class); doReturn(method).when(request).getMethod(); @@ -685,8 +726,8 @@ public class RibbonLoadBalancingHttpClientTests { verify(response, times(0)).close(); verify(delegate, times(3)).execute(any(HttpUriRequest.class)); verify(lb, times(2)).chooseServer(eq(serviceName)); - assertEquals(2, myBackOffPolicy.getCount()); - assertEquals(2, myRetryListener.getOnError()); + assertThat(myBackOffPolicy.getCount()).isEqualTo(2); + assertThat(myRetryListener.getOnError()).isEqualTo(2); } @Test @@ -705,14 +746,17 @@ public class RibbonLoadBalancingHttpClientTests { StatusLine statusLine = mock(StatusLine.class); doReturn(200).when(statusLine).getStatusCode(); doReturn(statusLine).when(response).getStatusLine(); - doThrow(new IOException("boom")).doThrow(new IOException("boom again")).doReturn(response). - when(delegate).execute(any(HttpUriRequest.class)); + doThrow(new IOException("boom")).doThrow(new IOException("boom again")) + .doReturn(response).when(delegate).execute(any(HttpUriRequest.class)); ILoadBalancer lb = mock(ILoadBalancer.class); - RibbonLoadBalancerContext ribbonLoadBalancerContext = new RibbonLoadBalancerContext(lb); + RibbonLoadBalancerContext ribbonLoadBalancerContext = new RibbonLoadBalancerContext( + lb); MyBackOffPolicy myBackOffPolicy = new MyBackOffPolicy(); MyRetryListener myRetryListener = new MyRetryListener(); - RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry(retriesNextServer, retriesSameServer, retryable, retryOnAllOps, - serviceName, host, port, delegate, lb, "", myBackOffPolicy, false, new RetryListener[]{}); + RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry( + retriesNextServer, retriesSameServer, retryable, retryOnAllOps, + serviceName, host, port, delegate, lb, "", myBackOffPolicy, false, + new RetryListener[] {}); client.setRibbonLoadBalancerContext(ribbonLoadBalancerContext); RibbonApacheHttpRequest request = mock(RibbonApacheHttpRequest.class); doReturn(method).when(request).getMethod(); @@ -724,8 +768,8 @@ public class RibbonLoadBalancingHttpClientTests { verify(response, times(0)).close(); verify(delegate, times(3)).execute(any(HttpUriRequest.class)); verify(lb, times(2)).chooseServer(eq(serviceName)); - assertEquals(2, myBackOffPolicy.getCount()); - assertEquals(0, myRetryListener.getOnError()); + assertThat(myBackOffPolicy.getCount()).isEqualTo(2); + assertThat(myRetryListener.getOnError()).isEqualTo(0); } @Test(expected = TerminatedRetryException.class) @@ -744,13 +788,15 @@ public class RibbonLoadBalancingHttpClientTests { StatusLine statusLine = mock(StatusLine.class); doReturn(200).when(statusLine).getStatusCode(); doReturn(statusLine).when(response).getStatusLine(); - doThrow(new IOException("boom")).doThrow(new IOException("boom again")).doReturn(response). - when(delegate).execute(any(HttpUriRequest.class)); + doThrow(new IOException("boom")).doThrow(new IOException("boom again")) + .doReturn(response).when(delegate).execute(any(HttpUriRequest.class)); ILoadBalancer lb = mock(ILoadBalancer.class); MyBackOffPolicy myBackOffPolicy = new MyBackOffPolicy(); MyRetryListenerNotRetry myRetryListenerNotRetry = new MyRetryListenerNotRetry(); - RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry(retriesNextServer, retriesSameServer, retryable, retryOnAllOps, - serviceName, host, port, delegate, lb, "", myBackOffPolicy, false, new RetryListener[]{myRetryListenerNotRetry}); + RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry( + retriesNextServer, retriesSameServer, retryable, retryOnAllOps, + serviceName, host, port, delegate, lb, "", myBackOffPolicy, false, + new RetryListener[] { myRetryListenerNotRetry }); RibbonApacheHttpRequest request = mock(RibbonApacheHttpRequest.class); doReturn(method).when(request).getMethod(); doReturn(uri).when(request).getURI(); @@ -777,13 +823,15 @@ public class RibbonLoadBalancingHttpClientTests { StatusLine statusLine = mock(StatusLine.class); doReturn(200).when(statusLine).getStatusCode(); doReturn(statusLine).when(response).getStatusLine(); - doThrow(new IOException("boom")).doThrow(new IOException("boom again")).doReturn(response). - when(delegate).execute(any(HttpUriRequest.class)); + doThrow(new IOException("boom")).doThrow(new IOException("boom again")) + .doReturn(response).when(delegate).execute(any(HttpUriRequest.class)); ILoadBalancer lb = mock(ILoadBalancer.class); - RibbonLoadBalancerContext ribbonLoadBalancerContext = new RibbonLoadBalancerContext(lb); + RibbonLoadBalancerContext ribbonLoadBalancerContext = new RibbonLoadBalancerContext( + lb); MyBackOffPolicy myBackOffPolicy = new MyBackOffPolicy(); - RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry(retriesNextServer, retriesSameServer, retryable, retryOnAllOps, - serviceName, host, port, delegate, lb, "", myBackOffPolicy, false); + RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry( + retriesNextServer, retriesSameServer, retryable, retryOnAllOps, + serviceName, host, port, delegate, lb, "", myBackOffPolicy, false); client.setRibbonLoadBalancerContext(ribbonLoadBalancerContext); RibbonApacheHttpRequest request = mock(RibbonApacheHttpRequest.class); doReturn(method).when(request).getMethod(); @@ -795,11 +843,12 @@ public class RibbonLoadBalancingHttpClientTests { verify(response, times(0)).close(); verify(delegate, times(3)).execute(any(HttpUriRequest.class)); verify(lb, times(2)).chooseServer(eq(serviceName)); - assertEquals(2, myBackOffPolicy.getCount()); + assertThat(myBackOffPolicy.getCount()).isEqualTo(2); } - - private RetryableRibbonLoadBalancingHttpClient setupClientForServerValidation(String serviceName, String host, int port, - CloseableHttpClient delegate, ILoadBalancer lb) throws Exception { + + private RetryableRibbonLoadBalancingHttpClient setupClientForServerValidation( + String serviceName, String host, int port, CloseableHttpClient delegate, + ILoadBalancer lb) throws Exception { ServerIntrospector introspector = mock(ServerIntrospector.class); RetryHandler retryHandler = new DefaultLoadBalancerRetryHandler(1, 1, true); DefaultClientConfigImpl clientConfig = new DefaultClientConfigImpl(); @@ -809,19 +858,21 @@ public class RibbonLoadBalancingHttpClientTests { clientConfig.set(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES, ""); clientConfig.set(CommonClientConfigKey.IsSecure, false); clientConfig.setClientName(serviceName); - RibbonLoadBalancerContext context = new RibbonLoadBalancerContext(lb, clientConfig, retryHandler); + RibbonLoadBalancerContext context = new RibbonLoadBalancerContext(lb, + clientConfig, retryHandler); SpringClientFactory clientFactory = mock(SpringClientFactory.class); doReturn(context).when(clientFactory).getLoadBalancerContext(eq(serviceName)); doReturn(clientConfig).when(clientFactory).getClientConfig(eq(serviceName)); - LoadBalancedRetryFactory factory = new RibbonLoadBalancedRetryFactory(clientFactory); - RetryableRibbonLoadBalancingHttpClient client = new RetryableRibbonLoadBalancingHttpClient(delegate, - clientConfig, introspector, factory); + LoadBalancedRetryFactory factory = new RibbonLoadBalancedRetryFactory( + clientFactory); + RetryableRibbonLoadBalancingHttpClient client = new RetryableRibbonLoadBalancingHttpClient( + delegate, clientConfig, introspector, factory); client.setLoadBalancer(lb); client.setRibbonLoadBalancerContext(context); ReflectionTestUtils.setField(client, "delegate", delegate); return client; } - + @Test public void noServersFoundTest() throws Exception { String serviceName = "noservers"; @@ -831,8 +882,9 @@ public class RibbonLoadBalancingHttpClientTests { URI uri = new URI("http://" + host + ":" + port); CloseableHttpClient delegate = mock(CloseableHttpClient.class); ILoadBalancer lb = mock(ILoadBalancer.class); - - RetryableRibbonLoadBalancingHttpClient client = setupClientForServerValidation(serviceName, host, port, delegate, lb); + + RetryableRibbonLoadBalancingHttpClient client = setupClientForServerValidation( + serviceName, host, port, delegate, lb); RibbonApacheHttpRequest request = mock(RibbonApacheHttpRequest.class); doReturn(null).when(lb).chooseServer(eq(serviceName)); doReturn(method).when(request).getMethod(); @@ -843,11 +895,13 @@ public class RibbonLoadBalancingHttpClientTests { try { client.execute(request, null); fail("Expected IOException for no servers available"); - } catch (ClientException ex) { - assertThat(ex.getMessage(), containsString("Load balancer does not have available server for client")); + } + catch (ClientException ex) { + assertThat(ex.getMessage()) + .contains("Load balancer does not have available server for client"); } } - + @Test public void invalidServerTest() throws Exception { String serviceName = "noservers"; @@ -857,10 +911,11 @@ public class RibbonLoadBalancingHttpClientTests { URI uri = new URI("http://" + host + ":" + port); CloseableHttpClient delegate = mock(CloseableHttpClient.class); ILoadBalancer lb = mock(ILoadBalancer.class); - - RetryableRibbonLoadBalancingHttpClient client = setupClientForServerValidation(serviceName, host, port, delegate, lb); + + RetryableRibbonLoadBalancingHttpClient client = setupClientForServerValidation( + serviceName, host, port, delegate, lb); RibbonApacheHttpRequest request = mock(RibbonApacheHttpRequest.class); - doReturn(new Server(null,8000)).when(lb).chooseServer(eq(serviceName)); + doReturn(new Server(null, 8000)).when(lb).chooseServer(eq(serviceName)); doReturn(method).when(request).getMethod(); doReturn(uri).when(request).getURI(); doReturn(request).when(request).withNewUri(any(URI.class)); @@ -869,70 +924,24 @@ public class RibbonLoadBalancingHttpClientTests { try { client.execute(request, null); fail("Expected IOException for no servers available"); - } catch (ClientException ex) { - assertThat(ex.getMessage(), containsString("Invalid Server for: ")); } - } - - @Configuration - protected static class UseDefaults { - - } - - @Configuration - protected static class FollowRedirects { - @Bean - public IClientConfig clientConfig() { - DefaultClientConfigImpl config = new DefaultClientConfigImpl(); - config.set(CommonClientConfigKey.FollowRedirects, true); - return config; - } - } - - @Configuration - protected static class DoNotFollowRedirects { - @Bean - public IClientConfig clientConfig() { - DefaultClientConfigImpl config = new DefaultClientConfigImpl(); - config.set(CommonClientConfigKey.FollowRedirects, false); - return config; - } - } - - @Configuration - protected static class Timeouts { - @Bean - public IClientConfig clientConfig() { - DefaultClientConfigImpl config = new DefaultClientConfigImpl(); - config.set(CommonClientConfigKey.ConnectTimeout, 60000); - config.set(CommonClientConfigKey.ReadTimeout, 50000); - return config; - } - } - - - @Configuration - protected static class Connections { - @Bean - public IClientConfig clientConfig() { - DefaultClientConfigImpl config = new DefaultClientConfigImpl(); - config.set(CommonClientConfigKey.MaxTotalConnections, 101); - config.set(CommonClientConfigKey.MaxConnectionsPerHost, 201); - return config; + catch (ClientException ex) { + assertThat(ex.getMessage()).contains("Invalid Server for: "); } } private RequestConfig getBuiltRequestConfig(Class defaultConfigurationClass, IClientConfig configOverride) throws Exception { - return getBuiltRequestConfig(defaultConfigurationClass, configOverride, new SpringClientFactory()); + return getBuiltRequestConfig(defaultConfigurationClass, configOverride, + new SpringClientFactory()); } private RequestConfig getBuiltRequestConfig(Class defaultConfigurationClass, - IClientConfig configOverride, SpringClientFactory factory) - throws Exception { + IClientConfig configOverride, SpringClientFactory factory) throws Exception { - factory.setApplicationContext(new AnnotationConfigApplicationContext(HttpClientConfiguration.class, - RibbonAutoConfiguration.class, defaultConfigurationClass)); + factory.setApplicationContext( + new AnnotationConfigApplicationContext(HttpClientConfiguration.class, + RibbonAutoConfiguration.class, defaultConfigurationClass)); String serviceName = "foo"; String host = serviceName; int port = 80; @@ -943,17 +952,16 @@ public class RibbonLoadBalancingHttpClientTests { ReflectionTestUtils.setField(client, "delegate", delegate); ReflectionTestUtils.setField(client, "lb", loadBalancer); - CloseableHttpResponse httpResponse = mock(CloseableHttpResponse.class); + CloseableHttpResponse httpResponse = mock(CloseableHttpResponse.class); StatusLine statusLine = mock(StatusLine.class); doReturn(200).when(statusLine).getStatusCode(); doReturn(statusLine).when(httpResponse).getStatusLine(); - given(delegate.execute(any(HttpUriRequest.class))).willReturn( - httpResponse); + given(delegate.execute(any(HttpUriRequest.class))).willReturn(httpResponse); RibbonApacheHttpRequest request = mock(RibbonApacheHttpRequest.class); doReturn(uri).when(request).getURI(); doReturn(request).when(request).withNewUri(any(URI.class)); - given(request.toRequest(any(RequestConfig.class))).willReturn( - mock(HttpUriRequest.class)); + given(request.toRequest(any(RequestConfig.class))) + .willReturn(mock(HttpUriRequest.class)); client.execute(request, configOverride); @@ -973,13 +981,15 @@ public class RibbonLoadBalancingHttpClientTests { } @Override - public void backOff(BackOffContext backOffContext) throws BackOffInterruptedException { + public void backOff(BackOffContext backOffContext) + throws BackOffInterruptedException { count++; } int getCount() { return count; } + } class MyRetryListener implements RetryListener { @@ -991,37 +1001,100 @@ public class RibbonLoadBalancingHttpClientTests { } @Override - public boolean open(RetryContext context, RetryCallback callback) { + public boolean open(RetryContext context, + RetryCallback callback) { return true; } @Override - public void close(RetryContext context, RetryCallback callback, Throwable throwable) { + public void close(RetryContext context, + RetryCallback callback, Throwable throwable) { } @Override - public void onError(RetryContext context, RetryCallback callback, Throwable throwable) { + public void onError(RetryContext context, + RetryCallback callback, Throwable throwable) { onError++; } + + } + + @Configuration + protected static class DoNotFollowRedirects { + + @Bean + public IClientConfig clientConfig() { + DefaultClientConfigImpl config = new DefaultClientConfigImpl(); + config.set(CommonClientConfigKey.FollowRedirects, false); + return config; + } + + } + + @Configuration + protected static class Connections { + + @Bean + public IClientConfig clientConfig() { + DefaultClientConfigImpl config = new DefaultClientConfigImpl(); + config.set(CommonClientConfigKey.MaxTotalConnections, 101); + config.set(CommonClientConfigKey.MaxConnectionsPerHost, 201); + return config; + } + + } + + @Configuration + protected static class Timeouts { + + @Bean + public IClientConfig clientConfig() { + DefaultClientConfigImpl config = new DefaultClientConfigImpl(); + config.set(CommonClientConfigKey.ConnectTimeout, 60000); + config.set(CommonClientConfigKey.ReadTimeout, 50000); + return config; + } + + } + + @Configuration + protected static class UseDefaults { + + } + + @Configuration + protected static class FollowRedirects { + + @Bean + public IClientConfig clientConfig() { + DefaultClientConfigImpl config = new DefaultClientConfigImpl(); + config.set(CommonClientConfigKey.FollowRedirects, true); + return config; + } + } class MyRetryListenerNotRetry implements RetryListener { @Override - public boolean open(RetryContext context, RetryCallback callback) { + public boolean open(RetryContext context, + RetryCallback callback) { return false; } @Override - public void close(RetryContext context, RetryCallback callback, Throwable throwable) { + public void close(RetryContext context, + RetryCallback callback, Throwable throwable) { } @Override - public void onError(RetryContext context, RetryCallback callback, Throwable throwable) { + public void onError(RetryContext context, + RetryCallback callback, Throwable throwable) { } + } } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpLoadBalancingClientTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpLoadBalancingClientTests.java index 755e997b0..d54afec0d 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpLoadBalancingClientTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpLoadBalancingClientTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,9 +16,12 @@ package org.springframework.cloud.netflix.ribbon.okhttp; +import com.netflix.client.config.CommonClientConfigKey; +import com.netflix.client.config.DefaultClientConfigImpl; +import com.netflix.client.config.IClientConfig; import okhttp3.OkHttpClient; - import org.junit.Test; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.netflix.ribbon.DefaultServerIntrospector; import org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration; @@ -26,12 +29,8 @@ import org.springframework.cloud.netflix.ribbon.SpringClientFactory; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import com.netflix.client.config.CommonClientConfigKey; -import com.netflix.client.config.DefaultClientConfigImpl; -import com.netflix.client.config.IClientConfig; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Spencer Gibb @@ -42,21 +41,21 @@ public class OkHttpLoadBalancingClientTests { public void testOkHttpClientUseDefaultsNoOverride() throws Exception { OkHttpClient result = getHttpClient(UseDefaults.class, null); - assertThat(result.followRedirects(), is(false)); + assertThat(result.followRedirects()).isFalse(); } @Test public void testOkHttpClientDoNotFollowRedirectsNoOverride() throws Exception { OkHttpClient result = getHttpClient(DoNotFollowRedirects.class, null); - assertThat(result.followRedirects(), is(false)); + assertThat(result.followRedirects()).isFalse(); } @Test public void testOkHttpClientFollowRedirectsNoOverride() throws Exception { OkHttpClient result = getHttpClient(FollowRedirects.class, null); - assertThat(result.followRedirects(), is(true)); + assertThat(result.followRedirects()).isTrue(); } @Test @@ -69,7 +68,7 @@ public class OkHttpLoadBalancingClientTests { OkHttpClient result = getHttpClient(DoNotFollowRedirects.class, override); - assertThat(result.followRedirects(), is(true)); + assertThat(result.followRedirects()).isTrue(); } @Test @@ -82,21 +81,21 @@ public class OkHttpLoadBalancingClientTests { OkHttpClient result = getHttpClient(FollowRedirects.class, override); - assertThat(result.followRedirects(), is(false)); + assertThat(result.followRedirects()).isFalse(); } @Test public void testTimeouts() throws Exception { OkHttpClient result = getHttpClient(Timeouts.class, null); - assertThat(result.readTimeoutMillis(), is(50000)); - assertThat(result.connectTimeoutMillis(), is(60000)); + assertThat(result.readTimeoutMillis()).isEqualTo(50000); + assertThat(result.connectTimeoutMillis()).isEqualTo(60000); } @Test public void testDefaultTimeouts() throws Exception { OkHttpClient result = getHttpClient(UseDefaults.class, null); - assertThat(result.readTimeoutMillis(), is(1000)); - assertThat(result.connectTimeoutMillis(), is(1000)); + assertThat(result.readTimeoutMillis()).isEqualTo(1000); + assertThat(result.connectTimeoutMillis()).isEqualTo(1000); } @Test @@ -105,34 +104,35 @@ public class OkHttpLoadBalancingClientTests { override.set(CommonClientConfigKey.ConnectTimeout, 60); override.set(CommonClientConfigKey.ReadTimeout, 50); OkHttpClient result = getHttpClient(Timeouts.class, override); - assertThat(result.readTimeoutMillis(), is(50)); - assertThat(result.connectTimeoutMillis(), is(60)); + assertThat(result.readTimeoutMillis()).isEqualTo(50); + assertThat(result.connectTimeoutMillis()).isEqualTo(60); } @Test public void testUpdatedTimeouts() throws Exception { SpringClientFactory factory = new SpringClientFactory(); OkHttpClient result = getHttpClient(Timeouts.class, null, factory); - assertThat(result.readTimeoutMillis(), is(50000)); - assertThat(result.connectTimeoutMillis(), is(60000)); + assertThat(result.readTimeoutMillis()).isEqualTo(50000); + assertThat(result.connectTimeoutMillis()).isEqualTo(60000); IClientConfig config = factory.getClientConfig("service"); config.set(CommonClientConfigKey.ConnectTimeout, 60); config.set(CommonClientConfigKey.ReadTimeout, 50); result = getHttpClient(Timeouts.class, null, factory); - assertThat(result.readTimeoutMillis(), is(50)); - assertThat(result.connectTimeoutMillis(), is(60)); + assertThat(result.readTimeoutMillis()).isEqualTo(50); + assertThat(result.connectTimeoutMillis()).isEqualTo(60); } private OkHttpClient getHttpClient(Class defaultConfigurationClass, - IClientConfig configOverride) throws Exception { - return getHttpClient(defaultConfigurationClass, configOverride, new SpringClientFactory()); + IClientConfig configOverride) throws Exception { + return getHttpClient(defaultConfigurationClass, configOverride, + new SpringClientFactory()); } private OkHttpClient getHttpClient(Class defaultConfigurationClass, - IClientConfig configOverride, - SpringClientFactory factory) throws Exception { - factory.setApplicationContext(new AnnotationConfigApplicationContext( - RibbonAutoConfiguration.class, OkHttpClientConfiguration.class, defaultConfigurationClass)); + IClientConfig configOverride, SpringClientFactory factory) throws Exception { + factory.setApplicationContext( + new AnnotationConfigApplicationContext(RibbonAutoConfiguration.class, + OkHttpClientConfiguration.class, defaultConfigurationClass)); OkHttpLoadBalancingClient client = factory.getClient("service", OkHttpLoadBalancingClient.class); @@ -142,15 +142,19 @@ public class OkHttpLoadBalancingClientTests { @Configuration protected static class OkHttpClientConfiguration { + @Autowired(required = false) IClientConfig clientConfig; + @Bean public OkHttpLoadBalancingClient okHttpLoadBalancingClient() { - if(clientConfig == null) { + if (clientConfig == null) { clientConfig = new DefaultClientConfigImpl(); } - return new OkHttpLoadBalancingClient(new OkHttpClient(), clientConfig, new DefaultServerIntrospector()); + return new OkHttpLoadBalancingClient(new OkHttpClient(), clientConfig, + new DefaultServerIntrospector()); } + } @Configuration @@ -160,26 +164,31 @@ public class OkHttpLoadBalancingClientTests { @Configuration protected static class FollowRedirects { + @Bean public IClientConfig clientConfig() { DefaultClientConfigImpl config = new DefaultClientConfigImpl(); config.set(CommonClientConfigKey.FollowRedirects, true); return config; } + } @Configuration protected static class DoNotFollowRedirects { + @Bean public IClientConfig clientConfig() { DefaultClientConfigImpl config = new DefaultClientConfigImpl(); config.set(CommonClientConfigKey.FollowRedirects, false); return config; } + } @Configuration protected static class Timeouts { + @Bean public IClientConfig clientConfig() { DefaultClientConfigImpl config = new DefaultClientConfigImpl(); @@ -187,6 +196,7 @@ public class OkHttpLoadBalancingClientTests { config.set(CommonClientConfigKey.ReadTimeout, 50000); return config; } + } } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonRequestTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonRequestTests.java index 09a48c62c..01b29d677 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonRequestTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonRequestTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,30 +12,25 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.ribbon.okhttp; -import okhttp3.Request; -import okhttp3.RequestBody; -import okio.Buffer; - import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; + +import okhttp3.Request; +import okhttp3.RequestBody; +import okio.Buffer; import org.junit.Test; + import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; import org.springframework.cloud.netflix.ribbon.support.RibbonRequestCustomizer; import org.springframework.util.LinkedMultiValueMap; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Spencer Gibb @@ -56,12 +51,12 @@ public class OkHttpRibbonRequestTests { Request request = httpRequest.toRequest(); - assertThat("body is not null", request.body(), is(nullValue())); - assertThat("uri is wrong", request.url().toString(), startsWith(uri)); - assertThat("my-header is wrong", request.header("my-header"), - is(equalTo("my-value"))); - assertThat("myparam is missing", request.url().queryParameter("myparam"), - is(equalTo("myparamval"))); + assertThat(request.body()).as("body is not null").isNull(); + assertThat(request.url().toString()).as("uri is wrong").startsWith(uri); + assertThat(request.header("my-header")).as("my-header is wrong") + .isEqualTo("my-value"); + assertThat(request.url().queryParameter("myparam")).as("myparam is missing") + .isEqualTo("myparamval"); } @Test @@ -110,23 +105,24 @@ public class OkHttpRibbonRequestTests { Request request = httpRequest.toRequest(); - assertThat("uri is wrong", request.url().toString(), startsWith(uri)); + assertThat(request.url().toString()).as("uri is wrong").startsWith(uri); if (addContentLengthHeader) { - assertThat("Content-Length is wrong", request.header("Content-Length"), - is(equalTo(lengthString))); + assertThat(request.header("Content-Length")).as("Content-Length is wrong") + .isEqualTo(lengthString); } - assertThat("from-customizer is wrong", request.header("from-customizer"), - is(equalTo("foo"))); + assertThat(request.header("from-customizer")).as("from-customizer is wrong") + .isEqualTo("foo"); if (!method.equalsIgnoreCase("get")) { - assertThat("body is null", request.body(), is(notNullValue())); + assertThat(request.body()).as("body is null").isNotNull(); RequestBody body = request.body(); - assertThat("contentLength is wrong", body.contentLength(), - is(equalTo((long) entityValue.length()))); + assertThat(body.contentLength()).as("contentLength is wrong") + .isEqualTo((long) entityValue.length()); Buffer content = new Buffer(); body.writeTo(content); String string = content.readByteString().utf8(); - assertThat("content is wrong", string, is(equalTo(entityValue))); + assertThat(string).as("content is wrong").isEqualTo(entityValue); } } + } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonResponseTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonResponseTests.java index 8a65c9fa5..6371886fc 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonResponseTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonResponseTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,21 +16,19 @@ package org.springframework.cloud.netflix.ribbon.okhttp; +import java.net.URI; + import okhttp3.HttpUrl; import okhttp3.MediaType; import okhttp3.Protocol; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; - -import java.net.URI; import org.junit.Test; + import org.springframework.http.HttpStatus; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Spencer Gibb @@ -44,32 +42,31 @@ public class OkHttpRibbonResponseTests { OkHttpRibbonResponse httpResponse = new OkHttpRibbonResponse(response, uri); - assertThat(httpResponse.isSuccess(), is(true)); - assertThat(httpResponse.hasPayload(), is(false)); - assertThat(httpResponse.getPayload(), is(nullValue())); - assertThat(httpResponse.getInputStream(), is(nullValue())); + assertThat(httpResponse.isSuccess()).isTrue(); + assertThat(httpResponse.hasPayload()).isFalse(); + assertThat(httpResponse.getPayload()).isNull(); + assertThat(httpResponse.getInputStream()).isNull(); } @Test public void testNotNullEntity() throws Exception { URI uri = URI.create("http://example.com"); Response response = response(uri) - .body(ResponseBody.create(MediaType.parse("text/plain"), "abcd")) - .build(); + .body(ResponseBody.create(MediaType.parse("text/plain"), "abcd")).build(); OkHttpRibbonResponse httpResponse = new OkHttpRibbonResponse(response, uri); - assertThat(httpResponse.isSuccess(), is(true)); - assertThat(httpResponse.hasPayload(), is(true)); - assertThat(httpResponse.getPayload(), is(notNullValue())); - assertThat(httpResponse.getInputStream(), is(notNullValue())); + assertThat(httpResponse.isSuccess()).isTrue(); + assertThat(httpResponse.hasPayload()).isTrue(); + assertThat(httpResponse.getPayload()).isNotNull(); + assertThat(httpResponse.getInputStream()).isNotNull(); } Response.Builder response(URI uri) { return new Response.Builder() .request(new Request.Builder().url(HttpUrl.get(uri)).build()) - .protocol(Protocol.HTTP_1_1) - .code(HttpStatus.OK.value()) + .protocol(Protocol.HTTP_1_1).code(HttpStatus.OK.value()) .message(HttpStatus.OK.getReasonPhrase()); } + } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/SpringRetryDisableOkHttpClientTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/SpringRetryDisableOkHttpClientTests.java index 263a412d8..39792aae8 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/SpringRetryDisableOkHttpClientTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/SpringRetryDisableOkHttpClientTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,14 +12,15 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ + package org.springframework.cloud.netflix.ribbon.okhttp; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory; @@ -30,33 +31,34 @@ import org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration; import org.springframework.cloud.test.ClassPathExclusions; import org.springframework.cloud.test.ModifiedClassPathRunner; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.instanceOf; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Ryan Baxter * @author Biju Kunjummen */ @RunWith(ModifiedClassPathRunner.class) -@ClassPathExclusions({"spring-retry-*.jar", "spring-boot-starter-aop-*.jar"}) +@ClassPathExclusions({ "spring-retry-*.jar", "spring-boot-starter-aop-*.jar" }) public class SpringRetryDisableOkHttpClientTests { @Test public void testLoadBalancedRetryFactoryBean() { - new ApplicationContextRunner() - .withPropertyValues("ribbon.okhttp.enabled=true") - .withConfiguration(AutoConfigurations.of(RibbonAutoConfiguration.class, - LoadBalancerAutoConfiguration.class, - HttpClientConfiguration.class, RibbonClientConfiguration.class)) - .withUserConfiguration( - OkHttpLoadBalancingClientTests.OkHttpClientConfiguration.class) - .run(context -> { - Map factories = context.getBeansOfType(LoadBalancedRetryFactory.class); - assertThat(factories.values(), hasSize(0)); - Map clients = context.getBeansOfType(OkHttpLoadBalancingClient.class); - assertThat(clients.values(), hasSize(1)); - assertThat(clients.values().toArray()[0], instanceOf(OkHttpLoadBalancingClient.class)); - }); + new ApplicationContextRunner().withPropertyValues("ribbon.okhttp.enabled=true") + .withConfiguration(AutoConfigurations.of(RibbonAutoConfiguration.class, + LoadBalancerAutoConfiguration.class, + HttpClientConfiguration.class, RibbonClientConfiguration.class)) + .withUserConfiguration( + OkHttpLoadBalancingClientTests.OkHttpClientConfiguration.class) + .run(context -> { + Map factories = context + .getBeansOfType(LoadBalancedRetryFactory.class); + assertThat(factories.values()).hasSize(0); + Map clients = context + .getBeansOfType(OkHttpLoadBalancingClient.class); + assertThat(clients.values()).hasSize(1); + assertThat(clients.values().toArray()[0]) + .isInstanceOf(OkHttpLoadBalancingClient.class); + }); } + } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/SpringRetryEnabledOkHttpClientTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/SpringRetryEnabledOkHttpClientTests.java index b08e532fb..ff3c39905 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/SpringRetryEnabledOkHttpClientTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/SpringRetryEnabledOkHttpClientTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,17 +13,24 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.cloud.netflix.ribbon.okhttp; -import okhttp3.OkHttpClient; -import okhttp3.Request; +package org.springframework.cloud.netflix.ribbon.okhttp; import java.net.URI; import java.util.Map; -import org.hamcrest.core.IsNull; +import com.netflix.client.ClientException; +import com.netflix.client.DefaultLoadBalancerRetryHandler; +import com.netflix.client.RetryHandler; +import com.netflix.client.config.CommonClientConfigKey; +import com.netflix.client.config.DefaultClientConfigImpl; +import com.netflix.loadbalancer.ILoadBalancer; +import com.netflix.loadbalancer.Server; +import okhttp3.OkHttpClient; +import okhttp3.Request; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.BeansException; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory; @@ -43,19 +50,8 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.util.ReflectionTestUtils; -import com.netflix.client.ClientException; -import com.netflix.client.DefaultLoadBalancerRetryHandler; -import com.netflix.client.RetryHandler; -import com.netflix.client.config.CommonClientConfigKey; -import com.netflix.client.config.DefaultClientConfigImpl; -import com.netflix.loadbalancer.ILoadBalancer; -import com.netflix.loadbalancer.Server; - -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doReturn; @@ -65,42 +61,47 @@ import static org.mockito.Mockito.mock; * @author Ryan Baxter */ @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(value = { "ribbon.okhttp.enabled: true", "ribbon.httpclient.enabled: false" }) +@SpringBootTest({ "ribbon.okhttp.enabled: true", "ribbon.httpclient.enabled: false" }) @ContextConfiguration(classes = { RibbonAutoConfiguration.class, HttpClientConfiguration.class, RibbonClientConfiguration.class, LoadBalancerAutoConfiguration.class }) public class SpringRetryEnabledOkHttpClientTests implements ApplicationContextAware { private ApplicationContext context; + private ILoadBalancer loadBalancer; - + @Test public void testLoadBalancedRetryFactoryBean() throws Exception { Map factories = context .getBeansOfType(LoadBalancedRetryFactory.class); - assertThat(factories.values(), hasSize(1)); - assertThat(factories.values().toArray()[0], - instanceOf(RibbonLoadBalancedRetryFactory.class)); + assertThat(factories.values()).hasSize(1); + assertThat(factories.values().toArray()[0]) + .isInstanceOf(RibbonLoadBalancedRetryFactory.class); Map clients = context .getBeansOfType(OkHttpLoadBalancingClient.class); - assertThat(clients.values(), hasSize(1)); - assertThat(clients.values().toArray()[0], - instanceOf(RetryableOkHttpLoadBalancingClient.class)); - + assertThat(clients.values()).hasSize(1); + assertThat(clients.values().toArray()[0]) + .isInstanceOf(RetryableOkHttpLoadBalancingClient.class); + RibbonLoadBalancerContext ribbonLoadBalancerContext = (RibbonLoadBalancerContext) ReflectionTestUtils - .getField(clients.values().toArray()[0], RetryableOkHttpLoadBalancingClient.class, "ribbonLoadBalancerContext"); - assertThat("RetryableOkHttpLoadBalancingClient.ribbonLoadBalancerContext should not be null", - ribbonLoadBalancerContext, IsNull.notNullValue()); - + .getField(clients.values().toArray()[0], + RetryableOkHttpLoadBalancingClient.class, + "ribbonLoadBalancerContext"); + assertThat(ribbonLoadBalancerContext).as( + "RetryableOkHttpLoadBalancingClient.ribbonLoadBalancerContext should not be null") + .isNotNull(); + } @Override public void setApplicationContext(ApplicationContext context) throws BeansException { this.context = context; } - - private RetryableOkHttpLoadBalancingClient setupClientForServerValidation(String serviceName, String host, int port, - OkHttpClient delegate, ILoadBalancer lb) throws Exception { + + private RetryableOkHttpLoadBalancingClient setupClientForServerValidation( + String serviceName, String host, int port, OkHttpClient delegate, + ILoadBalancer lb) throws Exception { ServerIntrospector introspector = mock(ServerIntrospector.class); RetryHandler retryHandler = new DefaultLoadBalancerRetryHandler(1, 1, true); DefaultClientConfigImpl clientConfig = new DefaultClientConfigImpl(); @@ -110,18 +111,20 @@ public class SpringRetryEnabledOkHttpClientTests implements ApplicationContextAw clientConfig.set(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES, ""); clientConfig.set(CommonClientConfigKey.IsSecure, false); clientConfig.setClientName(serviceName); - RibbonLoadBalancerContext context = new RibbonLoadBalancerContext(lb, clientConfig, retryHandler); + RibbonLoadBalancerContext context = new RibbonLoadBalancerContext(lb, + clientConfig, retryHandler); SpringClientFactory clientFactory = mock(SpringClientFactory.class); doReturn(context).when(clientFactory).getLoadBalancerContext(eq(serviceName)); doReturn(clientConfig).when(clientFactory).getClientConfig(eq(serviceName)); - LoadBalancedRetryFactory factory = new RibbonLoadBalancedRetryFactory(clientFactory); - RetryableOkHttpLoadBalancingClient client = new RetryableOkHttpLoadBalancingClient(delegate, clientConfig, introspector, - factory); + LoadBalancedRetryFactory factory = new RibbonLoadBalancedRetryFactory( + clientFactory); + RetryableOkHttpLoadBalancingClient client = new RetryableOkHttpLoadBalancingClient( + delegate, clientConfig, introspector, factory); client.setLoadBalancer(lb); ReflectionTestUtils.setField(client, "delegate", delegate); return client; } - + @Test public void noServersFoundTest() throws Exception { String serviceName = "noservers"; @@ -131,8 +134,9 @@ public class SpringRetryEnabledOkHttpClientTests implements ApplicationContextAw URI uri = new URI("http://" + host + ":" + port); OkHttpClient delegate = mock(OkHttpClient.class); ILoadBalancer lb = mock(ILoadBalancer.class); - - RetryableOkHttpLoadBalancingClient client = setupClientForServerValidation(serviceName, host, port, delegate, lb); + + RetryableOkHttpLoadBalancingClient client = setupClientForServerValidation( + serviceName, host, port, delegate, lb); OkHttpRibbonRequest request = mock(OkHttpRibbonRequest.class); doReturn(null).when(lb).chooseServer(eq(serviceName)); doReturn(method).when(request).getMethod(); @@ -143,11 +147,13 @@ public class SpringRetryEnabledOkHttpClientTests implements ApplicationContextAw try { client.execute(request, null); fail("Expected ClientException for no servers available"); - } catch (ClientException ex) { - assertThat(ex.getMessage(), containsString("Load balancer does not have available server for client")); + } + catch (ClientException ex) { + assertThat(ex.getMessage()) + .contains("Load balancer does not have available server for client"); } } - + @Test public void invalidServerTest() throws Exception { String serviceName = "noservers"; @@ -157,10 +163,11 @@ public class SpringRetryEnabledOkHttpClientTests implements ApplicationContextAw URI uri = new URI("http://" + host + ":" + port); OkHttpClient delegate = mock(OkHttpClient.class); ILoadBalancer lb = mock(ILoadBalancer.class); - - RetryableOkHttpLoadBalancingClient client = setupClientForServerValidation(serviceName, host, port, delegate, lb); + + RetryableOkHttpLoadBalancingClient client = setupClientForServerValidation( + serviceName, host, port, delegate, lb); OkHttpRibbonRequest request = mock(OkHttpRibbonRequest.class); - doReturn(new Server(null,8000)).when(lb).chooseServer(eq(serviceName)); + doReturn(new Server(null, 8000)).when(lb).chooseServer(eq(serviceName)); doReturn(method).when(request).getMethod(); doReturn(uri).when(request).getURI(); doReturn(request).when(request).withNewUri(any(URI.class)); @@ -170,8 +177,10 @@ public class SpringRetryEnabledOkHttpClientTests implements ApplicationContextAw try { client.execute(request, null); fail("Expected ClientException for no Invalid Host"); - } catch (ClientException ex) { - assertThat(ex.getMessage(), containsString("Invalid Server for: ")); + } + catch (ClientException ex) { + assertThat(ex.getMessage()).contains("Invalid Server for: "); } } + } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/support/ContextAwareRequestTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/support/ContextAwareRequestTests.java index b8abf6290..491ffde20 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/support/ContextAwareRequestTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/support/ContextAwareRequestTests.java @@ -1,37 +1,35 @@ /* + * Copyright 2013-2019 the original author or authors. * - * * Copyright 2013-2016 the original author or authors. - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.netflix.ribbon.support; - import java.net.URI; import java.util.Arrays; import java.util.Collections; + import org.junit.After; import org.junit.Before; import org.junit.Test; + import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; @@ -41,6 +39,7 @@ import static org.mockito.Mockito.mock; public class ContextAwareRequestTests { private RibbonCommandContext context; + private ContextAwareRequest request; @Before @@ -67,24 +66,24 @@ public class ContextAwareRequestTests { @Test public void getContext() throws Exception { - assertEquals(context, request.getContext()); + assertThat(request.getContext()).isEqualTo(context); } @Test public void getMethod() throws Exception { - assertEquals(HttpMethod.GET, request.getMethod()); + assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); } @Test public void getURI() throws Exception { - assertEquals(new URI("http://foo"), request.getURI()); + assertThat(request.getURI()).isEqualTo(new URI("http://foo")); RibbonCommandContext badUriContext = mock(RibbonCommandContext.class); doReturn(new LinkedMultiValueMap()).when(badUriContext).getHeaders(); doReturn("foobar").when(badUriContext).getUri(); ContextAwareRequest badUriRequest = new TestContextAwareRequest(badUriContext); - assertNull(badUriRequest.getURI()); + assertThat(badUriRequest.getURI()).isNull(); } @@ -94,26 +93,27 @@ public class ContextAwareRequestTests { headers.put("header1", Collections.emptyList()); headers.put("header2", Arrays.asList("value1", "value2")); headers.put("header3", Arrays.asList("value1")); - assertEquals(headers, request.getHeaders()); + assertThat(request.getHeaders()).isEqualTo(headers); } @Test public void getLoadBalancerKey() throws Exception { - assertEquals("testLoadBalancerKey", request.getLoadBalancerKey()); + assertThat(request.getLoadBalancerKey()).isEqualTo("testLoadBalancerKey"); RibbonCommandContext defaultContext = mock(RibbonCommandContext.class); doReturn(new LinkedMultiValueMap()).when(defaultContext).getHeaders(); doReturn(null).when(defaultContext).getLoadBalancerKey(); ContextAwareRequest defaultRequest = new TestContextAwareRequest(defaultContext); - assertNull(defaultRequest.getLoadBalancerKey()); + assertThat(defaultRequest.getLoadBalancerKey()).isNull(); } static class TestContextAwareRequest extends ContextAwareRequest { - public TestContextAwareRequest(RibbonCommandContext context) { + TestContextAwareRequest(RibbonCommandContext context) { super(context); } + } -} \ No newline at end of file +} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/support/RibbonCommandContextTest.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/support/RibbonCommandContextTest.java index 5e21c41d1..8047dca11 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/support/RibbonCommandContextTest.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/support/RibbonCommandContextTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,22 +16,18 @@ package org.springframework.cloud.netflix.ribbon.support; -import okhttp3.Request; - import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Collections; + +import okhttp3.Request; import org.junit.Test; + import org.springframework.http.HttpMethod; import org.springframework.util.LinkedMultiValueMap; -import com.google.common.collect.Lists; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Andre Dörnbrack @@ -47,22 +43,22 @@ public class RibbonCommandContextTest { givenRibbonCommandContextIsSetup(); InputStream requestEntity = ribbonCommandContext.getRequestEntity(); - assertTrue(requestEntity instanceof ResettableServletInputStreamWrapper); + assertThat(requestEntity instanceof ResettableServletInputStreamWrapper).isTrue(); whenInputStreamIsConsumed(requestEntity); - assertEquals(-1, requestEntity.read()); + assertThat(requestEntity.read()).isEqualTo(-1); requestEntity.reset(); - assertNotEquals(-1, requestEntity.read()); + assertThat(requestEntity.read()).isNotEqualTo(-1); whenInputStreamIsConsumed(requestEntity); - assertEquals(-1, requestEntity.read()); + assertThat(requestEntity.read()).isEqualTo(-1); requestEntity.reset(); - assertNotEquals(-1, requestEntity.read()); + assertThat(requestEntity.read()).isNotEqualTo(-1); whenInputStreamIsConsumed(requestEntity); - assertEquals(-1, requestEntity.read()); + assertThat(requestEntity.read()).isEqualTo(-1); } private void whenInputStreamIsConsumed(InputStream requestEntity) throws IOException { @@ -90,7 +86,7 @@ public class RibbonCommandContextTest { ribbonCommandContext = new RibbonCommandContext("serviceId", HttpMethod.POST.toString(), "/my/route", true, headers, params, new ByteArrayInputStream(TEST_CONTENT), - Lists.newArrayList(requestCustomizer)); + Collections.singletonList(requestCustomizer)); } @Test @@ -100,10 +96,11 @@ public class RibbonCommandContextTest { RibbonCommandContext testContext = new RibbonCommandContext("serviceId", HttpMethod.POST.toString(), "/my/route", true, headers, params, - new ByteArrayInputStream(TEST_CONTENT), Collections.emptyList(), - null, null); + new ByteArrayInputStream(TEST_CONTENT), + Collections.emptyList(), null, null); - assertNotEquals(0, testContext.hashCode()); - assertNotNull(testContext.toString()); + assertThat(testContext.hashCode()).isNotEqualTo(0); + assertThat(testContext.toString()).isNotNull(); } -} \ No newline at end of file + +} diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/RibbonClientDefaultConfigurationTests.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/RibbonClientDefaultConfigurationTests.java index 8037ffed8..0b5cf34f8 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/RibbonClientDefaultConfigurationTests.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/RibbonClientDefaultConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,23 +16,22 @@ package org.springframework.cloud.netflix.ribbon.test; +import com.netflix.loadbalancer.BestAvailableRule; +import com.netflix.loadbalancer.PingUrl; +import com.netflix.loadbalancer.Server; +import com.netflix.loadbalancer.ServerListSubsetFilter; +import com.netflix.loadbalancer.ZoneAwareLoadBalancer; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.netflix.ribbon.SpringClientFactory; import org.springframework.cloud.netflix.ribbon.test.RibbonClientDefaultConfigurationTestsConfig.BazServiceList; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.netflix.loadbalancer.BestAvailableRule; -import com.netflix.loadbalancer.PingUrl; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerListSubsetFilter; -import com.netflix.loadbalancer.ZoneAwareLoadBalancer; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -48,20 +47,20 @@ public class RibbonClientDefaultConfigurationTests { @Test public void ruleOverridesDefault() throws Exception { - assertThat("wrong rule type", getLoadBalancer("baz").getRule(), - is(instanceOf(BestAvailableRule.class))); + assertThat(getLoadBalancer("baz").getRule()).as("wrong rule type") + .isInstanceOf(BestAvailableRule.class); } @Test public void pingOverridesDefault() throws Exception { - assertThat("wrong ping type", getLoadBalancer("baz").getPing(), - is(instanceOf(PingUrl.class))); + assertThat(getLoadBalancer("baz").getPing()).as("wrong ping type") + .isInstanceOf(PingUrl.class); } @Test public void serverListOverridesDefault() throws Exception { - assertThat("wrong server list type", getLoadBalancer("baz").getServerListImpl(), - is(instanceOf(BazServiceList.class))); + assertThat(getLoadBalancer("baz").getServerListImpl()) + .as("wrong server list type").isInstanceOf(BazServiceList.class); } @SuppressWarnings("unchecked") @@ -71,8 +70,8 @@ public class RibbonClientDefaultConfigurationTests { @Test public void serverListFilterOverride() throws Exception { - assertThat("wrong filter type", getLoadBalancer("baz").getFilter(), - is(instanceOf(ServerListSubsetFilter.class))); + assertThat(getLoadBalancer("baz").getFilter()).as("wrong filter type") + .isInstanceOf(ServerListSubsetFilter.class); } } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/RibbonClientDefaultConfigurationTestsConfig.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/RibbonClientDefaultConfigurationTestsConfig.java index fb1346ff2..f5cd6ef25 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/RibbonClientDefaultConfigurationTestsConfig.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/RibbonClientDefaultConfigurationTestsConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,20 +12,10 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.ribbon.test; -import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; -import org.springframework.cloud.commons.httpclient.HttpClientConfiguration; -import org.springframework.cloud.commons.util.UtilAutoConfiguration; -import org.springframework.cloud.netflix.archaius.ArchaiusAutoConfiguration; -import org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration; -import org.springframework.cloud.netflix.ribbon.RibbonClients; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.BestAvailableRule; import com.netflix.loadbalancer.ConfigurationBasedServerList; @@ -36,21 +26,35 @@ import com.netflix.loadbalancer.Server; import com.netflix.loadbalancer.ServerList; import com.netflix.loadbalancer.ServerListSubsetFilter; +import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; +import org.springframework.cloud.commons.httpclient.HttpClientConfiguration; +import org.springframework.cloud.commons.util.UtilAutoConfiguration; +import org.springframework.cloud.netflix.archaius.ArchaiusAutoConfiguration; +import org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration; +import org.springframework.cloud.netflix.ribbon.RibbonClients; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; + /** * @author Spencer Gibb */ @Configuration @Import({ PropertyPlaceholderAutoConfiguration.class, ArchaiusAutoConfiguration.class, - UtilAutoConfiguration.class, RibbonAutoConfiguration.class, HttpClientConfiguration.class }) + UtilAutoConfiguration.class, RibbonAutoConfiguration.class, + HttpClientConfiguration.class }) // tag::sample_default_ribbon_config[] @RibbonClients(defaultConfiguration = DefaultRibbonConfig.class) public class RibbonClientDefaultConfigurationTestsConfig { public static class BazServiceList extends ConfigurationBasedServerList { + public BazServiceList(IClientConfig config) { super.initWithNiwsConfig(config); } + } + } @Configuration @@ -78,4 +82,4 @@ class DefaultRibbonConfig { } } -// end::sample_default_ribbon_config[] \ No newline at end of file +// end::sample_default_ribbon_config[] diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/TestAutoConfiguration.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/TestAutoConfiguration.java index add2f2d9b..00eee7992 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/TestAutoConfiguration.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/TestAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,17 +34,18 @@ import org.springframework.security.provisioning.InMemoryUserDetailsManager; * @author Spencer Gibb */ @Configuration -@Import({NoopDiscoveryClientAutoConfiguration.class}) +@Import({ NoopDiscoveryClientAutoConfiguration.class }) @AutoConfigureBefore(SecurityAutoConfiguration.class) public class TestAutoConfiguration { public static final String USER = "user"; + public static final String PASSWORD = "{noop}password"; @Configuration @Order(Ordered.HIGHEST_PRECEDENCE) - protected static class TestSecurityConfiguration extends WebSecurityConfigurerAdapter { - + protected static class TestSecurityConfiguration + extends WebSecurityConfigurerAdapter { TestSecurityConfiguration() { super(true); @@ -53,18 +54,18 @@ public class TestAutoConfiguration { @Bean public UserDetailsService userDetailsService() { InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); - manager.createUser(User.withUsername(USER).password(PASSWORD).roles("USER").build()); + manager.createUser( + User.withUsername(USER).password(PASSWORD).roles("USER").build()); return manager; } @Override protected void configure(HttpSecurity http) throws Exception { // super.configure(http); - http.antMatcher("/proxy-username") - .httpBasic() - .and() - .authorizeRequests().antMatchers("/**").permitAll(); + http.antMatcher("/proxy-username").httpBasic().and().authorizeRequests() + .antMatchers("/**").permitAll(); } } + } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/TestLoadBalancer.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/TestLoadBalancer.java index 0de2ce21b..b9c4230c2 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/TestLoadBalancer.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/TestLoadBalancer.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,4 +23,5 @@ import com.netflix.loadbalancer.ZoneAwareLoadBalancer; * @author Spencer Gibb */ public class TestLoadBalancer extends ZoneAwareLoadBalancer { + } diff --git a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/TestServerList.java b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/TestServerList.java index 70335a180..e7e7dccb9 100644 --- a/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/TestServerList.java +++ b/spring-cloud-netflix-ribbon/src/test/java/org/springframework/cloud/netflix/ribbon/test/TestServerList.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,6 +18,7 @@ package org.springframework.cloud.netflix.ribbon.test; import java.util.ArrayList; import java.util.List; + import com.netflix.loadbalancer.Server; import com.netflix.loadbalancer.ServerList; @@ -45,4 +46,5 @@ public class TestServerList implements ServerList { public List getUpdatedListOfServers() { return servers; } + } diff --git a/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/LocalApplicationHealthCheckHandler.java b/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/LocalApplicationHealthCheckHandler.java index d6b53c2e0..7f7859622 100644 --- a/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/LocalApplicationHealthCheckHandler.java +++ b/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/LocalApplicationHealthCheckHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,26 +16,28 @@ package org.springframework.cloud.netflix.sidecar; +import com.netflix.appinfo.HealthCheckHandler; +import com.netflix.appinfo.InstanceInfo.InstanceStatus; + +import org.springframework.boot.actuate.health.HealthIndicator; +import org.springframework.boot.actuate.health.Status; + import static com.netflix.appinfo.InstanceInfo.InstanceStatus.DOWN; import static com.netflix.appinfo.InstanceInfo.InstanceStatus.OUT_OF_SERVICE; import static com.netflix.appinfo.InstanceInfo.InstanceStatus.UNKNOWN; import static com.netflix.appinfo.InstanceInfo.InstanceStatus.UP; -import com.netflix.appinfo.HealthCheckHandler; -import com.netflix.appinfo.InstanceInfo.InstanceStatus; -import org.springframework.boot.actuate.health.HealthIndicator; -import org.springframework.boot.actuate.health.Status; - /** - * Eureka HealthCheckHandler that translates boot health status to - * InstanceStatus so the proper status of the non-JVM app is sent to Eureka. -* @author Spencer Gibb -*/ + * Eureka HealthCheckHandler that translates boot health status to InstanceStatus so the + * proper status of the non-JVM app is sent to Eureka. + * + * @author Spencer Gibb + */ class LocalApplicationHealthCheckHandler implements HealthCheckHandler { private final HealthIndicator healthIndicator; - public LocalApplicationHealthCheckHandler(HealthIndicator healthIndicator) { + LocalApplicationHealthCheckHandler(HealthIndicator healthIndicator) { this.healthIndicator = healthIndicator; } @@ -44,11 +46,14 @@ class LocalApplicationHealthCheckHandler implements HealthCheckHandler { Status status = healthIndicator.health().getStatus(); if (status.equals(Status.UP)) { return UP; - } else if (status.equals(Status.OUT_OF_SERVICE)) { + } + else if (status.equals(Status.OUT_OF_SERVICE)) { return OUT_OF_SERVICE; - } else if (status.equals(Status.DOWN)) { + } + else if (status.equals(Status.DOWN)) { return DOWN; } return UNKNOWN; } + } diff --git a/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/LocalApplicationHealthIndicator.java b/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/LocalApplicationHealthIndicator.java index 6646b7871..49d7498ee 100644 --- a/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/LocalApplicationHealthIndicator.java +++ b/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/LocalApplicationHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,14 +16,14 @@ package org.springframework.cloud.netflix.sidecar; +import java.net.URI; +import java.util.Map; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.health.AbstractHealthIndicator; import org.springframework.boot.actuate.health.Health; import org.springframework.web.client.RestTemplate; -import java.net.URI; -import java.util.Map; - /** * @author Spencer Gibb * @author Fabrizio Di Napoli @@ -68,4 +68,5 @@ public class LocalApplicationHealthIndicator extends AbstractHealthIndicator { private Health.Builder getWarning(Health.Builder builder) { return builder.unknown().withDetail("warning", "no status field in response"); } + } diff --git a/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/SidecarConfiguration.java b/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/SidecarConfiguration.java index 0d6fb8b48..f57efe188 100644 --- a/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/SidecarConfiguration.java +++ b/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/SidecarConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,17 +16,20 @@ package org.springframework.cloud.netflix.sidecar; +import java.util.Map; + +import com.netflix.appinfo.HealthCheckHandler; +import com.netflix.discovery.EurekaClientConfig; import org.apache.http.client.HttpClient; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; -import static org.springframework.cloud.commons.util.IdUtils.getDefaultInstanceId; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.web.client.RestTemplateBuilder; @@ -41,29 +44,27 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.util.StringUtils; - -import com.netflix.appinfo.HealthCheckHandler; -import com.netflix.discovery.EurekaClientConfig; import org.springframework.web.client.RestTemplate; -import java.util.Map; +import static org.springframework.cloud.commons.util.IdUtils.getDefaultInstanceId; /** * Sidecar Configuration that setting up {@link com.netflix.appinfo.EurekaInstanceConfig}. *

- * Depends on {@link SidecarProperties} and {@code eureka.instance.hostname} property. Since there is two way to - * configure hostname: + * Depends on {@link SidecarProperties} and {@code eureka.instance.hostname} property. + * Since there is two way to configure hostname: *

    - *
  1. {@code eureka.instance.hostname} property
  2. - *
  3. {@link SidecarProperties#hostname}
  4. + *
  5. {@code eureka.instance.hostname} property
  6. + *
  7. {@link SidecarProperties#hostname}
  8. *
- * {@code eureka.instance.hostname} will always win against {@link SidecarProperties#hostname} due to - * {@code @ConfigurationProperties("eureka.instance")} on {@link EurekaInstanceConfigBeanConfiguration}. + * {@code eureka.instance.hostname} will always win against + * {@link SidecarProperties#hostname} due to + * {@code @ConfigurationProperties("eureka.instance")} on + * {@link EurekaInstanceConfigBeanConfiguration}. * * @author Spencer Gibb * @author Ryan Baxter * @author Fabrizio Di Napoli - * * @see EurekaInstanceConfigBeanConfiguration */ @Configuration @@ -81,16 +82,47 @@ public class SidecarConfiguration { return new SidecarProperties(); } + @Bean + @ConditionalOnMissingClass("org.apache.http.client.HttpClient") + public RestTemplate restTemplate() { + return new RestTemplateBuilder().build(); + } + + @Bean + @ConditionalOnClass(HttpClient.class) + public RestTemplate sslRestTemplate(SidecarProperties properties) { + RestTemplateBuilder builder = new RestTemplateBuilder(); + if (properties.acceptAllSslCertificates()) { + CloseableHttpClient httpClient = HttpClients.custom() + .setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); + HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); + requestFactory.setHttpClient(httpClient); + builder = builder.requestFactory(() -> requestFactory); + } + return builder.build(); + } + + @Bean + public LocalApplicationHealthIndicator localApplicationHealthIndicator() { + return new LocalApplicationHealthIndicator(); + } + + @Bean + public SidecarController sidecarController() { + return new SidecarController(); + } + @Configuration @ConditionalOnClass(EurekaClientConfig.class) protected static class EurekaInstanceConfigBeanConfiguration { + @Autowired private SidecarProperties sidecarProperties; @Autowired private InetUtils inetUtils; - @Value(value = "${management.server.port:${MANAGEMENT_PORT:#{null}}}") + @Value("${management.server.port:${MANAGEMENT_PORT:#{null}}}") private Integer managementPort; @Value("${server.port:${SERVER_PORT:${PORT:8080}}}") @@ -115,7 +147,8 @@ public class SidecarConfiguration { } @Bean - public EurekaInstanceConfigBean eurekaInstanceConfigBean(ManagementMetadataProvider managementMetadataProvider) { + public EurekaInstanceConfigBean eurekaInstanceConfigBean( + ManagementMetadataProvider managementMetadataProvider) { EurekaInstanceConfigBean config = new EurekaInstanceConfigBean(inetUtils); String springAppName = this.env.getProperty("spring.application.name", ""); int port = this.sidecarProperties.getPort(); @@ -139,19 +172,18 @@ public class SidecarConfiguration { config.setIpAddress(ipAddress); } String scheme = config.getSecurePortEnabled() ? "https" : "http"; - ManagementMetadata metadata = managementMetadataProvider.get(config, serverPort, - serverContextPath, managementContextPath, managementPort); + ManagementMetadata metadata = managementMetadataProvider.get(config, + serverPort, serverContextPath, managementContextPath, managementPort); - if(metadata != null) { + if (metadata != null) { config.setStatusPageUrl(metadata.getStatusPageUrl()); config.setHealthCheckUrl(metadata.getHealthCheckUrl()); - if(config.isSecurePortEnabled()) { + if (config.isSecurePortEnabled()) { config.setSecureHealthCheckUrl(metadata.getSecureHealthCheckUrl()); } Map metadataMap = config.getMetadataMap(); - if (metadataMap.get("management.port") == null) { - metadataMap.put("management.port", String.valueOf(metadata.getManagementPort())); - } + metadataMap.computeIfAbsent("management.port", + k -> String.valueOf(metadata.getManagementPort())); } config.setHomePageUrl(scheme + "://" + config.getHostname() + ":" + port + config.getHomePageUrlPath()); @@ -163,37 +195,7 @@ public class SidecarConfiguration { final LocalApplicationHealthIndicator healthIndicator) { return new LocalApplicationHealthCheckHandler(healthIndicator); } - } - @Bean - @ConditionalOnMissingClass("org.apache.http.client.HttpClient") - public RestTemplate restTemplate() { - return new RestTemplateBuilder().build(); - } - - @Bean - @ConditionalOnClass(HttpClient.class) - public RestTemplate sslRestTemplate(SidecarProperties properties) { - RestTemplateBuilder builder = new RestTemplateBuilder(); - if(properties.acceptAllSslCertificates()) { - CloseableHttpClient httpClient = HttpClients.custom() - .setSSLHostnameVerifier(new NoopHostnameVerifier()) - .build(); - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); - requestFactory.setHttpClient(httpClient); - builder = builder.requestFactory(() -> requestFactory); - } - return builder.build(); - } - - @Bean - public LocalApplicationHealthIndicator localApplicationHealthIndicator() { - return new LocalApplicationHealthIndicator(); - } - - @Bean - public SidecarController sidecarController() { - return new SidecarController(); } } diff --git a/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/SidecarProperties.java b/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/SidecarProperties.java index 894e1083b..7c41476c3 100644 --- a/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/SidecarProperties.java +++ b/spring-cloud-netflix-sidecar/src/main/java/org/springframework/cloud/netflix/sidecar/SidecarProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -106,36 +106,37 @@ public class SidecarProperties { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } SidecarProperties that = (SidecarProperties) o; - return Objects.equals(healthUri, that.healthUri) && - Objects.equals(homePageUri, that.homePageUri) && - port == that.port && - Objects.equals(securePortEnabled, that.securePortEnabled) && - Objects.equals(hostname, that.hostname) && - Objects.equals(ipAddress, that.ipAddress) && - Objects.equals(acceptAllSslCertificates, that.acceptAllSslCertificates); + return Objects.equals(healthUri, that.healthUri) + && Objects.equals(homePageUri, that.homePageUri) && port == that.port + && Objects.equals(securePortEnabled, that.securePortEnabled) + && Objects.equals(hostname, that.hostname) + && Objects.equals(ipAddress, that.ipAddress) && Objects + .equals(acceptAllSslCertificates, that.acceptAllSslCertificates); } @Override public int hashCode() { - return Objects.hash( - healthUri, homePageUri, port, hostname, ipAddress,acceptAllSslCertificates, securePortEnabled - ); + return Objects.hash(healthUri, homePageUri, port, hostname, ipAddress, + acceptAllSslCertificates, securePortEnabled); } @Override public String toString() { - return new StringBuilder("SidecarProperties{") - .append("healthUri=").append(healthUri).append(", ") - .append("homePageUri=").append(homePageUri).append(", ") - .append("port=").append(port).append(", ") - .append("hostname='").append(hostname).append("', ") - .append("ipAddress='").append(ipAddress).append("', ") - .append("securePortEnabled='").append(securePortEnabled).append("', ") - .append("acceptAllSslCertificates='").append(acceptAllSslCertificates).append("'}") - .toString(); + return new StringBuilder("SidecarProperties{").append("healthUri=") + .append(healthUri).append(", ").append("homePageUri=").append(homePageUri) + .append(", ").append("port=").append(port).append(", ") + .append("hostname='").append(hostname).append("', ").append("ipAddress='") + .append(ipAddress).append("', ").append("securePortEnabled='") + .append(securePortEnabled).append("', ") + .append("acceptAllSslCertificates='").append(acceptAllSslCertificates) + .append("'}").toString(); } } diff --git a/spring-cloud-netflix-sidecar/src/test/java/org/springframework/cloud/netflix/sidecar/LocalApplicationHealthCheckHandlerTests.java b/spring-cloud-netflix-sidecar/src/test/java/org/springframework/cloud/netflix/sidecar/LocalApplicationHealthCheckHandlerTests.java index caf4b376c..a31d631a5 100644 --- a/spring-cloud-netflix-sidecar/src/test/java/org/springframework/cloud/netflix/sidecar/LocalApplicationHealthCheckHandlerTests.java +++ b/spring-cloud-netflix-sidecar/src/test/java/org/springframework/cloud/netflix/sidecar/LocalApplicationHealthCheckHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,17 +16,18 @@ package org.springframework.cloud.netflix.sidecar; -import static org.junit.Assert.assertEquals; -import static org.mockito.MockitoAnnotations.initMocks; -import static org.mockito.BDDMockito.*; - import com.netflix.appinfo.InstanceInfo.InstanceStatus; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; + import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.MockitoAnnotations.initMocks; + /** * @author Spencer Gibb */ @@ -63,8 +64,10 @@ public class LocalApplicationHealthCheckHandlerTests { private void assertStatus(InstanceStatus expected, Health.Builder builder) { given(healthIndicator.health()).willReturn(builder.build()); - LocalApplicationHealthCheckHandler handler = new LocalApplicationHealthCheckHandler(healthIndicator); + LocalApplicationHealthCheckHandler handler = new LocalApplicationHealthCheckHandler( + healthIndicator); InstanceStatus status = handler.getStatus(InstanceStatus.UP); - assertEquals(expected, status); + assertThat(status).isEqualTo(expected); } + } diff --git a/spring-cloud-netflix-sidecar/src/test/java/org/springframework/cloud/netflix/sidecar/SidecarApplication.java b/spring-cloud-netflix-sidecar/src/test/java/org/springframework/cloud/netflix/sidecar/SidecarApplication.java index 44f61adbd..ac175eae6 100644 --- a/spring-cloud-netflix-sidecar/src/test/java/org/springframework/cloud/netflix/sidecar/SidecarApplication.java +++ b/spring-cloud-netflix-sidecar/src/test/java/org/springframework/cloud/netflix/sidecar/SidecarApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.sidecar; @@ -39,19 +38,25 @@ public class SidecarApplication { @Bean public ManagementMetadataProvider managementMetadataProvider() { - //The default management metadata provider checks for random ports, we dont care about this in tests + // The default management metadata provider checks for random ports, we dont care + // about this in tests return new DefaultManagementMetadataProvider() { @Override - public ManagementMetadata get(EurekaInstanceConfigBean instance, int serverPort, String serverContextPath, String managementContextPath, Integer managementPort) { - String healthCheckUrl = getHealthCheckUrl(instance, serverPort, serverContextPath, - managementContextPath, managementPort, false); - String statusPageUrl = getStatusPageUrl(instance, serverPort, serverContextPath, - managementContextPath, managementPort); + public ManagementMetadata get(EurekaInstanceConfigBean instance, + int serverPort, String serverContextPath, + String managementContextPath, Integer managementPort) { + String healthCheckUrl = getHealthCheckUrl(instance, serverPort, + serverContextPath, managementContextPath, managementPort, false); + String statusPageUrl = getStatusPageUrl(instance, serverPort, + serverContextPath, managementContextPath, managementPort); - ManagementMetadata metadata = new ManagementMetadata(healthCheckUrl, statusPageUrl, managementPort == null ? serverPort : managementPort); - if(instance.isSecurePortEnabled()) { - metadata.setSecureHealthCheckUrl(getHealthCheckUrl(instance, serverPort, serverContextPath, - managementContextPath, managementPort, true)); + ManagementMetadata metadata = new ManagementMetadata(healthCheckUrl, + statusPageUrl, + managementPort == null ? serverPort : managementPort); + if (instance.isSecurePortEnabled()) { + metadata.setSecureHealthCheckUrl( + getHealthCheckUrl(instance, serverPort, serverContextPath, + managementContextPath, managementPort, true)); } return metadata; } diff --git a/spring-cloud-netflix-sidecar/src/test/java/org/springframework/cloud/netflix/sidecar/SidecarApplicationTests.java b/spring-cloud-netflix-sidecar/src/test/java/org/springframework/cloud/netflix/sidecar/SidecarApplicationTests.java index 307832933..06dbac0e6 100644 --- a/spring-cloud-netflix-sidecar/src/test/java/org/springframework/cloud/netflix/sidecar/SidecarApplicationTests.java +++ b/spring-cloud-netflix-sidecar/src/test/java/org/springframework/cloud/netflix/sidecar/SidecarApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,131 +16,154 @@ package org.springframework.cloud.netflix.sidecar; -import static org.junit.Assert.assertNull; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean; import org.springframework.test.context.junit4.SpringRunner; - -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; import org.springframework.web.client.RestTemplate; +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + public class SidecarApplicationTests { @RunWith(SpringRunner.class) @SpringBootTest(classes = SidecarApplication.class, webEnvironment = RANDOM_PORT, properties = { - "spring.application.name=mytest", "spring.cloud.client.hostname=mhhost", "spring.application.instance_id=1", - "eureka.instance.hostname=mhhost", "sidecar.port=7000", "sidecar.ip-address=127.0.0.1" }) + "spring.application.name=mytest", "spring.cloud.client.hostname=mhhost", + "spring.application.instance_id=1", "eureka.instance.hostname=mhhost", + "sidecar.port=7000", "sidecar.ip-address=127.0.0.1" }) public static class EurekaTestConfigBeanTest { + @Autowired EurekaInstanceConfigBean config; @Test public void testEurekaConfigBean() { - assertThat(this.config.getAppname(), equalTo("mytest")); - assertThat(this.config.getHostname(), equalTo("mhhost")); - assertThat(this.config.getInstanceId(), equalTo("mhhost:mytest:1")); - assertThat(this.config.getNonSecurePort(), equalTo(7000)); + assertThat(this.config.getAppname()).isEqualTo("mytest"); + assertThat(this.config.getHostname()).isEqualTo("mhhost"); + assertThat(this.config.getInstanceId()).isEqualTo("mhhost:mytest:1"); + assertThat(this.config.getNonSecurePort()).isEqualTo(7000); } + } @RunWith(SpringRunner.class) @SpringBootTest(classes = SidecarApplication.class, webEnvironment = RANDOM_PORT, properties = { - "spring.application.name=mytest", "spring.cloud.client.hostname=mhhost", "spring.application.instance_id=1", - "sidecar.hostname=mhhost", "sidecar.port=7000", "sidecar.ip-address=127.0.0.1" }) + "spring.application.name=mytest", "spring.cloud.client.hostname=mhhost", + "spring.application.instance_id=1", "sidecar.hostname=mhhost", + "sidecar.port=7000", "sidecar.ip-address=127.0.0.1" }) public static class NewPropertyEurekaTestConfigBeanTest { + @Autowired EurekaInstanceConfigBean config; @Test public void testEurekaConfigBean() { - assertThat(this.config.getAppname(), equalTo("mytest")); - assertThat(this.config.getHostname(), equalTo("mhhost")); - assertThat(this.config.getInstanceId(), equalTo("mhhost:mytest:1")); - assertThat(this.config.getNonSecurePort(), equalTo(7000)); + assertThat(config.getAppname()).isEqualTo("mytest"); + assertThat(config.getHostname()).isEqualTo("mhhost"); + assertThat(config.getInstanceId()).isEqualTo("mhhost:mytest:1"); + assertThat(config.getNonSecurePort()).isEqualTo(7000); } + } @RunWith(SpringRunner.class) @SpringBootTest(classes = SidecarApplication.class, webEnvironment = RANDOM_PORT, properties = { - "spring.application.name=mytest", "spring.cloud.client.hostname=mhhost", "spring.application.instance_id=1", - "eureka.instance.hostname=mhhost1", "sidecar.hostname=mhhost2", "sidecar.port=7000", "sidecar.ip-address=127.0.0.1" }) + "spring.application.name=mytest", "spring.cloud.client.hostname=mhhost", + "spring.application.instance_id=1", "eureka.instance.hostname=mhhost1", + "sidecar.hostname=mhhost2", "sidecar.port=7000", + "sidecar.ip-address=127.0.0.1" }) public static class BothPropertiesEurekaTestConfigBeanTest { + @Autowired EurekaInstanceConfigBean config; @Test public void testEurekaConfigBeanEurekaInstanceHostnamePropertyShouldBeUsed() { - assertThat(this.config.getAppname(), equalTo("mytest")); - assertThat(this.config.getHostname(), equalTo("mhhost1")); - assertThat(this.config.getInstanceId(), equalTo("mhhost:mytest:1")); - assertThat(this.config.getNonSecurePort(), equalTo(7000)); + assertThat(config.getAppname()).isEqualTo("mytest"); + assertThat(config.getHostname()).isEqualTo("mhhost1"); + assertThat(config.getInstanceId()).isEqualTo("mhhost:mytest:1"); + assertThat(config.getNonSecurePort()).isEqualTo(7000); } + } @RunWith(SpringRunner.class) @SpringBootTest(classes = SidecarApplication.class, webEnvironment = RANDOM_PORT, properties = { - "spring.application.name=mytest", "spring.cloud.client.hostname=mhhost", "spring.application.instance_id=1", - "eureka.instance.hostname=mhhost1", "sidecar.hostname=mhhost2", "sidecar.port=7000", "sidecar.ip-address=10.0.0.1", - "eureka.instance.prefer-ip-address=true"}) + "spring.application.name=mytest", "spring.cloud.client.hostname=mhhost", + "spring.application.instance_id=1", "eureka.instance.hostname=mhhost1", + "sidecar.hostname=mhhost2", "sidecar.port=7000", + "sidecar.ip-address=10.0.0.1", "eureka.instance.prefer-ip-address=true" }) public static class PreferIpAddressTest { + @Autowired EurekaInstanceConfigBean config; @Test public void testEurekaConfigBeanPreferIpAddress() { - assertThat(this.config.getAppname(), equalTo("mytest")); - assertThat(this.config.getHostname(), equalTo("10.0.0.1")); - assertThat(this.config.getInstanceId(), equalTo("mhhost:mytest:1")); - assertThat(this.config.getNonSecurePort(), equalTo(7000)); + assertThat(config.getAppname()).isEqualTo("mytest"); + assertThat(config.getHostname()).isEqualTo("10.0.0.1"); + assertThat(config.getInstanceId()).isEqualTo("mhhost:mytest:1"); + assertThat(config.getNonSecurePort()).isEqualTo(7000); } + } @RunWith(SpringRunner.class) @SpringBootTest(classes = SidecarApplication.class, webEnvironment = RANDOM_PORT, value = { - "spring.application.name=mytest", "spring.cloud.client.hostname=mhhost", "spring.application.instance_id=1", - "eureka.instance.hostname=mhhost1", "sidecar.hostname=mhhost2", "sidecar.port=7000", "sidecar.ipAddress=127.0.0.1", - "management.context-path=/foo"}) + "spring.application.name=mytest", "spring.cloud.client.hostname=mhhost", + "spring.application.instance_id=1", "eureka.instance.hostname=mhhost1", + "sidecar.hostname=mhhost2", "sidecar.port=7000", + "sidecar.ipAddress=127.0.0.1", "management.context-path=/foo" }) public static class ManagementContextPathStatusAndHealthCheckUrls { + @Autowired EurekaInstanceConfigBean config; public void testStatusAndHealthCheckUrls() { - assertThat(this.config.getStatusPageUrl(), equalTo("http://mhhost2:0/foo/info")); - assertThat(this.config.getHealthCheckUrl(), equalTo("http://mhhost2:0/foo/health")); + assertThat(config.getStatusPageUrl()).isEqualTo("http://mhhost2:0/foo/info"); + assertThat(config.getHealthCheckUrl()) + .isEqualTo("http://mhhost2:0/foo/health"); } + } @RunWith(SpringRunner.class) @SpringBootTest(classes = SidecarApplication.class, webEnvironment = RANDOM_PORT, value = { - "spring.application.name=mytest", "spring.cloud.client.hostname=mhhost", "spring.application.instance_id=1", - "eureka.instance.hostname=mhhost1", "sidecar.hostname=mhhost2", "sidecar.port=7000", "sidecar.ipAddress=127.0.0.1", - "server.context-path=/foo"}) + "spring.application.name=mytest", "spring.cloud.client.hostname=mhhost", + "spring.application.instance_id=1", "eureka.instance.hostname=mhhost1", + "sidecar.hostname=mhhost2", "sidecar.port=7000", + "sidecar.ipAddress=127.0.0.1", "server.context-path=/foo" }) public static class ServerContextPathStatusAndHealthCheckUrls { + @Autowired EurekaInstanceConfigBean config; @Test public void testStatusAndHealthCheckUrls() { - assertThat(this.config.getStatusPageUrl(), equalTo("http://mhhost2:0/foo/info")); - assertThat(this.config.getHealthCheckUrl(), equalTo("http://mhhost2:0/foo/health")); + assertThat(config.getStatusPageUrl()).isEqualTo("http://mhhost2:0/foo/info"); + assertThat(config.getHealthCheckUrl()) + .isEqualTo("http://mhhost2:0/foo/health"); } + } @RunWith(SpringRunner.class) - @SpringBootTest(classes = SidecarApplication.class, webEnvironment = RANDOM_PORT, value = {"sidecar.accept-all-ssl-certificates=false"}) + @SpringBootTest(classes = SidecarApplication.class, webEnvironment = RANDOM_PORT, value = { + "sidecar.accept-all-ssl-certificates=false" }) public static class AcceptAllSslCertificatesContext { + @Autowired RestTemplate restTemplate; @Test public void testUseRestTemplateWhenHttpClientIsNotAvailable() { - assertNull(restTemplate.getRequestFactory()); + assertThat(restTemplate.getRequestFactory()).isNull(); } + } @RunWith(SpringRunner.class) @@ -148,12 +171,15 @@ public class SidecarApplicationTests { "sidecar.port=7000", "sidecar.ip-address=127.0.0.1", "sidecar.secure-port-enabled=true" }) public static class SecurePortEnabled { + @Autowired EurekaInstanceConfigBean config; @Test public void testThatSecureEnabledOptionIsSetFromPropertyFile() { - assertThat(this.config.isSecurePortEnabled(), equalTo(true)); + assertThat(this.config.isSecurePortEnabled()).isEqualTo(true); } + } + } diff --git a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/EnableTurbineStream.java b/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/EnableTurbineStream.java index b4d3de829..5b367b12b 100644 --- a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/EnableTurbineStream.java +++ b/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/EnableTurbineStream.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,8 @@ import java.lang.annotation.Target; import org.springframework.context.annotation.Import; /** - * Run the RxNetty based Spring Cloud Turbine Stream server. - * Based on Netflix Turbine 2 and Spring Cloud Stream + * Run the RxNetty based Spring Cloud Turbine Stream server. Based on Netflix Turbine 2 + * and Spring Cloud Stream * * @author Spencer Gibb */ diff --git a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/HystrixStreamAggregator.java b/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/HystrixStreamAggregator.java index f67bd72b7..c50475640 100644 --- a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/HystrixStreamAggregator.java +++ b/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/HystrixStreamAggregator.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,9 +22,9 @@ import java.util.List; import java.util.Map; import com.fasterxml.jackson.databind.ObjectMapper; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import rx.subjects.PublishSubject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.integration.annotation.ServiceActivator; @@ -32,8 +32,6 @@ import org.springframework.messaging.handler.annotation.Payload; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; -import rx.subjects.PublishSubject; - /** * @author Spencer Gibb */ diff --git a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineApplication.java b/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineApplication.java index 2fa397024..143110aeb 100644 --- a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineApplication.java +++ b/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineApplication.java @@ -1,17 +1,39 @@ +/* + * Copyright 2015-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.springframework.cloud.netflix.turbine.stream; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.annotation.Configuration; +/** + * Turbine application class. + * + * @author Dave Syer + * @author Spencer Gibb + */ @Configuration @EnableAutoConfiguration @EnableTurbineStream public class TurbineApplication { public static void main(String[] args) { - new SpringApplicationBuilder(TurbineApplication.class).properties( - "spring.config.name=turbine").run(args); + new SpringApplicationBuilder(TurbineApplication.class) + .properties("spring.config.name=turbine").run(args); } } diff --git a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineController.java b/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineController.java index 3817ee9d3..f98a785ac 100644 --- a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineController.java +++ b/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineController.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,35 +25,44 @@ import com.netflix.turbine.aggregator.StreamAggregator; import com.netflix.turbine.internal.JsonUtility; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.springframework.http.MediaType; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; - import reactor.core.publisher.Flux; import rx.Observable; import rx.RxReactiveStreams; import rx.subjects.PublishSubject; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * Turbine stream controller. + * + * @author Spencer Gibb + * @author Ryan Baxter + */ @RestController public class TurbineController { - private static final Log log = LogFactory.getLog(TurbineController.class); - private final Flux flux; + private static final Log log = LogFactory.getLog(TurbineController.class); - public TurbineController(PublishSubject> hystrixSubject) { - Observable> stream = StreamAggregator.aggregateGroupedStreams(hystrixSubject.groupBy( - data -> InstanceKey.create((String) data.get("instanceId")))) - .doOnUnsubscribe(() -> log.info("Unsubscribing aggregation.")) - .doOnSubscribe(() -> log.info("Starting aggregation")).flatMap(o -> o); - Flux> ping = Flux.interval(Duration.ofSeconds(5), Duration.ofSeconds(10)) - .map(l -> Collections.singletonMap("type", (Object) "ping")) - .share(); - flux = Flux.merge(RxReactiveStreams.toPublisher(stream), ping) - .share().map(map -> JsonUtility.mapToJson(map)); - } + private final Flux flux; + + public TurbineController(PublishSubject> hystrixSubject) { + Observable> stream = StreamAggregator + .aggregateGroupedStreams(hystrixSubject.groupBy( + data -> InstanceKey.create((String) data.get("instanceId")))) + .doOnUnsubscribe(() -> log.info("Unsubscribing aggregation.")) + .doOnSubscribe(() -> log.info("Starting aggregation")).flatMap(o -> o); + Flux> ping = Flux + .interval(Duration.ofSeconds(5), Duration.ofSeconds(10)) + .map(l -> Collections.singletonMap("type", (Object) "ping")).share(); + flux = Flux.merge(RxReactiveStreams.toPublisher(stream), ping).share() + .map(map -> JsonUtility.mapToJson(map)); + } + + @GetMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE) + public Flux stream() { + return this.flux; + } - @GetMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE) - public Flux stream() { - return this.flux; - } } diff --git a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamAutoConfiguration.java b/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamAutoConfiguration.java index ecdb026cc..746918bf6 100644 --- a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamAutoConfiguration.java +++ b/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,7 @@ import java.util.Map; import javax.annotation.PostConstruct; import com.fasterxml.jackson.databind.ObjectMapper; +import rx.subjects.PublishSubject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; @@ -31,8 +32,6 @@ import org.springframework.cloud.stream.config.BindingServiceProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import rx.subjects.PublishSubject; - /** * Autoconfiguration for a Spring Cloud Turbine using Spring Cloud Stream. Enabled by * default if spring-cloud-stream is on the classpath, and can be switched off with diff --git a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamClient.java b/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamClient.java index 1e727b739..07c2e0578 100644 --- a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamClient.java +++ b/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamClient.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,12 @@ import org.springframework.messaging.SubscribableChannel; */ public interface TurbineStreamClient { + /** + * Turbine Stream Input name. + */ String INPUT = "turbineStreamInput"; @Input(INPUT) SubscribableChannel turbineStreamInput(); + } diff --git a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamConfiguration.java b/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamConfiguration.java index 69b2a899e..d32a475d9 100644 --- a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamConfiguration.java +++ b/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,6 +32,7 @@ import org.springframework.context.annotation.Configuration; @Configuration @EnableConfigurationProperties(TurbineStreamProperties.class) public class TurbineStreamConfiguration { + @Bean public HasFeatures Feature() { return HasFeatures.namedFeature("Turbine (Stream)", @@ -44,7 +45,8 @@ public class TurbineStreamConfiguration { } @Bean - public TurbineController turbineController(PublishSubject> hystrixSubject) { + public TurbineController turbineController( + PublishSubject> hystrixSubject) { return new TurbineController(hystrixSubject); } diff --git a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamProperties.java b/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamProperties.java index c1deec9d1..086ea8369 100644 --- a/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamProperties.java +++ b/spring-cloud-netflix-turbine-stream/src/main/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,6 @@ package org.springframework.cloud.netflix.turbine.stream; import java.util.Objects; -import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.netflix.hystrix.HystrixConstants; import org.springframework.http.MediaType; @@ -52,10 +51,12 @@ public class TurbineStreamProperties { @Override public boolean equals(Object o) { - if (this == o) + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } TurbineStreamProperties that = (TurbineStreamProperties) o; return Objects.equals(destination, that.destination) && Objects.equals(contentType, that.contentType); @@ -68,8 +69,8 @@ public class TurbineStreamProperties { @Override public String toString() { - return new StringBuilder("TurbineStreamProperties{") - .append(", ").append("destination='").append(destination).append("', ") + return new StringBuilder("TurbineStreamProperties{").append(", ") + .append("destination='").append(destination).append("', ") .append("contentType='").append(contentType).append("'}").toString(); } diff --git a/spring-cloud-netflix-turbine-stream/src/test/java/org/springframework/cloud/netflix/turbine/stream/HystrixStreamAggregatorTests.java b/spring-cloud-netflix-turbine-stream/src/test/java/org/springframework/cloud/netflix/turbine/stream/HystrixStreamAggregatorTests.java index 318c90dec..bdac1e9de 100644 --- a/spring-cloud-netflix-turbine-stream/src/test/java/org/springframework/cloud/netflix/turbine/stream/HystrixStreamAggregatorTests.java +++ b/spring-cloud-netflix-turbine-stream/src/test/java/org/springframework/cloud/netflix/turbine/stream/HystrixStreamAggregatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,18 +19,15 @@ package org.springframework.cloud.netflix.turbine.stream; import java.util.Map; import com.fasterxml.jackson.databind.ObjectMapper; - import org.junit.Rule; import org.junit.Test; +import rx.subjects.PublishSubject; import org.springframework.boot.test.rule.OutputCapture; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.not; -import static org.junit.Assert.assertThat; - -import rx.subjects.PublishSubject; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.core.IsNot.not; public class HystrixStreamAggregatorTests { @@ -44,10 +41,41 @@ public class HystrixStreamAggregatorTests { @Rule public OutputCapture output = new OutputCapture(); + private static String PAYLOAD = "{\"origin\":{\"host\":\"dsyer\",\"port\":-1," + + "\"serviceId\":\"application\",\"id\":\"application\"},\"data\":{\"type\":" + + "\"HystrixCommand\",\"name\":\"application.ok\",\"group\":\"MyService\"," + + "\"currentTime\":1457089387160,\"isCircuitBreakerOpen\":false," + + "\"errorPercentage\":0,\"errorCount\":0,\"requestCount\":0," + + "\"rollingCountCollapsedRequests\":0,\"rollingCountExceptionsThrown\":0," + + "\"rollingCountFailure\":0,\"rollingCountFallbackFailure\":0," + + "\"rollingCountFallbackRejection\":0,\"rollingCountFallbackSuccess\":0," + + "\"rollingCountResponsesFromCache\":0,\"rollingCountSemaphoreRejected\":0," + + "\"rollingCountShortCircuited\":0,\"rollingCountSuccess\":1," + + "\"rollingCountThreadPoolRejected\":0,\"rollingCountTimeout\":0," + + "\"currentConcurrentExecutionCount\":0,\"latencyExecute_mean\":0," + + "\"latencyExecute\":{\"0\":0,\"25\":0,\"50\":0,\"75\":0,\"90\":0,\"95\":0," + + "\"99\":0,\"99.5\":0,\"100\":0},\"latencyTotal_mean\":0,\"latencyTotal" + + "\":{\"0\":0,\"25\":0,\"50\":0,\"75\":0,\"90\":0,\"95\":0,\"99\":0,\"99.5" + + "\":0,\"100\":0},\"propertyValue_circuitBreakerRequestVolumeThreshold\":20," + + "\"propertyValue_circuitBreakerSleepWindowInMilliseconds\":5000," + + "\"propertyValue_circuitBreakerErrorThresholdPercentage\":50," + + "\"propertyValue_circuitBreakerForceOpen\":false," + + "\"propertyValue_circuitBreakerForceClosed\":false," + + "\"propertyValue_circuitBreakerEnabled\":true," + + "\"propertyValue_executionIsolationStrategy\":\"THREAD\"," + + "\"propertyValue_executionIsolationThreadTimeoutInMilliseconds\":1000," + + "\"propertyValue_executionIsolationThreadInterruptOnTimeout\":true," + + "\"propertyValue_executionIsolationThreadPoolKeyOverride\":null," + + "\"propertyValue_executionIsolationSemaphoreMaxConcurrentRequests\":10," + + "\"propertyValue_fallbackIsolationSemaphoreMaxConcurrentRequests\":10," + + "\"propertyValue_metricsRollingStatisticalWindowInMilliseconds\":10000," + + "\"propertyValue_requestCacheEnabled\":true," + + "\"propertyValue_requestLogEnabled\":true,\"reportingHosts\":1}}"; + @Test public void messageDecoded() throws Exception { this.publisher.subscribe(map -> { - assertThat(map.get("type"), equalTo("HystrixCommand")); + assertThat(map.get("type")).isEqualTo("HystrixCommand"); }); this.aggregator.sendToSubject(PAYLOAD.getBytes()); this.output.expect(not(containsString("ERROR"))); @@ -56,16 +84,17 @@ public class HystrixStreamAggregatorTests { @Test public void messageWrappedInArray() throws Exception { this.publisher.subscribe(map -> { - assertThat(map.get("type"), equalTo("HystrixCommand")); + assertThat(map.get("type")).isEqualTo("HystrixCommand"); }); - this.aggregator.sendToSubject(new StringBuilder().append("[").append(PAYLOAD).append("]").toString().getBytes()); + this.aggregator.sendToSubject(new StringBuilder().append("[").append(PAYLOAD) + .append("]").toString().getBytes()); this.output.expect(not(containsString("ERROR"))); } @Test public void doubleEncodedMessage() throws Exception { this.publisher.subscribe(map -> { - assertThat(map.get("type"), equalTo("HystrixCommand")); + assertThat(map.get("type")).isEqualTo("HystrixCommand"); }); // If The JSON is embedded in a JSON String this is what it looks like String payload = "\"" + PAYLOAD.replace("\"", "\\\"") + "\""; @@ -73,5 +102,4 @@ public class HystrixStreamAggregatorTests { this.output.expect(not(containsString("ERROR"))); } - private static String PAYLOAD = "{\"origin\":{\"host\":\"dsyer\",\"port\":-1,\"serviceId\":\"application\",\"id\":\"application\"},\"data\":{\"type\":\"HystrixCommand\",\"name\":\"application.ok\",\"group\":\"MyService\",\"currentTime\":1457089387160,\"isCircuitBreakerOpen\":false,\"errorPercentage\":0,\"errorCount\":0,\"requestCount\":0,\"rollingCountCollapsedRequests\":0,\"rollingCountExceptionsThrown\":0,\"rollingCountFailure\":0,\"rollingCountFallbackFailure\":0,\"rollingCountFallbackRejection\":0,\"rollingCountFallbackSuccess\":0,\"rollingCountResponsesFromCache\":0,\"rollingCountSemaphoreRejected\":0,\"rollingCountShortCircuited\":0,\"rollingCountSuccess\":1,\"rollingCountThreadPoolRejected\":0,\"rollingCountTimeout\":0,\"currentConcurrentExecutionCount\":0,\"latencyExecute_mean\":0,\"latencyExecute\":{\"0\":0,\"25\":0,\"50\":0,\"75\":0,\"90\":0,\"95\":0,\"99\":0,\"99.5\":0,\"100\":0},\"latencyTotal_mean\":0,\"latencyTotal\":{\"0\":0,\"25\":0,\"50\":0,\"75\":0,\"90\":0,\"95\":0,\"99\":0,\"99.5\":0,\"100\":0},\"propertyValue_circuitBreakerRequestVolumeThreshold\":20,\"propertyValue_circuitBreakerSleepWindowInMilliseconds\":5000,\"propertyValue_circuitBreakerErrorThresholdPercentage\":50,\"propertyValue_circuitBreakerForceOpen\":false,\"propertyValue_circuitBreakerForceClosed\":false,\"propertyValue_circuitBreakerEnabled\":true,\"propertyValue_executionIsolationStrategy\":\"THREAD\",\"propertyValue_executionIsolationThreadTimeoutInMilliseconds\":1000,\"propertyValue_executionIsolationThreadInterruptOnTimeout\":true,\"propertyValue_executionIsolationThreadPoolKeyOverride\":null,\"propertyValue_executionIsolationSemaphoreMaxConcurrentRequests\":10,\"propertyValue_fallbackIsolationSemaphoreMaxConcurrentRequests\":10,\"propertyValue_metricsRollingStatisticalWindowInMilliseconds\":10000,\"propertyValue_requestCacheEnabled\":true,\"propertyValue_requestLogEnabled\":true,\"reportingHosts\":1}}"; } diff --git a/spring-cloud-netflix-turbine-stream/src/test/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamConfigurationTest.java b/spring-cloud-netflix-turbine-stream/src/test/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamConfigurationTest.java index 382795607..b3d705be2 100644 --- a/spring-cloud-netflix-turbine-stream/src/test/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamConfigurationTest.java +++ b/spring-cloud-netflix-turbine-stream/src/test/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamConfigurationTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,26 +16,20 @@ package org.springframework.cloud.netflix.turbine.stream; -import org.junit.Before; -import org.junit.Test; -import rx.Observable; -import rx.functions.Func1; - import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.NoSuchElementException; -import static org.junit.Assert.assertEquals; +import org.junit.Before; /** * @author Yongsung Yoon */ public class TurbineStreamConfigurationTest { + TurbineStreamConfiguration turbineStreamConfiguration; + List> testMetricList; @Before @@ -44,7 +38,7 @@ public class TurbineStreamConfigurationTest { testMetricList = createBasicTestMetricList(); } - private List> createBasicTestMetricList() { + private List> createBasicTestMetricList() { List> testDataList = new ArrayList<>(); HashMap map = new HashMap<>(); map.put("instanceId", "abc:127.0.0.1:8080"); @@ -71,4 +65,5 @@ public class TurbineStreamConfigurationTest { return testDataList; } + } diff --git a/spring-cloud-netflix-turbine-stream/src/test/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamTests.java b/spring-cloud-netflix-turbine-stream/src/test/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamTests.java index db16edabc..0ea44d13b 100644 --- a/spring-cloud-netflix-turbine-stream/src/test/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamTests.java +++ b/spring-cloud-netflix-turbine-stream/src/test/java/org/springframework/cloud/netflix/turbine/stream/TurbineStreamTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.turbine.stream; @@ -69,9 +68,10 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen // https://github.com/spring-cloud/spring-cloud-netflix/issues/1948 "spring.cloud.stream.bindings.turbineStreamInput.destination=hystrixStreamOutput", "spring.jmx.enabled=true", "stubrunner.workOffline=true", - "stubrunner.ids=org.springframework.cloud:spring-cloud-netflix-hystrix-stream:${projectVersion:2.0.0.BUILD-SNAPSHOT}:stubs"}) + "stubrunner.ids=org.springframework.cloud:spring-cloud-netflix-hystrix-stream:${projectVersion:2.0.0.BUILD-SNAPSHOT}:stubs" }) @AutoConfigureStubRunner(stubsMode = StubsMode.LOCAL) public class TurbineStreamTests { + @Autowired StubTrigger stubTrigger; @@ -90,40 +90,21 @@ public class TurbineStreamTests { @LocalServerPort int port; - @EnableAutoConfiguration - @EnableTurbineStream - public static class Application { - // Workaround for stub runner lowercasing id somewhere - @Bean - BeanDefinitionRegistryPostProcessor myBeanDefinitionRegistryPostProcessor() { - return new BeanDefinitionRegistryPostProcessor() { - @Override - public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { - BeanDefinition beanDefinition = registry.getBeanDefinition(TurbineStreamClient.INPUT); - registry.registerBeanDefinition(TurbineStreamClient.INPUT.toLowerCase(), beanDefinition); - } - - @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } - }; - } - } - @Test public void contextLoads() throws Exception { rest.getInterceptors().add(new NonClosingInterceptor()); int count = ((MessageChannelMetrics) input).getSendCount(); ResponseEntity response = rest.execute( - new URI("http://localhost:" + port + "/"), - HttpMethod.GET, null, this::extract); - assertThat(response.getHeaders().getContentType().isCompatibleWith(MediaType.TEXT_EVENT_STREAM)) - .isTrue(); + new URI("http://localhost:" + port + "/"), HttpMethod.GET, null, + this::extract); + assertThat(response.getHeaders().getContentType() + .isCompatibleWith(MediaType.TEXT_EVENT_STREAM)).isTrue(); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); Map metrics = extractMetrics(response.getBody()); assertThat(metrics).containsEntry("type", "HystrixCommand"); assertThat(((MessageChannelMetrics) input).getSendCount()).isEqualTo(count + 1); } - + private boolean containsMetrics(String line) { return line.startsWith("data:") && !line.contains("Ping"); } @@ -162,17 +143,50 @@ public class TurbineStreamTests { .headers(response.getHeaders()).body(responseBody); } + @EnableAutoConfiguration + @EnableTurbineStream + public static class Application { + + // Workaround for stub runner lowercasing id somewhere + @Bean + BeanDefinitionRegistryPostProcessor myBeanDefinitionRegistryPostProcessor() { + return new BeanDefinitionRegistryPostProcessor() { + @Override + public void postProcessBeanDefinitionRegistry( + BeanDefinitionRegistry registry) throws BeansException { + BeanDefinition beanDefinition = registry + .getBeanDefinition(TurbineStreamClient.INPUT); + registry.registerBeanDefinition( + TurbineStreamClient.INPUT.toLowerCase(), beanDefinition); + } + + @Override + public void postProcessBeanFactory( + ConfigurableListableBeanFactory beanFactory) + throws BeansException { + } + }; + } + + } + /** * Special interceptor that prevents the response from being closed and allows us to * assert on the contents of an event stream. */ private class NonClosingInterceptor implements ClientHttpRequestInterceptor { + @Override + public ClientHttpResponse intercept(HttpRequest request, byte[] body, + ClientHttpRequestExecution execution) throws IOException { + return new NonClosingResponse(execution.execute(request, body)); + } + private class NonClosingResponse implements ClientHttpResponse { private ClientHttpResponse delegate; - public NonClosingResponse(ClientHttpResponse delegate) { + NonClosingResponse(ClientHttpResponse delegate) { this.delegate = delegate; } @@ -207,11 +221,6 @@ public class TurbineStreamTests { } - @Override - public ClientHttpResponse intercept(HttpRequest request, byte[] body, - ClientHttpRequestExecution execution) throws IOException { - return new NonClosingResponse(execution.execute(request, body)); - } - } + } diff --git a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/ClusterInformation.java b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/ClusterInformation.java index 92414a595..729cd2361 100644 --- a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/ClusterInformation.java +++ b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/ClusterInformation.java @@ -1,26 +1,48 @@ +/* + * Copyright 2013-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.springframework.cloud.netflix.turbine; import java.util.Objects; +/** + * @author Anastasiia Smirnova + * @author Ryan Baxter Contains cluster-relevant information, such as name and link. + */ public class ClusterInformation { - private String name; - private String link; + private String name; - public ClusterInformation(){}; + private String link; - public ClusterInformation(String name, String link) { - this.name = name; - this.link = link; - } + public ClusterInformation() { + } - public String getName() { - return name; - } + public ClusterInformation(String name, String link) { + this.name = name; + this.link = link; + } - public String getLink() { - return link; - } + public String getName() { + return name; + } + + public String getLink() { + return link; + } public void setName(String name) { this.name = name; @@ -30,25 +52,27 @@ public class ClusterInformation { this.link = link; } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - ClusterInformation that = (ClusterInformation) o; - return Objects.equals(name, that.name) && - Objects.equals(link, that.link); - } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ClusterInformation that = (ClusterInformation) o; + return Objects.equals(name, that.name) && Objects.equals(link, that.link); + } - @Override - public int hashCode() { - return Objects.hash(name, link); - } + @Override + public int hashCode() { + return Objects.hash(name, link); + } + + @Override + public String toString() { + return "ClusterInformation{" + "name='" + name + '\'' + ", link='" + link + '\'' + + '}'; + } - @Override - public String toString() { - return "ClusterInformation{" + - "name='" + name + '\'' + - ", link='" + link + '\'' + - '}'; - } } diff --git a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/CommonsInstanceDiscovery.java b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/CommonsInstanceDiscovery.java index 333d6ac65..3cc59c966 100644 --- a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/CommonsInstanceDiscovery.java +++ b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/CommonsInstanceDiscovery.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,24 +21,24 @@ import java.util.Collection; import java.util.List; import java.util.Map; +import com.netflix.turbine.discovery.Instance; +import com.netflix.turbine.discovery.InstanceDiscovery; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.expression.Expression; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; -import com.netflix.turbine.discovery.Instance; -import com.netflix.turbine.discovery.InstanceDiscovery; - /** - * Class that encapsulates an {@link InstanceDiscovery} - * implementation that uses Spring Cloud Commons (see https://github.com/spring-cloud/spring-cloud-commons) - * The plugin requires a list of applications configured. It then queries the set of - * instances for * each application. Instance information retrieved from the {@link DiscoveryClient} - * must be translated to * something that Turbine can understand i.e the - * {@link Instance} class. + * Class that encapsulates an {@link InstanceDiscovery} implementation that uses Spring + * Cloud Commons (see https://github.com/spring-cloud/spring-cloud-commons) The plugin + * requires a list of applications configured. It then queries the set of instances for * + * each application. Instance information retrieved from the {@link DiscoveryClient} must + * be translated to * something that Turbine can understand i.e the {@link Instance} + * class. *

* All the logic to perform this translation can be overriden here, so that you can * provide your own implementation if needed. @@ -50,25 +50,32 @@ public class CommonsInstanceDiscovery implements InstanceDiscovery { private static final Log log = LogFactory.getLog(CommonsInstanceDiscovery.class); private static final String DEFAULT_CLUSTER_NAME_EXPRESSION = "serviceId"; + protected static final String PORT_KEY = "port"; + protected static final String SECURE_PORT_KEY = "securePort"; + protected static final String FUSED_HOST_PORT_KEY = "fusedHostPort"; private final Expression clusterNameExpression; + private DiscoveryClient discoveryClient; + private TurbineProperties turbineProperties; + private final boolean combineHostPort; - public CommonsInstanceDiscovery(TurbineProperties turbineProperties, DiscoveryClient discoveryClient) { + public CommonsInstanceDiscovery(TurbineProperties turbineProperties, + DiscoveryClient discoveryClient) { this(turbineProperties, DEFAULT_CLUSTER_NAME_EXPRESSION); this.discoveryClient = discoveryClient; } - protected CommonsInstanceDiscovery(TurbineProperties turbineProperties, String defaultExpression) { + protected CommonsInstanceDiscovery(TurbineProperties turbineProperties, + String defaultExpression) { this.turbineProperties = turbineProperties; SpelExpressionParser parser = new SpelExpressionParser(); - String clusterNameExpression = turbineProperties - .getClusterNameExpression(); + String clusterNameExpression = turbineProperties.getClusterNameExpression(); if (clusterNameExpression == null) { clusterNameExpression = defaultExpression; } @@ -89,8 +96,8 @@ public class CommonsInstanceDiscovery implements InstanceDiscovery { } /** - * Method that queries DiscoveryClient for a list of configured application names - * @return Collection + * Method that queries DiscoveryClient for a list of configured application names. + * @return Collection of instances */ @Override public Collection getInstanceList() throws Exception { @@ -126,9 +133,10 @@ public class CommonsInstanceDiscovery implements InstanceDiscovery { /** * helper that fetches the Instances for each application from DiscoveryClient. - * @param serviceId - * @return List - * @throws Exception + * @param serviceId Id of the service whose instances should be returned + * @return List of instances + * @throws Exception - retrieving and marshalling service instances may result in an + * Exception */ protected List getInstancesForApp(String serviceId) throws Exception { List instances = new ArrayList<>(); @@ -157,15 +165,16 @@ public class CommonsInstanceDiscovery implements InstanceDiscovery { /** * Private helper that marshals the information from each instance into something that * Turbine can understand. Override this method for your own implementation. - * @param serviceInstance + * @param serviceInstance whose information should be marshaled * @return Instance */ Instance marshall(ServiceInstance serviceInstance) { String hostname = serviceInstance.getHost(); - String managementPort = serviceInstance.getMetadata().get("management.port"); - String port = managementPort == null ? String.valueOf(serviceInstance.getPort()) : managementPort; + String managementPort = serviceInstance.getMetadata().get("management.port"); + String port = managementPort == null ? String.valueOf(serviceInstance.getPort()) + : managementPort; String cluster = getClusterName(serviceInstance); - Boolean status = Boolean.TRUE; //TODO: where to get? + Boolean status = Boolean.TRUE; // TODO: where to get? if (hostname != null && cluster != null && status != null) { Instance instance = getInstance(hostname, port, cluster, status); @@ -181,7 +190,8 @@ public class CommonsInstanceDiscovery implements InstanceDiscovery { } } - protected void addMetadata(Instance instance, String hostname, String port, boolean securePortEnabled, String securePort, Map metadata) { + protected void addMetadata(Instance instance, String hostname, String port, + boolean securePortEnabled, String securePort, Map metadata) { // add metadata if (metadata != null) { instance.getAttributes().putAll(metadata); @@ -193,20 +203,24 @@ public class CommonsInstanceDiscovery implements InstanceDiscovery { instance.getAttributes().put(SECURE_PORT_KEY, securePort); } if (this.isCombineHostPort()) { - String fusedHostPort = securePortEnabled ? hostname+":"+securePort : instance.getHostname() ; + String fusedHostPort = securePortEnabled ? hostname + ":" + securePort + : instance.getHostname(); instance.getAttributes().put(FUSED_HOST_PORT_KEY, fusedHostPort); } } - protected Instance getInstance(String hostname, String port, String cluster, Boolean status) { - String hostPart = this.isCombineHostPort() ? hostname+":"+port : hostname; + protected Instance getInstance(String hostname, String port, String cluster, + Boolean status) { + String hostPart = this.isCombineHostPort() ? hostname + ":" + port : hostname; return new Instance(hostPart, cluster, status); } /** - * Helper that fetches the cluster name. Cluster is a Turbine concept and not a commons - * concept. By default we choose the amazon serviceId as the cluster. A custom + * Helper that fetches the cluster name. Cluster is a Turbine concept and not a + * commons concept. By default we choose the amazon serviceId as the cluster. A custom * implementation can be plugged in by overriding this method. + * @param object cluster whose name should be evaluated + * @return String name of the cluster */ protected String getClusterName(Object object) { StandardEvaluationContext context = new StandardEvaluationContext(object); diff --git a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/ConfigurationBasedTurbineClustersProvider.java b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/ConfigurationBasedTurbineClustersProvider.java index 74c5baf6c..01acba7e8 100644 --- a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/ConfigurationBasedTurbineClustersProvider.java +++ b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/ConfigurationBasedTurbineClustersProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,22 +16,26 @@ package org.springframework.cloud.netflix.turbine; +import java.util.List; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import java.util.List; - /** * Provides clusters names for Turbine based on configuration value. * * @author Anastasiia Smirnova */ -public class ConfigurationBasedTurbineClustersProvider implements TurbineClustersProvider { +public class ConfigurationBasedTurbineClustersProvider + implements TurbineClustersProvider { + + private static final Log log = LogFactory + .getLog(ConfigurationBasedTurbineClustersProvider.class); - private static final Log log = LogFactory.getLog(ConfigurationBasedTurbineClustersProvider.class); private final TurbineAggregatorProperties properties; - public ConfigurationBasedTurbineClustersProvider(TurbineAggregatorProperties turbineAggregatorProperties) { + public ConfigurationBasedTurbineClustersProvider( + TurbineAggregatorProperties turbineAggregatorProperties) { this.properties = turbineAggregatorProperties; } @@ -41,4 +45,5 @@ public class ConfigurationBasedTurbineClustersProvider implements TurbineCluster log.trace("Using clusters names: " + clusterNames); return clusterNames; } + } diff --git a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/EurekaBasedTurbineClustersProvider.java b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/EurekaBasedTurbineClustersProvider.java index 879275105..63a9c70c3 100644 --- a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/EurekaBasedTurbineClustersProvider.java +++ b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/EurekaBasedTurbineClustersProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,15 +16,15 @@ package org.springframework.cloud.netflix.turbine; +import java.util.ArrayList; +import java.util.List; + import com.netflix.discovery.EurekaClient; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import java.util.ArrayList; -import java.util.List; - /** * Provides clusters names for Turbine based on applications names registered in Eureka. * @@ -32,7 +32,9 @@ import java.util.List; */ public class EurekaBasedTurbineClustersProvider implements TurbineClustersProvider { - private static final Log log = LogFactory.getLog(EurekaBasedTurbineClustersProvider.class); + private static final Log log = LogFactory + .getLog(EurekaBasedTurbineClustersProvider.class); + private final EurekaClient eurekaClient; public EurekaBasedTurbineClustersProvider(EurekaClient eurekaClient) { @@ -42,7 +44,8 @@ public class EurekaBasedTurbineClustersProvider implements TurbineClustersProvid @Override public List getClusterNames() { Applications applications = eurekaClient.getApplications(); - List registeredApplications = applications.getRegisteredApplications(); + List registeredApplications = applications + .getRegisteredApplications(); List appNames = new ArrayList<>(registeredApplications.size()); for (Application application : registeredApplications) { appNames.add(application.getName()); @@ -50,4 +53,5 @@ public class EurekaBasedTurbineClustersProvider implements TurbineClustersProvid log.trace("Using clusters names: " + appNames); return appNames; } + } diff --git a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/EurekaInstanceDiscovery.java b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/EurekaInstanceDiscovery.java index 426ce991c..0a1e95c2c 100644 --- a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/EurekaInstanceDiscovery.java +++ b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/EurekaInstanceDiscovery.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,21 +48,23 @@ public class EurekaInstanceDiscovery extends CommonsInstanceDiscovery { private static final Log log = LogFactory.getLog(EurekaInstanceDiscovery.class); private static final String EUREKA_DEFAULT_CLUSTER_NAME_EXPRESSION = "appName"; + private static final String ASG_KEY = "asg"; private final EurekaClient eurekaClient; - - public EurekaInstanceDiscovery(TurbineProperties turbineProperties, EurekaClient eurekaClient) { + public EurekaInstanceDiscovery(TurbineProperties turbineProperties, + EurekaClient eurekaClient) { super(turbineProperties, EUREKA_DEFAULT_CLUSTER_NAME_EXPRESSION); this.eurekaClient = eurekaClient; } /** * Private helper that fetches the Instances for each application. - * @param serviceId - * @return List - * @throws Exception + * @param serviceId of the service that the instance list should be returned for + * @return List of instances for a given service id + * @throws Exception - retrieving and marshalling service instances may result in an + * Exception */ @Override protected List getInstancesForApp(String serviceId) throws Exception { @@ -96,23 +98,26 @@ public class EurekaInstanceDiscovery extends CommonsInstanceDiscovery { * Private helper that marshals the information from each instance into something that * Turbine can understand. Override this method for your own implementation for * parsing Eureka info. - * @param instanceInfo - * @return Instance + * @param instanceInfo {@link InstanceInfo} to marshal + * @return {@link Instance} marshaled from provided {@link InstanceInfo} */ Instance marshall(InstanceInfo instanceInfo) { String hostname = instanceInfo.getHostName(); final String managementPort = instanceInfo.getMetadata().get("management.port"); - String port = managementPort == null ? String.valueOf(instanceInfo.getPort()) : managementPort; + String port = managementPort == null ? String.valueOf(instanceInfo.getPort()) + : managementPort; String cluster = getClusterName(instanceInfo); Boolean status = parseInstanceStatus(instanceInfo.getStatus()); if (hostname != null && cluster != null && status != null) { Instance instance = getInstance(hostname, port, cluster, status); Map metadata = instanceInfo.getMetadata(); - boolean securePortEnabled = instanceInfo.isPortEnabled(InstanceInfo.PortType.SECURE); + boolean securePortEnabled = instanceInfo + .isPortEnabled(InstanceInfo.PortType.SECURE); String securePort = String.valueOf(instanceInfo.getSecurePort()); - addMetadata(instance, hostname, port, securePortEnabled, securePort, metadata); + addMetadata(instance, hostname, port, securePortEnabled, securePort, + metadata); // add amazon metadata String asgName = instanceInfo.getASGName(); @@ -134,7 +139,9 @@ public class EurekaInstanceDiscovery extends CommonsInstanceDiscovery { } /** - * Helper that returns whether the instance is Up of Down + * Helper that returns whether the instance is Up of Down. + * @param status {@link InstanceStatus} instance to evaluate the status from + * @return {@code true} if {@link InstanceStatus} is UP */ protected Boolean parseInstanceStatus(InstanceStatus status) { if (status == null) { @@ -143,5 +150,4 @@ public class EurekaInstanceDiscovery extends CommonsInstanceDiscovery { return status == InstanceStatus.UP; } - } diff --git a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/SpringAggregatorFactory.java b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/SpringAggregatorFactory.java index efc53e524..ed2c05f86 100644 --- a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/SpringAggregatorFactory.java +++ b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/SpringAggregatorFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,7 +26,6 @@ import com.netflix.turbine.monitor.TurbineDataMonitor; import com.netflix.turbine.monitor.cluster.AggregateClusterMonitor; import com.netflix.turbine.monitor.cluster.ClusterMonitor; import com.netflix.turbine.monitor.cluster.ClusterMonitorFactory; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -35,7 +34,8 @@ import static com.netflix.turbine.monitor.cluster.AggregateClusterMonitor.Aggreg /** * @author Spencer Gibb */ -public class SpringAggregatorFactory implements ClusterMonitorFactory { +public class SpringAggregatorFactory + implements ClusterMonitorFactory { private static final Log log = LogFactory.getLog(SpringAggregatorFactory.class); @@ -46,8 +46,8 @@ public class SpringAggregatorFactory implements ClusterMonitorFactory + * @return {@link com.netflix.turbine.monitor.cluster.ClusterMonitor} + * {@link com.netflix.turbine.data.AggDataFromCluster} */ @Override public ClusterMonitor getClusterMonitor(String name) { @@ -73,7 +73,9 @@ public class SpringAggregatorFactory implements ClusterMonitorFactory clusterMonitor = (ClusterMonitor) findOrRegisterAggregateMonitor(clusterName); + + ClusterMonitor clusterMonitor = (ClusterMonitor) findOrRegisterAggregateMonitor( + clusterName); clusterMonitor.registerListenertoClusterMonitor(this.StaticListener); try { clusterMonitor.startMonitor(); @@ -87,7 +89,7 @@ public class SpringAggregatorFactory implements ClusterMonitorFactory getClusterNames(); + } diff --git a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineController.java b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineController.java index 3fb3a920d..789ec7d5f 100644 --- a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineController.java +++ b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineController.java @@ -1,12 +1,34 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.springframework.cloud.netflix.turbine; +import java.util.Collection; + +import javax.servlet.http.HttpServletRequest; + import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; -import javax.servlet.http.HttpServletRequest; -import java.util.Collection; - +/** + * Defines endpoints to use with the Turbine. + * + * @author Anastasiia Smirnova + */ @RestController public class TurbineController { diff --git a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineHttpConfiguration.java b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineHttpConfiguration.java index 53b89301e..90a74eba3 100644 --- a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineHttpConfiguration.java +++ b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineHttpConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,11 @@ package org.springframework.cloud.netflix.turbine; +import com.netflix.discovery.EurekaClient; +import com.netflix.turbine.discovery.InstanceDiscovery; import com.netflix.turbine.monitor.cluster.ClusterMonitorFactory; +import com.netflix.turbine.streaming.servlet.TurbineStreamServlet; + import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; @@ -28,10 +32,6 @@ import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import com.netflix.discovery.EurekaClient; -import com.netflix.turbine.discovery.InstanceDiscovery; -import com.netflix.turbine.streaming.servlet.TurbineStreamServlet; - /** * @author Spencer Gibb */ @@ -77,19 +77,21 @@ public class TurbineHttpConfiguration { @Bean @ConditionalOnMissingBean public TurbineLifecycle turbineLifecycle(InstanceDiscovery instanceDiscovery, - ClusterMonitorFactory factory) { + ClusterMonitorFactory factory) { return new TurbineLifecycle(instanceDiscovery, factory); } @Bean @ConditionalOnMissingBean - public ClusterMonitorFactory clusterMonitorFactory(TurbineClustersProvider clustersProvider) { + public ClusterMonitorFactory clusterMonitorFactory( + TurbineClustersProvider clustersProvider) { return new SpringAggregatorFactory(clustersProvider); } @Bean @ConditionalOnMissingBean - public TurbineClustersProvider clustersProvider(TurbineAggregatorProperties turbineAggregatorProperties) { + public TurbineClustersProvider clustersProvider( + TurbineAggregatorProperties turbineAggregatorProperties) { return new ConfigurationBasedTurbineClustersProvider(turbineAggregatorProperties); } @@ -99,7 +101,8 @@ public class TurbineHttpConfiguration { @Bean @ConditionalOnMissingBean - public InstanceDiscovery instanceDiscovery(TurbineProperties turbineProperties, EurekaClient eurekaClient) { + public InstanceDiscovery instanceDiscovery(TurbineProperties turbineProperties, + EurekaClient eurekaClient) { return new EurekaInstanceDiscovery(turbineProperties, eurekaClient); } @@ -111,8 +114,11 @@ public class TurbineHttpConfiguration { @Bean @ConditionalOnMissingBean - public InstanceDiscovery instanceDiscovery(TurbineProperties turbineProperties, DiscoveryClient discoveryClient) { + public InstanceDiscovery instanceDiscovery(TurbineProperties turbineProperties, + DiscoveryClient discoveryClient) { return new CommonsInstanceDiscovery(turbineProperties, discoveryClient); } + } + } diff --git a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineInformationService.java b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineInformationService.java index dc89fd1b2..c17cc7bd4 100644 --- a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineInformationService.java +++ b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineInformationService.java @@ -1,35 +1,62 @@ +/* + * Copyright 2018-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.springframework.cloud.netflix.turbine; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; + import com.netflix.turbine.data.AggDataFromCluster; import com.netflix.turbine.data.DataFromSingleInstance; import com.netflix.turbine.monitor.MonitorConsole; import com.netflix.turbine.monitor.TurbineDataMonitor; import com.netflix.turbine.monitor.cluster.ClusterMonitor; + import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; -import javax.servlet.http.HttpServletRequest; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - import static com.netflix.turbine.monitor.cluster.AggregateClusterMonitor.AggregatorClusterMonitorConsole; +/** + * Service providing information on Turbine clusters. + * + * @author Anastasiia Smirnova + */ public class TurbineInformationService { - public Collection getClusterInformations(HttpServletRequest request) { + public Collection getClusterInformations( + HttpServletRequest request) { String hostName = getHostName(request); return getClusterInformations(hostName); } private Collection getClusterInformations(String hostName) { - Collection> monitors = AggregatorClusterMonitorConsole.getAllMonitors(); + Collection> monitors = AggregatorClusterMonitorConsole + .getAllMonitors(); List clusterInformations = new ArrayList<>(); for (TurbineDataMonitor monitor : monitors) { ClusterMonitor clusterMonitor = (ClusterMonitor) monitor; - MonitorConsole instanceConsole = clusterMonitor.getInstanceMonitors(); - for (TurbineDataMonitor single : instanceConsole.getAllMonitors()) { + MonitorConsole instanceConsole = clusterMonitor + .getInstanceMonitors(); + for (TurbineDataMonitor single : instanceConsole + .getAllMonitors()) { String cluster = single.getStatsInstance().getCluster(); ClusterInformation info = new ClusterInformation(cluster, getLink(hostName, cluster)); diff --git a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineLifecycle.java b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineLifecycle.java index 019a8ce75..059f37ace 100644 --- a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineLifecycle.java +++ b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineLifecycle.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,25 +16,27 @@ package org.springframework.cloud.netflix.turbine; -import com.netflix.turbine.monitor.cluster.ClusterMonitorFactory; -import org.springframework.context.SmartLifecycle; -import org.springframework.core.Ordered; - import com.netflix.turbine.discovery.InstanceDiscovery; import com.netflix.turbine.init.TurbineInit; +import com.netflix.turbine.monitor.cluster.ClusterMonitorFactory; import com.netflix.turbine.plugins.PluginsFactory; +import org.springframework.context.SmartLifecycle; +import org.springframework.core.Ordered; + /** * @author Spencer Gibb */ public class TurbineLifecycle implements SmartLifecycle, Ordered { private final InstanceDiscovery instanceDiscovery; + private final ClusterMonitorFactory factory; private volatile boolean running; - public TurbineLifecycle(InstanceDiscovery instanceDiscovery, ClusterMonitorFactory factory) { + public TurbineLifecycle(InstanceDiscovery instanceDiscovery, + ClusterMonitorFactory factory) { this.instanceDiscovery = instanceDiscovery; this.factory = factory; } diff --git a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineProperties.java b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineProperties.java index 4dfd0f14d..08df21e4f 100644 --- a/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineProperties.java +++ b/spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/TurbineProperties.java @@ -74,12 +74,16 @@ public class TurbineProperties { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } TurbineProperties that = (TurbineProperties) o; - return Objects.equals(clusterNameExpression, that.clusterNameExpression) && - Objects.equals(appConfig, that.appConfig) && - Objects.equals(combineHostPort, that.combineHostPort); + return Objects.equals(clusterNameExpression, that.clusterNameExpression) + && Objects.equals(appConfig, that.appConfig) + && Objects.equals(combineHostPort, that.combineHostPort); } @Override @@ -89,11 +93,10 @@ public class TurbineProperties { @Override public String toString() { - return new StringBuilder("TurbineProperties{") - .append("clusterNameExpression='").append(clusterNameExpression).append("', ") - .append("appConfig='").append(appConfig).append("', ") - .append("combineHostPort=").append(combineHostPort).append("}") - .toString(); + return new StringBuilder("TurbineProperties{").append("clusterNameExpression='") + .append(clusterNameExpression).append("', ").append("appConfig='") + .append(appConfig).append("', ").append("combineHostPort=") + .append(combineHostPort).append("}").toString(); } } diff --git a/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/AdhocTurbineTestSuite.java b/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/AdhocTurbineTestSuite.java index e00879738..8cd403f6b 100644 --- a/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/AdhocTurbineTestSuite.java +++ b/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/AdhocTurbineTestSuite.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.turbine; @@ -32,4 +31,5 @@ import org.junit.runners.Suite; }) @Ignore public class AdhocTurbineTestSuite { + } diff --git a/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/CommonsInstanceDiscoveryTests.java b/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/CommonsInstanceDiscoveryTests.java index e13b0ee68..6064372c3 100644 --- a/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/CommonsInstanceDiscoveryTests.java +++ b/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/CommonsInstanceDiscoveryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,14 +18,14 @@ package org.springframework.cloud.netflix.turbine; import java.util.Collections; +import com.netflix.turbine.discovery.Instance; import org.junit.Before; import org.junit.Test; + import org.springframework.cloud.client.DefaultServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; -import com.netflix.turbine.discovery.Instance; - -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -34,6 +34,7 @@ import static org.mockito.Mockito.mock; public class CommonsInstanceDiscoveryTests { private DiscoveryClient discoveryClient; + private TurbineProperties turbineProperties; @Before @@ -49,13 +50,18 @@ public class CommonsInstanceDiscoveryTests { String appName = "testAppName"; int port = 8443; String hostName = "myhost"; - DefaultServiceInstance serviceInstance = new DefaultServiceInstance(appName, hostName, port, true); + DefaultServiceInstance serviceInstance = new DefaultServiceInstance(appName, + hostName, port, true); Instance instance = discovery.marshall(serviceInstance); - assertEquals("port is wrong", String.valueOf(port), instance.getAttributes().get("port")); - assertEquals("securePort is wrong", String.valueOf(port), instance.getAttributes().get("securePort")); + assertThat(instance.getAttributes().get("port")).as("port is wrong") + .isEqualTo(String.valueOf(port)); + assertThat(instance.getAttributes().get("securePort")).as("securePort is wrong") + .isEqualTo(String.valueOf(port)); - String urlPath = SpringClusterMonitor.ClusterConfigBasedUrlClosure.getUrlPath(instance); - assertEquals("url is wrong", "https://"+hostName+":"+port+"/actuator/hystrix.stream", urlPath); + String urlPath = SpringClusterMonitor.ClusterConfigBasedUrlClosure + .getUrlPath(instance); + assertThat(urlPath).as("url is wrong").isEqualTo( + "https://" + hostName + ":" + port + "/actuator/hystrix.stream"); } @Test @@ -65,25 +71,31 @@ public class CommonsInstanceDiscoveryTests { String appName = "testAppName"; int port = 8080; String hostName = "myhost"; - DefaultServiceInstance serviceInstance = new DefaultServiceInstance(appName, hostName, port, false); + DefaultServiceInstance serviceInstance = new DefaultServiceInstance(appName, + hostName, port, false); Instance instance = discovery.marshall(serviceInstance); - assertEquals("hostname is wrong", hostName+":"+port, instance.getHostname()); - assertEquals("port is wrong", String.valueOf(port), instance.getAttributes().get("port")); + assertThat(instance.getHostname()).as("hostname is wrong") + .isEqualTo(hostName + ":" + port); + assertThat(instance.getAttributes().get("port")).as("port is wrong") + .isEqualTo(String.valueOf(port)); - String urlPath = SpringClusterMonitor.ClusterConfigBasedUrlClosure.getUrlPath(instance); - assertEquals("url is wrong", "http://"+hostName+":"+port+"/actuator/hystrix.stream", urlPath); + String urlPath = SpringClusterMonitor.ClusterConfigBasedUrlClosure + .getUrlPath(instance); + assertThat(urlPath).as("url is wrong").isEqualTo( + "http://" + hostName + ":" + port + "/actuator/hystrix.stream"); String clusterName = discovery.getClusterName(serviceInstance); - assertEquals("clusterName is wrong", appName, clusterName); + assertThat(clusterName).as("clusterName is wrong").isEqualTo(appName); } @Test public void testGetClusterName() { CommonsInstanceDiscovery discovery = createDiscovery(); String appName = "testAppName"; - DefaultServiceInstance serviceInstance = new DefaultServiceInstance(appName, "myhost", 8080, false); + DefaultServiceInstance serviceInstance = new DefaultServiceInstance(appName, + "myhost", 8080, false); String clusterName = discovery.getClusterName(serviceInstance); - assertEquals("clusterName is wrong", appName, clusterName); + assertThat(clusterName).as("clusterName is wrong").isEqualTo(appName); } @Test @@ -92,12 +104,16 @@ public class CommonsInstanceDiscoveryTests { String appName = "testAppName"; int port = 8080; String hostName = "myhost"; - DefaultServiceInstance serviceInstance = new DefaultServiceInstance(appName, hostName, port, false); + DefaultServiceInstance serviceInstance = new DefaultServiceInstance(appName, + hostName, port, false); Instance instance = discovery.marshall(serviceInstance); - assertEquals("port is wrong", String.valueOf(port), instance.getAttributes().get("port")); + assertThat(instance.getAttributes().get("port")).as("port is wrong") + .isEqualTo(String.valueOf(port)); - String urlPath = SpringClusterMonitor.ClusterConfigBasedUrlClosure.getUrlPath(instance); - assertEquals("url is wrong", "http://"+hostName+":"+port+"/actuator/hystrix.stream", urlPath); + String urlPath = SpringClusterMonitor.ClusterConfigBasedUrlClosure + .getUrlPath(instance); + assertThat(urlPath).as("url is wrong").isEqualTo( + "http://" + hostName + ":" + port + "/actuator/hystrix.stream"); } @Test @@ -107,29 +123,39 @@ public class CommonsInstanceDiscoveryTests { int port = 8080; int managementPort = 8081; String hostName = "myhost"; - DefaultServiceInstance serviceInstance = new DefaultServiceInstance(appName, hostName, port, false); - serviceInstance.getMetadata().put("management.port", String.valueOf(managementPort)); + DefaultServiceInstance serviceInstance = new DefaultServiceInstance(appName, + hostName, port, false); + serviceInstance.getMetadata().put("management.port", + String.valueOf(managementPort)); Instance instance = discovery.marshall(serviceInstance); - assertEquals("port is wrong", String.valueOf(managementPort), instance.getAttributes().get("port")); + assertThat(instance.getAttributes().get("port")).as("port is wrong") + .isEqualTo(String.valueOf(managementPort)); - String urlPath = SpringClusterMonitor.ClusterConfigBasedUrlClosure.getUrlPath(instance); - assertEquals("url is wrong", "http://"+hostName+":"+managementPort+"/actuator/hystrix.stream", urlPath); + String urlPath = SpringClusterMonitor.ClusterConfigBasedUrlClosure + .getUrlPath(instance); + assertThat(urlPath).as("url is wrong").isEqualTo( + "http://" + hostName + ":" + managementPort + "/actuator/hystrix.stream"); } @Test public void testGetSecurePort() { CommonsInstanceDiscovery discovery = createDiscovery(); String appName = "testAppName"; - //int port = 8080; + // int port = 8080; int port = 8443; String hostName = "myhost"; - DefaultServiceInstance serviceInstance = new DefaultServiceInstance(appName, hostName, port, true); + DefaultServiceInstance serviceInstance = new DefaultServiceInstance(appName, + hostName, port, true); Instance instance = discovery.marshall(serviceInstance); - assertEquals("port is wrong", String.valueOf(port), instance.getAttributes().get("port")); - assertEquals("securePort is wrong", String.valueOf(port), instance.getAttributes().get("securePort")); + assertThat(instance.getAttributes().get("port")).as("port is wrong") + .isEqualTo(String.valueOf(port)); + assertThat(instance.getAttributes().get("securePort")).as("securePort is wrong") + .isEqualTo(String.valueOf(port)); - String urlPath = SpringClusterMonitor.ClusterConfigBasedUrlClosure.getUrlPath(instance); - assertEquals("url is wrong", "https://"+hostName+":"+port+"/actuator/hystrix.stream", urlPath); + String urlPath = SpringClusterMonitor.ClusterConfigBasedUrlClosure + .getUrlPath(instance); + assertThat(urlPath).as("url is wrong").isEqualTo( + "https://" + hostName + ":" + port + "/actuator/hystrix.stream"); } @Test @@ -138,9 +164,10 @@ public class CommonsInstanceDiscoveryTests { CommonsInstanceDiscovery discovery = createDiscovery(); String appName = "testAppName"; String hostName = "myhost"; - DefaultServiceInstance serviceInstance = new DefaultServiceInstance(appName, hostName, 8080, true); + DefaultServiceInstance serviceInstance = new DefaultServiceInstance(appName, + hostName, 8080, true); String clusterName = discovery.getClusterName(serviceInstance); - assertEquals("clusterName is wrong", hostName, clusterName); + assertThat(clusterName).as("clusterName is wrong").isEqualTo(hostName); } @Test @@ -150,9 +177,11 @@ public class CommonsInstanceDiscoveryTests { String metadataProperty = "myCluster"; String appName = "testAppName"; String hostName = "myhost"; - DefaultServiceInstance serviceInstance = new DefaultServiceInstance(appName, hostName, 8080, true, Collections.singletonMap("cluster", metadataProperty)); + DefaultServiceInstance serviceInstance = new DefaultServiceInstance(appName, + hostName, 8080, true, + Collections.singletonMap("cluster", metadataProperty)); String clusterName = discovery.getClusterName(serviceInstance); - assertEquals("clusterName is wrong", metadataProperty, clusterName); + assertThat(clusterName).as("clusterName is wrong").isEqualTo(metadataProperty); } private CommonsInstanceDiscovery createDiscovery() { diff --git a/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/ConfigurationBasedTurbineClustersProviderTest.java b/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/ConfigurationBasedTurbineClustersProviderTest.java index 5115f3421..b247bd9d3 100644 --- a/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/ConfigurationBasedTurbineClustersProviderTest.java +++ b/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/ConfigurationBasedTurbineClustersProviderTest.java @@ -1,10 +1,26 @@ -package org.springframework.cloud.netflix.turbine; +/* + * Copyright 2017-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ -import org.junit.Test; +package org.springframework.cloud.netflix.turbine; import java.util.Arrays; import java.util.List; +import org.junit.Test; + import static org.assertj.core.api.Assertions.assertThat; public class ConfigurationBasedTurbineClustersProviderTest { @@ -29,4 +45,5 @@ public class ConfigurationBasedTurbineClustersProviderTest { assertThat(clusterNames).containsOnly("cluster1", "cluster2", "cluster3"); } -} \ No newline at end of file + +} diff --git a/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/EurekaBasedTurbineClustersProviderTest.java b/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/EurekaBasedTurbineClustersProviderTest.java index 1b7ebcf71..92e477047 100644 --- a/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/EurekaBasedTurbineClustersProviderTest.java +++ b/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/EurekaBasedTurbineClustersProviderTest.java @@ -1,12 +1,28 @@ +/* + * Copyright 2017-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.springframework.cloud.netflix.turbine; +import java.util.List; + import com.netflix.discovery.EurekaClient; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import org.junit.Test; -import java.util.List; - import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; @@ -15,7 +31,9 @@ import static org.mockito.Mockito.when; public class EurekaBasedTurbineClustersProviderTest { EurekaClient eurekaClient = mock(EurekaClient.class); - TurbineClustersProvider provider = new EurekaBasedTurbineClustersProvider(eurekaClient); + + TurbineClustersProvider provider = new EurekaBasedTurbineClustersProvider( + eurekaClient); @Test public void shouldProvideAllClustersNames() throws Exception { @@ -39,4 +57,5 @@ public class EurekaBasedTurbineClustersProviderTest { when(application.getName()).thenReturn(name); return application; } -} \ No newline at end of file + +} diff --git a/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/EurekaInstanceDiscoveryTests.java b/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/EurekaInstanceDiscoveryTests.java index ecd51a17d..811f38b03 100644 --- a/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/EurekaInstanceDiscoveryTests.java +++ b/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/EurekaInstanceDiscoveryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,14 +16,13 @@ package org.springframework.cloud.netflix.turbine; -import org.junit.Before; -import org.junit.Test; - import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.EurekaClient; import com.netflix.turbine.discovery.Instance; +import org.junit.Before; +import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -32,7 +31,9 @@ import static org.mockito.Mockito.mock; public class EurekaInstanceDiscoveryTests { private EurekaClient eurekaClient; + private TurbineProperties turbineProperties; + private InstanceInfo.Builder builder; @Before @@ -45,47 +46,51 @@ public class EurekaInstanceDiscoveryTests { @Test public void testSecureCombineHostPort() { turbineProperties.setCombineHostPort(true); - EurekaInstanceDiscovery discovery = new EurekaInstanceDiscovery( - turbineProperties, eurekaClient); + EurekaInstanceDiscovery discovery = new EurekaInstanceDiscovery(turbineProperties, + eurekaClient); String appName = "testAppName"; int port = 8080; int securePort = 8443; String hostName = "myhost"; - InstanceInfo instanceInfo = builder.setAppName(appName) - .setHostName(hostName) - .setPort(port) - .setSecurePort(securePort) - .enablePort(InstanceInfo.PortType.SECURE, true) - .build(); + InstanceInfo instanceInfo = builder.setAppName(appName).setHostName(hostName) + .setPort(port).setSecurePort(securePort) + .enablePort(InstanceInfo.PortType.SECURE, true).build(); Instance instance = discovery.marshall(instanceInfo); - assertEquals("port is wrong", String.valueOf(port), instance.getAttributes().get("port")); - assertEquals("securePort is wrong", String.valueOf(securePort), instance.getAttributes().get("securePort")); + assertThat(instance.getAttributes().get("port")).as("port is wrong") + .isEqualTo(String.valueOf(port)); + assertThat(instance.getAttributes().get("securePort")).as("securePort is wrong") + .isEqualTo(String.valueOf(securePort)); - String urlPath = SpringClusterMonitor.ClusterConfigBasedUrlClosure.getUrlPath(instance); - assertEquals("url is wrong", "https://"+hostName+":"+securePort+"/actuator/hystrix.stream", urlPath); + String urlPath = SpringClusterMonitor.ClusterConfigBasedUrlClosure + .getUrlPath(instance); + assertThat(urlPath).as("url is wrong").isEqualTo( + "https://" + hostName + ":" + securePort + "/actuator/hystrix.stream"); } @Test public void testCombineHostPort() { turbineProperties.setCombineHostPort(true); - EurekaInstanceDiscovery discovery = new EurekaInstanceDiscovery( - turbineProperties, eurekaClient); + EurekaInstanceDiscovery discovery = new EurekaInstanceDiscovery(turbineProperties, + eurekaClient); String appName = "testAppName"; int port = 8080; String hostName = "myhost"; - InstanceInfo instanceInfo = builder.setAppName(appName) - .setHostName(hostName) - .setPort(port) - .build(); + InstanceInfo instanceInfo = builder.setAppName(appName).setHostName(hostName) + .setPort(port).build(); Instance instance = discovery.marshall(instanceInfo); - assertEquals("hostname is wrong", hostName+":"+port, instance.getHostname()); - assertEquals("port is wrong", String.valueOf(port), instance.getAttributes().get("port")); + assertThat(instance.getHostname()).as("hostname is wrong") + .isEqualTo(hostName + ":" + port); + assertThat(instance.getAttributes().get("port")).as("port is wrong") + .isEqualTo(String.valueOf(port)); - String urlPath = SpringClusterMonitor.ClusterConfigBasedUrlClosure.getUrlPath(instance); - assertEquals("url is wrong", "http://"+hostName+":"+port+"/actuator/hystrix.stream", urlPath); + String urlPath = SpringClusterMonitor.ClusterConfigBasedUrlClosure + .getUrlPath(instance); + assertThat(urlPath).as("url is wrong").isEqualTo( + "http://" + hostName + ":" + port + "/actuator/hystrix.stream"); String clusterName = discovery.getClusterName(instanceInfo); - assertEquals("clusterName is wrong", appName.toUpperCase(), clusterName); + assertThat(clusterName).as("clusterName is wrong") + .isEqualTo(appName.toUpperCase()); } @Test @@ -96,20 +101,23 @@ public class EurekaInstanceDiscoveryTests { int port = 8080; int managementPort = 8081; String hostName = "myhost"; - InstanceInfo instanceInfo = builder.setAppName(appName).setHostName(hostName).setPort(port) - .build(); + InstanceInfo instanceInfo = builder.setAppName(appName).setHostName(hostName) + .setPort(port).build(); instanceInfo.getMetadata().put("management.port", "8081"); Instance instance = discovery.marshall(instanceInfo); - assertEquals("hostname is wrong", hostName + ":" + managementPort, instance.getHostname()); - assertEquals("port is wrong", String.valueOf(managementPort), - instance.getAttributes().get("port")); + assertThat(instance.getHostname()).as("hostname is wrong") + .isEqualTo(hostName + ":" + managementPort); + assertThat(instance.getAttributes().get("port")).as("port is wrong") + .isEqualTo(String.valueOf(managementPort)); - String urlPath = SpringClusterMonitor.ClusterConfigBasedUrlClosure.getUrlPath(instance); - assertEquals("url is wrong", - "http://" + hostName + ":" + managementPort + "/actuator/hystrix.stream", urlPath); + String urlPath = SpringClusterMonitor.ClusterConfigBasedUrlClosure + .getUrlPath(instance); + assertThat(urlPath).as("url is wrong").isEqualTo( + "http://" + hostName + ":" + managementPort + "/actuator/hystrix.stream"); String clusterName = discovery.getClusterName(instanceInfo); - assertEquals("clusterName is wrong", appName.toUpperCase(), clusterName); + assertThat(clusterName).as("clusterName is wrong") + .isEqualTo(appName.toUpperCase()); } @Test @@ -119,69 +127,74 @@ public class EurekaInstanceDiscoveryTests { String appName = "testAppName"; InstanceInfo instanceInfo = builder.setAppName(appName).build(); String clusterName = discovery.getClusterName(instanceInfo); - assertEquals("clusterName is wrong", appName.toUpperCase(), clusterName); + assertThat(clusterName).as("clusterName is wrong") + .isEqualTo(appName.toUpperCase()); } @Test public void testGetPort() { - EurekaInstanceDiscovery discovery = new EurekaInstanceDiscovery( - turbineProperties, eurekaClient); + EurekaInstanceDiscovery discovery = new EurekaInstanceDiscovery(turbineProperties, + eurekaClient); String appName = "testAppName"; int port = 8080; String hostName = "myhost"; - InstanceInfo instanceInfo = builder.setAppName(appName) - .setHostName(hostName) - .setPort(port) - .build(); + InstanceInfo instanceInfo = builder.setAppName(appName).setHostName(hostName) + .setPort(port).build(); Instance instance = discovery.marshall(instanceInfo); - assertEquals("port is wrong", String.valueOf(port), instance.getAttributes().get("port")); + assertThat(instance.getAttributes().get("port")).as("port is wrong") + .isEqualTo(String.valueOf(port)); - String urlPath = SpringClusterMonitor.ClusterConfigBasedUrlClosure.getUrlPath(instance); - assertEquals("url is wrong", "http://"+hostName+":"+port+"/actuator/hystrix.stream", urlPath); + String urlPath = SpringClusterMonitor.ClusterConfigBasedUrlClosure + .getUrlPath(instance); + assertThat(urlPath).as("url is wrong").isEqualTo( + "http://" + hostName + ":" + port + "/actuator/hystrix.stream"); } @Test public void testGetSecurePort() { - EurekaInstanceDiscovery discovery = new EurekaInstanceDiscovery( - turbineProperties, eurekaClient); + EurekaInstanceDiscovery discovery = new EurekaInstanceDiscovery(turbineProperties, + eurekaClient); String appName = "testAppName"; int port = 8080; int securePort = 8443; String hostName = "myhost"; - InstanceInfo instanceInfo = builder.setAppName(appName) - .setHostName(hostName) - .setPort(port) - .setSecurePort(securePort) - .enablePort(InstanceInfo.PortType.SECURE, true) - .build(); + InstanceInfo instanceInfo = builder.setAppName(appName).setHostName(hostName) + .setPort(port).setSecurePort(securePort) + .enablePort(InstanceInfo.PortType.SECURE, true).build(); Instance instance = discovery.marshall(instanceInfo); - assertEquals("port is wrong", String.valueOf(port), instance.getAttributes().get("port")); - assertEquals("securePort is wrong", String.valueOf(securePort), instance.getAttributes().get("securePort")); + assertThat(instance.getAttributes().get("port")).as("port is wrong") + .isEqualTo(String.valueOf(port)); + assertThat(instance.getAttributes().get("securePort")).as("securePort is wrong") + .isEqualTo(String.valueOf(securePort)); - String urlPath = SpringClusterMonitor.ClusterConfigBasedUrlClosure.getUrlPath(instance); - assertEquals("url is wrong", "https://"+hostName+":"+securePort+"/actuator/hystrix.stream", urlPath); + String urlPath = SpringClusterMonitor.ClusterConfigBasedUrlClosure + .getUrlPath(instance); + assertThat(urlPath).as("url is wrong").isEqualTo( + "https://" + hostName + ":" + securePort + "/actuator/hystrix.stream"); } @Test public void testGetClusterNameCustomExpression() { turbineProperties.setClusterNameExpression("aSGName"); - EurekaInstanceDiscovery discovery = new EurekaInstanceDiscovery(turbineProperties, eurekaClient); + EurekaInstanceDiscovery discovery = new EurekaInstanceDiscovery(turbineProperties, + eurekaClient); String asgName = "myAsgName"; - InstanceInfo instanceInfo = builder - .setAppName("testApp").setASGName(asgName).build(); + InstanceInfo instanceInfo = builder.setAppName("testApp").setASGName(asgName) + .build(); String clusterName = discovery.getClusterName(instanceInfo); - assertEquals("clusterName is wrong", asgName, clusterName); + assertThat(clusterName).as("clusterName is wrong").isEqualTo(asgName); } @Test public void testGetClusterNameInstanceMetadataMapExpression() { turbineProperties.setClusterNameExpression("metadata['cluster']"); - EurekaInstanceDiscovery discovery = new EurekaInstanceDiscovery(turbineProperties, eurekaClient); + EurekaInstanceDiscovery discovery = new EurekaInstanceDiscovery(turbineProperties, + eurekaClient); String metadataProperty = "myCluster"; - InstanceInfo instanceInfo = builder - .setAppName("testApp").add("cluster", metadataProperty).build(); + InstanceInfo instanceInfo = builder.setAppName("testApp") + .add("cluster", metadataProperty).build(); String clusterName = discovery.getClusterName(instanceInfo); - assertEquals("clusterName is wrong", metadataProperty, clusterName); + assertThat(clusterName).as("clusterName is wrong").isEqualTo(metadataProperty); } } diff --git a/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/TurbineAggregatorPropertiesTest.java b/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/TurbineAggregatorPropertiesTest.java index 04799811a..d92624396 100644 --- a/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/TurbineAggregatorPropertiesTest.java +++ b/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/TurbineAggregatorPropertiesTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,13 +12,13 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.turbine; import org.junit.After; import org.junit.Test; + import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.context.annotation.AnnotationConfigApplicationContext; @@ -47,8 +47,9 @@ public class TurbineAggregatorPropertiesTest { @Test public void shouldLoadCustomProperties() { - TestPropertyValues.of( - "turbine.aggregator.clusterConfig=cluster1, cluster2, cluster3").applyTo(this.context); + TestPropertyValues + .of("turbine.aggregator.clusterConfig=cluster1, cluster2, cluster3") + .applyTo(this.context); setupContext(); TurbineAggregatorProperties actual = getProperties(); @@ -68,5 +69,7 @@ public class TurbineAggregatorPropertiesTest { @Configuration @EnableConfigurationProperties(TurbineAggregatorProperties.class) static class TestConfiguration { + } -} \ No newline at end of file + +} diff --git a/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/TurbineHttpTests.java b/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/TurbineHttpTests.java index e56be6871..f5ac31ebb 100644 --- a/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/TurbineHttpTests.java +++ b/spring-cloud-netflix-turbine/src/test/java/org/springframework/cloud/netflix/turbine/TurbineHttpTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Spencer Gibb @@ -45,37 +45,45 @@ import static org.junit.Assert.assertEquals; @SpringBootTest(classes = TurbineHttpTests.TurbineHttpSampleApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class TurbineHttpTests { - private static final ClusterInformation foo = new ClusterInformation("foo", "http://foo"); - private static final ClusterInformation bar = new ClusterInformation("bar", "http://bar"); + private static final ClusterInformation foo = new ClusterInformation("foo", + "http://foo"); + + private static final ClusterInformation bar = new ClusterInformation("bar", + "http://bar"); @Autowired TestRestTemplate rest; + @Test + public void contextLoads() { + ClusterInformation[] clusters = rest.getForObject("/clusters", + ClusterInformation[].class); + System.err.println(Arrays.asList(clusters)); + assertThat(clusters.length).isEqualTo(2); + assertThat(clusters[0]).isEqualTo(foo); + assertThat(clusters[1]).isEqualTo(bar); + } + @SpringBootConfiguration @EnableAutoConfiguration @EnableTurbine protected static class TurbineHttpSampleApplication { + @Bean @Primary TurbineInformationService myInfoService() { return new TurbineInformationService() { - @Override - public Collection getClusterInformations(HttpServletRequest request) { + @Override + public Collection getClusterInformations( + HttpServletRequest request) { List clusterInformationList = new ArrayList(); clusterInformationList.add(foo); clusterInformationList.add(bar); return clusterInformationList; - } - }; + } + }; } + } - @Test - public void contextLoads() { - ClusterInformation[] clusters = rest.getForObject("/clusters", ClusterInformation[].class); - System.err.println(Arrays.asList(clusters)); - assertEquals(2, clusters.length); - assertEquals(foo, clusters[0]); - assertEquals(bar, clusters[1]); - } } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/EnableZuulProxy.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/EnableZuulProxy.java index 41327b2b1..43ee68ef6 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/EnableZuulProxy.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/EnableZuulProxy.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,4 +40,5 @@ import org.springframework.context.annotation.Import; @Retention(RetentionPolicy.RUNTIME) @Import(ZuulProxyMarkerConfiguration.class) public @interface EnableZuulProxy { + } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/FiltersEndpoint.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/FiltersEndpoint.java index 3cf22ffab..9ee2ffbf8 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/FiltersEndpoint.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/FiltersEndpoint.java @@ -1,3 +1,19 @@ +/* + * Copyright 2017-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.springframework.cloud.netflix.zuul; import java.util.ArrayList; @@ -6,12 +22,12 @@ import java.util.List; import java.util.Map; import java.util.TreeMap; -import org.springframework.boot.actuate.endpoint.annotation.Endpoint; -import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; - import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.filters.FilterRegistry; +import org.springframework.boot.actuate.endpoint.annotation.Endpoint; +import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; + /** * Endpoint for listing Zuul filters. * diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/RibbonCommandFactoryConfiguration.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/RibbonCommandFactoryConfiguration.java index b44f6f81f..e350a38bd 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/RibbonCommandFactoryConfiguration.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/RibbonCommandFactoryConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,6 +60,36 @@ public class RibbonCommandFactoryConfiguration { return new RestClientRibbonCommandFactory(clientFactory, zuulProperties, zuulFallbackProviders); } + + } + + @Target({ ElementType.TYPE, ElementType.METHOD }) + @Retention(RetentionPolicy.RUNTIME) + @Documented + @Conditional(OnRibbonHttpClientCondition.class) + @interface ConditionalOnRibbonHttpClient { + + } + + private static class OnRibbonHttpClientCondition extends AnyNestedCondition { + + OnRibbonHttpClientCondition() { + super(ConfigurationPhase.PARSE_CONFIGURATION); + } + + @ConditionalOnProperty(name = "ribbon.httpclient.enabled", matchIfMissing = true) + static class RibbonProperty { + + } + + } + + @Target({ ElementType.TYPE, ElementType.METHOD }) + @Retention(RetentionPolicy.RUNTIME) + @Documented + @Conditional(OnRibbonOkHttpClientCondition.class) + @interface ConditionalOnRibbonOkHttpClient { + } @Configuration @@ -77,6 +107,7 @@ public class RibbonCommandFactoryConfiguration { return new OkHttpRibbonCommandFactory(clientFactory, zuulProperties, zuulFallbackProviders); } + } @Configuration @@ -90,53 +121,44 @@ public class RibbonCommandFactoryConfiguration { @ConditionalOnMissingBean public RibbonCommandFactory ribbonCommandFactory( SpringClientFactory clientFactory, ZuulProperties zuulProperties) { - return new HttpClientRibbonCommandFactory(clientFactory, zuulProperties, zuulFallbackProviders); - } - } - - @Target({ ElementType.TYPE, ElementType.METHOD }) - @Retention(RetentionPolicy.RUNTIME) - @Documented - @Conditional(OnRibbonHttpClientCondition.class) - @interface ConditionalOnRibbonHttpClient { } - - private static class OnRibbonHttpClientCondition extends AnyNestedCondition { - public OnRibbonHttpClientCondition() { - super(ConfigurationPhase.PARSE_CONFIGURATION); + return new HttpClientRibbonCommandFactory(clientFactory, zuulProperties, + zuulFallbackProviders); } - @ConditionalOnProperty(name = "ribbon.httpclient.enabled", matchIfMissing = true) - static class RibbonProperty {} } - @Target({ ElementType.TYPE, ElementType.METHOD }) - @Retention(RetentionPolicy.RUNTIME) - @Documented - @Conditional(OnRibbonOkHttpClientCondition.class) - @interface ConditionalOnRibbonOkHttpClient { } - private static class OnRibbonOkHttpClientCondition extends AnyNestedCondition { - public OnRibbonOkHttpClientCondition() { + + OnRibbonOkHttpClientCondition() { super(ConfigurationPhase.PARSE_CONFIGURATION); } @ConditionalOnProperty("ribbon.okhttp.enabled") - static class RibbonProperty {} + static class RibbonProperty { + + } + } @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Documented @Conditional(OnRibbonRestClientCondition.class) - @interface ConditionalOnRibbonRestClient { } + @interface ConditionalOnRibbonRestClient { + + } private static class OnRibbonRestClientCondition extends AnyNestedCondition { - public OnRibbonRestClientCondition() { + + OnRibbonRestClientCondition() { super(ConfigurationPhase.PARSE_CONFIGURATION); } @ConditionalOnProperty("ribbon.restclient.enabled") - static class RibbonProperty {} + static class RibbonProperty { + + } + } - + } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/RoutesEndpoint.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/RoutesEndpoint.java index 70c70e9ee..2218f09a2 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/RoutesEndpoint.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/RoutesEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,9 @@ import java.util.Map; import java.util.Objects; import java.util.Set; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; import org.springframework.boot.actuate.endpoint.annotation.Selector; @@ -30,11 +33,8 @@ import org.springframework.cloud.netflix.zuul.filters.RouteLocator; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - /** - * Endpoint to display the zuul proxy routes + * Endpoint to display the zuul proxy routes. * * @author Spencer Gibb * @author Dave Syer @@ -85,12 +85,16 @@ public class RoutesEndpoint implements ApplicationEventPublisherAware { /** * Expose Zuul {@link Route} information with details. + * @param format used to determine whether only locations or route details should be + * provided + * @return a map of routes and their details */ @ReadOperation public Object invokeRouteDetails(@Selector String format) { if (FORMAT_DETAILS.equalsIgnoreCase(format)) { return invokeRouteDetails(); - } else { + } + else { return invoke(); } } @@ -173,18 +177,21 @@ public class RoutesEndpoint implements ApplicationEventPublisherAware { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } RouteDetails that = (RouteDetails) o; - return Objects.equals(id, that.id) && - Objects.equals(fullPath, that.fullPath) && - Objects.equals(path, that.path) && - Objects.equals(location, that.location) && - Objects.equals(prefix, that.prefix) && - Objects.equals(retryable, that.retryable) && - Objects.equals(sensitiveHeaders, that.sensitiveHeaders) && - customSensitiveHeaders == that.customSensitiveHeaders && - prefixStripped == that.prefixStripped; + return Objects.equals(id, that.id) && Objects.equals(fullPath, that.fullPath) + && Objects.equals(path, that.path) + && Objects.equals(location, that.location) + && Objects.equals(prefix, that.prefix) + && Objects.equals(retryable, that.retryable) + && Objects.equals(sensitiveHeaders, that.sensitiveHeaders) + && customSensitiveHeaders == that.customSensitiveHeaders + && prefixStripped == that.prefixStripped; } @Override @@ -192,6 +199,7 @@ public class RoutesEndpoint implements ApplicationEventPublisherAware { return Objects.hash(id, fullPath, path, location, prefix, retryable, sensitiveHeaders, customSensitiveHeaders, prefixStripped); } + } } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulFilterInitializer.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulFilterInitializer.java index 166eecc73..6fa75eb24 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulFilterInitializer.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulFilterInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,15 +22,15 @@ import java.util.Map; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.util.ReflectionUtils; - import com.netflix.zuul.FilterLoader; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.filters.FilterRegistry; import com.netflix.zuul.monitoring.CounterFactory; import com.netflix.zuul.monitoring.TracerFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.util.ReflectionUtils; /** * Initializes various Zuul components including {@link ZuulFilter}. @@ -43,16 +43,18 @@ public class ZuulFilterInitializer { private static final Log log = LogFactory.getLog(ZuulFilterInitializer.class); private final Map filters; + private final CounterFactory counterFactory; + private final TracerFactory tracerFactory; + private final FilterLoader filterLoader; + private final FilterRegistry filterRegistry; public ZuulFilterInitializer(Map filters, - CounterFactory counterFactory, - TracerFactory tracerFactory, - FilterLoader filterLoader, - FilterRegistry filterRegistry) { + CounterFactory counterFactory, TracerFactory tracerFactory, + FilterLoader filterLoader, FilterRegistry filterRegistry) { this.filters = filters; this.counterFactory = counterFactory; this.tracerFactory = tracerFactory; diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulProxyAutoConfiguration.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulProxyAutoConfiguration.java index 1cccc61b6..23b0e81d5 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulProxyAutoConfiguration.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulProxyAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul; @@ -20,6 +19,7 @@ package org.springframework.cloud.netflix.zuul; import java.util.Collections; import java.util.List; +import com.netflix.zuul.filters.FilterRegistry; import org.apache.http.impl.client.CloseableHttpClient; import org.springframework.beans.factory.annotation.Autowired; @@ -52,8 +52,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; -import com.netflix.zuul.filters.FilterRegistry; - /** * @author Spencer Gibb * @author Dave Syer @@ -89,15 +87,18 @@ public class ZuulProxyAutoConfiguration extends ZuulServerAutoConfiguration { @Bean @ConditionalOnMissingBean(DiscoveryClientRouteLocator.class) public DiscoveryClientRouteLocator discoveryRouteLocator() { - return new DiscoveryClientRouteLocator(this.server.getServlet().getContextPath(), this.discovery, this.zuulProperties, - this.serviceRouteMapper, this.registration); + return new DiscoveryClientRouteLocator(this.server.getServlet().getContextPath(), + this.discovery, this.zuulProperties, this.serviceRouteMapper, + this.registration); } // pre filters @Bean @ConditionalOnMissingBean(PreDecorationFilter.class) - public PreDecorationFilter preDecorationFilter(RouteLocator routeLocator, ProxyRequestHelper proxyRequestHelper) { - return new PreDecorationFilter(routeLocator, this.server.getServlet().getContextPath(), this.zuulProperties, + public PreDecorationFilter preDecorationFilter(RouteLocator routeLocator, + ProxyRequestHelper proxyRequestHelper) { + return new PreDecorationFilter(routeLocator, + this.server.getServlet().getContextPath(), this.zuulProperties, proxyRequestHelper); } @@ -112,7 +113,8 @@ public class ZuulProxyAutoConfiguration extends ZuulServerAutoConfiguration { } @Bean - @ConditionalOnMissingBean({SimpleHostRoutingFilter.class, CloseableHttpClient.class}) + @ConditionalOnMissingBean({ SimpleHostRoutingFilter.class, + CloseableHttpClient.class }) public SimpleHostRoutingFilter simpleHostRoutingFilter(ProxyRequestHelper helper, ZuulProperties zuulProperties, ApacheHttpClientConnectionManagerFactory connectionManagerFactory, @@ -122,12 +124,10 @@ public class ZuulProxyAutoConfiguration extends ZuulServerAutoConfiguration { } @Bean - @ConditionalOnMissingBean({SimpleHostRoutingFilter.class}) + @ConditionalOnMissingBean({ SimpleHostRoutingFilter.class }) public SimpleHostRoutingFilter simpleHostRoutingFilter2(ProxyRequestHelper helper, - ZuulProperties zuulProperties, - CloseableHttpClient httpClient) { - return new SimpleHostRoutingFilter(helper, zuulProperties, - httpClient); + ZuulProperties zuulProperties, CloseableHttpClient httpClient) { + return new SimpleHostRoutingFilter(helper, zuulProperties, httpClient); } @Bean @@ -176,5 +176,7 @@ public class ZuulProxyAutoConfiguration extends ZuulServerAutoConfiguration { } return helper; } + } + } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulProxyMarkerConfiguration.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulProxyMarkerConfiguration.java index 451442bfd..06efba020 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulProxyMarkerConfiguration.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulProxyMarkerConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul; @@ -21,19 +20,22 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** - * Responsible for adding in a marker bean to trigger activation of - * {@link ZuulProxyAutoConfiguration} + * Responsible for adding in a marker bean to trigger activation of + * {@link ZuulProxyAutoConfiguration}. * * @author Biju Kunjummen */ @Configuration public class ZuulProxyMarkerConfiguration { + @Bean public Marker zuulProxyMarkerBean() { return new Marker(); } class Marker { + } + } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulRouteApplicationContextInitializer.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulRouteApplicationContextInitializer.java index 5d11d4493..a55f7affc 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulRouteApplicationContextInitializer.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulRouteApplicationContextInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,36 +16,37 @@ package org.springframework.cloud.netflix.zuul; -import org.springframework.cloud.netflix.ribbon.RibbonApplicationContextInitializer; -import org.springframework.cloud.netflix.ribbon.SpringClientFactory; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; - import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; +import org.springframework.cloud.netflix.ribbon.RibbonApplicationContextInitializer; +import org.springframework.cloud.netflix.ribbon.SpringClientFactory; +import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; + /** - * Responsible for taking in the list of registered serviceid's (Ribbon client names) - * and creating the Spring {@link org.springframework.context.ApplicationContext} on - * start-up + * Responsible for taking in the list of registered serviceid's (Ribbon client names) and + * creating the Spring {@link org.springframework.context.ApplicationContext} on start-up. * * @author Biju Kunjummen */ -public class ZuulRouteApplicationContextInitializer extends - RibbonApplicationContextInitializer { +public class ZuulRouteApplicationContextInitializer + extends RibbonApplicationContextInitializer { + public ZuulRouteApplicationContextInitializer(SpringClientFactory springClientFactory, ZuulProperties zuulProperties) { super(springClientFactory, getServiceIdsFromZuulProps(zuulProperties)); } - private static List getServiceIdsFromZuulProps(ZuulProperties zuulProperties) { + private static List getServiceIdsFromZuulProps( + ZuulProperties zuulProperties) { Map zuulRoutes = zuulProperties.getRoutes(); Collection registeredRoutes = zuulRoutes.values(); List serviceIds = new ArrayList<>(); if (registeredRoutes != null) { - for (ZuulProperties.ZuulRoute route: registeredRoutes) { + for (ZuulProperties.ZuulRoute route : registeredRoutes) { String serviceId = route.getServiceId(); if (serviceId != null) { serviceIds.add(serviceId); @@ -54,4 +55,5 @@ public class ZuulRouteApplicationContextInitializer extends } return serviceIds; } + } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulServerAutoConfiguration.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulServerAutoConfiguration.java index e47e80951..87a642e12 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulServerAutoConfiguration.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulServerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,15 +12,23 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul; import java.util.Collection; import java.util.Collections; -import java.util.Map; import java.util.List; +import java.util.Map; + +import com.netflix.zuul.FilterLoader; +import com.netflix.zuul.ZuulFilter; +import com.netflix.zuul.filters.FilterRegistry; +import com.netflix.zuul.filters.ZuulServletFilter; +import com.netflix.zuul.http.ZuulServlet; +import com.netflix.zuul.monitoring.CounterFactory; +import com.netflix.zuul.monitoring.TracerFactory; +import io.micrometer.core.instrument.MeterRegistry; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; @@ -67,16 +75,6 @@ import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import com.netflix.zuul.FilterLoader; -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.filters.FilterRegistry; -import com.netflix.zuul.filters.ZuulServletFilter; -import com.netflix.zuul.http.ZuulServlet; -import com.netflix.zuul.monitoring.CounterFactory; -import com.netflix.zuul.monitoring.TracerFactory; - -import io.micrometer.core.instrument.MeterRegistry; - import static java.util.Collections.emptyList; /** @@ -86,7 +84,7 @@ import static java.util.Collections.emptyList; */ @Configuration @EnableConfigurationProperties({ ZuulProperties.class }) -@ConditionalOnClass({ZuulServlet.class, ZuulServletFilter.class}) +@ConditionalOnClass({ ZuulServlet.class, ZuulServletFilter.class }) @ConditionalOnBean(ZuulServerMarkerConfiguration.Marker.class) // Make sure to get the ServerProperties from the same place as a normal web app would // FIXME @Import(ServerPropertiesAutoConfiguration.class) @@ -108,7 +106,8 @@ public class ZuulServerAutoConfiguration { @Bean public HasFeatures zuulFeature() { - return HasFeatures.namedFeature("Zuul (Simple)", ZuulServerAutoConfiguration.class); + return HasFeatures.namedFeature("Zuul (Simple)", + ZuulServerAutoConfiguration.class); } @Bean @@ -141,8 +140,7 @@ public class ZuulServerAutoConfiguration { protected final Map getCorsConfigurations() { if (this.corsConfigurations == null) { ZuulCorsRegistry registry = new ZuulCorsRegistry(); - this.configurers - .forEach(configurer -> configurer.addCorsMappings(registry)); + this.configurers.forEach(configurer -> configurer.addCorsMappings(registry)); this.corsConfigurations = registry.getCorsConfigurations(); } return this.corsConfigurations; @@ -157,8 +155,8 @@ public class ZuulServerAutoConfiguration { @ConditionalOnMissingBean(name = "zuulServlet") @ConditionalOnProperty(name = "zuul.use-filter", havingValue = "false", matchIfMissing = true) public ServletRegistrationBean zuulServlet() { - ServletRegistrationBean servlet = new ServletRegistrationBean<>(new ZuulServlet(), - this.zuulProperties.getServletPattern()); + ServletRegistrationBean servlet = new ServletRegistrationBean<>( + new ZuulServlet(), this.zuulProperties.getServletPattern()); // The whole point of exposing this servlet is to provide a route that doesn't // buffer requests. servlet.addInitParameter("buffer-requests", "false"); @@ -168,9 +166,10 @@ public class ZuulServerAutoConfiguration { @Bean @ConditionalOnMissingBean(name = "zuulServletFilter") @ConditionalOnProperty(name = "zuul.use-filter", havingValue = "true", matchIfMissing = false) - public FilterRegistrationBean zuulServletFilter(){ + public FilterRegistrationBean zuulServletFilter() { final FilterRegistrationBean filterRegistration = new FilterRegistrationBean<>(); - filterRegistration.setUrlPatterns(Collections.singleton(this.zuulProperties.getServletPattern())); + filterRegistration.setUrlPatterns( + Collections.singleton(this.zuulProperties.getServletPattern())); filterRegistration.setFilter(new ZuulServletFilter()); filterRegistration.setOrder(Ordered.LOWEST_PRECEDENCE); // The whole point of exposing this servlet is to provide a route that doesn't @@ -219,7 +218,7 @@ public class ZuulServerAutoConfiguration { } @Bean - @ConditionalOnProperty(value = "zuul.ribbon.eager-load.enabled") + @ConditionalOnProperty("zuul.ribbon.eager-load.enabled") public ZuulRouteApplicationContextInitializer zuulRoutesApplicationContextInitiazer( SpringClientFactory springClientFactory) { return new ZuulRouteApplicationContextInitializer(springClientFactory, @@ -233,11 +232,12 @@ public class ZuulServerAutoConfiguration { private Map filters; @Bean - public ZuulFilterInitializer zuulFilterInitializer( - CounterFactory counterFactory, TracerFactory tracerFactory) { + public ZuulFilterInitializer zuulFilterInitializer(CounterFactory counterFactory, + TracerFactory tracerFactory) { FilterLoader filterLoader = FilterLoader.getInstance(); FilterRegistry filterRegistry = FilterRegistry.instance(); - return new ZuulFilterInitializer(this.filters, counterFactory, tracerFactory, filterLoader, filterRegistry); + return new ZuulFilterInitializer(this.filters, counterFactory, tracerFactory, + filterLoader, filterRegistry); } } @@ -252,6 +252,7 @@ public class ZuulServerAutoConfiguration { public CounterFactory counterFactory(MeterRegistry meterRegistry) { return new DefaultCounterFactory(meterRegistry); } + } @Configuration @@ -307,6 +308,7 @@ public class ZuulServerAutoConfiguration { private void reset() { this.zuulHandlerMapping.setDirty(true); } + } private static class ZuulCorsRegistry extends CorsRegistry { @@ -315,5 +317,7 @@ public class ZuulServerAutoConfiguration { protected Map getCorsConfigurations() { return super.getCorsConfigurations(); } + } + } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulServerMarkerConfiguration.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulServerMarkerConfiguration.java index 93947877b..75df89283 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulServerMarkerConfiguration.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulServerMarkerConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul; @@ -21,19 +20,22 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** - * Responsible for adding in a marker bean to trigger activation of - * {@link ZuulServerAutoConfiguration} + * Responsible for adding in a marker bean to trigger activation of + * {@link ZuulServerAutoConfiguration}. * * @author Biju Kunjummen */ @Configuration public class ZuulServerMarkerConfiguration { + @Bean public Marker zuulServerMarkerBean() { return new Marker(); } class Marker { + } + } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulServletFilter.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulServletFilter.java index 93f3c2e00..3b06b08be 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulServletFilter.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/ZuulServletFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul; @@ -30,19 +29,24 @@ import com.netflix.zuul.context.RequestContext; * @author Craig Andrews */ public class ZuulServletFilter extends com.netflix.zuul.filters.ZuulServletFilter { + @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { // Workaround https://github.com/Netflix/zuul/pull/430 - // This class can be removed, and com.netflix.zuul.filters.ZuulServletFilter used in its place, + // This class can be removed, and com.netflix.zuul.filters.ZuulServletFilter used + // in its place, // when using a Zuul release with that change in it. - // Marks this request as having passed through the "Zuul engine", as opposed to servlets - // explicitly bound in web.xml, for which requests will not have the same data attached - RequestContext context = RequestContext.getCurrentContext(); - context.setZuulEngineRan(); + // Marks this request as having passed through the "Zuul engine", as opposed to + // servlets + // explicitly bound in web.xml, for which requests will not have the same data + // attached + RequestContext context = RequestContext.getCurrentContext(); + context.setZuulEngineRan(); super.doFilter(servletRequest, servletResponse, filterChain); } + } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/CompositeRouteLocator.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/CompositeRouteLocator.java index a106d97ac..6256c1c53 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/CompositeRouteLocator.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/CompositeRouteLocator.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.netflix.zuul.filters; import java.util.ArrayList; @@ -29,7 +30,9 @@ import org.springframework.util.Assert; * */ public class CompositeRouteLocator implements RefreshableRouteLocator { + private final Collection routeLocators; + private ArrayList rl; public CompositeRouteLocator(Collection routeLocators) { @@ -76,4 +79,5 @@ public class CompositeRouteLocator implements RefreshableRouteLocator { } } } -} \ No newline at end of file + +} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/ProxyRequestHelper.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/ProxyRequestHelper.java index 7197ce98b..a0d6aa44e 100755 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/ProxyRequestHelper.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/ProxyRequestHelper.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,13 +27,16 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; -import java.util.regex.Pattern; import java.util.Set; +import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; +import com.netflix.zuul.context.RequestContext; +import com.netflix.zuul.util.HTTPRequestUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.cloud.netflix.zuul.util.RequestUtils; import org.springframework.http.HttpHeaders; import org.springframework.util.LinkedMultiValueMap; @@ -42,12 +45,7 @@ import org.springframework.web.util.UriTemplate; import org.springframework.web.util.UriUtils; import org.springframework.web.util.WebUtils; -import com.netflix.zuul.context.RequestContext; -import com.netflix.zuul.util.HTTPRequestUtils; - import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.REQUEST_URI_KEY; -import static org.springframework.http.HttpHeaders.CONTENT_ENCODING; -import static org.springframework.http.HttpHeaders.CONTENT_LENGTH; /** * @author Dave Syer @@ -64,8 +62,14 @@ public class ProxyRequestHelper { */ public static final String IGNORED_HEADERS = "ignoredHeaders"; + /** + * Form feed pattern. + */ public static final Pattern FORM_FEED_PATTERN = Pattern.compile("\f"); + /** + * Colon pattern. + */ public static final Pattern COLON_PATTERN = Pattern.compile(":"); private Set ignoredHeaders = new LinkedHashSet<>(); @@ -81,8 +85,9 @@ public class ProxyRequestHelper { private boolean urlDecoded = true; @Deprecated - //TODO Remove in 2.1.x - public ProxyRequestHelper() {} + // TODO Remove in 2.1.x + public ProxyRequestHelper() { + } public ProxyRequestHelper(ZuulProperties zuulProperties) { this.ignoredHeaders.addAll(zuulProperties.getIgnoredHeaders()); @@ -100,13 +105,13 @@ public class ProxyRequestHelper { } @Deprecated - //TODO Remove in 2.1.x + // TODO Remove in 2.1.x public void setIgnoredHeaders(Set ignoredHeaders) { this.ignoredHeaders.addAll(ignoredHeaders); } @Deprecated - //TODO Remove in 2.1.x + // TODO Remove in 2.1.x public void setTraceRequestBody(boolean traceRequestBody) { this.traceRequestBody = traceRequestBody; } @@ -170,11 +175,11 @@ public class ProxyRequestHelper { } Map zuulRequestHeaders = context.getZuulRequestHeaders(); for (String header : zuulRequestHeaders.keySet()) { - if (isIncludedHeader(header)){ + if (isIncludedHeader(header)) { headers.set(header, zuulRequestHeaders.get(header)); } } - if(!headers.containsKey(HttpHeaders.ACCEPT_ENCODING)) { + if (!headers.containsKey(HttpHeaders.ACCEPT_ENCODING)) { headers.set(HttpHeaders.ACCEPT_ENCODING, "gzip"); } return headers; @@ -235,7 +240,7 @@ public class ProxyRequestHelper { } switch (name) { case "host": - if(addHostHeader) { + if (addHostHeader) { return true; } case "connection": @@ -273,10 +278,10 @@ public class ProxyRequestHelper { } /** - * Get url encoded query string. Pay special attention to single parameters with no values - * and parameter names with colon (:) from use of UriTemplate. + * Get url encoded query string. Pay special attention to single parameters with no + * values and parameter names with colon (:) from use of UriTemplate. * @param params Un-encoded request parameters - * @return + * @return url-encoded query String built from provided parameters */ public String getQueryString(MultiValueMap params) { if (params.isEmpty()) { @@ -289,7 +294,8 @@ public class ProxyRequestHelper { for (String value : params.get(param)) { query.append("&"); query.append(param); - if (!"".equals(value)) { // don't add =, if original is ?wsdl, output is not ?wsdl= + if (!"".equals(value)) { // don't add =, if original is ?wsdl, output is + // not ?wsdl= String key = param; // if form feed is already part of param name double // since form feed is used as the colon replacement below @@ -313,4 +319,5 @@ public class ProxyRequestHelper { UriTemplate template = new UriTemplate("?" + query.toString().substring(1)); return template.expand(singles).toString(); } + } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/Route.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/Route.java index 2c327ef31..161cc691d 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/Route.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/Route.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,6 +22,13 @@ import java.util.Set; import org.springframework.util.StringUtils; +/** + * Represents Zuul route. + * + * @author Dave Syer + * @author Biju Kunjummen + * @author Gregor Zurowski + */ public class Route { public Route(String id, String path, String location, String prefix, @@ -42,7 +49,7 @@ public class Route { } public Route(String id, String path, String location, String prefix, - Boolean retryable, Set ignoredHeaders, boolean prefixStripped) { + Boolean retryable, Set ignoredHeaders, boolean prefixStripped) { this(id, path, location, prefix, retryable, ignoredHeaders); this.prefixStripped = prefixStripped; } @@ -139,18 +146,21 @@ public class Route { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } Route that = (Route) o; - return customSensitiveHeaders == that.customSensitiveHeaders && - prefixStripped == that.prefixStripped && - Objects.equals(id, that.id) && - Objects.equals(fullPath, that.fullPath) && - Objects.equals(path, that.path) && - Objects.equals(location, that.location) && - Objects.equals(prefix, that.prefix) && - Objects.equals(retryable, that.retryable) && - Objects.equals(sensitiveHeaders, that.sensitiveHeaders); + return customSensitiveHeaders == that.customSensitiveHeaders + && prefixStripped == that.prefixStripped && Objects.equals(id, that.id) + && Objects.equals(fullPath, that.fullPath) + && Objects.equals(path, that.path) + && Objects.equals(location, that.location) + && Objects.equals(prefix, that.prefix) + && Objects.equals(retryable, that.retryable) + && Objects.equals(sensitiveHeaders, that.sensitiveHeaders); } @Override @@ -161,16 +171,15 @@ public class Route { @Override public String toString() { - return new StringBuilder("Route{") - .append("id='").append(id).append("', ") - .append("fullPath='").append(fullPath).append("', ") - .append("path='").append(path).append("', ") - .append("location='").append(location).append("', ") - .append("prefix='").append(prefix).append("', ") + return new StringBuilder("Route{").append("id='").append(id).append("', ") + .append("fullPath='").append(fullPath).append("', ").append("path='") + .append(path).append("', ").append("location='").append(location) + .append("', ").append("prefix='").append(prefix).append("', ") .append("retryable=").append(retryable).append(", ") .append("sensitiveHeaders=").append(sensitiveHeaders).append(", ") - .append("customSensitiveHeaders=").append(customSensitiveHeaders).append(", ") - .append("prefixStripped=").append(prefixStripped) - .append("}").toString(); + .append("customSensitiveHeaders=").append(customSensitiveHeaders) + .append(", ").append("prefixStripped=").append(prefixStripped).append("}") + .toString(); } -} \ No newline at end of file + +} diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/RouteLocator.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/RouteLocator.java index 7c7e38575..68ff4337a 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/RouteLocator.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/RouteLocator.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,16 +26,20 @@ public interface RouteLocator { /** * Ignored route paths (or patterns), if any. + * @return {@link Collection} of ignored paths */ Collection getIgnoredPaths(); /** * A map of route path (pattern) to location (e.g. service id or URL). + * @return {@link List} of routes */ List getRoutes(); /** * Maps a path to an actual route with full metadata. + * @param path used to match the {@link Route} + * @return matching {@link Route} based on the provided path */ Route getMatchingRoute(String path); diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/SimpleRouteLocator.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/SimpleRouteLocator.java index a9b216ea2..456414231 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/SimpleRouteLocator.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/SimpleRouteLocator.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.filters; @@ -24,8 +23,10 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicReference; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.cloud.netflix.zuul.filters.ZuulProperties.ZuulRoute; import org.springframework.cloud.netflix.zuul.util.RequestUtils; import org.springframework.core.Ordered; @@ -49,9 +50,11 @@ public class SimpleRouteLocator implements RouteLocator, Ordered { private PathMatcher pathMatcher = new AntPathMatcher(); private String dispatcherServletPath = "/"; + private String zuulServletPath; private AtomicReference> routes = new AtomicReference<>(); + private int order = DEFAULT_ORDER; public SimpleRouteLocator(String servletPath, ZuulProperties properties) { @@ -74,8 +77,9 @@ public class SimpleRouteLocator implements RouteLocator, Ordered { } catch (Exception e) { if (log.isWarnEnabled()) { - log.warn("Invalid route, routeId: " + route.getId() + ", routeServiceId: " - + route.getServiceId() + ", msg: " + e.getMessage()); + log.warn("Invalid route, routeId: " + route.getId() + + ", routeServiceId: " + route.getServiceId() + ", msg: " + + e.getMessage()); } if (log.isDebugEnabled()) { log.debug("", e); @@ -185,6 +189,7 @@ public class SimpleRouteLocator implements RouteLocator, Ordered { /** * Compute a map of path pattern to route. The default is just a static map from the * {@link ZuulProperties}, but subclasses can add dynamic calculations. + * @return map of Zuul routes */ protected Map locateRoutes() { LinkedHashMap routesMap = new LinkedHashMap<>(); @@ -210,7 +215,8 @@ public class SimpleRouteLocator implements RouteLocator, Ordered { if (RequestUtils.isDispatcherServletRequest() && StringUtils.hasText(this.dispatcherServletPath)) { - if (!this.dispatcherServletPath.equals("/") && path.startsWith(this.dispatcherServletPath)) { + if (!this.dispatcherServletPath.equals("/") + && path.startsWith(this.dispatcherServletPath)) { adjustedPath = path.substring(this.dispatcherServletPath.length()); log.debug("Stripped dispatcherServletPath"); } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/TraceProxyRequestHelper.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/TraceProxyRequestHelper.java index b69966459..2c95e0f8b 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/TraceProxyRequestHelper.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/TraceProxyRequestHelper.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.filters; @@ -50,8 +49,9 @@ public class TraceProxyRequestHelper extends ProxyRequestHelper { private HttpTraceRepository traces; @Deprecated - //TODO Remove in 2.1.x - public TraceProxyRequestHelper(){} + // TODO Remove in 2.1.x + public TraceProxyRequestHelper() { + } public TraceProxyRequestHelper(ZuulProperties zuulProperties) { super(zuulProperties); @@ -96,11 +96,49 @@ public class TraceProxyRequestHelper extends ProxyRequestHelper { return info; } + void debugHeaders(MultiValueMap headers, Map map) { + for (Entry> entry : headers.entrySet()) { + Collection collection = entry.getValue(); + Object value = collection; + if (collection.size() < 2) { + value = collection.isEmpty() ? "" : collection.iterator().next(); + } + map.put(entry.getKey(), value); + } + } + + public void appendDebug(Map info, int status, + MultiValueMap headers) { + if (this.traces != null) { + @SuppressWarnings("unchecked") + Map trace = (Map) info.get("headers"); + Map output = new LinkedHashMap<>(); + trace.put("response", output); + debugHeaders(headers, output); + output.put("status", "" + status); + } + } + + private void debugRequestEntity(Map info, InputStream inputStream) + throws IOException { + if (RequestContext.getCurrentContext().isChunkedRequestBody()) { + info.put("body", ""); + return; + } + char[] buffer = new char[4096]; + int count = new InputStreamReader(inputStream, Charset.forName("UTF-8")) + .read(buffer, 0, buffer.length); + if (count > 0) { + String entity = new String(buffer).substring(0, count); + info.put("body", entity.length() < 4096 ? entity : entity + ""); + } + } + private class ServletTraceableRequest implements TraceableRequest { + private HttpServletRequest request; - public ServletTraceableRequest(HttpServletRequest request) { - + ServletTraceableRequest(HttpServletRequest request) { this.request = request; } @@ -146,44 +184,7 @@ public class TraceProxyRequestHelper extends ProxyRequestHelper { } return list; } - } - void debugHeaders(MultiValueMap headers, Map map) { - for (Entry> entry : headers.entrySet()) { - Collection collection = entry.getValue(); - Object value = collection; - if (collection.size() < 2) { - value = collection.isEmpty() ? "" : collection.iterator().next(); - } - map.put(entry.getKey(), value); - } - } - - public void appendDebug(Map info, int status, - MultiValueMap headers) { - if (this.traces != null) { - @SuppressWarnings("unchecked") - Map trace = (Map) info.get("headers"); - Map output = new LinkedHashMap<>(); - trace.put("response", output); - debugHeaders(headers, output); - output.put("status", "" + status); - } - } - - private void debugRequestEntity(Map info, InputStream inputStream) - throws IOException { - if (RequestContext.getCurrentContext().isChunkedRequestBody()) { - info.put("body", ""); - return; - } - char[] buffer = new char[4096]; - int count = new InputStreamReader(inputStream, Charset.forName("UTF-8")) - .read(buffer, 0, buffer.length); - if (count > 0) { - String entity = new String(buffer).substring(0, count); - info.put("body", entity.length() < 4096 ? entity : entity + ""); - } } } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/ZuulProperties.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/ZuulProperties.java index 04f7e6fd0..e2439a90d 100755 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/ZuulProperties.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/ZuulProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,13 +16,6 @@ package org.springframework.cloud.netflix.zuul.filters; -import com.netflix.hystrix.HystrixCommandProperties.ExecutionIsolationStrategy; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.core.style.ToStringCreator; -import org.springframework.util.ClassUtils; -import org.springframework.util.StringUtils; - -import javax.annotation.PostConstruct; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; @@ -34,6 +27,15 @@ import java.util.Objects; import java.util.Set; import java.util.concurrent.TimeUnit; +import javax.annotation.PostConstruct; + +import com.netflix.hystrix.HystrixCommandProperties.ExecutionIsolationStrategy; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.core.style.ToStringCreator; +import org.springframework.util.ClassUtils; +import org.springframework.util.StringUtils; + import static com.netflix.hystrix.HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE; /** @@ -49,7 +51,8 @@ public class ZuulProperties { /** * Headers that are generally expected to be added by Spring Security, and hence often * duplicated if the proxy and the backend are secured with Spring. By default they - * are added to the ignored headers if Spring Security is present and ignoreSecurityHeaders = true. + * are added to the ignored headers if Spring Security is present and + * ignoreSecurityHeaders = true. */ public static final List SECURITY_HEADERS = Arrays.asList("Pragma", "Cache-Control", "X-Frame-Options", "X-Content-Type-Options", @@ -101,13 +104,14 @@ public class ZuulProperties { private Set ignoredHeaders = new LinkedHashSet<>(); /** - * Flag to say that SECURITY_HEADERS are added to ignored headers if spring security is on the classpath. - * By setting ignoreSecurityHeaders to false we can switch off this default behaviour. This should be used together with - * disabling the default spring security headers - * see https://docs.spring.io/spring-security/site/docs/current/reference/html/headers.html#default-security-headers + * Flag to say that SECURITY_HEADERS are added to ignored headers if spring security + * is on the classpath. By setting ignoreSecurityHeaders to false we can switch off + * this default behaviour. This should be used together with disabling the default + * spring security headers see + * https://docs.spring.io/spring-security/site/docs/current/reference/html/headers.html#default-security-headers */ private boolean ignoreSecurityHeaders = true; - + /** * Flag to force the original query string encoding when building the backend URI in * SimpleHostRoutingFilter. When activated, query string will be built using @@ -156,13 +160,13 @@ public class ZuulProperties { Arrays.asList("Cookie", "Set-Cookie", "Authorization")); /** - * Flag to say whether the hostname for ssl connections should be verified or not. Default is true. - * This should only be used in test setups! + * Flag to say whether the hostname for ssl connections should be verified or not. + * Default is true. This should only be used in test setups! */ - private boolean sslHostnameValidationEnabled =true; + private boolean sslHostnameValidationEnabled = true; private ExecutionIsolationStrategy ribbonIsolationStrategy = SEMAPHORE; - + private HystrixSemaphore semaphore = new HystrixSemaphore(); private HystrixThreadPool threadPool = new HystrixThreadPool(); @@ -177,16 +181,17 @@ public class ZuulProperties { */ private boolean includeDebugHeader = false; - /** - * Setting for SendResponseFilter for the initial stream buffer size. - */ - private int initialStreamBufferSize = 8192; + /** + * Setting for SendResponseFilter for the initial stream buffer size. + */ + private int initialStreamBufferSize = 8192; public Set getIgnoredHeaders() { Set ignoredHeaders = new LinkedHashSet<>(this.ignoredHeaders); if (ClassUtils.isPresent( "org.springframework.security.config.annotation.web.WebSecurityConfigurer", - null) && Collections.disjoint(ignoredHeaders, SECURITY_HEADERS) && ignoreSecurityHeaders) { + null) && Collections.disjoint(ignoredHeaders, SECURITY_HEADERS) + && ignoreSecurityHeaders) { // Allow Spring Security in the gateway to control these headers ignoredHeaders.addAll(SECURITY_HEADERS); } @@ -213,430 +218,6 @@ public class ZuulProperties { } } - public static class ZuulRoute { - - /** - * The ID of the route (the same as its map key by default). - */ - private String id; - - /** - * The path (pattern) for the route, e.g. /foo/**. - */ - private String path; - - /** - * The service ID (if any) to map to this route. You can specify a physical URL or - * a service, but not both. - */ - private String serviceId; - - /** - * A full physical URL to map to the route. An alternative is to use a service ID - * and service discovery to find the physical address. - */ - private String url; - - /** - * Flag to determine whether the prefix for this route (the path, minus pattern - * patcher) should be stripped before forwarding. - */ - private boolean stripPrefix = true; - - /** - * Flag to indicate that this route should be retryable (if supported). Generally - * retry requires a service ID and ribbon. - */ - private Boolean retryable; - - /** - * List of sensitive headers that are not passed to downstream requests. Defaults - * to a "safe" set of headers that commonly contain user credentials. It's OK to - * remove those from the list if the downstream service is part of the same system - * as the proxy, so they are sharing authentication data. If using a physical URL - * outside your own domain, then generally it would be a bad idea to leak user - * credentials. - */ - private Set sensitiveHeaders = new LinkedHashSet<>(); - - private boolean customSensitiveHeaders = false; - - public ZuulRoute() {} - - public ZuulRoute(String id, String path, String serviceId, String url, - boolean stripPrefix, Boolean retryable, Set sensitiveHeaders) { - this.id = id; - this.path = path; - this.serviceId = serviceId; - this.url = url; - this.stripPrefix = stripPrefix; - this.retryable = retryable; - this.sensitiveHeaders = sensitiveHeaders; - this.customSensitiveHeaders = sensitiveHeaders != null; - } - - public ZuulRoute(String text) { - String location = null; - String path = text; - if (text.contains("=")) { - String[] values = StringUtils - .trimArrayElements(StringUtils.split(text, "=")); - location = values[1]; - path = values[0]; - } - this.id = extractId(path); - if (!path.startsWith("/")) { - path = "/" + path; - } - setLocation(location); - this.path = path; - } - - public ZuulRoute(String path, String location) { - this.id = extractId(path); - this.path = path; - setLocation(location); - } - - public String getLocation() { - if (StringUtils.hasText(this.url)) { - return this.url; - } - return this.serviceId; - } - - public void setLocation(String location) { - if (location != null - && (location.startsWith("http:") || location.startsWith("https:"))) { - this.url = location; - } - else { - this.serviceId = location; - } - } - - private String extractId(String path) { - path = path.startsWith("/") ? path.substring(1) : path; - path = path.replace("/*", "").replace("*", ""); - return path; - } - - public Route getRoute(String prefix) { - return new Route(this.id, this.path, getLocation(), prefix, this.retryable, - isCustomSensitiveHeaders() ? this.sensitiveHeaders : null, - this.stripPrefix); - } - - public void setSensitiveHeaders(Set headers) { - this.customSensitiveHeaders = true; - this.sensitiveHeaders = new LinkedHashSet<>(headers); - } - - public boolean isCustomSensitiveHeaders() { - return this.customSensitiveHeaders; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getPath() { - return path; - } - - public void setPath(String path) { - this.path = path; - } - - public String getServiceId() { - return serviceId; - } - - public void setServiceId(String serviceId) { - this.serviceId = serviceId; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public boolean isStripPrefix() { - return stripPrefix; - } - - public void setStripPrefix(boolean stripPrefix) { - this.stripPrefix = stripPrefix; - } - - public Boolean getRetryable() { - return retryable; - } - - public void setRetryable(Boolean retryable) { - this.retryable = retryable; - } - - public Set getSensitiveHeaders() { - return sensitiveHeaders; - } - - public void setCustomSensitiveHeaders(boolean customSensitiveHeaders) { - this.customSensitiveHeaders = customSensitiveHeaders; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - ZuulRoute that = (ZuulRoute) o; - return customSensitiveHeaders == that.customSensitiveHeaders && - Objects.equals(id, that.id) && - Objects.equals(path, that.path) && - Objects.equals(retryable, that.retryable) && - Objects.equals(sensitiveHeaders, that.sensitiveHeaders) && - Objects.equals(serviceId, that.serviceId) && - stripPrefix == that.stripPrefix && - Objects.equals(url, that.url); - } - - @Override - public int hashCode() { - return Objects.hash(customSensitiveHeaders, id, path, retryable, - sensitiveHeaders, serviceId, stripPrefix, url); - } - - @Override public String toString() { - return new StringBuilder("ZuulRoute{").append("id='").append(id).append("', ") - .append("path='").append(path).append("', ") - .append("serviceId='").append(serviceId).append("', ") - .append("url='").append(url).append("', ") - .append("stripPrefix=").append(stripPrefix).append(", ") - .append("retryable=").append(retryable).append(", ") - .append("sensitiveHeaders=").append(sensitiveHeaders).append(", ") - .append("customSensitiveHeaders=").append(customSensitiveHeaders).append(", ") - .append("}").toString(); - } - - } - - public static class Host { - /** - * The maximum number of total connections the proxy can hold open to backends. - */ - private int maxTotalConnections = 200; - /** - * The maximum number of connections that can be used by a single route. - */ - private int maxPerRouteConnections = 20; - /** - * The socket timeout in millis. Defaults to 10000. - */ - private int socketTimeoutMillis = 10000; - /** - * The connection timeout in millis. Defaults to 2000. - */ - private int connectTimeoutMillis = 2000; - /** - * The timeout in milliseconds used when requesting a connection - * from the connection manager. Defaults to -1, undefined use the system default. - */ - private int connectionRequestTimeoutMillis = -1; - /** - * The lifetime for the connection pool. - */ - private long timeToLive = -1; - /** - * The time unit for timeToLive. - */ - private TimeUnit timeUnit = TimeUnit.MILLISECONDS; - - public Host() { - } - - public Host(int maxTotalConnections, int maxPerRouteConnections, - int socketTimeoutMillis, int connectTimeoutMillis, long timeToLive, - TimeUnit timeUnit) { - this.maxTotalConnections = maxTotalConnections; - this.maxPerRouteConnections = maxPerRouteConnections; - this.socketTimeoutMillis = socketTimeoutMillis; - this.connectTimeoutMillis = connectTimeoutMillis; - this.timeToLive = timeToLive; - this.timeUnit = timeUnit; - } - - public int getMaxTotalConnections() { - return maxTotalConnections; - } - - public void setMaxTotalConnections(int maxTotalConnections) { - this.maxTotalConnections = maxTotalConnections; - } - - public int getMaxPerRouteConnections() { - return maxPerRouteConnections; - } - - public void setMaxPerRouteConnections(int maxPerRouteConnections) { - this.maxPerRouteConnections = maxPerRouteConnections; - } - - public int getSocketTimeoutMillis() { - return socketTimeoutMillis; - } - - public void setSocketTimeoutMillis(int socketTimeoutMillis) { - this.socketTimeoutMillis = socketTimeoutMillis; - } - - public int getConnectTimeoutMillis() { - return connectTimeoutMillis; - } - - public void setConnectTimeoutMillis(int connectTimeoutMillis) { - this.connectTimeoutMillis = connectTimeoutMillis; - } - - public int getConnectionRequestTimeoutMillis() { - return connectionRequestTimeoutMillis; - } - - public void setConnectionRequestTimeoutMillis(int connectionRequestTimeoutMillis) { - this.connectionRequestTimeoutMillis = connectionRequestTimeoutMillis; - } - - public long getTimeToLive() { - return timeToLive; - } - - public void setTimeToLive(long timeToLive) { - this.timeToLive = timeToLive; - } - - public TimeUnit getTimeUnit() { - return timeUnit; - } - - public void setTimeUnit(TimeUnit timeUnit) { - this.timeUnit = timeUnit; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Host host = (Host) o; - return maxTotalConnections == host.maxTotalConnections && - maxPerRouteConnections == host.maxPerRouteConnections && - socketTimeoutMillis == host.socketTimeoutMillis && - connectTimeoutMillis == host.connectTimeoutMillis && - connectionRequestTimeoutMillis == host.connectionRequestTimeoutMillis && - timeToLive == host.timeToLive && - timeUnit == host.timeUnit; - } - - @Override - public int hashCode() { - return Objects.hash(maxTotalConnections, maxPerRouteConnections, socketTimeoutMillis, connectTimeoutMillis, - connectionRequestTimeoutMillis, timeToLive, timeUnit); - } - - @Override - public String toString() { - return new ToStringCreator(this) - .append("maxTotalConnections", maxTotalConnections) - .append("maxPerRouteConnections", maxPerRouteConnections) - .append("socketTimeoutMillis", socketTimeoutMillis) - .append("connectTimeoutMillis", connectTimeoutMillis) - .append("connectionRequestTimeoutMillis", connectionRequestTimeoutMillis) - .append("timeToLive", timeToLive) - .append("timeUnit", timeUnit) - .toString(); - } - } - - public static class HystrixSemaphore { - /** - * The maximum number of total semaphores for Hystrix. - */ - private int maxSemaphores = 100; - - public HystrixSemaphore() {} - - public HystrixSemaphore(int maxSemaphores) { - this.maxSemaphores = maxSemaphores; - } - - public int getMaxSemaphores() { - return maxSemaphores; - } - - public void setMaxSemaphores(int maxSemaphores) { - this.maxSemaphores = maxSemaphores; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - HystrixSemaphore that = (HystrixSemaphore) o; - return maxSemaphores == that.maxSemaphores; - } - - @Override - public int hashCode() { - return Objects.hash(maxSemaphores); - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("HystrixSemaphore{"); - sb.append("maxSemaphores=").append(maxSemaphores); - sb.append('}'); - return sb.toString(); - } - } - - public static class HystrixThreadPool { - /** - * Flag to determine whether RibbonCommands should use separate thread pools for hystrix. - * By setting to true, RibbonCommands will be executed in a hystrix's thread pool that it is associated with. - * Each RibbonCommand will be associated with a thread pool according to its commandKey (serviceId). - * As default, all commands will be executed in a single thread pool whose threadPoolKey is "RibbonCommand". - * This property is only applicable when using THREAD as ribbonIsolationStrategy - */ - private boolean useSeparateThreadPools = false; - - /** - * A prefix for HystrixThreadPoolKey of hystrix's thread pool that is allocated to each service Id. - * This property is only applicable when using THREAD as ribbonIsolationStrategy and useSeparateThreadPools = true - */ - private String threadPoolKeyPrefix = ""; - - public boolean isUseSeparateThreadPools() { - return useSeparateThreadPools; - } - - public void setUseSeparateThreadPools(boolean useSeparateThreadPools) { - this.useSeparateThreadPools = useSeparateThreadPools; - } - - public String getThreadPoolKeyPrefix() { - return threadPoolKeyPrefix; - } - - public void setThreadPoolKeyPrefix(String threadPoolKeyPrefix) { - this.threadPoolKeyPrefix = threadPoolKeyPrefix; - } - } - public String getServletPattern() { String path = this.servletPath; if (!path.startsWith("/")) { @@ -844,73 +425,543 @@ public class ZuulProperties { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } ZuulProperties that = (ZuulProperties) o; - return addHostHeader == that.addHostHeader && - addProxyHeaders == that.addProxyHeaders && - forceOriginalQueryStringEncoding == that.forceOriginalQueryStringEncoding && - Objects.equals(host, that.host) && - Objects.equals(ignoredHeaders, that.ignoredHeaders) && - Objects.equals(ignoredPatterns, that.ignoredPatterns) && - Objects.equals(ignoredServices, that.ignoredServices) && - ignoreLocalService == that.ignoreLocalService && - ignoreSecurityHeaders == that.ignoreSecurityHeaders && - Objects.equals(prefix, that.prefix) && - removeSemicolonContent == that.removeSemicolonContent && - Objects.equals(retryable, that.retryable) && - Objects.equals(ribbonIsolationStrategy, that.ribbonIsolationStrategy) && - Objects.equals(routes, that.routes) && - Objects.equals(semaphore, that.semaphore) && - Objects.equals(sensitiveHeaders, that.sensitiveHeaders) && - Objects.equals(servletPath, that.servletPath) && - sslHostnameValidationEnabled == that.sslHostnameValidationEnabled && - stripPrefix == that.stripPrefix && - setContentLength == that.setContentLength && - includeDebugHeader == that.includeDebugHeader && - initialStreamBufferSize == that.initialStreamBufferSize && - Objects.equals(threadPool, that.threadPool) && - traceRequestBody == that.traceRequestBody; + return addHostHeader == that.addHostHeader + && addProxyHeaders == that.addProxyHeaders + && forceOriginalQueryStringEncoding == that.forceOriginalQueryStringEncoding + && Objects.equals(host, that.host) + && Objects.equals(ignoredHeaders, that.ignoredHeaders) + && Objects.equals(ignoredPatterns, that.ignoredPatterns) + && Objects.equals(ignoredServices, that.ignoredServices) + && ignoreLocalService == that.ignoreLocalService + && ignoreSecurityHeaders == that.ignoreSecurityHeaders + && Objects.equals(prefix, that.prefix) + && removeSemicolonContent == that.removeSemicolonContent + && Objects.equals(retryable, that.retryable) + && Objects.equals(ribbonIsolationStrategy, that.ribbonIsolationStrategy) + && Objects.equals(routes, that.routes) + && Objects.equals(semaphore, that.semaphore) + && Objects.equals(sensitiveHeaders, that.sensitiveHeaders) + && Objects.equals(servletPath, that.servletPath) + && sslHostnameValidationEnabled == that.sslHostnameValidationEnabled + && stripPrefix == that.stripPrefix + && setContentLength == that.setContentLength + && includeDebugHeader == that.includeDebugHeader + && initialStreamBufferSize == that.initialStreamBufferSize + && Objects.equals(threadPool, that.threadPool) + && traceRequestBody == that.traceRequestBody; } @Override public int hashCode() { - return Objects.hash(addHostHeader, addProxyHeaders, forceOriginalQueryStringEncoding, - host, ignoredHeaders, ignoredPatterns, ignoredServices, ignoreLocalService, - ignoreSecurityHeaders, prefix, removeSemicolonContent, retryable, - ribbonIsolationStrategy, routes, semaphore, sensitiveHeaders, servletPath, - sslHostnameValidationEnabled, stripPrefix, threadPool, traceRequestBody, - setContentLength, includeDebugHeader, initialStreamBufferSize); + return Objects.hash(addHostHeader, addProxyHeaders, + forceOriginalQueryStringEncoding, host, ignoredHeaders, ignoredPatterns, + ignoredServices, ignoreLocalService, ignoreSecurityHeaders, prefix, + removeSemicolonContent, retryable, ribbonIsolationStrategy, routes, + semaphore, sensitiveHeaders, servletPath, sslHostnameValidationEnabled, + stripPrefix, threadPool, traceRequestBody, setContentLength, + includeDebugHeader, initialStreamBufferSize); } @Override public String toString() { - return new StringBuilder("ZuulProperties{") - .append("prefix='").append(prefix).append("', ") - .append("stripPrefix=").append(stripPrefix).append(", ") - .append("retryable=").append(retryable).append(", ") - .append("routes=").append(routes).append(", ") - .append("addProxyHeaders=").append(addProxyHeaders).append(", ") - .append("addHostHeader=").append(addHostHeader).append(", ") - .append("ignoredServices=").append(ignoredServices).append(", ") - .append("ignoredPatterns=").append(ignoredPatterns).append(", ") - .append("ignoredHeaders=").append(ignoredHeaders).append(", ") - .append("ignoreSecurityHeaders=").append(ignoreSecurityHeaders).append(", ") - .append("forceOriginalQueryStringEncoding=").append(forceOriginalQueryStringEncoding).append(", ") + return new StringBuilder("ZuulProperties{").append("prefix='").append(prefix) + .append("', ").append("stripPrefix=").append(stripPrefix).append(", ") + .append("retryable=").append(retryable).append(", ").append("routes=") + .append(routes).append(", ").append("addProxyHeaders=") + .append(addProxyHeaders).append(", ").append("addHostHeader=") + .append(addHostHeader).append(", ").append("ignoredServices=") + .append(ignoredServices).append(", ").append("ignoredPatterns=") + .append(ignoredPatterns).append(", ").append("ignoredHeaders=") + .append(ignoredHeaders).append(", ").append("ignoreSecurityHeaders=") + .append(ignoreSecurityHeaders).append(", ") + .append("forceOriginalQueryStringEncoding=") + .append(forceOriginalQueryStringEncoding).append(", ") .append("servletPath='").append(servletPath).append("', ") .append("ignoreLocalService=").append(ignoreLocalService).append(", ") - .append("host=").append(host).append(", ") - .append("traceRequestBody=").append(traceRequestBody).append(", ") - .append("removeSemicolonContent=").append(removeSemicolonContent).append(", ") - .append("sensitiveHeaders=").append(sensitiveHeaders).append(", ") - .append("sslHostnameValidationEnabled=").append(sslHostnameValidationEnabled).append(", ") - .append("ribbonIsolationStrategy=").append(ribbonIsolationStrategy).append(", ") - .append("semaphore=").append(semaphore).append(", ") + .append("host=").append(host).append(", ").append("traceRequestBody=") + .append(traceRequestBody).append(", ").append("removeSemicolonContent=") + .append(removeSemicolonContent).append(", ").append("sensitiveHeaders=") + .append(sensitiveHeaders).append(", ") + .append("sslHostnameValidationEnabled=") + .append(sslHostnameValidationEnabled).append(", ") + .append("ribbonIsolationStrategy=").append(ribbonIsolationStrategy) + .append(", ").append("semaphore=").append(semaphore).append(", ") .append("threadPool=").append(threadPool).append(", ") .append("setContentLength=").append(setContentLength).append(", ") .append("includeDebugHeader=").append(includeDebugHeader).append(", ") - .append("initialStreamBufferSize=").append(initialStreamBufferSize).append(", ") - .append("}").toString(); + .append("initialStreamBufferSize=").append(initialStreamBufferSize) + .append(", ").append("}").toString(); + } + + /** + * Represents a Zuul route. + */ + public static class ZuulRoute { + + /** + * The ID of the route (the same as its map key by default). + */ + private String id; + + /** + * The path (pattern) for the route, e.g. /foo/**. + */ + private String path; + + /** + * The service ID (if any) to map to this route. You can specify a physical URL or + * a service, but not both. + */ + private String serviceId; + + /** + * A full physical URL to map to the route. An alternative is to use a service ID + * and service discovery to find the physical address. + */ + private String url; + + /** + * Flag to determine whether the prefix for this route (the path, minus pattern + * patcher) should be stripped before forwarding. + */ + private boolean stripPrefix = true; + + /** + * Flag to indicate that this route should be retryable (if supported). Generally + * retry requires a service ID and ribbon. + */ + private Boolean retryable; + + /** + * List of sensitive headers that are not passed to downstream requests. Defaults + * to a "safe" set of headers that commonly contain user credentials. It's OK to + * remove those from the list if the downstream service is part of the same system + * as the proxy, so they are sharing authentication data. If using a physical URL + * outside your own domain, then generally it would be a bad idea to leak user + * credentials. + */ + private Set sensitiveHeaders = new LinkedHashSet<>(); + + private boolean customSensitiveHeaders = false; + + public ZuulRoute() { + } + + public ZuulRoute(String id, String path, String serviceId, String url, + boolean stripPrefix, Boolean retryable, Set sensitiveHeaders) { + this.id = id; + this.path = path; + this.serviceId = serviceId; + this.url = url; + this.stripPrefix = stripPrefix; + this.retryable = retryable; + this.sensitiveHeaders = sensitiveHeaders; + this.customSensitiveHeaders = sensitiveHeaders != null; + } + + public ZuulRoute(String text) { + String location = null; + String path = text; + if (text.contains("=")) { + String[] values = StringUtils + .trimArrayElements(StringUtils.split(text, "=")); + location = values[1]; + path = values[0]; + } + this.id = extractId(path); + if (!path.startsWith("/")) { + path = "/" + path; + } + setLocation(location); + this.path = path; + } + + public ZuulRoute(String path, String location) { + this.id = extractId(path); + this.path = path; + setLocation(location); + } + + public String getLocation() { + if (StringUtils.hasText(this.url)) { + return this.url; + } + return this.serviceId; + } + + public void setLocation(String location) { + if (location != null + && (location.startsWith("http:") || location.startsWith("https:"))) { + this.url = location; + } + else { + this.serviceId = location; + } + } + + private String extractId(String path) { + path = path.startsWith("/") ? path.substring(1) : path; + path = path.replace("/*", "").replace("*", ""); + return path; + } + + public Route getRoute(String prefix) { + return new Route(this.id, this.path, getLocation(), prefix, this.retryable, + isCustomSensitiveHeaders() ? this.sensitiveHeaders : null, + this.stripPrefix); + } + + public boolean isCustomSensitiveHeaders() { + return this.customSensitiveHeaders; + } + + public void setCustomSensitiveHeaders(boolean customSensitiveHeaders) { + this.customSensitiveHeaders = customSensitiveHeaders; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public String getServiceId() { + return serviceId; + } + + public void setServiceId(String serviceId) { + this.serviceId = serviceId; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public boolean isStripPrefix() { + return stripPrefix; + } + + public void setStripPrefix(boolean stripPrefix) { + this.stripPrefix = stripPrefix; + } + + public Boolean getRetryable() { + return retryable; + } + + public void setRetryable(Boolean retryable) { + this.retryable = retryable; + } + + public Set getSensitiveHeaders() { + return sensitiveHeaders; + } + + public void setSensitiveHeaders(Set headers) { + this.customSensitiveHeaders = true; + this.sensitiveHeaders = new LinkedHashSet<>(headers); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ZuulRoute that = (ZuulRoute) o; + return customSensitiveHeaders == that.customSensitiveHeaders + && Objects.equals(id, that.id) && Objects.equals(path, that.path) + && Objects.equals(retryable, that.retryable) + && Objects.equals(sensitiveHeaders, that.sensitiveHeaders) + && Objects.equals(serviceId, that.serviceId) + && stripPrefix == that.stripPrefix && Objects.equals(url, that.url); + } + + @Override + public int hashCode() { + return Objects.hash(customSensitiveHeaders, id, path, retryable, + sensitiveHeaders, serviceId, stripPrefix, url); + } + + @Override + public String toString() { + return new StringBuilder("ZuulRoute{").append("id='").append(id).append("', ") + .append("path='").append(path).append("', ").append("serviceId='") + .append(serviceId).append("', ").append("url='").append(url) + .append("', ").append("stripPrefix=").append(stripPrefix).append(", ") + .append("retryable=").append(retryable).append(", ") + .append("sensitiveHeaders=").append(sensitiveHeaders).append(", ") + .append("customSensitiveHeaders=").append(customSensitiveHeaders) + .append(", ").append("}").toString(); + } + + } + + /** + * Represents a host. + */ + public static class Host { + + /** + * The maximum number of total connections the proxy can hold open to backends. + */ + private int maxTotalConnections = 200; + + /** + * The maximum number of connections that can be used by a single route. + */ + private int maxPerRouteConnections = 20; + + /** + * The socket timeout in millis. Defaults to 10000. + */ + private int socketTimeoutMillis = 10000; + + /** + * The connection timeout in millis. Defaults to 2000. + */ + private int connectTimeoutMillis = 2000; + + /** + * The timeout in milliseconds used when requesting a connection from the + * connection manager. Defaults to -1, undefined use the system default. + */ + private int connectionRequestTimeoutMillis = -1; + + /** + * The lifetime for the connection pool. + */ + private long timeToLive = -1; + + /** + * The time unit for timeToLive. + */ + private TimeUnit timeUnit = TimeUnit.MILLISECONDS; + + public Host() { + } + + public Host(int maxTotalConnections, int maxPerRouteConnections, + int socketTimeoutMillis, int connectTimeoutMillis, long timeToLive, + TimeUnit timeUnit) { + this.maxTotalConnections = maxTotalConnections; + this.maxPerRouteConnections = maxPerRouteConnections; + this.socketTimeoutMillis = socketTimeoutMillis; + this.connectTimeoutMillis = connectTimeoutMillis; + this.timeToLive = timeToLive; + this.timeUnit = timeUnit; + } + + public int getMaxTotalConnections() { + return maxTotalConnections; + } + + public void setMaxTotalConnections(int maxTotalConnections) { + this.maxTotalConnections = maxTotalConnections; + } + + public int getMaxPerRouteConnections() { + return maxPerRouteConnections; + } + + public void setMaxPerRouteConnections(int maxPerRouteConnections) { + this.maxPerRouteConnections = maxPerRouteConnections; + } + + public int getSocketTimeoutMillis() { + return socketTimeoutMillis; + } + + public void setSocketTimeoutMillis(int socketTimeoutMillis) { + this.socketTimeoutMillis = socketTimeoutMillis; + } + + public int getConnectTimeoutMillis() { + return connectTimeoutMillis; + } + + public void setConnectTimeoutMillis(int connectTimeoutMillis) { + this.connectTimeoutMillis = connectTimeoutMillis; + } + + public int getConnectionRequestTimeoutMillis() { + return connectionRequestTimeoutMillis; + } + + public void setConnectionRequestTimeoutMillis( + int connectionRequestTimeoutMillis) { + this.connectionRequestTimeoutMillis = connectionRequestTimeoutMillis; + } + + public long getTimeToLive() { + return timeToLive; + } + + public void setTimeToLive(long timeToLive) { + this.timeToLive = timeToLive; + } + + public TimeUnit getTimeUnit() { + return timeUnit; + } + + public void setTimeUnit(TimeUnit timeUnit) { + this.timeUnit = timeUnit; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Host host = (Host) o; + return maxTotalConnections == host.maxTotalConnections + && maxPerRouteConnections == host.maxPerRouteConnections + && socketTimeoutMillis == host.socketTimeoutMillis + && connectTimeoutMillis == host.connectTimeoutMillis + && connectionRequestTimeoutMillis == host.connectionRequestTimeoutMillis + && timeToLive == host.timeToLive && timeUnit == host.timeUnit; + } + + @Override + public int hashCode() { + return Objects.hash(maxTotalConnections, maxPerRouteConnections, + socketTimeoutMillis, connectTimeoutMillis, + connectionRequestTimeoutMillis, timeToLive, timeUnit); + } + + @Override + public String toString() { + return new ToStringCreator(this) + .append("maxTotalConnections", maxTotalConnections) + .append("maxPerRouteConnections", maxPerRouteConnections) + .append("socketTimeoutMillis", socketTimeoutMillis) + .append("connectTimeoutMillis", connectTimeoutMillis) + .append("connectionRequestTimeoutMillis", + connectionRequestTimeoutMillis) + .append("timeToLive", timeToLive).append("timeUnit", timeUnit) + .toString(); + } + + } + + /** + * Represents Hystrix Sempahores. + */ + public static class HystrixSemaphore { + + /** + * The maximum number of total semaphores for Hystrix. + */ + private int maxSemaphores = 100; + + public HystrixSemaphore() { + } + + public HystrixSemaphore(int maxSemaphores) { + this.maxSemaphores = maxSemaphores; + } + + public int getMaxSemaphores() { + return maxSemaphores; + } + + public void setMaxSemaphores(int maxSemaphores) { + this.maxSemaphores = maxSemaphores; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HystrixSemaphore that = (HystrixSemaphore) o; + return maxSemaphores == that.maxSemaphores; + } + + @Override + public int hashCode() { + return Objects.hash(maxSemaphores); + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("HystrixSemaphore{"); + sb.append("maxSemaphores=").append(maxSemaphores); + sb.append('}'); + return sb.toString(); + } + + } + + /** + * Represents Hystrix ThreadPool. + */ + public static class HystrixThreadPool { + + /** + * Flag to determine whether RibbonCommands should use separate thread pools for + * hystrix. By setting to true, RibbonCommands will be executed in a hystrix's + * thread pool that it is associated with. Each RibbonCommand will be associated + * with a thread pool according to its commandKey (serviceId). As default, all + * commands will be executed in a single thread pool whose threadPoolKey is + * "RibbonCommand". This property is only applicable when using THREAD as + * ribbonIsolationStrategy + */ + private boolean useSeparateThreadPools = false; + + /** + * A prefix for HystrixThreadPoolKey of hystrix's thread pool that is allocated to + * each service Id. This property is only applicable when using THREAD as + * ribbonIsolationStrategy and useSeparateThreadPools = true + */ + private String threadPoolKeyPrefix = ""; + + public boolean isUseSeparateThreadPools() { + return useSeparateThreadPools; + } + + public void setUseSeparateThreadPools(boolean useSeparateThreadPools) { + this.useSeparateThreadPools = useSeparateThreadPools; + } + + public String getThreadPoolKeyPrefix() { + return threadPoolKeyPrefix; + } + + public void setThreadPoolKeyPrefix(String threadPoolKeyPrefix) { + this.threadPoolKeyPrefix = threadPoolKeyPrefix; + } + } } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/discovery/DiscoveryClientRouteLocator.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/discovery/DiscoveryClientRouteLocator.java index d35deb4b4..59fbc5621 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/discovery/DiscoveryClientRouteLocator.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/discovery/DiscoveryClientRouteLocator.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +23,7 @@ import java.util.Map.Entry; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.netflix.zuul.filters.RefreshableRouteLocator; @@ -45,6 +46,9 @@ public class DiscoveryClientRouteLocator extends SimpleRouteLocator private static final Log log = LogFactory.getLog(DiscoveryClientRouteLocator.class); + /** + * Default route. + */ public static final String DEFAULT_ROUTE = "/**"; private DiscoveryClient discovery; @@ -55,8 +59,8 @@ public class DiscoveryClientRouteLocator extends SimpleRouteLocator @Deprecated public DiscoveryClientRouteLocator(String servletPath, DiscoveryClient discovery, - ZuulProperties properties) { - this(servletPath, discovery, properties, (ServiceInstance)null); + ZuulProperties properties) { + this(servletPath, discovery, properties, (ServiceInstance) null); } public DiscoveryClientRouteLocator(String servletPath, DiscoveryClient discovery, @@ -77,12 +81,13 @@ public class DiscoveryClientRouteLocator extends SimpleRouteLocator @Deprecated public DiscoveryClientRouteLocator(String servletPath, DiscoveryClient discovery, ZuulProperties properties, ServiceRouteMapper serviceRouteMapper) { - this(servletPath, discovery, properties, (ServiceInstance)null); + this(servletPath, discovery, properties, (ServiceInstance) null); this.serviceRouteMapper = serviceRouteMapper; } public DiscoveryClientRouteLocator(String servletPath, DiscoveryClient discovery, - ZuulProperties properties, ServiceRouteMapper serviceRouteMapper, ServiceInstance localServiceInstance) { + ZuulProperties properties, ServiceRouteMapper serviceRouteMapper, + ServiceInstance localServiceInstance) { this(servletPath, discovery, properties, localServiceInstance); this.serviceRouteMapper = serviceRouteMapper; } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/discovery/PatternServiceRouteMapper.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/discovery/PatternServiceRouteMapper.java index 7e80ca5c8..9c690057c 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/discovery/PatternServiceRouteMapper.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/discovery/PatternServiceRouteMapper.java @@ -1,3 +1,19 @@ +/* + * Copyright 2015-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.springframework.cloud.netflix.zuul.filters.discovery; import java.util.regex.Matcher; @@ -28,6 +44,7 @@ public class PatternServiceRouteMapper implements ServiceRouteMapper { * "(?.*)-(?v.*$)" */ private Pattern servicePattern; + /** * A RegExp that refer to named groups define in servicePattern. Ex : * "${version}/${name}" @@ -43,7 +60,6 @@ public class PatternServiceRouteMapper implements ServiceRouteMapper { * Use servicePattern to extract groups and routePattern to construct the route. * * If there is no matches, the serviceId is returned. - * * @param serviceId service discovered name * @return route path */ @@ -57,9 +73,9 @@ public class PatternServiceRouteMapper implements ServiceRouteMapper { /** * Route with regex and replace can be a bit messy when used with conditional named - * group. We clean here first and trailing '/' and remove multiple consecutive '/' - * @param route - * @return + * group. We clean here first and trailing '/' and remove multiple consecutive '/'. + * @param route a {@link String} representation of the route to be cleaned + * @return cleaned up route {@link String} */ private String cleanRoute(final String route) { String routeToClean = MULTIPLE_SLASH_PATTERN.matcher(route).replaceAll("/"); @@ -71,4 +87,5 @@ public class PatternServiceRouteMapper implements ServiceRouteMapper { } return routeToClean; } + } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/discovery/ServiceRouteMapper.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/discovery/ServiceRouteMapper.java index 6fb0083cd..84de2ab9a 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/discovery/ServiceRouteMapper.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/discovery/ServiceRouteMapper.java @@ -1,3 +1,19 @@ +/* + * Copyright 2015-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.springframework.cloud.netflix.zuul.filters.discovery; /** @@ -10,9 +26,9 @@ public interface ServiceRouteMapper { /** * Take a service Id (its discovered name) and return a route path. - * * @param serviceId service discovered name * @return route path */ String apply(String serviceId); + } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/discovery/SimpleServiceRouteMapper.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/discovery/SimpleServiceRouteMapper.java index 151502ca4..153c55841 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/discovery/SimpleServiceRouteMapper.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/discovery/SimpleServiceRouteMapper.java @@ -1,3 +1,19 @@ +/* + * Copyright 2015-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.springframework.cloud.netflix.zuul.filters.discovery; /** @@ -6,8 +22,10 @@ package org.springframework.cloud.netflix.zuul.filters.discovery; * A simple passthru service route mapper. */ public class SimpleServiceRouteMapper implements ServiceRouteMapper { + @Override public String apply(String serviceId) { return serviceId; } + } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/post/LocationRewriteFilter.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/post/LocationRewriteFilter.java index 1cbdf4aef..c9e5408ff 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/post/LocationRewriteFilter.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/post/LocationRewriteFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,13 +12,16 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ + package org.springframework.cloud.netflix.zuul.filters.post; +import java.net.URI; + import com.netflix.util.Pair; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.netflix.zuul.filters.Route; import org.springframework.cloud.netflix.zuul.filters.RouteLocator; @@ -30,13 +33,11 @@ import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; import org.springframework.web.util.UrlPathHelper; -import java.net.URI; - import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.POST_TYPE; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SEND_RESPONSE_FILTER_ORDER; /** - * {@link ZuulFilter} Responsible for rewriting the Location header to be the Zuul URL + * {@link ZuulFilter} Responsible for rewriting the Location header to be the Zuul URL. * * @author Biju Kunjummen */ @@ -157,4 +158,5 @@ public class LocationRewriteFilter extends ZuulFilter { } return null; } + } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/post/SendErrorFilter.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/post/SendErrorFilter.java index 12e72297b..93ec2938e 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/post/SendErrorFilter.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/post/SendErrorFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ package org.springframework.cloud.netflix.zuul.filters.post; +import java.net.SocketTimeoutException; + import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; @@ -32,20 +34,20 @@ import org.springframework.http.HttpStatus; import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; -import java.net.SocketTimeoutException; - import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.ERROR_TYPE; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SEND_ERROR_FILTER_ORDER; /** - * Error {@link ZuulFilter} that forwards to /error (by default) if {@link RequestContext#getThrowable()} is not null. + * Error {@link ZuulFilter} that forwards to /error (by default) if + * {@link RequestContext#getThrowable()} is not null. * * @author Spencer Gibb */ -//TODO: move to error package in Edgware +// TODO: move to error package in Edgware public class SendErrorFilter extends ZuulFilter { private static final Log log = LogFactory.getLog(SendErrorFilter.class); + protected static final String SEND_ERROR_FILTER_RAN = "sendErrorFilter.ran"; @Value("${error.path:/error}") @@ -76,17 +78,19 @@ public class SendErrorFilter extends ZuulFilter { ExceptionHolder exception = findZuulException(ctx.getThrowable()); HttpServletRequest request = ctx.getRequest(); - request.setAttribute("javax.servlet.error.status_code", exception.getStatusCode()); + request.setAttribute("javax.servlet.error.status_code", + exception.getStatusCode()); log.warn("Error during filtering", exception.getThrowable()); - request.setAttribute("javax.servlet.error.exception", exception.getThrowable()); + request.setAttribute("javax.servlet.error.exception", + exception.getThrowable()); if (StringUtils.hasText(exception.getErrorCause())) { - request.setAttribute("javax.servlet.error.message", exception.getErrorCause()); + request.setAttribute("javax.servlet.error.message", + exception.getErrorCause()); } - RequestDispatcher dispatcher = request.getRequestDispatcher( - this.errorPath); + RequestDispatcher dispatcher = request.getRequestDispatcher(this.errorPath); if (dispatcher != null) { ctx.set(SEND_ERROR_FILTER_RAN, true); if (!ctx.getResponse().isCommitted()) { @@ -115,14 +119,15 @@ public class SendErrorFilter extends ZuulFilter { return new ZuulExceptionHolder(zuulException); } // this was a failure initiated by one of the local filters - if(throwable.getCause().getCause() instanceof ZuulException) { - return new ZuulExceptionHolder((ZuulException) throwable.getCause().getCause()); + if (throwable.getCause().getCause() instanceof ZuulException) { + return new ZuulExceptionHolder( + (ZuulException) throwable.getCause().getCause()); } } - + if (throwable.getCause() instanceof ZuulException) { // wrapped zuul exception - return new ZuulExceptionHolder((ZuulException) throwable.getCause()); + return new ZuulExceptionHolder((ZuulException) throwable.getCause()); } if (throwable instanceof ZuulException) { @@ -134,19 +139,26 @@ public class SendErrorFilter extends ZuulFilter { return new DefaultExceptionHolder(throwable); } + public void setErrorPath(String errorPath) { + this.errorPath = errorPath; + } + protected interface ExceptionHolder { + Throwable getThrowable(); - default int getStatusCode() { - return HttpStatus.INTERNAL_SERVER_ERROR.value(); + default int getStatusCode() { + return HttpStatus.INTERNAL_SERVER_ERROR.value(); } - default String getErrorCause() { - return null; + default String getErrorCause() { + return null; } + } protected static class DefaultExceptionHolder implements ExceptionHolder { + private final Throwable throwable; public DefaultExceptionHolder(Throwable throwable) { @@ -157,9 +169,11 @@ public class SendErrorFilter extends ZuulFilter { public Throwable getThrowable() { return this.throwable; } + } protected static class ZuulExceptionHolder implements ExceptionHolder { + private final ZuulException exception; public ZuulExceptionHolder(ZuulException exception) { @@ -180,10 +194,7 @@ public class SendErrorFilter extends ZuulFilter { public String getErrorCause() { return this.exception.errorCause; } - } - public void setErrorPath(String errorPath) { - this.errorPath = errorPath; } } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/post/SendResponseFilter.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/post/SendResponseFilter.java index 9502f94ce..568d9c9c9 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/post/SendResponseFilter.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/post/SendResponseFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,16 +29,16 @@ import java.util.zip.GZIPInputStream; import javax.servlet.http.HttpServletResponse; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.util.ReflectionUtils; - import com.netflix.util.Pair; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.constants.ZuulHeaders; import com.netflix.zuul.context.RequestContext; import com.netflix.zuul.util.HTTPRequestUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; +import org.springframework.util.ReflectionUtils; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.POST_TYPE; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.ROUTING_DEBUG_KEY; @@ -46,7 +46,8 @@ import static org.springframework.cloud.netflix.zuul.filters.support.FilterConst import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.X_ZUUL_DEBUG_HEADER; /** - * Post {@link ZuulFilter} that writes responses from proxied requests to the current response. + * Post {@link ZuulFilter} that writes responses from proxied requests to the current + * response. * * @author Spencer Gibb * @author Dave Syer @@ -57,6 +58,7 @@ public class SendResponseFilter extends ZuulFilter { private static final Log log = LogFactory.getLog(SendResponseFilter.class); private boolean useServlet31 = true; + private ZuulProperties zuulProperties; private ThreadLocal buffers; @@ -72,10 +74,12 @@ public class SendResponseFilter extends ZuulFilter { // minimum support in Spring 5 is 3.0 so we need to keep tihs try { HttpServletResponse.class.getMethod("setContentLengthLong", long.class); - } catch(NoSuchMethodException e) { + } + catch (NoSuchMethodException e) { useServlet31 = false; } - buffers = ThreadLocal.withInitial(() -> new byte[zuulProperties.getInitialStreamBufferSize()]); + buffers = ThreadLocal + .withInitial(() -> new byte[zuulProperties.getInitialStreamBufferSize()]); } /* for testing */ boolean isUseServlet31() { @@ -97,8 +101,8 @@ public class SendResponseFilter extends ZuulFilter { RequestContext context = RequestContext.getCurrentContext(); return context.getThrowable() == null && (!context.getZuulResponseHeaders().isEmpty() - || context.getResponseDataStream() != null - || context.getResponseBody() != null); + || context.getResponseDataStream() != null + || context.getResponseBody() != null); } @Override @@ -124,18 +128,18 @@ public class SendResponseFilter extends ZuulFilter { if (servletResponse.getCharacterEncoding() == null) { // only set if not set servletResponse.setCharacterEncoding("UTF-8"); } - + OutputStream outStream = servletResponse.getOutputStream(); InputStream is = null; try { if (context.getResponseBody() != null) { String body = context.getResponseBody(); is = new ByteArrayInputStream( - body.getBytes(servletResponse.getCharacterEncoding())); + body.getBytes(servletResponse.getCharacterEncoding())); } else { is = context.getResponseDataStream(); - if (is!=null && context.getResponseGZipped()) { + if (is != null && context.getResponseGZipped()) { // if origin response is gzipped, and client has not requested gzip, // decompress stream before sending to client // else, stream gzip directly to client @@ -147,22 +151,24 @@ public class SendResponseFilter extends ZuulFilter { } } } - - if (is!=null) { + + if (is != null) { writeResponse(is, outStream); } } finally { /** - * We must ensure that the InputStream provided by our upstream pooling mechanism is ALWAYS closed - * even in the case of wrapped streams, which are supplied by pooled sources such as Apache's - * PoolingHttpClientConnectionManager. In that particular case, the underlying HTTP connection will - * be returned back to the connection pool iif either close() is explicitly called, a read - * error occurs, or the end of the underlying stream is reached. If, however a write error occurs, we will - * end up leaking a connection from the pool without an explicit close() - * - * @author Johannes Edmeier - */ + * We must ensure that the InputStream provided by our upstream pooling + * mechanism is ALWAYS closed even in the case of wrapped streams, which are + * supplied by pooled sources such as Apache's + * PoolingHttpClientConnectionManager. In that particular case, the underlying + * HTTP connection will be returned back to the connection pool iif either + * close() is explicitly called, a read error occurs, or the end of the + * underlying stream is reached. If, however a write error occurs, we will end + * up leaking a connection from the pool without an explicit close() + * + * @author Johannes Edmeier + */ if (is != null) { try { is.close(); @@ -186,17 +192,17 @@ public class SendResponseFilter extends ZuulFilter { } } - protected InputStream handleGzipStream(InputStream in) throws Exception { - // Record bytes read during GZip initialization to allow to rewind the stream if needed + // Record bytes read during GZip initialization to allow to rewind the stream if + // needed // RecordingInputStream stream = new RecordingInputStream(in); try { return new GZIPInputStream(stream); } catch (java.util.zip.ZipException | java.io.EOFException ex) { - - if (stream.getBytesRead()==0) { + + if (stream.getBytesRead() == 0) { // stream was empty, return the original "empty" stream return in; } @@ -204,9 +210,8 @@ public class SendResponseFilter extends ZuulFilter { // reset the stream and assume an unencoded response log.warn( "gzip response expected but failed to read gzip headers, assuming unencoded response for request " - + RequestContext.getCurrentContext() - .getRequest().getRequestURL() - .toString()); + + RequestContext.getCurrentContext().getRequest() + .getRequestURL().toString()); stream.reset(); return stream; @@ -217,7 +222,6 @@ public class SendResponseFilter extends ZuulFilter { } } - protected boolean isGzipRequested(RequestContext context) { final String requestEncoding = context.getRequest() .getHeader(ZuulHeaders.ACCEPT_ENCODING); @@ -225,8 +229,7 @@ public class SendResponseFilter extends ZuulFilter { return requestEncoding != null && HTTPRequestUtils.getInstance().isGzipped(requestEncoding); } - - + private void writeResponse(InputStream zin, OutputStream out) throws Exception { byte[] bytes = buffers.get(); int bytesRead = -1; @@ -257,10 +260,12 @@ public class SendResponseFilter extends ZuulFilter { } if (includeContentLengthHeader(context)) { Long contentLength = context.getOriginContentLength(); - if(useServlet31) { + if (useServlet31) { servletResponse.setContentLengthLong(contentLength); - } else { - //Try and set some kind of content length if we can safely convert the Long to an int + } + else { + // Try and set some kind of content length if we can safely convert the + // Long to an int if (isLongSafe(contentLength)) { servletResponse.setContentLength(contentLength.intValue()); } @@ -277,77 +282,81 @@ public class SendResponseFilter extends ZuulFilter { if (!this.zuulProperties.isSetContentLength()) { return false; } - + // Only if Content-Length is provided if (context.getOriginContentLength() == null) { return false; } - - // If response is compressed, include header only if we are not about to decompress it + + // If response is compressed, include header only if we are not about to + // decompress it if (context.getResponseGZipped()) { return context.isGzipRequested(); } - + // Forward it in all other cases return true; } - - + /** * InputStream recording bytes read to allow for a reset() until recording is stopped. */ private static class RecordingInputStream extends InputStream { private InputStream delegate; + private ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - - public RecordingInputStream(InputStream delegate) { + + RecordingInputStream(InputStream delegate) { super(); this.delegate = Objects.requireNonNull(delegate); } - + @Override public int read() throws IOException { int read = delegate.read(); - - if (buffer!=null && read!=-1) { + + if (buffer != null && read != -1) { buffer.write(read); } - + return read; } - + @Override public int read(byte[] b, int off, int len) throws IOException { int read = delegate.read(b, off, len); - - if (buffer!=null && read!=-1) { + + if (buffer != null && read != -1) { buffer.write(b, off, read); } - + return read; } - + public void reset() { - if (buffer==null) { + if (buffer == null) { throw new IllegalStateException("Stream is not recording"); } - this.delegate = new SequenceInputStream(new ByteArrayInputStream(buffer.toByteArray()), delegate); + this.delegate = new SequenceInputStream( + new ByteArrayInputStream(buffer.toByteArray()), delegate); this.buffer = new ByteArrayOutputStream(); } public int getBytesRead() { - return (buffer==null)?-1:buffer.size(); + return (buffer == null) ? -1 : buffer.size(); } - + public void stopRecording() { this.buffer = null; } - + @Override public void close() throws IOException { this.delegate.close(); } + } + } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/DebugFilter.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/DebugFilter.java index 3f43d69de..949c8c708 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/DebugFilter.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/DebugFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,8 +29,8 @@ import static org.springframework.cloud.netflix.zuul.filters.support.FilterConst import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE; /** - * Pre {@link ZuulFilter} that sets {@link RequestContext} debug attributes to true if - * the "debug" request parameter is set. + * Pre {@link ZuulFilter} that sets {@link RequestContext} debug attributes to true if the + * "debug" request parameter is set. * * @author Spencer Gibb */ diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/FormBodyWrapperFilter.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/FormBodyWrapperFilter.java index 5f1fef74e..4e3da5c9e 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/FormBodyWrapperFilter.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/FormBodyWrapperFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,6 +26,11 @@ import javax.servlet.ServletRequest; import javax.servlet.ServletRequestWrapper; import javax.servlet.http.HttpServletRequest; +import com.netflix.zuul.ZuulFilter; +import com.netflix.zuul.context.RequestContext; +import com.netflix.zuul.http.HttpServletRequestWrapper; +import com.netflix.zuul.http.ServletInputStreamWrapper; + import org.springframework.cloud.netflix.zuul.util.RequestContentDataExtractor; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpOutputMessage; @@ -38,23 +43,20 @@ import org.springframework.util.MultiValueMap; import org.springframework.util.ReflectionUtils; import org.springframework.web.servlet.DispatcherServlet; -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.context.RequestContext; -import com.netflix.zuul.http.HttpServletRequestWrapper; -import com.netflix.zuul.http.ServletInputStreamWrapper; - import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE; /** - * Pre {@link ZuulFilter} that parses form data and reencodes it for downstream services + * Pre {@link ZuulFilter} that parses form data and reencodes it for downstream services. * * @author Dave Syer */ public class FormBodyWrapperFilter extends ZuulFilter { private FormHttpMessageConverter formHttpMessageConverter; + private Field requestField; + private Field servletRequestField; public FormBodyWrapperFilter() { @@ -146,7 +148,7 @@ public class FormBodyWrapperFilter extends ZuulFilter { private int contentLength; - public FormBodyRequestWrapper(HttpServletRequest request) { + FormBodyRequestWrapper(HttpServletRequest request) { super(request); this.request = request; } @@ -187,12 +189,14 @@ public class FormBodyWrapperFilter extends ZuulFilter { return; } try { - MultiValueMap builder = RequestContentDataExtractor.extract(this.request); + MultiValueMap builder = RequestContentDataExtractor + .extract(this.request); FormHttpOutputMessage data = new FormHttpOutputMessage(); this.contentType = MediaType.valueOf(this.request.getContentType()); data.getHeaders().setContentType(this.contentType); - FormBodyWrapperFilter.this.formHttpMessageConverter.write(builder, this.contentType, data); + FormBodyWrapperFilter.this.formHttpMessageConverter.write(builder, + this.contentType, data); // copy new content type including multipart boundary this.contentType = data.getHeaders().getContentType(); byte[] input = data.getInput(); @@ -207,6 +211,7 @@ public class FormBodyWrapperFilter extends ZuulFilter { private class FormHttpOutputMessage implements HttpOutputMessage { private HttpHeaders headers = new HttpHeaders(); + private ByteArrayOutputStream output = new ByteArrayOutputStream(); @Override diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/PreDecorationFilter.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/PreDecorationFilter.java index a1cc941fc..c0ec7edea 100755 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/PreDecorationFilter.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/PreDecorationFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,8 +22,11 @@ import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; +import com.netflix.zuul.ZuulFilter; +import com.netflix.zuul.context.RequestContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.cloud.netflix.zuul.filters.ProxyRequestHelper; import org.springframework.cloud.netflix.zuul.filters.Route; import org.springframework.cloud.netflix.zuul.filters.RouteLocator; @@ -34,9 +37,6 @@ import org.springframework.http.HttpHeaders; import org.springframework.util.StringUtils; import org.springframework.web.util.UrlPathHelper; -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.context.RequestContext; - import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.FORWARD_LOCATION_PREFIX; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.FORWARD_TO_KEY; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.HTTPS_PORT; @@ -58,8 +58,16 @@ import static org.springframework.cloud.netflix.zuul.filters.support.FilterConst import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.X_FORWARDED_PROTO_HEADER; /** - * Pre {@link ZuulFilter} that determines where and how to route based on the supplied {@link RouteLocator}. - * Also sets various proxy related headers for downstream requests. + * Pre {@link ZuulFilter} that determines where and how to route based on the supplied + * {@link RouteLocator}. Also sets various proxy related headers for downstream requests. + * + * @author Spencer Gibb + * @author Dave Syer + * @author Philip Webb + * @author Stefan Fussenegger + * @author Adrian Ivan + * @author Jacques-Etienne Beaudet + * @author Durigon Durigon */ public class PreDecorationFilter extends ZuulFilter { @@ -71,6 +79,9 @@ public class PreDecorationFilter extends ZuulFilter { @Deprecated public static final int FILTER_ORDER = PRE_DECORATION_FILTER_ORDER; + /** + * A double slash pattern. + */ public static final Pattern DOUBLE_SLASH = Pattern.compile("//"); private RouteLocator routeLocator; @@ -83,11 +94,12 @@ public class PreDecorationFilter extends ZuulFilter { private ProxyRequestHelper proxyRequestHelper; - public PreDecorationFilter(RouteLocator routeLocator, String dispatcherServletPath, ZuulProperties properties, - ProxyRequestHelper proxyRequestHelper) { + public PreDecorationFilter(RouteLocator routeLocator, String dispatcherServletPath, + ZuulProperties properties, ProxyRequestHelper proxyRequestHelper) { this.routeLocator = routeLocator; this.properties = properties; - this.urlPathHelper.setRemoveSemicolonContent(properties.isRemoveSemicolonContent()); + this.urlPathHelper + .setRemoveSemicolonContent(properties.isRemoveSemicolonContent()); this.urlPathHelper.setUrlDecode(properties.isDecodeUrl()); this.dispatcherServletPath = dispatcherServletPath; this.proxyRequestHelper = proxyRequestHelper; @@ -107,13 +119,15 @@ public class PreDecorationFilter extends ZuulFilter { public boolean shouldFilter() { RequestContext ctx = RequestContext.getCurrentContext(); return !ctx.containsKey(FORWARD_TO_KEY) // a filter has already forwarded - && !ctx.containsKey(SERVICE_ID_KEY); // a filter has already determined serviceId + && !ctx.containsKey(SERVICE_ID_KEY); // a filter has already determined + // serviceId } @Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); - final String requestURI = this.urlPathHelper.getPathWithinApplication(ctx.getRequest()); + final String requestURI = this.urlPathHelper + .getPathWithinApplication(ctx.getRequest()); Route route = this.routeLocator.getMatchingRoute(requestURI); if (route != null) { String location = route.getLocation(); @@ -121,24 +135,28 @@ public class PreDecorationFilter extends ZuulFilter { ctx.put(REQUEST_URI_KEY, route.getPath()); ctx.put(PROXY_KEY, route.getId()); if (!route.isCustomSensitiveHeaders()) { - this.proxyRequestHelper - .addIgnoredHeaders(this.properties.getSensitiveHeaders().toArray(new String[0])); + this.proxyRequestHelper.addIgnoredHeaders( + this.properties.getSensitiveHeaders().toArray(new String[0])); } else { - this.proxyRequestHelper.addIgnoredHeaders(route.getSensitiveHeaders().toArray(new String[0])); + this.proxyRequestHelper.addIgnoredHeaders( + route.getSensitiveHeaders().toArray(new String[0])); } if (route.getRetryable() != null) { ctx.put(RETRYABLE_KEY, route.getRetryable()); } - if (location.startsWith(HTTP_SCHEME+":") || location.startsWith(HTTPS_SCHEME+":")) { + if (location.startsWith(HTTP_SCHEME + ":") + || location.startsWith(HTTPS_SCHEME + ":")) { ctx.setRouteHost(getUrl(location)); ctx.addOriginResponseHeader(SERVICE_HEADER, location); } else if (location.startsWith(FORWARD_LOCATION_PREFIX)) { ctx.set(FORWARD_TO_KEY, - StringUtils.cleanPath(location.substring(FORWARD_LOCATION_PREFIX.length()) + route.getPath())); + StringUtils.cleanPath( + location.substring(FORWARD_LOCATION_PREFIX.length()) + + route.getPath())); ctx.setRouteHost(null); return null; } @@ -150,7 +168,8 @@ public class PreDecorationFilter extends ZuulFilter { } if (this.properties.isAddProxyHeaders()) { addProxyHeaders(ctx, route); - String xforwardedfor = ctx.getRequest().getHeader(X_FORWARDED_FOR_HEADER); + String xforwardedfor = ctx.getRequest() + .getHeader(X_FORWARDED_FOR_HEADER); String remoteAddr = ctx.getRequest().getRemoteAddr(); if (xforwardedfor == null) { xforwardedfor = remoteAddr; @@ -161,7 +180,8 @@ public class PreDecorationFilter extends ZuulFilter { ctx.addZuulRequestHeader(X_FORWARDED_FOR_HEADER, xforwardedfor); } if (this.properties.isAddHostHeader()) { - ctx.addZuulRequestHeader(HttpHeaders.HOST, toHostHeader(ctx.getRequest())); + ctx.addZuulRequestHeader(HttpHeaders.HOST, + toHostHeader(ctx.getRequest())); } } } @@ -195,7 +215,8 @@ public class PreDecorationFilter extends ZuulFilter { fallBackUri = "/" + fallBackUri; } - String forwardURI = (fallbackPrefix == null) ? fallBackUri : fallbackPrefix + fallBackUri; + String forwardURI = (fallbackPrefix == null) ? fallBackUri + : fallbackPrefix + fallBackUri; forwardURI = DOUBLE_SLASH.matcher(forwardURI).replaceAll("/"); return forwardURI; } @@ -211,16 +232,19 @@ public class PreDecorationFilter extends ZuulFilter { if (!hasHeader(request, X_FORWARDED_PORT_HEADER)) { if (hasHeader(request, X_FORWARDED_PROTO_HEADER)) { StringBuilder builder = new StringBuilder(); - for (String previous : StringUtils.commaDelimitedListToStringArray(request.getHeader(X_FORWARDED_PROTO_HEADER))) { - if (builder.length()>0) { + for (String previous : StringUtils.commaDelimitedListToStringArray( + request.getHeader(X_FORWARDED_PROTO_HEADER))) { + if (builder.length() > 0) { builder.append(","); } - builder.append(HTTPS_SCHEME.equals(previous) ? HTTPS_PORT : HTTP_PORT); + builder.append( + HTTPS_SCHEME.equals(previous) ? HTTPS_PORT : HTTP_PORT); } builder.append(",").append(port); port = builder.toString(); } - } else { + } + else { port = request.getHeader(X_FORWARDED_PORT_HEADER) + "," + port; } if (hasHeader(request, X_FORWARDED_PROTO_HEADER)) { @@ -278,4 +302,5 @@ public class PreDecorationFilter extends ZuulFilter { throw new IllegalStateException("Target URL is malformed", ex); } } + } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/Servlet30RequestWrapper.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/Servlet30RequestWrapper.java index 32fdff0eb..bcfc3691c 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/Servlet30RequestWrapper.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/Servlet30RequestWrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,14 +16,15 @@ package org.springframework.cloud.netflix.zuul.filters.pre; -import com.netflix.zuul.http.HttpServletRequestWrapper; - import javax.servlet.http.HttpServletRequest; +import com.netflix.zuul.http.HttpServletRequestWrapper; + /** * A Servlet 3.0 compliant wrapper. */ class Servlet30RequestWrapper extends HttpServletRequestWrapper { + private HttpServletRequest request; Servlet30RequestWrapper(HttpServletRequest request) { @@ -32,11 +33,13 @@ class Servlet30RequestWrapper extends HttpServletRequestWrapper { } /** - * There is a bug in zuul 1.2.2 where HttpServletRequestWrapper.getRequest returns a wrapped request rather than the raw one. + * There is a bug in zuul 1.2.2 where HttpServletRequestWrapper.getRequest returns a + * wrapped request rather than the raw one. * @return the original HttpServletRequest */ @Override public HttpServletRequest getRequest() { return this.request; } + } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/Servlet30WrapperFilter.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/Servlet30WrapperFilter.java index b7516415b..6740cfdc4 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/Servlet30WrapperFilter.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/Servlet30WrapperFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,20 +20,21 @@ import java.lang.reflect.Field; import javax.servlet.http.HttpServletRequest; -import org.springframework.cloud.netflix.zuul.util.RequestUtils; -import org.springframework.util.Assert; -import org.springframework.util.ReflectionUtils; - import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; import com.netflix.zuul.http.HttpServletRequestWrapper; +import org.springframework.cloud.netflix.zuul.util.RequestUtils; +import org.springframework.util.Assert; +import org.springframework.util.ReflectionUtils; + import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SERVLET_30_WRAPPER_FILTER_ORDER; /** - * Pre {@link ZuulFilter} that wraps requests in a Servlet 3.0 compliant wrapper. - * Zuul's default wrapper is only Servlet 2.5 compliant. + * Pre {@link ZuulFilter} that wraps requests in a Servlet 3.0 compliant wrapper. Zuul's + * default wrapper is only Servlet 2.5 compliant. + * * @author Spencer Gibb */ public class Servlet30WrapperFilter extends ZuulFilter { diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/ServletDetectionFilter.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/ServletDetectionFilter.java index 7dae24ecf..627dd9d4c 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/ServletDetectionFilter.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/pre/ServletDetectionFilter.java @@ -18,23 +18,24 @@ package org.springframework.cloud.netflix.zuul.filters.pre; import javax.servlet.http.HttpServletRequest; -import org.springframework.web.servlet.DispatcherServlet; - import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; import com.netflix.zuul.http.HttpServletRequestWrapper; import com.netflix.zuul.http.ZuulServlet; +import org.springframework.web.servlet.DispatcherServlet; + import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.IS_DISPATCHER_SERVLET_REQUEST_KEY; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SERVLET_DETECTION_FILTER_ORDER; /** - * Detects whether a request is ran through the {@link DispatcherServlet} or {@link ZuulServlet}. - * The purpose was to detect this up-front at the very beginning of Zuul filter processing - * and rely on this information in all filters. - * RequestContext is used such that the information is accessible to classes - * which do not have a request reference. + * Detects whether a request is ran through the {@link DispatcherServlet} or + * {@link ZuulServlet}. The purpose was to detect this up-front at the very beginning of + * Zuul filter processing and rely on this information in all filters. RequestContext is + * used such that the information is accessible to classes which do not have a request + * reference. + * * @author Adrian Ivan */ public class ServletDetectionFilter extends ZuulFilter { @@ -48,8 +49,8 @@ public class ServletDetectionFilter extends ZuulFilter { } /** - * Must run before other filters that rely on the difference between - * DispatcherServlet and ZuulServlet. + * Must run before other filters that rely on the difference between DispatcherServlet + * and ZuulServlet. */ @Override public int filterOrder() { @@ -58,25 +59,27 @@ public class ServletDetectionFilter extends ZuulFilter { @Override public boolean shouldFilter() { - return true; + return true; } @Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); - if (!(request instanceof HttpServletRequestWrapper) + if (!(request instanceof HttpServletRequestWrapper) && isDispatcherServletRequest(request)) { ctx.set(IS_DISPATCHER_SERVLET_REQUEST_KEY, true); - } else { + } + else { ctx.set(IS_DISPATCHER_SERVLET_REQUEST_KEY, false); } return null; } - + private boolean isDispatcherServletRequest(HttpServletRequest request) { - return request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null; - } + return request.getAttribute( + DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null; + } } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/FallbackProvider.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/FallbackProvider.java index 380479248..d648a7443 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/FallbackProvider.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/FallbackProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,14 +30,14 @@ public interface FallbackProvider { * The route this fallback will be used for. * @return The route the fallback will be used for. */ - public String getRoute(); + String getRoute(); /** * Provides a fallback response based on the cause of the failed execution. - * * @param route The route the fallback is for * @param cause cause of the main method failure, may be null * @return the fallback response */ ClientHttpResponse fallbackResponse(String route, Throwable cause); + } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RestClientRibbonCommand.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RestClientRibbonCommand.java index 72f5dff09..36c7b9a07 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RestClientRibbonCommand.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RestClientRibbonCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.filters.route; @@ -21,40 +20,47 @@ import java.io.InputStream; import java.net.URI; import java.util.List; -import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.cloud.netflix.zuul.filters.route.support.AbstractRibbonCommand; -import org.springframework.http.HttpMethod; -import org.springframework.util.MultiValueMap; import com.netflix.client.config.IClientConfig; import com.netflix.client.http.HttpRequest; import com.netflix.client.http.HttpResponse; import com.netflix.niws.client.http.RestClient; +import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; +import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; +import org.springframework.cloud.netflix.zuul.filters.route.support.AbstractRibbonCommand; +import org.springframework.http.HttpMethod; +import org.springframework.util.MultiValueMap; + import static org.springframework.cloud.netflix.ribbon.support.RibbonRequestCustomizer.Runner.customize; /** - * Hystrix wrapper around Eureka Ribbon command + * Hystrix wrapper around Eureka Ribbon command. * - * see original + * see original + * + * @author Spencer Gibb + * @author Stephane Lagraulet + * @author Ryan Baxter */ @SuppressWarnings("deprecation") -public class RestClientRibbonCommand extends AbstractRibbonCommand { +public class RestClientRibbonCommand + extends AbstractRibbonCommand { public RestClientRibbonCommand(String commandKey, RestClient client, - RibbonCommandContext context, ZuulProperties zuulProperties) { + RibbonCommandContext context, ZuulProperties zuulProperties) { super(commandKey, client, context, zuulProperties); } public RestClientRibbonCommand(String commandKey, RestClient client, - RibbonCommandContext context, ZuulProperties zuulProperties, - FallbackProvider zuulFallbackProvider) { + RibbonCommandContext context, ZuulProperties zuulProperties, + FallbackProvider zuulFallbackProvider) { super(commandKey, client, context, zuulProperties, zuulFallbackProvider); } public RestClientRibbonCommand(String commandKey, RestClient client, - RibbonCommandContext context, ZuulProperties zuulProperties, - FallbackProvider zuulFallbackProvider, IClientConfig config) { + RibbonCommandContext context, ZuulProperties zuulProperties, + FallbackProvider zuulFallbackProvider, IClientConfig config) { super(commandKey, client, context, zuulProperties, zuulFallbackProvider, config); } @@ -73,7 +79,8 @@ public class RestClientRibbonCommand extends AbstractRibbonCommandemptySet()); + this(clientFactory, new ZuulProperties(), + Collections.emptySet()); } public RestClientRibbonCommandFactory(SpringClientFactory clientFactory, - ZuulProperties zuulProperties, - Set zuulFallbackProviders) { + ZuulProperties zuulProperties, Set zuulFallbackProviders) { super(zuulFallbackProviders); this.clientFactory = clientFactory; this.zuulProperties = zuulProperties; @@ -55,10 +54,10 @@ public class RestClientRibbonCommandFactory extends AbstractRibbonCommandFactory public RestClientRibbonCommand create(RibbonCommandContext context) { String serviceId = context.getServiceId(); FallbackProvider fallbackProvider = getFallbackProvider(serviceId); - RestClient restClient = this.clientFactory.getClient(serviceId, - RestClient.class); + RestClient restClient = this.clientFactory.getClient(serviceId, RestClient.class); return new RestClientRibbonCommand(context.getServiceId(), restClient, context, - this.zuulProperties, fallbackProvider, clientFactory.getClientConfig(serviceId)); + this.zuulProperties, fallbackProvider, + clientFactory.getClientConfig(serviceId)); } public SpringClientFactory getClientFactory() { diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonCommand.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonCommand.java index 519a0f844..4ca464c39 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonCommand.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,10 +17,12 @@ package org.springframework.cloud.netflix.zuul.filters.route; import com.netflix.hystrix.HystrixExecutable; + import org.springframework.http.client.ClientHttpResponse; /** * @author Spencer Gibb */ public interface RibbonCommand extends HystrixExecutable { + } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonCommandFactory.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonCommandFactory.java index 48cbaf497..b28674e92 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonCommandFactory.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonCommandFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,9 @@ package org.springframework.cloud.netflix.zuul.filters.route; import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; /** + * @param a {@link RibbonCommand subtype} * @author Spencer Gibb + * */ public interface RibbonCommandFactory { diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonRoutingFilter.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonRoutingFilter.java index d1f182f76..52c398a66 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonRoutingFilter.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonRoutingFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,8 +23,14 @@ import java.util.Map; import javax.servlet.http.HttpServletRequest; +import com.netflix.client.ClientException; +import com.netflix.hystrix.exception.HystrixRuntimeException; +import com.netflix.zuul.ZuulFilter; +import com.netflix.zuul.context.RequestContext; +import com.netflix.zuul.exception.ZuulException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; import org.springframework.cloud.netflix.ribbon.support.RibbonRequestCustomizer; import org.springframework.cloud.netflix.zuul.filters.ProxyRequestHelper; @@ -33,22 +39,17 @@ import org.springframework.http.HttpStatus; import org.springframework.http.client.ClientHttpResponse; import org.springframework.util.MultiValueMap; -import com.netflix.client.ClientException; -import com.netflix.hystrix.exception.HystrixRuntimeException; -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.context.RequestContext; -import com.netflix.zuul.exception.ZuulException; - +import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.LOAD_BALANCER_KEY; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.REQUEST_ENTITY_KEY; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.RETRYABLE_KEY; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.RIBBON_ROUTING_FILTER_ORDER; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.ROUTE_TYPE; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SERVICE_ID_KEY; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.LOAD_BALANCER_KEY; /** - * Route {@link ZuulFilter} that uses Ribbon, Hystrix and pluggable http clients to send requests. - * ServiceIds are found in the {@link RequestContext} attribute {@link org.springframework.cloud.netflix.zuul.filters.support.FilterConstants#SERVICE_ID_KEY}. + * Route {@link ZuulFilter} that uses Ribbon, Hystrix and pluggable http clients to send + * requests. ServiceIds are found in the {@link RequestContext} attribute + * {@link org.springframework.cloud.netflix.zuul.filters.support.FilterConstants#SERVICE_ID_KEY}. * * @author Spencer Gibb * @author Dave Syer @@ -59,13 +60,16 @@ public class RibbonRoutingFilter extends ZuulFilter { private static final Log log = LogFactory.getLog(RibbonRoutingFilter.class); protected ProxyRequestHelper helper; + protected RibbonCommandFactory ribbonCommandFactory; + protected List requestCustomizers; + private boolean useServlet31 = true; public RibbonRoutingFilter(ProxyRequestHelper helper, - RibbonCommandFactory ribbonCommandFactory, - List requestCustomizers) { + RibbonCommandFactory ribbonCommandFactory, + List requestCustomizers) { this.helper = helper; this.ribbonCommandFactory = ribbonCommandFactory; this.requestCustomizers = requestCustomizers; @@ -73,13 +77,14 @@ public class RibbonRoutingFilter extends ZuulFilter { // Spring 5 minimum support is 3.0, so this stays try { HttpServletRequest.class.getMethod("getContentLengthLong"); - } catch(NoSuchMethodException e) { + } + catch (NoSuchMethodException e) { useServlet31 = false; } } @Deprecated - //TODO Remove in 2.1.x + // TODO Remove in 2.1.x public RibbonRoutingFilter(RibbonCommandFactory ribbonCommandFactory) { this(new ProxyRequestHelper(), ribbonCommandFactory, null); } @@ -145,7 +150,8 @@ public class RibbonRoutingFilter extends ZuulFilter { // remove double slashes uri = uri.replace("//", "/"); - long contentLength = useServlet31 ? request.getContentLengthLong(): request.getContentLength(); + long contentLength = useServlet31 ? request.getContentLengthLong() + : request.getContentLength(); return new RibbonCommandContext(serviceId, verb, uri, retryable, headers, params, requestEntity, this.requestCustomizers, contentLength, loadBalancerKey); @@ -159,7 +165,8 @@ public class RibbonRoutingFilter extends ZuulFilter { RibbonCommand command = this.ribbonCommandFactory.create(context); try { ClientHttpResponse response = command.execute(); - this.helper.appendDebug(info, response.getRawStatusCode(), response.getHeaders()); + this.helper.appendDebug(info, response.getRawStatusCode(), + response.getHeaders()); return response; } catch (HystrixRuntimeException ex) { diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/SendForwardFilter.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/SendForwardFilter.java index e8a31d03c..4d82a32ce 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/SendForwardFilter.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/SendForwardFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,18 +18,19 @@ package org.springframework.cloud.netflix.zuul.filters.route; import javax.servlet.RequestDispatcher; -import org.springframework.util.ReflectionUtils; - import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; +import org.springframework.util.ReflectionUtils; + import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.FORWARD_TO_KEY; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.ROUTE_TYPE; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SEND_FORWARD_FILTER_ORDER; /** * Route {@link ZuulFilter} that forwards requests using the {@link RequestDispatcher}. - * Forwarding location is located in the {@link RequestContext} attribute {@link org.springframework.cloud.netflix.zuul.filters.support.FilterConstants#FORWARD_TO_KEY}. + * Forwarding location is located in the {@link RequestContext} attribute + * {@link org.springframework.cloud.netflix.zuul.filters.support.FilterConstants#FORWARD_TO_KEY}. * Useful for forwarding to endpoints in the current application. * * @author Dave Syer diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/SimpleHostRoutingFilter.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/SimpleHostRoutingFilter.java index 7d4a117d5..b24f67cde 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/SimpleHostRoutingFilter.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/SimpleHostRoutingFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,9 +22,9 @@ import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; -import java.util.regex.Pattern; import java.util.Timer; import java.util.TimerTask; +import java.util.regex.Pattern; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; @@ -82,7 +82,8 @@ import static org.springframework.cloud.netflix.zuul.filters.support.FilterConst * @author Bilal Alp * @author Gang Li */ -public class SimpleHostRoutingFilter extends ZuulFilter implements ApplicationListener { +public class SimpleHostRoutingFilter extends ZuulFilter + implements ApplicationListener { private static final Log log = LogFactory.getLog(SimpleHostRoutingFilter.class); @@ -92,15 +93,23 @@ public class SimpleHostRoutingFilter extends ZuulFilter implements ApplicationLi "SimpleHostRoutingFilter.connectionManagerTimer", true); private boolean sslHostnameValidationEnabled; + private boolean forceOriginalQueryStringEncoding; private ProxyRequestHelper helper; + private Host hostProperties; + private ApacheHttpClientConnectionManagerFactory connectionManagerFactory; + private ApacheHttpClientFactory httpClientFactory; + private HttpClientConnectionManager connectionManager; + private CloseableHttpClient httpClient; + private boolean customHttpClient = false; + private boolean useServlet31 = true; @Override @@ -111,7 +120,7 @@ public class SimpleHostRoutingFilter extends ZuulFilter implements ApplicationLi @Deprecated public void onPropertyChange(EnvironmentChangeEvent event) { - if(!customHttpClient) { + if (!customHttpClient) { boolean createNewClient = false; for (String key : event.getKeys()) { @@ -124,7 +133,8 @@ public class SimpleHostRoutingFilter extends ZuulFilter implements ApplicationLi if (createNewClient) { try { SimpleHostRoutingFilter.this.httpClient.close(); - } catch (IOException ex) { + } + catch (IOException ex) { log.error("error closing client", ex); } SimpleHostRoutingFilter.this.httpClient = newClient(); @@ -146,7 +156,7 @@ public class SimpleHostRoutingFilter extends ZuulFilter implements ApplicationLi } public SimpleHostRoutingFilter(ProxyRequestHelper helper, ZuulProperties properties, - CloseableHttpClient httpClient) { + CloseableHttpClient httpClient) { this.helper = helper; this.hostProperties = properties.getHost(); this.sslHostnameValidationEnabled = properties.isSslHostnameValidationEnabled(); @@ -159,13 +169,13 @@ public class SimpleHostRoutingFilter extends ZuulFilter implements ApplicationLi @PostConstruct private void initialize() { - if(!customHttpClient) { + if (!customHttpClient) { this.connectionManager = connectionManagerFactory.newConnectionManager( !this.sslHostnameValidationEnabled, this.hostProperties.getMaxTotalConnections(), this.hostProperties.getMaxPerRouteConnections(), - this.hostProperties.getTimeToLive(), this.hostProperties.getTimeUnit(), - null); + this.hostProperties.getTimeToLive(), + this.hostProperties.getTimeUnit(), null); this.httpClient = newClient(); this.connectionManagerTimer.schedule(new TimerTask() { @Override @@ -173,7 +183,8 @@ public class SimpleHostRoutingFilter extends ZuulFilter implements ApplicationLi if (SimpleHostRoutingFilter.this.connectionManager == null) { return; } - SimpleHostRoutingFilter.this.connectionManager.closeExpiredConnections(); + SimpleHostRoutingFilter.this.connectionManager + .closeExpiredConnections(); } }, 30000, 5000); } @@ -256,14 +267,14 @@ public class SimpleHostRoutingFilter extends ZuulFilter implements ApplicationLi return findClientException(t.getCause()); } - protected void checkServletVersion() { // To support Servlet API 3.1 we need to check if getContentLengthLong exists // Spring 5 minimum support is 3.0, so this stays try { HttpServletRequest.class.getMethod("getContentLengthLong"); useServlet31 = true; - } catch(NoSuchMethodException e) { + } + catch (NoSuchMethodException e) { useServlet31 = false; } } @@ -278,13 +289,14 @@ public class SimpleHostRoutingFilter extends ZuulFilter implements ApplicationLi protected CloseableHttpClient newClient() { final RequestConfig requestConfig = RequestConfig.custom() - .setConnectionRequestTimeout(this.hostProperties.getConnectionRequestTimeoutMillis()) + .setConnectionRequestTimeout( + this.hostProperties.getConnectionRequestTimeoutMillis()) .setSocketTimeout(this.hostProperties.getSocketTimeoutMillis()) .setConnectTimeout(this.hostProperties.getConnectTimeoutMillis()) .setCookieSpec(CookieSpecs.IGNORE_COOKIES).build(); - return httpClientFactory.createBuilder(). - setDefaultRequestConfig(requestConfig). - setConnectionManager(this.connectionManager).disableRedirectHandling().build(); + return httpClientFactory.createBuilder().setDefaultRequestConfig(requestConfig) + .setConnectionManager(this.connectionManager).disableRedirectHandling() + .build(); } private CloseableHttpResponse forward(CloseableHttpClient httpclient, String verb, @@ -295,7 +307,8 @@ public class SimpleHostRoutingFilter extends ZuulFilter implements ApplicationLi requestEntity); URL host = RequestContext.getCurrentContext().getRouteHost(); HttpHost httpHost = getHttpHost(host); - uri = StringUtils.cleanPath(MULTIPLE_SLASH_PATTERN.matcher(host.getPath() + uri).replaceAll("/")); + uri = StringUtils.cleanPath( + MULTIPLE_SLASH_PATTERN.matcher(host.getPath() + uri).replaceAll("/")); long contentLength = getContentLength(request); ContentType contentType = null; @@ -405,7 +418,8 @@ public class SimpleHostRoutingFilter extends ZuulFilter implements ApplicationLi protected InputStream getRequestBody(HttpServletRequest request) { InputStream requestEntity = null; try { - requestEntity = (InputStream) RequestContext.getCurrentContext().get(REQUEST_ENTITY_KEY); + requestEntity = (InputStream) RequestContext.getCurrentContext() + .get(REQUEST_ENTITY_KEY); if (requestEntity == null) { requestEntity = request.getInputStream(); } @@ -430,7 +444,7 @@ public class SimpleHostRoutingFilter extends ZuulFilter implements ApplicationLi /** * Add header names to exclude from proxied response in the current request. - * @param names + * @param names names of headers to exclude */ protected void addIgnoredHeaders(String... names) { this.helper.addIgnoredHeaders(names); @@ -446,7 +460,7 @@ public class SimpleHostRoutingFilter extends ZuulFilter implements ApplicationLi // Get the header value as a long in order to more correctly proxy very large requests protected long getContentLength(HttpServletRequest request) { - if(useServlet31){ + if (useServlet31) { return request.getContentLengthLong(); } String contentLengthHeader = request.getHeader(HttpHeaders.CONTENT_LENGTH); @@ -454,8 +468,10 @@ public class SimpleHostRoutingFilter extends ZuulFilter implements ApplicationLi try { return Long.parseLong(contentLengthHeader); } - catch (NumberFormatException e){} + catch (NumberFormatException e) { + } } return request.getContentLength(); } + } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommand.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommand.java index ca24c4eea..d33c76a82 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommand.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,47 +12,44 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.filters.route.apache; +import com.netflix.client.config.IClientConfig; + import org.springframework.cloud.netflix.ribbon.apache.RibbonApacheHttpRequest; import org.springframework.cloud.netflix.ribbon.apache.RibbonApacheHttpResponse; import org.springframework.cloud.netflix.ribbon.apache.RibbonLoadBalancingHttpClient; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; +import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider; import org.springframework.cloud.netflix.zuul.filters.route.support.AbstractRibbonCommand; -import com.netflix.client.config.IClientConfig; /** * @author Spencer Gibb * @author Ryan Baxter */ -public class HttpClientRibbonCommand extends AbstractRibbonCommand { +public class HttpClientRibbonCommand extends + AbstractRibbonCommand { public HttpClientRibbonCommand(final String commandKey, - final RibbonLoadBalancingHttpClient client, - final RibbonCommandContext context, - final ZuulProperties zuulProperties) { + final RibbonLoadBalancingHttpClient client, + final RibbonCommandContext context, final ZuulProperties zuulProperties) { super(commandKey, client, context, zuulProperties); } public HttpClientRibbonCommand(final String commandKey, - final RibbonLoadBalancingHttpClient client, - final RibbonCommandContext context, - final ZuulProperties zuulProperties, - final FallbackProvider zuulFallbackProvider) { + final RibbonLoadBalancingHttpClient client, + final RibbonCommandContext context, final ZuulProperties zuulProperties, + final FallbackProvider zuulFallbackProvider) { super(commandKey, client, context, zuulProperties, zuulFallbackProvider); } public HttpClientRibbonCommand(final String commandKey, - final RibbonLoadBalancingHttpClient client, - final RibbonCommandContext context, - final ZuulProperties zuulProperties, - final FallbackProvider zuulFallbackProvider, - final IClientConfig config) { + final RibbonLoadBalancingHttpClient client, + final RibbonCommandContext context, final ZuulProperties zuulProperties, + final FallbackProvider zuulFallbackProvider, final IClientConfig config) { super(commandKey, client, context, zuulProperties, zuulFallbackProvider, config); } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommandFactory.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommandFactory.java index 92842247b..e514290bb 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommandFactory.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommandFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,10 +21,10 @@ import java.util.Set; import org.springframework.cloud.netflix.ribbon.SpringClientFactory; import org.springframework.cloud.netflix.ribbon.apache.RibbonLoadBalancingHttpClient; +import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider; import org.springframework.cloud.netflix.zuul.filters.route.support.AbstractRibbonCommandFactory; -import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; /** * @author Christian Lohmann @@ -33,15 +33,16 @@ import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; public class HttpClientRibbonCommandFactory extends AbstractRibbonCommandFactory { private final SpringClientFactory clientFactory; - + private final ZuulProperties zuulProperties; - public HttpClientRibbonCommandFactory(SpringClientFactory clientFactory, ZuulProperties zuulProperties) { + public HttpClientRibbonCommandFactory(SpringClientFactory clientFactory, + ZuulProperties zuulProperties) { this(clientFactory, zuulProperties, Collections.emptySet()); } - public HttpClientRibbonCommandFactory(SpringClientFactory clientFactory, ZuulProperties zuulProperties, - Set fallbackProviders) { + public HttpClientRibbonCommandFactory(SpringClientFactory clientFactory, + ZuulProperties zuulProperties, Set fallbackProviders) { super(fallbackProviders); this.clientFactory = clientFactory; this.zuulProperties = zuulProperties; @@ -49,14 +50,15 @@ public class HttpClientRibbonCommandFactory extends AbstractRibbonCommandFactory @Override public HttpClientRibbonCommand create(final RibbonCommandContext context) { - FallbackProvider zuulFallbackProvider = getFallbackProvider(context.getServiceId()); + FallbackProvider zuulFallbackProvider = getFallbackProvider( + context.getServiceId()); final String serviceId = context.getServiceId(); - final RibbonLoadBalancingHttpClient client = this.clientFactory.getClient( - serviceId, RibbonLoadBalancingHttpClient.class); + final RibbonLoadBalancingHttpClient client = this.clientFactory + .getClient(serviceId, RibbonLoadBalancingHttpClient.class); client.setLoadBalancer(this.clientFactory.getLoadBalancer(serviceId)); - return new HttpClientRibbonCommand(serviceId, client, context, zuulProperties, zuulFallbackProvider, - clientFactory.getClientConfig(serviceId)); + return new HttpClientRibbonCommand(serviceId, client, context, zuulProperties, + zuulFallbackProvider, clientFactory.getClientConfig(serviceId)); } } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommand.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommand.java index 2434fafbc..43bc058e2 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommand.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,47 +12,44 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.filters.route.okhttp; +import com.netflix.client.config.IClientConfig; + import org.springframework.cloud.netflix.ribbon.okhttp.OkHttpLoadBalancingClient; import org.springframework.cloud.netflix.ribbon.okhttp.OkHttpRibbonRequest; import org.springframework.cloud.netflix.ribbon.okhttp.OkHttpRibbonResponse; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; +import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider; import org.springframework.cloud.netflix.zuul.filters.route.support.AbstractRibbonCommand; -import com.netflix.client.config.IClientConfig; /** * @author Spencer Gibb * @author Ryan Baxter */ -public class OkHttpRibbonCommand extends AbstractRibbonCommand { +public class OkHttpRibbonCommand extends + AbstractRibbonCommand { public OkHttpRibbonCommand(final String commandKey, - final OkHttpLoadBalancingClient client, - final RibbonCommandContext context, - final ZuulProperties zuulProperties) { + final OkHttpLoadBalancingClient client, final RibbonCommandContext context, + final ZuulProperties zuulProperties) { super(commandKey, client, context, zuulProperties); } public OkHttpRibbonCommand(final String commandKey, - final OkHttpLoadBalancingClient client, - final RibbonCommandContext context, - final ZuulProperties zuulProperties, - final FallbackProvider zuulFallbackProvider) { + final OkHttpLoadBalancingClient client, final RibbonCommandContext context, + final ZuulProperties zuulProperties, + final FallbackProvider zuulFallbackProvider) { super(commandKey, client, context, zuulProperties, zuulFallbackProvider); } public OkHttpRibbonCommand(final String commandKey, - final OkHttpLoadBalancingClient client, - final RibbonCommandContext context, - final ZuulProperties zuulProperties, - final FallbackProvider zuulFallbackProvider, - final IClientConfig config) { + final OkHttpLoadBalancingClient client, final RibbonCommandContext context, + final ZuulProperties zuulProperties, + final FallbackProvider zuulFallbackProvider, final IClientConfig config) { super(commandKey, client, context, zuulProperties, zuulFallbackProvider, config); } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommandFactory.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommandFactory.java index 2070816b5..ce64d25c3 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommandFactory.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommandFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,8 +21,8 @@ import java.util.Set; import org.springframework.cloud.netflix.ribbon.SpringClientFactory; import org.springframework.cloud.netflix.ribbon.okhttp.OkHttpLoadBalancingClient; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; +import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider; import org.springframework.cloud.netflix.zuul.filters.route.support.AbstractRibbonCommandFactory; @@ -33,15 +33,16 @@ import org.springframework.cloud.netflix.zuul.filters.route.support.AbstractRibb public class OkHttpRibbonCommandFactory extends AbstractRibbonCommandFactory { private SpringClientFactory clientFactory; - + private ZuulProperties zuulProperties; - public OkHttpRibbonCommandFactory(SpringClientFactory clientFactory, ZuulProperties zuulProperties) { + public OkHttpRibbonCommandFactory(SpringClientFactory clientFactory, + ZuulProperties zuulProperties) { this(clientFactory, zuulProperties, Collections.emptySet()); } - public OkHttpRibbonCommandFactory(SpringClientFactory clientFactory, ZuulProperties zuulProperties, - Set zuulFallbackProviders) { + public OkHttpRibbonCommandFactory(SpringClientFactory clientFactory, + ZuulProperties zuulProperties, Set zuulFallbackProviders) { super(zuulFallbackProviders); this.clientFactory = clientFactory; this.zuulProperties = zuulProperties; @@ -51,12 +52,12 @@ public class OkHttpRibbonCommandFactory extends AbstractRibbonCommandFactory { public OkHttpRibbonCommand create(final RibbonCommandContext context) { final String serviceId = context.getServiceId(); FallbackProvider fallbackProvider = getFallbackProvider(serviceId); - final OkHttpLoadBalancingClient client = this.clientFactory.getClient( - serviceId, OkHttpLoadBalancingClient.class); + final OkHttpLoadBalancingClient client = this.clientFactory.getClient(serviceId, + OkHttpLoadBalancingClient.class); client.setLoadBalancer(this.clientFactory.getLoadBalancer(serviceId)); - return new OkHttpRibbonCommand(serviceId, client, context, zuulProperties, fallbackProvider, - clientFactory.getClientConfig(serviceId)); + return new OkHttpRibbonCommand(serviceId, client, context, zuulProperties, + fallbackProvider, clientFactory.getClientConfig(serviceId)); } } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/support/AbstractRibbonCommand.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/support/AbstractRibbonCommand.java index d970e051b..cd75baa63 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/support/AbstractRibbonCommand.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/support/AbstractRibbonCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,22 +12,10 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.filters.route.support; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration; -import org.springframework.cloud.netflix.ribbon.RibbonHttpResponse; -import org.springframework.cloud.netflix.ribbon.support.AbstractLoadBalancingClient; -import org.springframework.cloud.netflix.ribbon.support.ContextAwareRequest; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.cloud.netflix.zuul.filters.route.RibbonCommand; -import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; -import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider; -import org.springframework.http.client.ClientHttpResponse; import com.netflix.client.AbstractLoadBalancerAwareClient; import com.netflix.client.ClientRequest; import com.netflix.client.config.DefaultClientConfigImpl; @@ -44,17 +32,37 @@ import com.netflix.hystrix.HystrixCommandProperties.ExecutionIsolationStrategy; import com.netflix.hystrix.HystrixThreadPoolKey; import com.netflix.zuul.constants.ZuulConstants; import com.netflix.zuul.context.RequestContext; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration; +import org.springframework.cloud.netflix.ribbon.RibbonHttpResponse; +import org.springframework.cloud.netflix.ribbon.support.AbstractLoadBalancingClient; +import org.springframework.cloud.netflix.ribbon.support.ContextAwareRequest; +import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; +import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; +import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider; +import org.springframework.cloud.netflix.zuul.filters.route.RibbonCommand; +import org.springframework.http.client.ClientHttpResponse; /** + * @param {@link ClientRequest} subtype + * @param {@link AbstractLoadBalancingClient} subtype + * @param {@link ClientRequest} subtype + * @param {@link HttpResponse} subtype * @author Spencer Gibb */ public abstract class AbstractRibbonCommand, RQ extends ClientRequest, RS extends HttpResponse> extends HystrixCommand implements RibbonCommand { private static final Log LOGGER = LogFactory.getLog(AbstractRibbonCommand.class); + protected final LBC client; + protected RibbonCommandContext context; + protected FallbackProvider zuulFallbackProvider; + protected IClientConfig config; public AbstractRibbonCommand(LBC client, RibbonCommandContext context, @@ -68,20 +76,21 @@ public abstract class AbstractRibbonCommand 0) { + if (commandHystrixTimeout > 0) { hystrixTimeout = commandHystrixTimeout; } - else if(defaultHystrixTimeout > 0) { + else if (defaultHystrixTimeout > 0) { hystrixTimeout = defaultHystrixTimeout; - } else { + } + else { hystrixTimeout = ribbonTimeout; } - if(hystrixTimeout < ribbonTimeout) { - LOGGER.warn("The Hystrix timeout of " + hystrixTimeout + "ms for the command " + commandKey + - " is set lower than the combination of the Ribbon read and connect timeout, " + ribbonTimeout + "ms."); + if (hystrixTimeout < ribbonTimeout) { + LOGGER.warn("The Hystrix timeout of " + hystrixTimeout + "ms for the command " + + commandKey + + " is set lower than the combination of the Ribbon read and connect timeout, " + + ribbonTimeout + "ms."); } return hystrixTimeout; } @@ -121,29 +140,43 @@ public abstract class AbstractRibbonCommand configKey, int defaultValue) { - DynamicPropertyFactory dynamicPropertyFactory = DynamicPropertyFactory.getInstance(); - return dynamicPropertyFactory.getIntProperty(commandKey + "." + config.getNameSpace() + "." + property, config.get(configKey, defaultValue)).get(); + private static int getTimeout(IClientConfig config, String commandKey, + String property, IClientConfigKey configKey, int defaultValue) { + DynamicPropertyFactory dynamicPropertyFactory = DynamicPropertyFactory + .getInstance(); + return dynamicPropertyFactory + .getIntProperty(commandKey + "." + config.getNameSpace() + "." + property, + config.get(configKey, defaultValue)) + .get(); } @Deprecated - //TODO remove in 2.0.x - protected static Setter getSetter(final String commandKey, ZuulProperties zuulProperties) { + // TODO remove in 2.0.x + protected static Setter getSetter(final String commandKey, + ZuulProperties zuulProperties) { return getSetter(commandKey, zuulProperties, null); } @@ -154,18 +187,18 @@ public abstract class AbstractRibbonCommand fallbackProviderCache; + private FallbackProvider defaultFallbackProvider = null; - public AbstractRibbonCommandFactory(Set fallbackProviders){ + public AbstractRibbonCommandFactory(Set fallbackProviders) { this.fallbackProviderCache = new HashMap<>(); - for(FallbackProvider provider : fallbackProviders) { + for (FallbackProvider provider : fallbackProviders) { String route = provider.getRoute(); - if("*".equals(route) || route == null) { + if ("*".equals(route) || route == null) { defaultFallbackProvider = provider; - } else { + } + else { fallbackProviderCache.put(route, provider); } } @@ -46,9 +47,10 @@ public abstract class AbstractRibbonCommandFactory implements RibbonCommandFacto protected FallbackProvider getFallbackProvider(String route) { FallbackProvider provider = fallbackProviderCache.get(route); - if(provider == null) { + if (provider == null) { provider = defaultFallbackProvider; } return provider; } + } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/support/FilterConstants.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/support/FilterConstants.java index a2c24b3a6..fd708a699 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/support/FilterConstants.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/support/FilterConstants.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,118 +12,133 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.filters.support; +import com.netflix.zuul.ZuulFilter; + import org.springframework.cloud.netflix.zuul.filters.pre.DebugFilter; import org.springframework.cloud.netflix.zuul.filters.pre.Servlet30WrapperFilter; import org.springframework.cloud.netflix.zuul.filters.route.SendForwardFilter; -import com.netflix.zuul.ZuulFilter; - /** * @author Spencer Gibb */ -public class FilterConstants { +public final class FilterConstants { // KEY constants ----------------------------------- /** - * Zuul {@link com.netflix.zuul.context.RequestContext} key for use in {@link org.springframework.cloud.netflix.zuul.filters.pre.ServletDetectionFilter} + * Zuul {@link com.netflix.zuul.context.RequestContext} key for use in + * {@link org.springframework.cloud.netflix.zuul.filters.pre.ServletDetectionFilter}. */ public static final String IS_DISPATCHER_SERVLET_REQUEST_KEY = "isDispatcherServletRequest"; /** - * Zuul {@link com.netflix.zuul.context.RequestContext} key for use in {@link org.springframework.cloud.netflix.zuul.filters.route.SendForwardFilter} + * Zuul {@link com.netflix.zuul.context.RequestContext} key for use in + * {@link org.springframework.cloud.netflix.zuul.filters.route.SendForwardFilter}. */ public static final String FORWARD_TO_KEY = "forward.to"; /** - * Zuul {@link com.netflix.zuul.context.RequestContext} key for use in TODO: determine use + * Zuul {@link com.netflix.zuul.context.RequestContext} key for use in TODO: determine + * use. */ public static final String PROXY_KEY = "proxy"; /** - * Zuul {@link com.netflix.zuul.context.RequestContext} key for use in {@link org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter} + * Zuul {@link com.netflix.zuul.context.RequestContext} key for use in + * {@link org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter}. */ public static final String REQUEST_ENTITY_KEY = "requestEntity"; /** - * Zuul {@link com.netflix.zuul.context.RequestContext} key for use in to override the path of the request. + * Zuul {@link com.netflix.zuul.context.RequestContext} key for use in to override the + * path of the request. */ public static final String REQUEST_URI_KEY = "requestURI"; /** - * Zuul {@link com.netflix.zuul.context.RequestContext} key for use in {@link org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter} + * Zuul {@link com.netflix.zuul.context.RequestContext} key for use in + * {@link org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter}. */ public static final String RETRYABLE_KEY = "retryable"; /** - * Zuul {@link com.netflix.zuul.context.RequestContext} key for use in {@link org.springframework.cloud.netflix.zuul.filters.post.SendResponseFilter} + * Zuul {@link com.netflix.zuul.context.RequestContext} key for use in + * {@link org.springframework.cloud.netflix.zuul.filters.post.SendResponseFilter}. */ public static final String ROUTING_DEBUG_KEY = "routingDebug"; /** - * Zuul {@link com.netflix.zuul.context.RequestContext} key for use in {@link org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter} + * Zuul {@link com.netflix.zuul.context.RequestContext} key for use in + * {@link org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter}. */ public static final String SERVICE_ID_KEY = "serviceId"; /** - * Zuul {@link com.netflix.zuul.context.RequestContext} key for use in {@link org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter} + * Zuul {@link com.netflix.zuul.context.RequestContext} key for use in + * {@link org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter}. */ public static final String LOAD_BALANCER_KEY = "loadBalancerKey"; // ORDER constants ----------------------------------- /** - * Filter Order for {@link DebugFilter#filterOrder()} + * Filter Order for {@link DebugFilter#filterOrder()}. */ public static final int DEBUG_FILTER_ORDER = 1; /** - * Filter Order for {@link org.springframework.cloud.netflix.zuul.filters.pre.FormBodyWrapperFilter#filterOrder()} + * Filter Order for + * {@link org.springframework.cloud.netflix.zuul.filters.pre.FormBodyWrapperFilter#filterOrder()}. */ public static final int FORM_BODY_WRAPPER_FILTER_ORDER = -1; /** - * Filter Order for {@link org.springframework.cloud.netflix.zuul.filters.pre.PreDecorationFilter} + * Filter Order for + * {@link org.springframework.cloud.netflix.zuul.filters.pre.PreDecorationFilter}. */ public static final int PRE_DECORATION_FILTER_ORDER = 5; /** - * Filter Order for {@link org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter#filterOrder()} + * Filter Order for + * {@link org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter#filterOrder()}. */ public static final int RIBBON_ROUTING_FILTER_ORDER = 10; /** - * Filter Order for {@link org.springframework.cloud.netflix.zuul.filters.post.SendErrorFilter#filterOrder()} + * Filter Order for + * {@link org.springframework.cloud.netflix.zuul.filters.post.SendErrorFilter#filterOrder()}. */ public static final int SEND_ERROR_FILTER_ORDER = 0; /** - * Filter Order for {@link SendForwardFilter#filterOrder()} + * Filter Order for {@link SendForwardFilter#filterOrder()}. */ public static final int SEND_FORWARD_FILTER_ORDER = 500; /** - * Filter Order for {@link org.springframework.cloud.netflix.zuul.filters.post.SendResponseFilter#filterOrder()} + * Filter Order for + * {@link org.springframework.cloud.netflix.zuul.filters.post.SendResponseFilter#filterOrder()}. */ public static final int SEND_RESPONSE_FILTER_ORDER = 1000; /** - * Filter Order for {@link org.springframework.cloud.netflix.zuul.filters.route.SimpleHostRoutingFilter#filterOrder()} + * Filter Order for + * {@link org.springframework.cloud.netflix.zuul.filters.route.SimpleHostRoutingFilter#filterOrder()}. */ public static final int SIMPLE_HOST_ROUTING_FILTER_ORDER = 100; /** - * filter order for {@link Servlet30WrapperFilter#filterOrder()} + * filter order for {@link Servlet30WrapperFilter#filterOrder()}. */ public static final int SERVLET_30_WRAPPER_FILTER_ORDER = -2; /** - * filter order for {@link org.springframework.cloud.netflix.zuul.filters.pre.ServletDetectionFilter#filterOrder()} + * filter order for + * {@link org.springframework.cloud.netflix.zuul.filters.pre.ServletDetectionFilter#filterOrder()}. */ public static final int SERVLET_DETECTION_FILTER_ORDER = -3; @@ -152,69 +167,70 @@ public class FilterConstants { // OTHER constants ----------------------------------- /** - * Zuul {@link com.netflix.zuul.context.RequestContext} key for use in {@link org.springframework.cloud.netflix.zuul.filters.route.SendForwardFilter} + * Zuul {@link com.netflix.zuul.context.RequestContext} key for use in + * {@link org.springframework.cloud.netflix.zuul.filters.route.SendForwardFilter}. */ public static final String FORWARD_LOCATION_PREFIX = "forward:"; /** - * default http port + * Dfault http port. */ public static final int HTTP_PORT = 80; /** - * default https port + * Default https port. */ public static final int HTTPS_PORT = 443; /** - * http url scheme + * Http url scheme. */ public static final String HTTP_SCHEME = "http"; /** - * https url scheme + * Https url scheme. */ public static final String HTTPS_SCHEME = "https"; // HEADER constants ----------------------------------- /** - * X-* Header for the matching url. Used when routes use a url rather than serviceId + * X-* Header for the matching url. Used when routes use a url rather than serviceId. */ public static final String SERVICE_HEADER = "X-Zuul-Service"; /** - * X-* Header for the matching serviceId + * X-* Header for the matching serviceId. */ public static final String SERVICE_ID_HEADER = "X-Zuul-ServiceId"; /** - * X-Forwarded-For Header + * X-Forwarded-For Header. */ public static final String X_FORWARDED_FOR_HEADER = "X-Forwarded-For"; /** - * X-Forwarded-Host Header + * X-Forwarded-Host Header. */ public static final String X_FORWARDED_HOST_HEADER = "X-Forwarded-Host"; /** - * X-Forwarded-Prefix Header + * X-Forwarded-Prefix Header. */ public static final String X_FORWARDED_PREFIX_HEADER = "X-Forwarded-Prefix"; /** - * X-Forwarded-Port Header + * X-Forwarded-Port Header. */ public static final String X_FORWARDED_PORT_HEADER = "X-Forwarded-Port"; /** - * X-Forwarded-Proto Header + * X-Forwarded-Proto Header. */ public static final String X_FORWARDED_PROTO_HEADER = "X-Forwarded-Proto"; /** - * X-Zuul-Debug Header + * X-Zuul-Debug Header. */ public static final String X_ZUUL_DEBUG_HEADER = "X-Zuul-Debug-Header"; diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/metrics/DefaultCounterFactory.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/metrics/DefaultCounterFactory.java index e6dda3129..9827ba7c2 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/metrics/DefaultCounterFactory.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/metrics/DefaultCounterFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,11 +17,11 @@ package org.springframework.cloud.netflix.zuul.metrics; import com.netflix.zuul.monitoring.CounterFactory; - import io.micrometer.core.instrument.MeterRegistry; /** - * A counter based monitoring factory that uses {@link MeterRegistry} to increment counters. + * A counter based monitoring factory that uses {@link MeterRegistry} to increment + * counters. * * @author Anastasiia Smirnova */ @@ -37,4 +37,5 @@ public class DefaultCounterFactory extends CounterFactory { public void increment(String name) { this.meterRegistry.counter(name).increment(); } + } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/metrics/EmptyCounterFactory.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/metrics/EmptyCounterFactory.java index 319502c8a..f3f5eabce 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/metrics/EmptyCounterFactory.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/metrics/EmptyCounterFactory.java @@ -24,7 +24,9 @@ import com.netflix.zuul.monitoring.CounterFactory; * @author Anastasiia Smirnova */ public class EmptyCounterFactory extends CounterFactory { + @Override public void increment(String name) { } + } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/metrics/EmptyTracerFactory.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/metrics/EmptyTracerFactory.java index e46bcbe50..1ad57d8fe 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/metrics/EmptyTracerFactory.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/metrics/EmptyTracerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,6 +34,7 @@ public class EmptyTracerFactory extends TracerFactory { } private static final class EmptyTracer implements Tracer { + @Override public void setName(String name) { } @@ -41,5 +42,7 @@ public class EmptyTracerFactory extends TracerFactory { @Override public void stopAndLog() { } + } + } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/util/RequestContentDataExtractor.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/util/RequestContentDataExtractor.java index 88e9718e0..c2f62b5cf 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/util/RequestContentDataExtractor.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/util/RequestContentDataExtractor.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,12 +16,6 @@ package org.springframework.cloud.netflix.zuul.util; -import static java.util.Arrays.stream; -import static java.util.Collections.emptyMap; -import static org.springframework.util.StringUtils.isEmpty; -import static org.springframework.util.StringUtils.tokenizeToStringArray; -import static org.springframework.util.StringUtils.uriDecode; - import java.io.IOException; import java.nio.charset.Charset; import java.util.HashSet; @@ -43,16 +37,38 @@ import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.util.UriComponentsBuilder; -public class RequestContentDataExtractor { - public static MultiValueMap extract(HttpServletRequest request) throws IOException { - return (request instanceof MultipartHttpServletRequest) ? - extractFromMultipartRequest((MultipartHttpServletRequest) request) : - extractFromRequest(request); +import static java.util.Arrays.stream; +import static java.util.Collections.emptyMap; +import static org.springframework.util.StringUtils.isEmpty; +import static org.springframework.util.StringUtils.tokenizeToStringArray; +import static org.springframework.util.StringUtils.uriDecode; + +/** + * Utility class providing methods for extracting {@link HttpServletRequest} content as a + * {@link MultiValueMap}. + * + * @author Eloi Poch + * @author Spencer Gibb + * @author Dmitrii Priporov + * @author Ryan Baxter + */ +public final class RequestContentDataExtractor { + + private RequestContentDataExtractor() { + throw new AssertionError("Must not instantiate utility class."); } - private static MultiValueMap extractFromRequest(HttpServletRequest request) throws IOException { + public static MultiValueMap extract(HttpServletRequest request) + throws IOException { + return (request instanceof MultipartHttpServletRequest) + ? extractFromMultipartRequest((MultipartHttpServletRequest) request) + : extractFromRequest(request); + } + + private static MultiValueMap extractFromRequest( + HttpServletRequest request) throws IOException { MultiValueMap builder = new LinkedMultiValueMap<>(); - Set queryParams = findQueryParams(request); + Set queryParams = findQueryParams(request); for (Entry entry : request.getParameterMap().entrySet()) { String key = entry.getKey(); @@ -67,12 +83,12 @@ public class RequestContentDataExtractor { return builder; } - private static MultiValueMap extractFromMultipartRequest(MultipartHttpServletRequest request) - throws IOException { + private static MultiValueMap extractFromMultipartRequest( + MultipartHttpServletRequest request) throws IOException { MultiValueMap builder = new LinkedMultiValueMap<>(); Map> queryParamsGroupedByName = findQueryParamsGroupedByName( request); - Set queryParams = findQueryParams(request); + Set queryParams = findQueryParams(request); for (Entry entry : request.getParameterMap().entrySet()) { String key = entry.getKey(); @@ -80,7 +96,7 @@ public class RequestContentDataExtractor { .collect(Collectors.toList()); List listOfOnlyQueryParams = queryParamsGroupedByName.get(key); - if(listOfOnlyQueryParams != null) { + if (listOfOnlyQueryParams != null) { listOfOnlyQueryParams = listOfOnlyQueryParams.stream() .map(param -> uriDecode(param, Charset.defaultCharset())) .collect(Collectors.toList()); @@ -101,15 +117,18 @@ public class RequestContentDataExtractor { } } - for (Entry> parts : request.getMultiFileMap().entrySet()) { + for (Entry> parts : request.getMultiFileMap() + .entrySet()) { for (MultipartFile file : parts.getValue()) { HttpHeaders headers = new HttpHeaders(); - headers.setContentDispositionFormData(file.getName(), file.getOriginalFilename()); + headers.setContentDispositionFormData(file.getName(), + file.getOriginalFilename()); if (file.getContentType() != null) { headers.setContentType(MediaType.valueOf(file.getContentType())); } - HttpEntity entity = new HttpEntity<>(new InputStreamResource(file.getInputStream()), headers); + HttpEntity entity = new HttpEntity<>( + new InputStreamResource(file.getInputStream()), headers); builder.add(parts.getKey(), entity); } } @@ -130,7 +149,7 @@ public class RequestContentDataExtractor { private static Set findQueryParams(HttpServletRequest request) { Set result = new HashSet<>(); - String query = request.getQueryString(); + String query = request.getQueryString(); if (query != null) { for (String value : tokenizeToStringArray(query, "&")) { @@ -152,4 +171,5 @@ public class RequestContentDataExtractor { } return UriComponentsBuilder.fromUriString("?" + query).build().getQueryParams(); } + } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/util/RequestUtils.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/util/RequestUtils.java index fd1e7cafd..fa0ebb409 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/util/RequestUtils.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/util/RequestUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,20 +20,35 @@ import com.netflix.zuul.context.RequestContext; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.IS_DISPATCHER_SERVLET_REQUEST_KEY; -public class RequestUtils { +/** + * Utility class providing methods to verify if the current request is a dispatcher + * servlet or a Zuul servlet request. + * + * @author Adrian Ivan + * @author Spencer Gibb + */ +public final class RequestUtils { + + private RequestUtils() { + throw new AssertionError("Must not instantiate utility class."); + } /** - * @deprecated use {@link org.springframework.cloud.netflix.zuul.filters.support.FilterConstants#IS_DISPATCHER_SERVLET_REQUEST_KEY} + * @deprecated use + * {@link org.springframework.cloud.netflix.zuul.filters.support.FilterConstants#IS_DISPATCHER_SERVLET_REQUEST_KEY} */ @Deprecated public static final String IS_DISPATCHERSERVLETREQUEST = IS_DISPATCHER_SERVLET_REQUEST_KEY; - + public static boolean isDispatcherServletRequest() { - return RequestContext.getCurrentContext().getBoolean(IS_DISPATCHER_SERVLET_REQUEST_KEY); + return RequestContext.getCurrentContext() + .getBoolean(IS_DISPATCHER_SERVLET_REQUEST_KEY); } - + public static boolean isZuulServletRequest() { - //extra check for dispatcher since ZuulServlet can run from ZuulController - return !isDispatcherServletRequest() && RequestContext.getCurrentContext().getZuulEngineRan(); - } + // extra check for dispatcher since ZuulServlet can run from ZuulController + return !isDispatcherServletRequest() + && RequestContext.getCurrentContext().getZuulEngineRan(); + } + } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/util/ZuulRuntimeException.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/util/ZuulRuntimeException.java index 35e5c4e00..10493a4d4 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/util/ZuulRuntimeException.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/util/ZuulRuntimeException.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.util; @@ -32,4 +31,5 @@ public class ZuulRuntimeException extends RuntimeException { public ZuulRuntimeException(Exception ex) { super(ex); } + } diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/web/ZuulController.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/web/ZuulController.java index d8fe936d1..a84b6008d 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/web/ZuulController.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/web/ZuulController.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,12 +19,12 @@ package org.springframework.cloud.netflix.zuul.web; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.springframework.web.servlet.ModelAndView; -import org.springframework.web.servlet.mvc.ServletWrappingController; - import com.netflix.zuul.context.RequestContext; import com.netflix.zuul.http.ZuulServlet; +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.mvc.ServletWrappingController; + /** * @author Spencer Gibb */ @@ -37,7 +37,8 @@ public class ZuulController extends ServletWrappingController { } @Override - public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { + public ModelAndView handleRequest(HttpServletRequest request, + HttpServletResponse response) throws Exception { try { // We don't care about the other features of the base class, just want to // handle the request diff --git a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/web/ZuulHandlerMapping.java b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/web/ZuulHandlerMapping.java index 94697f90d..71b7c813a 100644 --- a/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/web/ZuulHandlerMapping.java +++ b/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/web/ZuulHandlerMapping.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.web; @@ -21,6 +20,8 @@ import java.util.Collection; import javax.servlet.http.HttpServletRequest; +import com.netflix.zuul.context.RequestContext; + import org.springframework.boot.web.servlet.error.ErrorController; import org.springframework.cloud.netflix.zuul.filters.RefreshableRouteLocator; import org.springframework.cloud.netflix.zuul.filters.Route; @@ -31,8 +32,6 @@ import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.servlet.HandlerExecutionChain; import org.springframework.web.servlet.handler.AbstractUrlHandlerMapping; -import com.netflix.zuul.context.RequestContext; - /** * MVC HandlerMapping that maps incoming request paths to remote services. * @@ -60,8 +59,9 @@ public class ZuulHandlerMapping extends AbstractUrlHandlerMapping { } @Override - protected HandlerExecutionChain getCorsHandlerExecutionChain(HttpServletRequest request, - HandlerExecutionChain chain, CorsConfiguration config) { + protected HandlerExecutionChain getCorsHandlerExecutionChain( + HttpServletRequest request, HandlerExecutionChain chain, + CorsConfiguration config) { if (config == null) { // Allow CORS requests to go to the backend return chain; @@ -81,11 +81,15 @@ public class ZuulHandlerMapping extends AbstractUrlHandlerMapping { } @Override - protected Object lookupHandler(String urlPath, HttpServletRequest request) throws Exception { - if (this.errorController != null && urlPath.equals(this.errorController.getErrorPath())) { + protected Object lookupHandler(String urlPath, HttpServletRequest request) + throws Exception { + if (this.errorController != null + && urlPath.equals(this.errorController.getErrorPath())) { + return null; + } + if (isIgnoredPath(urlPath, this.routeLocator.getIgnoredPaths())) { return null; } - if (isIgnoredPath(urlPath, this.routeLocator.getIgnoredPaths())) return null; RequestContext ctx = RequestContext.getCurrentContext(); if (ctx.containsKey("forward.to")) { return null; diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ContextPathZuulProxyApplicationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ContextPathZuulProxyApplicationTests.java index 4c26246d5..7fd903e49 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ContextPathZuulProxyApplicationTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ContextPathZuulProxyApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,15 +12,16 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul; +import com.netflix.zuul.context.RequestContext; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -43,9 +44,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; -import com.netflix.zuul.context.RequestContext; - -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = ContextPathZuulProxyApplicationTests.ContextPathZuulProxyApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT, value = { @@ -83,8 +82,8 @@ public class ContextPathZuulProxyApplicationTests { ResponseEntity result = testRestTemplate.exchange( "http://localhost:" + this.port + "/app/self/1", HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Gotten 1!", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Gotten 1!"); } @Test @@ -95,12 +94,11 @@ public class ContextPathZuulProxyApplicationTests { ResponseEntity result = testRestTemplate.exchange( "http://localhost:" + this.port + "/app/strip", HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); // Prefix not stripped to it goes to /local/strip - assertEquals("Gotten strip!", result.getBody()); + assertThat(result.getBody()).isEqualTo("Gotten strip!"); } - // Don't use @SpringBootApplication because we don't want to component scan @Configuration @EnableAutoConfiguration @@ -115,4 +113,5 @@ public class ContextPathZuulProxyApplicationTests { } } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/FiltersEndpointTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/FiltersEndpointTests.java index b0925a640..59dd4b1ce 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/FiltersEndpointTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/FiltersEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul; @@ -20,8 +19,10 @@ package org.springframework.cloud.netflix.zuul; import java.util.List; import java.util.Map; +import com.netflix.zuul.ZuulFilter; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -30,10 +31,8 @@ import org.springframework.context.annotation.Bean; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.netflix.zuul.ZuulFilter; - +import static org.assertj.core.api.Assertions.assertThat; import static org.hibernate.validator.internal.util.Contracts.assertTrue; -import static org.junit.Assert.assertEquals; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; /** @@ -59,17 +58,17 @@ public class FiltersEndpointTests { foundFilter = true; // Verify filter's attributes - assertEquals(0, filterInfo.get("order")); + assertThat(filterInfo.get("order")).isEqualTo(0); break; // the search is over } } } - assertTrue(foundFilter, "Could not find expected sample filter from filters endpoint"); + assertTrue(foundFilter, + "Could not find expected sample filter from filters endpoint"); } - @SpringBootConfiguration @EnableAutoConfiguration @EnableZuulProxy @@ -83,6 +82,7 @@ public class FiltersEndpointTests { } static class TestFilter extends ZuulFilter { + @Override public String filterType() { return "sample"; @@ -102,5 +102,7 @@ public class FiltersEndpointTests { public int filterOrder() { return 0; } + } -} \ No newline at end of file + +} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/FormZuulProxyApplicationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/FormZuulProxyApplicationTests.java index 7fbceb616..1021fd051 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/FormZuulProxyApplicationTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/FormZuulProxyApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul; @@ -22,6 +21,10 @@ import java.io.IOException; import javax.inject.Inject; import javax.servlet.http.Part; +import com.netflix.loadbalancer.Server; +import com.netflix.loadbalancer.ServerList; +import com.netflix.zuul.ZuulFilter; +import com.netflix.zuul.context.RequestContext; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -57,13 +60,8 @@ import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerList; -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.context.RequestContext; - import static java.nio.charset.Charset.defaultCharset; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE; import static org.springframework.util.StreamUtils.copyToString; @@ -95,8 +93,8 @@ public class FormZuulProxyApplicationTests { ResponseEntity result = sendPost("/simplefzpat/form", form, headers); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted! {foo=[bar]}", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Posted! {foo=[bar]}"); } @Test @@ -108,8 +106,8 @@ public class FormZuulProxyApplicationTests { ResponseEntity result = sendPost("/simplefzpat/form", form, headers); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted! {foo=[bar]}", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Posted! {foo=[bar]}"); } @Test @@ -127,8 +125,8 @@ public class FormZuulProxyApplicationTests { ResponseEntity result = sendPost("/simplefzpat/file", form, headers); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted! bar", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Posted! bar"); } @Test @@ -147,8 +145,8 @@ public class FormZuulProxyApplicationTests { ResponseEntity result = sendPost("/simplefzpat/fileandform", form, headers); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted! bar!field!data", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Posted! bar!field!data"); } @Test @@ -164,8 +162,8 @@ public class FormZuulProxyApplicationTests { ResponseEntity result = sendPost("/simplefzpat/json", form, headers); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted! {foo=[bar]} as application/json", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Posted! {foo=[bar]} as application/json"); } @Test @@ -180,8 +178,8 @@ public class FormZuulProxyApplicationTests { ResponseEntity result = sendPost("/simplefzpat/form", form, headers); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted! {foo=[bar]}", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Posted! {foo=[bar]}"); } @Test @@ -194,18 +192,20 @@ public class FormZuulProxyApplicationTests { headers.setContentType(MediaType.valueOf( MediaType.APPLICATION_FORM_URLENCODED_VALUE + "; charset=UTF-8")); - ResponseEntity result = sendPost("/simplefzpat/form?uriParam=uriValue", form, headers); + ResponseEntity result = sendPost("/simplefzpat/form?uriParam=uriValue", form, + headers); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted! {uriParam=[uriValue], foo=[bar]}", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()) + .isEqualTo("Posted! {uriParam=[uriValue], foo=[bar]}"); } @Test public void getWithUrlParams() throws Exception { ResponseEntity result = sendGet("/simplefzpat/form?uriParam=uriValue"); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted! {uriParam=[uriValue]}", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Posted! {uriParam=[uriValue]}"); } private ResponseEntity sendPost(String url, MultiValueMap form, @@ -217,6 +217,7 @@ public class FormZuulProxyApplicationTests { private ResponseEntity sendGet(String url) { return restTemplate.getForEntity(url, String.class); } + } // Don't use @SpringBootApplication because we don't want to component scan diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/FormZuulServletProxyApplicationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/FormZuulServletProxyApplicationTests.java index a793cd58c..a4df61e76 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/FormZuulServletProxyApplicationTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/FormZuulServletProxyApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul; @@ -20,6 +19,10 @@ package org.springframework.cloud.netflix.zuul; import java.io.IOException; import java.io.InputStream; +import com.netflix.loadbalancer.Server; +import com.netflix.loadbalancer.ServerList; +import com.netflix.zuul.ZuulFilter; +import com.netflix.zuul.context.RequestContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.After; @@ -57,18 +60,14 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerList; -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.context.RequestContext; - -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE; @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = FormZuulServletProxyApplication.class, webEnvironment = RANDOM_PORT, - properties = {"zuul.routes[simplefzspat].path:/simplefzspat/**", "zuul.routes[simplefzspat].serviceId:simplefzspat"}) +@SpringBootTest(classes = FormZuulServletProxyApplication.class, webEnvironment = RANDOM_PORT, properties = { + "zuul.routes[simplefzspat].path:/simplefzspat/**", + "zuul.routes[simplefzspat].serviceId:simplefzspat" }) @DirtiesContext public class FormZuulServletProxyApplicationTests { @@ -92,10 +91,11 @@ public class FormZuulServletProxyApplicationTests { form.set("foo", "bar"); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); - ResponseEntity result = testRestTemplate.exchange("/zuul/simplefzspat/form", - HttpMethod.POST, new HttpEntity<>(form, headers), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted! {foo=[bar]}", result.getBody()); + ResponseEntity result = testRestTemplate.exchange( + "/zuul/simplefzspat/form", HttpMethod.POST, + new HttpEntity<>(form, headers), String.class); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Posted! {foo=[bar]}"); } @Test @@ -104,10 +104,11 @@ public class FormZuulServletProxyApplicationTests { form.set("foo", "bar"); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); - ResponseEntity result = testRestTemplate.exchange("/zuul/simplefzspat/form", - HttpMethod.POST, new HttpEntity<>(form, headers), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted! {foo=[bar]}", result.getBody()); + ResponseEntity result = testRestTemplate.exchange( + "/zuul/simplefzspat/form", HttpMethod.POST, + new HttpEntity<>(form, headers), String.class); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Posted! {foo=[bar]}"); } @Test @@ -121,10 +122,11 @@ public class FormZuulServletProxyApplicationTests { headers.setContentType(MediaType.MULTIPART_FORM_DATA); headers.set("Transfer-Encoding", "chunked"); headers.setContentLength(-1); - ResponseEntity result = testRestTemplate.exchange("/zuul/simplefzspat/file", - HttpMethod.POST, new HttpEntity<>(form, headers), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted! bar", result.getBody()); + ResponseEntity result = testRestTemplate.exchange( + "/zuul/simplefzspat/file", HttpMethod.POST, + new HttpEntity<>(form, headers), String.class); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Posted! bar"); } @Test @@ -134,11 +136,13 @@ public class FormZuulServletProxyApplicationTests { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.valueOf( MediaType.APPLICATION_FORM_URLENCODED_VALUE + "; charset=UTF-8")); - ResponseEntity result = testRestTemplate.exchange("/zuul/simplefzspat/form", - HttpMethod.POST, new HttpEntity<>(form, headers), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted! {foo=[bar]}", result.getBody()); + ResponseEntity result = testRestTemplate.exchange( + "/zuul/simplefzspat/form", HttpMethod.POST, + new HttpEntity<>(form, headers), String.class); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Posted! {foo=[bar]}"); } + } // Don't use @SpringBootApplication because we don't want to component scan @@ -150,7 +154,8 @@ public class FormZuulServletProxyApplicationTests { @Import(NoSecurityConfiguration.class) class FormZuulServletProxyApplication { - private static final Log log = LogFactory.getLog(FormZuulServletProxyApplication.class); + private static final Log log = LogFactory + .getLog(FormZuulServletProxyApplication.class); @RequestMapping(value = "/form", method = RequestMethod.POST) public String accept(@RequestParam MultiValueMap form) diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/RetryableZuulProxyApplicationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/RetryableZuulProxyApplicationTests.java index c5884b60c..7fc08a1b1 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/RetryableZuulProxyApplicationTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/RetryableZuulProxyApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul; @@ -21,7 +20,6 @@ import com.netflix.loadbalancer.Server; import com.netflix.loadbalancer.ServerList; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; - import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -29,10 +27,10 @@ import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.web.server.LocalServerPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; import org.springframework.cloud.netflix.ribbon.RibbonClient; import org.springframework.cloud.netflix.ribbon.StaticServerList; import org.springframework.cloud.netflix.zuul.filters.discovery.DiscoveryClientRouteLocator; @@ -55,13 +53,15 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = RetryableZuulProxyApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT, value = { - "zuul.routes[simplerzpat].path: /simplerzpat/**", "zuul.routes[simplerzpat].retryable: true", - "zuul.routes[simplerzpat].serviceId: simplerzpat", "ribbon.OkToRetryOnAllOperations: true", + "zuul.routes[simplerzpat].path: /simplerzpat/**", + "zuul.routes[simplerzpat].retryable: true", + "zuul.routes[simplerzpat].serviceId: simplerzpat", + "ribbon.OkToRetryOnAllOperations: true", "simplerzpat.ribbon.retryableStatusCodes: 404" }) @DirtiesContext public class RetryableZuulProxyApplicationTests { @@ -96,8 +96,8 @@ public class RetryableZuulProxyApplicationTests { headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); ResponseEntity result = testRestTemplate.exchange("/simplerzpat/poster", HttpMethod.POST, new HttpEntity<>(form, headers), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted! {foo=[bar]}", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Posted! {foo=[bar]}"); } } @@ -155,4 +155,5 @@ class RetryableRibbonClientConfiguration { return new StaticServerList<>(new Server("localhost", this.port), new Server("failed-localhost", this.port)); } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/RoutesEndpointDetailsTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/RoutesEndpointDetailsTests.java index e99af7497..b818fd47b 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/RoutesEndpointDetailsTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/RoutesEndpointDetailsTests.java @@ -1,19 +1,17 @@ /* + * Copyright 2013-2019 the original author or authors. * - * * Copyright 2013-2016 the original author or authors. - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.netflix.zuul; @@ -30,12 +28,13 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; + import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.netflix.zuul.filters.Route; import org.springframework.cloud.netflix.zuul.filters.RouteLocator; import org.springframework.context.ApplicationEventPublisher; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; @@ -48,8 +47,11 @@ import static org.mockito.Mockito.verify; @SpringBootTest @RunWith(MockitoJUnitRunner.class) public class RoutesEndpointDetailsTests { + private RouteLocator locator; + private RoutesEndpoint endpoint; + @Mock private ApplicationEventPublisher publisher; @@ -64,8 +66,10 @@ public class RoutesEndpointDetailsTests { @Override public List getRoutes() { List routes = new ArrayList<>(); - routes.add(new Route("foo", "foopath", "foolocation", null, true, Collections.EMPTY_SET)); - routes.add(new Route("bar", "barpath", "barlocation", "bar-prefix", true, Collections.EMPTY_SET)); + routes.add(new Route("foo", "foopath", "foolocation", null, true, + Collections.EMPTY_SET)); + routes.add(new Route("bar", "barpath", "barlocation", "bar-prefix", true, + Collections.EMPTY_SET)); return routes; } @@ -81,10 +85,10 @@ public class RoutesEndpointDetailsTests { public void reset() throws Exception { this.endpoint.setApplicationEventPublisher(publisher); Map result = new HashMap<>(); - for(Route r : locator.getRoutes()) { + for (Route r : locator.getRoutes()) { result.put(r.getFullPath(), r.getLocation()); } - assertEquals(result , endpoint.reset()); + assertThat(endpoint.reset()).isEqualTo(result); verify(endpoint, times(1)).invoke(); verify(publisher, times(1)).publishEvent(isA(RoutesRefreshedEvent.class)); } @@ -95,8 +99,9 @@ public class RoutesEndpointDetailsTests { for (Route route : locator.getRoutes()) { results.put(route.getFullPath(), new RoutesEndpoint.RouteDetails(route)); } - assertEquals(results, this.endpoint.invokeRouteDetails(RoutesEndpoint.FORMAT_DETAILS)); + assertThat(this.endpoint.invokeRouteDetails(RoutesEndpoint.FORMAT_DETAILS)) + .isEqualTo(results); verify(endpoint, times(1)).invokeRouteDetails(); } -} \ No newline at end of file +} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/RoutesEndpointIntegrationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/RoutesEndpointIntegrationTests.java index 0f132fe7c..fc47a3d6b 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/RoutesEndpointIntegrationTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/RoutesEndpointIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul; @@ -22,6 +21,7 @@ import java.util.Map; import org.assertj.core.api.Assertions; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -40,10 +40,7 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.bind.annotation.RestController; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; /** @@ -51,10 +48,13 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Gregor Zurowski */ @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = RANDOM_PORT, - value = {"zuul.routes.sslservice.url=https://localhost:8443", "management.security.enabled=false", "management.endpoints.web.exposure.include=*"}) +@SpringBootTest(webEnvironment = RANDOM_PORT, value = { + "zuul.routes.sslservice.url=https://localhost:8443", + "management.security.enabled=false", + "management.endpoints.web.exposure.include=*" }) @DirtiesContext public class RoutesEndpointIntegrationTests { + private static final String BASE_PATH = new WebEndpointProperties().getBasePath(); @Autowired @@ -66,36 +66,40 @@ public class RoutesEndpointIntegrationTests { @Test @SuppressWarnings("unchecked") public void getRoutesTest() { - ResponseEntity entity = restTemplate.getForEntity(BASE_PATH + "/routes", Map.class); + ResponseEntity entity = restTemplate.getForEntity(BASE_PATH + "/routes", + Map.class); Assertions.assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); Map routes = entity.getBody(); - assertEquals("https://localhost:8443", routes.get("/sslservice/**")); + assertThat(routes.get("/sslservice/**")).isEqualTo("https://localhost:8443"); } @Test @SuppressWarnings("unchecked") public void postRoutesTest() { - ResponseEntity entity = restTemplate.postForEntity(BASE_PATH + "/routes", null, Map.class); + ResponseEntity entity = restTemplate.postForEntity(BASE_PATH + "/routes", + null, Map.class); Assertions.assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); Map routes = entity.getBody(); - assertEquals("https://localhost:8443", routes.get("/sslservice/**")); - assertTrue(refreshListener.wasCalled()); + assertThat(routes.get("/sslservice/**")).isEqualTo("https://localhost:8443"); + assertThat(refreshListener.wasCalled()).isTrue(); } @Test public void getRouteDetailsTest() { - ResponseEntity> responseEntity = restTemplate.exchange( - BASE_PATH + "/routes/details", HttpMethod.GET, null, new ParameterizedTypeReference>() { - }); + ResponseEntity> responseEntity = restTemplate + .exchange(BASE_PATH + "/routes/details", HttpMethod.GET, null, + new ParameterizedTypeReference>() { + }); - assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK)); + assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK); - RoutesEndpoint.RouteDetails details = responseEntity.getBody().get("/sslservice/**"); - assertThat(details.getPath(), is("/**")); - assertThat(details.getFullPath(), is("/sslservice/**")); - assertThat(details.getLocation(), is("https://localhost:8443")); - assertThat(details.getPrefix(), is("/sslservice")); - assertTrue(details.isPrefixStripped()); + RoutesEndpoint.RouteDetails details = responseEntity.getBody() + .get("/sslservice/**"); + assertThat(details.getPath()).isEqualTo("/**"); + assertThat(details.getFullPath()).isEqualTo("/sslservice/**"); + assertThat(details.getLocation()).isEqualTo("https://localhost:8443"); + assertThat(details.getPrefix()).isEqualTo("/sslservice"); + assertThat(details.isPrefixStripped()).isTrue(); } @Configuration @@ -104,9 +108,13 @@ public class RoutesEndpointIntegrationTests { @EnableZuulProxy @Import(NoSecurityConfiguration.class) static class SimpleZuulProxyApplication { + @Component - static class RoutesRefreshListener implements ApplicationListener { + static class RoutesRefreshListener + implements ApplicationListener { + private boolean called = false; + @Override public void onApplicationEvent(RoutesRefreshedEvent routesRefreshedEvent) { called = true; @@ -115,6 +123,9 @@ public class RoutesEndpointIntegrationTests { public boolean wasCalled() { return called; } + } + } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/RoutesEndpointTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/RoutesEndpointTests.java index ffe2de8fa..5a36079d6 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/RoutesEndpointTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/RoutesEndpointTests.java @@ -1,19 +1,17 @@ /* + * Copyright 2013-2019 the original author or authors. * - * * Copyright 2013-2016 the original author or authors. - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.netflix.zuul; @@ -27,10 +25,11 @@ import java.util.Map; import org.junit.Before; import org.junit.Test; + import org.springframework.cloud.netflix.zuul.filters.Route; import org.springframework.cloud.netflix.zuul.filters.RouteLocator; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Ryan Baxter @@ -51,8 +50,10 @@ public class RoutesEndpointTests { @Override public List getRoutes() { List routes = new ArrayList<>(); - routes.add(new Route("foo", "foopath", "foolocation", null, true, Collections.EMPTY_SET)); - routes.add(new Route("bar", "barpath", "barlocation", "/bar-prefix", true, Collections.EMPTY_SET)); + routes.add(new Route("foo", "foopath", "foolocation", null, true, + Collections.EMPTY_SET)); + routes.add(new Route("bar", "barpath", "barlocation", "/bar-prefix", true, + Collections.EMPTY_SET)); return routes; } @@ -67,10 +68,10 @@ public class RoutesEndpointTests { public void testInvoke() { RoutesEndpoint endpoint = new RoutesEndpoint(locator); Map result = new HashMap(); - for(Route r : locator.getRoutes()) { + for (Route r : locator.getRoutes()) { result.put(r.getFullPath(), r.getLocation()); } - assertEquals(result , endpoint.invoke()); + assertThat(endpoint.invoke()).isEqualTo(result); } @Test @@ -80,7 +81,7 @@ public class RoutesEndpointTests { for (Route route : locator.getRoutes()) { results.put(route.getFullPath(), new RoutesEndpoint.RouteDetails(route)); } - assertEquals(results, endpoint.invokeRouteDetails()); + assertThat(endpoint.invokeRouteDetails()).isEqualTo(results); } -} \ No newline at end of file +} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ServletPathZuulProxyApplicationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ServletPathZuulProxyApplicationTests.java index c54a4811f..c24c28ed7 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ServletPathZuulProxyApplicationTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ServletPathZuulProxyApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,18 +12,19 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul; import java.net.URI; +import com.netflix.zuul.context.RequestContext; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -48,9 +49,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; -import com.netflix.zuul.context.RequestContext; - -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; @RunWith(SpringJUnit4ClassRunner.class) @@ -83,18 +82,18 @@ public class ServletPathZuulProxyApplicationTests { } @Test - @Ignore //FIXME: 2.1.0 + @Ignore // FIXME: 2.1.0 public void getOnSelfViaSimpleHostRoutingFilter() { this.routes.addRoute("/self/**", "http://localhost:" + this.port + "/app/local"); this.endpoint.reset(); ResponseEntity result = testRestTemplate.exchange("/app/self/1", HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Gotten 1!", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Gotten 1!"); } @Test - @Ignore //FIXME: 2.1.0 + @Ignore // FIXME: 2.1.0 public void optionsOnRawEndpoint() throws Exception { ResponseEntity result = testRestTemplate.exchange( RequestEntity.options(new URI("/app/local/1")) @@ -103,12 +102,12 @@ public class ServletPathZuulProxyApplicationTests { String.class); HttpHeaders httpHeaders = result.getHeaders(); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("*", httpHeaders.getFirst("Access-Control-Allow-Origin")); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(httpHeaders.getFirst("Access-Control-Allow-Origin")).isEqualTo("*"); } @Test - @Ignore //FIXME: 2.1.0 + @Ignore // FIXME: 2.1.0 public void optionsOnSelf() throws Exception { this.routes.addRoute("/self/**", "http://localhost:" + this.port + "/app/local"); this.endpoint.reset(); @@ -119,30 +118,30 @@ public class ServletPathZuulProxyApplicationTests { String.class); HttpHeaders httpHeaders = result.getHeaders(); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("*", httpHeaders.getFirst("Access-Control-Allow-Origin")); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(httpHeaders.getFirst("Access-Control-Allow-Origin")).isEqualTo("*"); } @Test - @Ignore //FIXME: 2.1.0 + @Ignore // FIXME: 2.1.0 public void contentOnRawEndpoint() throws Exception { ResponseEntity result = testRestTemplate.exchange( RequestEntity.get(new URI("/app/local/1")).build(), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Gotten 1!", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Gotten 1!"); } @Test - @Ignore //FIXME: 2.1.0 + @Ignore // FIXME: 2.1.0 public void stripPrefixFalseAppendsPath() { this.routes.addRoute(new ZuulRoute("strip", "/strip/**", "strip", "http://localhost:" + this.port + "/app/local", false, false, null)); this.endpoint.reset(); ResponseEntity result = testRestTemplate.exchange("/app/strip", HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); // Prefix not stripped to it goes to /local/strip - assertEquals("Gotten strip!", result.getBody()); + assertThat(result.getBody()).isEqualTo("Gotten strip!"); } // Don't use @SpringBootApplication because we don't want to component scan @@ -160,4 +159,5 @@ public class ServletPathZuulProxyApplicationTests { } } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/SimpleZuulProxyApplicationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/SimpleZuulProxyApplicationTests.java index cebd303ec..1bc5b1595 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/SimpleZuulProxyApplicationTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/SimpleZuulProxyApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul; @@ -22,10 +21,12 @@ import java.net.URISyntaxException; import javax.servlet.http.HttpServletRequest; +import com.netflix.zuul.context.RequestContext; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -47,9 +48,7 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import com.netflix.zuul.context.RequestContext; - -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = SimpleZuulProxyApplicationTests.SimpleZuulProxyApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT, value = { @@ -120,19 +119,21 @@ public class SimpleZuulProxyApplicationTests { @Test public void getOnSelfWithComplexQueryParam() throws URISyntaxException { - String encodedQueryString = "foo=%7B%22project%22%3A%22stream%22%2C%22logger%22%3A%22javascript%22%2C%22platform%22%3A%22javascript%22%2C%22request%22%3A%7B%22url%22%3A%22https%3A%2F%2Ffoo%2Fadmin"; + String encodedQueryString = "foo=%7B%22project%22%3A%22stream%22%2C%22logger" + + "%22%3A%22javascript%22%2C%22platform%22%3A%22javascript%22%2C%22" + + "request%22%3A%7B%22url%22%3A%22https%3A%2F%2Ffoo%2Fadmin"; ResponseEntity result = testRestTemplate.exchange( new URI("/foo?" + encodedQueryString), HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals(encodedQueryString, result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo(encodedQueryString); } private void assertResponseCodeAndBody(ResponseEntity result, String expectedBody) { - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals(expectedBody, result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo(expectedBody); } private ResponseEntity executeSimpleRequest(HttpMethod httpMethod) { @@ -180,4 +181,5 @@ public class SimpleZuulProxyApplicationTests { } } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/SimpleZuulServerApplicationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/SimpleZuulServerApplicationTests.java index a60f7969b..1088c2771 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/SimpleZuulServerApplicationTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/SimpleZuulServerApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,31 +12,26 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; - import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.web.server.LocalServerPort; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; import org.springframework.cloud.netflix.zuul.filters.RouteLocator; import org.springframework.cloud.netflix.zuul.test.NoSecurityConfiguration; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; @@ -47,14 +42,12 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE; @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(webEnvironment = RANDOM_PORT, - properties = "zuul.routes[testclient]:/testing123/**") +@SpringBootTest(webEnvironment = RANDOM_PORT, properties = "zuul.routes[testclient]:/testing123/**") @DirtiesContext public class SimpleZuulServerApplicationTests { @@ -84,25 +77,24 @@ public class SimpleZuulServerApplicationTests { @Test public void bindRoute() { - assertNotNull(getRoute("/testing123/**")); + assertThat(getRoute("/testing123/**")).isNotNull(); } @Test public void getOnSelf() { ResponseEntity result = testRestTemplate.exchange("/", HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Hello world", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Hello world"); } @Test public void getOnSelfViaFilter() { ResponseEntity result = testRestTemplate.exchange("/testing123/1", HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); } - // Don't use @SpringBootApplication because we don't want to component scan @SpringBootConfiguration @EnableAutoConfiguration @@ -147,4 +139,5 @@ public class SimpleZuulServerApplicationTests { } } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulFilterInitializerTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulFilterInitializerTests.java index eb3d97c63..5a542fad0 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulFilterInitializerTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulFilterInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,30 +21,30 @@ import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.test.util.ReflectionTestUtils; -import org.springframework.util.ReflectionUtils; - import com.netflix.zuul.FilterLoader; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.filters.FilterRegistry; import com.netflix.zuul.monitoring.CounterFactory; import com.netflix.zuul.monitoring.TracerFactory; +import org.junit.Before; +import org.junit.Test; + +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; public class ZuulFilterInitializerTests { private Map filters; + private CounterFactory counterFactory; + private TracerFactory tracerFactory; + private FilterLoader filterLoader; + private FilterRegistry filterRegistry; private ZuulFilterInitializer initializer; @@ -56,8 +56,8 @@ public class ZuulFilterInitializerTests { tracerFactory = mock(TracerFactory.class); filterLoader = new FilterLoader(); filterRegistry = getFilterRegistry(); - initializer = new ZuulFilterInitializer(filters, - counterFactory, tracerFactory, filterLoader, filterRegistry); + initializer = new ZuulFilterInitializer(filters, counterFactory, tracerFactory, + filterLoader, filterRegistry); initializer.contextInitialized(); } @@ -65,10 +65,9 @@ public class ZuulFilterInitializerTests { @Test public void shouldSetupOnContextInitializedEvent() { - assertEquals(tracerFactory, TracerFactory.instance()); - assertEquals(counterFactory, CounterFactory.instance()); - assertThat(filterRegistry.getAllFilters()) - .containsAll(filters.values()); + assertThat(TracerFactory.instance()).isEqualTo(tracerFactory); + assertThat(CounterFactory.instance()).isEqualTo(counterFactory); + assertThat(filterRegistry.getAllFilters()).containsAll(filters.values()); initializer.contextDestroyed(); } @@ -78,10 +77,12 @@ public class ZuulFilterInitializerTests { initializer.contextDestroyed(); - assertNull(ReflectionTestUtils.getField(TracerFactory.class, "INSTANCE")); - assertNull(ReflectionTestUtils.getField(CounterFactory.class, "INSTANCE")); + assertThat(ReflectionTestUtils.getField(TracerFactory.class, "INSTANCE")) + .isNull(); + assertThat(ReflectionTestUtils.getField(CounterFactory.class, "INSTANCE")) + .isNull(); assertThat(filterRegistry.getAllFilters()).isEmpty(); - assertTrue(getHashFiltersByType().isEmpty()); + assertThat(getHashFiltersByType().isEmpty()).isTrue(); } private Map getHashFiltersByType() { @@ -108,4 +109,5 @@ public class ZuulFilterInitializerTests { throw new RuntimeException(e); } } -} \ No newline at end of file + +} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulProxyApplicationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulProxyApplicationTests.java index c4e6db24a..26fc7983d 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulProxyApplicationTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulProxyApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul; @@ -24,6 +23,7 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -53,16 +53,11 @@ import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import static java.util.Collections.singletonList; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest( - classes = ZuulProxyApplicationTests.ZuulProxyApplication.class, - webEnvironment = WebEnvironment.RANDOM_PORT, - properties = { - "zuul.routes.simplezpat:/simplezpat/**", - "logging.level.org.apache.http: DEBUG" - }) +@SpringBootTest(classes = ZuulProxyApplicationTests.ZuulProxyApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT, properties = { + "zuul.routes.simplezpat:/simplezpat/**", "logging.level.org.apache.http: DEBUG" }) @DirtiesContext public class ZuulProxyApplicationTests { @@ -85,18 +80,20 @@ public class ZuulProxyApplicationTests { @Test public void getHasCorrectTransferEncoding() { - ResponseEntity result = testRestTemplate.getForEntity(url(), String.class); + ResponseEntity result = testRestTemplate.getForEntity(url(), + String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("missing", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("missing"); } @Test public void postHasCorrectTransferEncoding() { - ResponseEntity result = testRestTemplate.postForEntity(url(), new HttpEntity<>("hello"), String.class); + ResponseEntity result = testRestTemplate.postForEntity(url(), + new HttpEntity<>("hello"), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("missing", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("missing"); } @Test @@ -107,7 +104,7 @@ public class ZuulProxyApplicationTests { ResponseEntity result = testRestTemplate.exchange(url(), HttpMethod.OPTIONS, new HttpEntity<>(headers), Void.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test @@ -118,7 +115,7 @@ public class ZuulProxyApplicationTests { ResponseEntity result = testRestTemplate.exchange(url(), HttpMethod.OPTIONS, new HttpEntity<>(headers), Void.class); - assertEquals(HttpStatus.FORBIDDEN, result.getStatusCode()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } @Test @@ -129,10 +126,9 @@ public class ZuulProxyApplicationTests { ResponseEntity result = testRestTemplate.exchange(url(), HttpMethod.OPTIONS, new HttpEntity<>(headers), Void.class); - assertEquals(HttpStatus.FORBIDDEN, result.getStatusCode()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } - private String url() { return "http://localhost:" + this.port + "/simplezpat/transferencoding"; } @@ -192,4 +188,5 @@ public class ZuulProxyApplicationTests { } } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulProxyAutoConfigurationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulProxyAutoConfigurationTests.java index c374d8231..e96763c15 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulProxyAutoConfigurationTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulProxyAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul; @@ -34,9 +33,9 @@ import static org.assertj.core.api.Assertions.assertThat; /** * To test the auto-configuration of Zuul Proxy - * + * * @author Biju Kunjummen - * + * */ @RunWith(SpringRunner.class) @@ -60,5 +59,7 @@ public class ZuulProxyAutoConfigurationTests { @EnableAutoConfiguration @EnableZuulProxy static class TestConfig { + } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulProxyConfigurationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulProxyConfigurationTests.java index ee7078412..d5ca4178e 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulProxyConfigurationTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulProxyConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul; @@ -41,12 +40,14 @@ public class ZuulProxyConfigurationTests { @Test public void testDefaultsToApacheHttpClient() { testClient(HttpClientRibbonCommandFactory.class, null); - testClient(HttpClientRibbonCommandFactory.class, "ribbon.httpclient.enabled=true"); + testClient(HttpClientRibbonCommandFactory.class, + "ribbon.httpclient.enabled=true"); } @Test public void testEnableRestClient() { - testClient(RestClientRibbonCommandFactory.class, "ribbon.restclient.enabled=true"); + testClient(RestClientRibbonCommandFactory.class, + "ribbon.restclient.enabled=true"); } @Test @@ -58,16 +59,16 @@ public class ZuulProxyConfigurationTests { if (property == null) { property = "aaa=bbb"; } - new WebApplicationContextRunner() - .withUserConfiguration(TestConfig.class) - .withPropertyValues(property) - .run(c -> assertThat(c).hasSingleBean(clientType)); + new WebApplicationContextRunner().withUserConfiguration(TestConfig.class) + .withPropertyValues(property) + .run(c -> assertThat(c).hasSingleBean(clientType)); } @SpringBootConfiguration @EnableAutoConfiguration @EnableZuulProxy static class TestConfig { + @Bean SpringClientFactory springClientFactory() { return mock(SpringClientFactory.class); @@ -77,6 +78,7 @@ public class ZuulProxyConfigurationTests { DiscoveryClient discoveryClient() { return mock(DiscoveryClient.class); } + } } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulServerAutoConfigurationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulServerAutoConfigurationTests.java index 95c8f8c1a..f83394519 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulServerAutoConfigurationTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/ZuulServerAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,13 +12,13 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -32,31 +32,32 @@ import static org.assertj.core.api.Assertions.assertThat; /** * To test the auto-configuration of Zuul Proxy - * + * * @author Biju Kunjummen - * + * */ @RunWith(SpringRunner.class) @SpringBootTest public class ZuulServerAutoConfigurationTests { - + @Autowired private RouteLocator routeLocator; @Autowired(required = false) private RibbonRoutingFilter ribbonRoutingFilter; - + @Test public void testAutoConfiguredBeans() { assertThat(routeLocator).isInstanceOf(CompositeRouteLocator.class); assertThat(ribbonRoutingFilter).isNull(); } - - + @Configuration @EnableAutoConfiguration @EnableZuulServer static class TestConfig { - } + + } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/CompositeRouteLocatorTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/CompositeRouteLocatorTests.java index abe5b3f4f..8691cbf4b 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/CompositeRouteLocatorTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/CompositeRouteLocatorTests.java @@ -1,13 +1,20 @@ -package org.springframework.cloud.netflix.zuul.filters; +/* + * Copyright 2017-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ -import static java.util.Arrays.asList; -import static org.hamcrest.CoreMatchers.hasItems; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; +package org.springframework.cloud.netflix.zuul.filters; import java.util.ArrayList; import java.util.Collection; @@ -16,41 +23,46 @@ import java.util.List; import org.junit.Test; +import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + /** * @author Johannes Edmeier */ public class CompositeRouteLocatorTests { + private CompositeRouteLocator locator; public CompositeRouteLocatorTests() { List locators = new ArrayList<>(); - locators.add(new TestRouteLocator(asList("ign1"), - asList(createRoute("1", "/pathA")))); locators.add( - new TestRouteLocator(asList("ign1", "ign2"), - asList(createRoute("2", "/pathA"), createRoute("2", "/pathB")))); + new TestRouteLocator(asList("ign1"), asList(createRoute("1", "/pathA")))); + locators.add(new TestRouteLocator(asList("ign1", "ign2"), + asList(createRoute("2", "/pathA"), createRoute("2", "/pathB")))); this.locator = new CompositeRouteLocator(locators); } @Test public void test_getIgnoredPaths() { - assertThat(locator.getIgnoredPaths(), hasItems("ign1", "ign2")); + assertThat(locator.getIgnoredPaths()).contains("ign1", "ign2"); } @Test public void test_getRoutes() { - assertThat(locator.getRoutes(), - hasItems(createRoute("1", "/pathA"), createRoute("2", "/pathB"))); + assertThat(locator.getRoutes()).contains(createRoute("1", "/pathA"), + createRoute("2", "/pathB")); } @Test public void test_getMatchingRoute() { - assertThat(locator.getMatchingRoute("/pathA"), notNullValue()); - assertThat(locator.getMatchingRoute("/pathA").getId(), is("1")); - assertThat("Locator 1 should take precedence", locator.getMatchingRoute("/pathB").getId(), - is("2")); - assertThat(locator.getMatchingRoute("/pathNot"), nullValue()); + assertThat(locator.getMatchingRoute("/pathA")).isNotNull(); + assertThat(locator.getMatchingRoute("/pathA").getId()).isEqualTo("1"); + assertThat(locator.getMatchingRoute("/pathB").getId()) + .as("Locator 1 should take precedence").isEqualTo("2"); + assertThat(locator.getMatchingRoute("/pathNot")).isNull(); } @Test @@ -65,10 +77,12 @@ public class CompositeRouteLocatorTests { } private static class TestRouteLocator implements RouteLocator { + private Collection ignoredPaths; + private List routes; - public TestRouteLocator(Collection ignoredPaths, List routes) { + TestRouteLocator(Collection ignoredPaths, List routes) { this.ignoredPaths = ignoredPaths; this.routes = routes; } @@ -94,4 +108,5 @@ public class CompositeRouteLocatorTests { } } -} \ No newline at end of file + +} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/CustomHostRoutingFilterTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/CustomHostRoutingFilterTests.java index c01d08967..3f2380add 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/CustomHostRoutingFilterTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/CustomHostRoutingFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.filters; @@ -66,11 +65,10 @@ import org.springframework.web.client.RestTemplate; import static junit.framework.TestCase.assertFalse; import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = CustomHostRoutingFilterTests.SampleCustomZuulProxyApplication.class, - webEnvironment = WebEnvironment.RANDOM_PORT, properties = { +@SpringBootTest(classes = CustomHostRoutingFilterTests.SampleCustomZuulProxyApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "server.servlet.context-path: /app" }) @DirtiesContext public class CustomHostRoutingFilterTests { @@ -101,8 +99,8 @@ public class CustomHostRoutingFilterTests { this.endpoint.reset(); ResponseEntity result = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/app/self/get/1", String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Get 1", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Get 1"); } @Test @@ -113,8 +111,8 @@ public class CustomHostRoutingFilterTests { params.add("id", "2"); ResponseEntity result = new TestRestTemplate().postForEntity( "http://localhost:" + this.port + "/app/self/post", params, String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Post 2", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Post 2"); } @Test @@ -124,8 +122,8 @@ public class CustomHostRoutingFilterTests { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/app/self/put/3", HttpMethod.PUT, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Put 3", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Put 3"); } @Test @@ -137,8 +135,8 @@ public class CustomHostRoutingFilterTests { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/app/self/patch/4", HttpMethod.PATCH, new HttpEntity<>(params), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Patch 45", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Patch 45"); } @Test @@ -147,7 +145,7 @@ public class CustomHostRoutingFilterTests { this.endpoint.reset(); ResponseEntity result = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/app/self/get/1", String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); assertTrue(result.getHeaders().containsKey("X-NotIgnored")); assertFalse(result.getHeaders().containsKey("X-Ignored")); } @@ -165,11 +163,10 @@ public class CustomHostRoutingFilterTests { ResponseEntity result2 = restTemplate.getForEntity( "http://localhost:" + this.port + "/app/self/cookie/2", String.class); - assertEquals("SetCookie 1", result1.getBody()); - assertEquals("GetCookie 1", result2.getBody()); + assertThat(result1.getBody()).isEqualTo("SetCookie 1"); + assertThat(result2.getBody()).isEqualTo("GetCookie 1"); } - @Configuration @EnableAutoConfiguration @RestController @@ -204,7 +201,8 @@ public class CustomHostRoutingFilterTests { } @RequestMapping(value = "/patch/{id}", method = RequestMethod.PATCH) - public String patch(@PathVariable String id, @RequestParam("patch") String patch) { + public String patch(@PathVariable String id, + @RequestParam("patch") String patch) { return "Patch " + id + patch; } @@ -217,28 +215,30 @@ public class CustomHostRoutingFilterTests { protected static class CustomZuulProxyConfig { @Bean - public ApacheHttpClientFactory customHttpClientFactory(HttpClientBuilder builder) { + public ApacheHttpClientFactory customHttpClientFactory( + HttpClientBuilder builder) { return new CustomApacheHttpClientFactory(builder); } @Bean public CloseableHttpClient closeableClient() { - return HttpClients.custom() - .setDefaultCookieStore(new BasicCookieStore()) + return HttpClients.custom().setDefaultCookieStore(new BasicCookieStore()) .setDefaultRequestConfig(RequestConfig.custom() .setCookieSpec(CookieSpecs.DEFAULT).build()) .build(); } @Bean - public SimpleHostRoutingFilter simpleHostRoutingFilter(ProxyRequestHelper helper, - ZuulProperties zuulProperties, CloseableHttpClient httpClient) { + public SimpleHostRoutingFilter simpleHostRoutingFilter( + ProxyRequestHelper helper, ZuulProperties zuulProperties, + CloseableHttpClient httpClient) { return new CustomHostRoutingFilter(helper, zuulProperties, httpClient); } private class CustomHostRoutingFilter extends SimpleHostRoutingFilter { - public CustomHostRoutingFilter(ProxyRequestHelper helper, - ZuulProperties zuulProperties, CloseableHttpClient httpClient) { + + CustomHostRoutingFilter(ProxyRequestHelper helper, + ZuulProperties zuulProperties, CloseableHttpClient httpClient) { super(helper, zuulProperties, httpClient); } @@ -247,15 +247,20 @@ public class CustomHostRoutingFilterTests { super.addIgnoredHeaders("X-Ignored"); return super.run(); } + } + private class CustomApacheHttpClientFactory + extends DefaultApacheHttpClientFactory { - private class CustomApacheHttpClientFactory extends DefaultApacheHttpClientFactory { - public CustomApacheHttpClientFactory(HttpClientBuilder builder) { + CustomApacheHttpClientFactory(HttpClientBuilder builder) { super(builder); } + } + } } -} \ No newline at end of file + +} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/ProxyRequestHelperTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/ProxyRequestHelperTests.java index bb922f224..a84b3a87b 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/ProxyRequestHelperTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/ProxyRequestHelperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,16 +37,7 @@ import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.MockitoAnnotations.initMocks; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.REQUEST_URI_KEY; @@ -83,16 +74,18 @@ public class ProxyRequestHelperTests { request.addHeader("multiName", "multiValue2"); RequestContext.getCurrentContext().setRequest(request); - TraceProxyRequestHelper helper = new TraceProxyRequestHelper(new ZuulProperties()); + TraceProxyRequestHelper helper = new TraceProxyRequestHelper( + new ZuulProperties()); this.traceRepository = new InMemoryHttpTraceRepository(); helper.setTraces(this.traceRepository); MultiValueMap headers = helper.buildZuulRequestHeaders(request); - helper.debug("POST", "http://example.com", headers, - new LinkedMultiValueMap<>(), request.getInputStream()); + helper.debug("POST", "http://example.com", headers, new LinkedMultiValueMap<>(), + request.getInputStream()); HttpTrace actual = this.traceRepository.findAll().get(0); - Assertions.assertThat(actual.getRequest().getHeaders()).containsKeys("singleName", "multiName"); + Assertions.assertThat(actual.getRequest().getHeaders()).containsKeys("singleName", + "multiName"); } @Test @@ -103,7 +96,7 @@ public class ProxyRequestHelperTests { zuulProperties.setTraceRequestBody(false); ProxyRequestHelper helper = new ProxyRequestHelper(zuulProperties); - assertThat("shouldDebugBody wrong", helper.shouldDebugBody(context), is(false)); + assertThat(helper.shouldDebugBody(context)).as("shouldDebugBody wrong").isFalse(); } @Test @@ -115,7 +108,7 @@ public class ProxyRequestHelperTests { ProxyRequestHelper helper = new ProxyRequestHelper(new ZuulProperties()); - assertThat("shouldDebugBody wrong", helper.shouldDebugBody(context), is(false)); + assertThat(helper.shouldDebugBody(context)).as("shouldDebugBody wrong").isFalse(); } @Test @@ -127,7 +120,7 @@ public class ProxyRequestHelperTests { ProxyRequestHelper helper = new ProxyRequestHelper(new ZuulProperties()); - assertThat("shouldDebugBody wrong", helper.shouldDebugBody(context), is(false)); + assertThat(helper.shouldDebugBody(context)).as("shouldDebugBody wrong").isFalse(); } @Test @@ -139,7 +132,7 @@ public class ProxyRequestHelperTests { ProxyRequestHelper helper = new ProxyRequestHelper(new ZuulProperties()); - assertThat("shouldDebugBody wrong", helper.shouldDebugBody(context), is(true)); + assertThat(helper.shouldDebugBody(context)).as("shouldDebugBody wrong").isTrue(); } @Test @@ -148,7 +141,7 @@ public class ProxyRequestHelperTests { ProxyRequestHelper helper = new ProxyRequestHelper(new ZuulProperties()); - assertThat("shouldDebugBody wrong", helper.shouldDebugBody(context), is(true)); + assertThat(helper.shouldDebugBody(context)).as("shouldDebugBody wrong").isTrue(); } @Test @@ -160,7 +153,7 @@ public class ProxyRequestHelperTests { ProxyRequestHelper helper = new ProxyRequestHelper(new ZuulProperties()); - assertThat("shouldDebugBody wrong", helper.shouldDebugBody(context), is(true)); + assertThat(helper.shouldDebugBody(context)).as("shouldDebugBody wrong").isTrue(); } @Test @@ -172,7 +165,7 @@ public class ProxyRequestHelperTests { ProxyRequestHelper helper = new ProxyRequestHelper(new ZuulProperties()); - assertThat("shouldDebugBody wrong", helper.shouldDebugBody(context), is(false)); + assertThat(helper.shouldDebugBody(context)).as("shouldDebugBody wrong").isFalse(); } @Test @@ -182,20 +175,21 @@ public class ProxyRequestHelperTests { request.addHeader("multiName", "multiValue1"); request.addHeader("multiName", "multiValue2"); - TraceProxyRequestHelper helper = new TraceProxyRequestHelper(new ZuulProperties()); + TraceProxyRequestHelper helper = new TraceProxyRequestHelper( + new ZuulProperties()); helper.setTraces(this.traceRepository); MultiValueMap headers = helper.buildZuulRequestHeaders(request); List singleName = headers.get("singleName"); - assertThat(singleName, is(notNullValue())); - assertThat(singleName.size(), is(1)); + assertThat(singleName).isNotNull(); + assertThat(singleName.size()).isEqualTo(1); List multiName = headers.get("multiName"); - assertThat(multiName, is(notNullValue())); - assertThat(multiName.size(), is(2)); + assertThat(multiName).isNotNull(); + assertThat(multiName.size()).isEqualTo(2); List missingName = headers.get("missingName"); - assertThat(missingName, is(nullValue())); + assertThat(missingName).isNull(); } @@ -208,8 +202,8 @@ public class ProxyRequestHelperTests { MultiValueMap headers = helper.buildZuulRequestHeaders(request); List acceptEncodings = headers.get("accept-encoding"); - assertThat(acceptEncodings, hasSize(1)); - assertThat(acceptEncodings, contains("gzip")); + assertThat(acceptEncodings).hasSize(1); + assertThat(acceptEncodings).containsExactly("gzip"); } @Test @@ -222,8 +216,8 @@ public class ProxyRequestHelperTests { MultiValueMap headers = helper.buildZuulRequestHeaders(request); List contentEncodings = headers.get("content-encoding"); - assertThat(contentEncodings, hasSize(1)); - assertThat(contentEncodings, contains("identity")); + assertThat(contentEncodings).hasSize(1); + assertThat(contentEncodings).containsExactly("identity"); } @Test @@ -236,8 +230,8 @@ public class ProxyRequestHelperTests { MultiValueMap headers = helper.buildZuulRequestHeaders(request); List acceptEncodings = headers.get("accept-encoding"); - assertThat(acceptEncodings, hasSize(1)); - assertThat(acceptEncodings, contains("identity")); + assertThat(acceptEncodings).hasSize(1); + assertThat(acceptEncodings).containsExactly("identity"); } @Test @@ -252,15 +246,15 @@ public class ProxyRequestHelperTests { MultiValueMap headers = helper.buildZuulRequestHeaders(request); List acceptEncodings = headers.get("host"); - assertThat(acceptEncodings, hasSize(1)); - assertThat(acceptEncodings, contains("foo.com")); + assertThat(acceptEncodings).hasSize(1); + assertThat(acceptEncodings).containsExactly("foo.com"); zuulProperties.setAddHostHeader(false); helper = new ProxyRequestHelper(zuulProperties); headers = helper.buildZuulRequestHeaders(request); acceptEncodings = headers.get("host"); - assertNull(acceptEncodings); + assertThat(acceptEncodings).isNull(); } @Test @@ -278,7 +272,7 @@ public class ProxyRequestHelperTests { headers.add(HttpHeaders.CONTENT_ENCODING.toLowerCase(), "gzip"); helper.setResponse(200, request.getInputStream(), headers); - assertTrue(context.getResponseGZipped()); + assertThat(context.getResponseGZipped()).isTrue(); } @Test @@ -297,10 +291,9 @@ public class ProxyRequestHelperTests { headers.add("some-header", "some-value"); helper.setResponse(200, request.getInputStream(), headers); - assertThat(context.getOriginResponseHeaders(), containsInAnyOrder( + assertThat(context.getOriginResponseHeaders()).contains( new Pair<>(HttpHeaders.CONTENT_TYPE, "text/plain"), - new Pair<>("some-header", "some-value") - )); + new Pair<>("some-header", "some-value")); } @Test @@ -318,7 +311,7 @@ public class ProxyRequestHelperTests { headers.add(HttpHeaders.CONTENT_ENCODING, "gzip"); helper.setResponse(200, request.getInputStream(), headers); - assertTrue(context.getResponseGZipped()); + assertThat(context.getResponseGZipped()).isTrue(); } @Test @@ -327,9 +320,10 @@ public class ProxyRequestHelperTests { params.add("a", "1234"); params.add("b", "5678"); - String queryString = new ProxyRequestHelper(new ZuulProperties()).getQueryString(params); + String queryString = new ProxyRequestHelper(new ZuulProperties()) + .getQueryString(params); - assertThat(queryString, is("?a=1234&b=5678")); + assertThat(queryString).isEqualTo("?a=1234&b=5678"); } @Test @@ -337,9 +331,10 @@ public class ProxyRequestHelperTests { MultiValueMap params = new LinkedMultiValueMap<>(); params.add("wsdl", ""); - String queryString = new ProxyRequestHelper(new ZuulProperties()).getQueryString(params); + String queryString = new ProxyRequestHelper(new ZuulProperties()) + .getQueryString(params); - assertThat(queryString, is("?wsdl")); + assertThat(queryString).isEqualTo("?wsdl"); } @Test @@ -347,9 +342,10 @@ public class ProxyRequestHelperTests { MultiValueMap params = new LinkedMultiValueMap<>(); params.add("foo", "weird#chars"); - String queryString = new ProxyRequestHelper(new ZuulProperties()).getQueryString(params); + String queryString = new ProxyRequestHelper(new ZuulProperties()) + .getQueryString(params); - assertThat(queryString, is("?foo=weird%23chars")); + assertThat(queryString).isEqualTo("?foo=weird%23chars"); } @Test @@ -359,9 +355,10 @@ public class ProxyRequestHelperTests { params.add("foobar", "bam"); params.add("foo\fbar", "bat"); // form feed is the colon replacement char - String queryString = new ProxyRequestHelper(new ZuulProperties()).getQueryString(params); + String queryString = new ProxyRequestHelper(new ZuulProperties()) + .getQueryString(params); - assertThat(queryString, is("?foo:bar=baz&foobar=bam&foo%0Cbar=bat")); + assertThat(queryString).isEqualTo("?foo:bar=baz&foobar=bam&foo%0Cbar=bat"); } @Test @@ -375,8 +372,9 @@ public class ProxyRequestHelperTests { context.setRequest(request); context.set(REQUEST_URI_KEY, decodedURI); - final String requestURI = new ProxyRequestHelper(new ZuulProperties()).buildZuulRequestURI(request); - assertThat(requestURI, equalTo(encodedURI)); + final String requestURI = new ProxyRequestHelper(new ZuulProperties()) + .buildZuulRequestURI(request); + assertThat(requestURI).isEqualTo(encodedURI); } @Test @@ -389,8 +387,9 @@ public class ProxyRequestHelperTests { context.setRequest(request); context.set(REQUEST_URI_KEY, decodedURI); - final String requestURI = new ProxyRequestHelper(new ZuulProperties()).buildZuulRequestURI(request); - assertThat(requestURI, equalTo(encodedURI)); + final String requestURI = new ProxyRequestHelper(new ZuulProperties()) + .buildZuulRequestURI(request); + assertThat(requestURI).isEqualTo(encodedURI); } @Test @@ -407,7 +406,7 @@ public class ProxyRequestHelperTests { String uri = helper.buildZuulRequestURI(request); - assertThat(uri, is(encodedRequestURI)); + assertThat(uri).isEqualTo(encodedRequestURI); } @Test @@ -423,6 +422,7 @@ public class ProxyRequestHelperTests { String uri = helper.buildZuulRequestURI(request); - assertThat(uri, is(encodedRequestURI)); + assertThat(uri).isEqualTo(encodedRequestURI); } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/SimpleRouteLocatorTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/SimpleRouteLocatorTests.java index 6abeaee7c..c85eea342 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/SimpleRouteLocatorTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/SimpleRouteLocatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,13 +27,8 @@ import org.junit.Test; import org.springframework.boot.test.rule.OutputCapture; import org.springframework.cloud.netflix.zuul.filters.ZuulProperties.ZuulRoute; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.hasItem; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.collection.IsCollectionWithSize.hasSize; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.containsString; /** * @author Tom Cawley @@ -59,7 +54,7 @@ public class SimpleRouteLocatorTests { this.properties.getRoutes().clear(); this.properties.getRoutes().put("foo", new ZuulRoute("/foo/**", "foo")); - assertThat(locator.getRoutes(), hasItem(createRoute("foo", "/**", "/foo"))); + assertThat(locator.getRoutes()).contains(createRoute("foo", "/**", "/foo")); } @Test @@ -70,8 +65,8 @@ public class SimpleRouteLocatorTests { this.properties.getRoutes().put("bar", new ZuulRoute("/bar/**", "bar")); final List routes = locator.getRoutes(); - assertThat(routes, hasItem(createRoute("bar", "/**", "/bar"))); - assertThat(routes, hasSize(1)); + assertThat(routes).contains(createRoute("bar", "/**", "/bar")); + assertThat(routes).hasSize(1); } @Test @@ -79,16 +74,20 @@ public class SimpleRouteLocatorTests { properties.setPrefix("/test"); properties.setStripPrefix(true); RouteLocator locator = new FilteringRouteLocator("/", properties); - properties.getRoutes().put("testservicea", new ZuulRoute("/testservicea/**", "testservicea")); - assertEquals("/test/testservicea/**", locator.getRoutes().get(0).getFullPath()); + properties.getRoutes().put("testservicea", + new ZuulRoute("/testservicea/**", "testservicea")); + assertThat(locator.getRoutes().get(0).getFullPath()) + .isEqualTo("/test/testservicea/**"); } @Test public void testPrefix() { properties.setPrefix("/test/"); RouteLocator locator = new FilteringRouteLocator("/", properties); - properties.getRoutes().put("testservicea", new ZuulRoute("/testservicea/**", "testservicea")); - assertEquals("/test/testservicea/**", locator.getRoutes().get(0).getFullPath()); + properties.getRoutes().put("testservicea", + new ZuulRoute("/testservicea/**", "testservicea")); + assertThat(locator.getRoutes().get(0).getFullPath()) + .isEqualTo("/test/testservicea/**"); } @Test @@ -98,8 +97,9 @@ public class SimpleRouteLocatorTests { this.properties.getRoutes().put("foo", new ZuulRoute("/foo/**", "foo")); this.properties.getRoutes().put("bar", new ZuulRoute("/bar/**", "bar")); - assertThat(locator.getMatchingRoute("/foo/1"), nullValue()); - assertThat(locator.getMatchingRoute("/bar/1"), is(createRoute("bar", "/1", "/bar"))); + assertThat(locator.getMatchingRoute("/foo/1")).isNull(); + assertThat(locator.getMatchingRoute("/bar/1")) + .isEqualTo(createRoute("bar", "/1", "/bar")); } @Test @@ -118,14 +118,14 @@ public class SimpleRouteLocatorTests { } private static class FilteringRouteLocator extends SimpleRouteLocator { - public FilteringRouteLocator(String servletPath, ZuulProperties properties) { + + FilteringRouteLocator(String servletPath, ZuulProperties properties) { super(servletPath, properties); } @Override public List getRoutes() { - return super.getRoutes().stream() - .filter(this::acceptRoute) + return super.getRoutes().stream().filter(this::acceptRoute) .collect(Collectors.toList()); } @@ -149,5 +149,7 @@ public class SimpleRouteLocatorTests { public Map getRoutesMap() { return super.getRoutesMap(); } + } -} \ No newline at end of file + +} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/ZuulPropertiesTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/ZuulPropertiesTests.java index 1f0c271c0..e13eb9398 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/ZuulPropertiesTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/ZuulPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,12 +22,10 @@ import java.util.Collections; import org.junit.After; import org.junit.Before; import org.junit.Test; + import org.springframework.cloud.netflix.zuul.filters.ZuulProperties.ZuulRoute; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * @author Dave Syer @@ -58,23 +56,25 @@ public class ZuulPropertiesTests { public void securityHeadersNotIgnored() { zuul.setIgnoreSecurityHeaders(false); - assertTrue(this.zuul.getIgnoredHeaders().isEmpty()); + assertThat(this.zuul.getIgnoredHeaders().isEmpty()).isTrue(); } @Test public void addIgnoredHeaders() { this.zuul.setIgnoredHeaders(Collections.singleton("x-foo")); - assertTrue(this.zuul.getIgnoredHeaders().contains("x-foo")); + assertThat(this.zuul.getIgnoredHeaders().contains("x-foo")).isTrue(); } @Test public void defaultSensitiveHeaders() { ZuulRoute route = new ZuulRoute("foo"); this.zuul.getRoutes().put("foo", route); - assertTrue(this.zuul.getRoutes().get("foo").getSensitiveHeaders().isEmpty()); - assertTrue(this.zuul.getSensitiveHeaders() - .containsAll(Arrays.asList("Cookie", "Set-Cookie", "Authorization"))); - assertFalse(route.isCustomSensitiveHeaders()); + assertThat(this.zuul.getRoutes().get("foo").getSensitiveHeaders().isEmpty()) + .isTrue(); + assertThat(this.zuul.getSensitiveHeaders() + .containsAll(Arrays.asList("Cookie", "Set-Cookie", "Authorization"))) + .isTrue(); + assertThat(route.isCustomSensitiveHeaders()).isFalse(); } @Test @@ -84,30 +84,31 @@ public class ZuulPropertiesTests { route.setSensitiveHeaders(Collections.singleton("x-foo")); this.zuul.getRoutes().put("foo", route); ZuulRoute foo = this.zuul.getRoutes().get("foo"); - assertTrue(foo.getSensitiveHeaders().contains("x-foo")); - assertFalse(foo.getSensitiveHeaders().contains("Cookie")); - assertTrue(foo.isCustomSensitiveHeaders()); - assertTrue(this.zuul.getSensitiveHeaders().contains("x-bar")); - assertFalse(this.zuul.getSensitiveHeaders().contains("Cookie")); + assertThat(foo.getSensitiveHeaders().contains("x-foo")).isTrue(); + assertThat(foo.getSensitiveHeaders().contains("Cookie")).isFalse(); + assertThat(foo.isCustomSensitiveHeaders()).isTrue(); + assertThat(this.zuul.getSensitiveHeaders().contains("x-bar")).isTrue(); + assertThat(this.zuul.getSensitiveHeaders().contains("Cookie")).isFalse(); } @Test public void createWithSensitiveHeaders() { this.zuul.setSensitiveHeaders(Collections.singleton("x-bar")); - ZuulRoute route = new ZuulRoute("foo", "/path", "foo", "/path", - false, false, Collections.singleton("x-foo")); + ZuulRoute route = new ZuulRoute("foo", "/path", "foo", "/path", false, false, + Collections.singleton("x-foo")); this.zuul.getRoutes().put("foo", route); ZuulRoute foo = this.zuul.getRoutes().get("foo"); - assertTrue(foo.getSensitiveHeaders().contains("x-foo")); - assertFalse(foo.getSensitiveHeaders().contains("Cookie")); - assertTrue(foo.isCustomSensitiveHeaders()); - assertTrue(this.zuul.getSensitiveHeaders().contains("x-bar")); - assertFalse(this.zuul.getSensitiveHeaders().contains("Cookie")); + assertThat(foo.getSensitiveHeaders().contains("x-foo")).isTrue(); + assertThat(foo.getSensitiveHeaders().contains("Cookie")).isFalse(); + assertThat(foo.isCustomSensitiveHeaders()).isTrue(); + assertThat(this.zuul.getSensitiveHeaders().contains("x-bar")).isTrue(); + assertThat(this.zuul.getSensitiveHeaders().contains("Cookie")).isFalse(); } @Test public void defaultHystrixThreadPool() { - assertFalse(this.zuul.getThreadPool().isUseSeparateThreadPools()); - assertEquals("", this.zuul.getThreadPool().getThreadPoolKeyPrefix()); + assertThat(this.zuul.getThreadPool().isUseSeparateThreadPools()).isFalse(); + assertThat(this.zuul.getThreadPool().getThreadPoolKeyPrefix()).isEqualTo(""); } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/discovery/DiscoveryClientRouteLocatorTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/discovery/DiscoveryClientRouteLocatorTests.java index 0b07485b4..dbf850ba7 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/discovery/DiscoveryClientRouteLocatorTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/discovery/DiscoveryClientRouteLocatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,10 +22,12 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import com.netflix.zuul.context.RequestContext; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; + import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.client.serviceregistry.Registration; import org.springframework.cloud.netflix.zuul.filters.Route; @@ -34,13 +36,7 @@ import org.springframework.cloud.netflix.zuul.filters.ZuulProperties.ZuulRoute; import org.springframework.cloud.netflix.zuul.util.RequestUtils; import org.springframework.core.env.ConfigurableEnvironment; -import com.netflix.zuul.context.RequestContext; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.MockitoAnnotations.initMocks; @@ -66,47 +62,6 @@ public class DiscoveryClientRouteLocatorTests { private ZuulProperties properties = new ZuulProperties(); - public static class RegexMapper { - private boolean enabled = false; - - private String servicePattern = "(?.*)-(?v.*$)"; - - private String routePattern = "${version}/${name}"; - - public RegexMapper() { - } - - public RegexMapper(boolean enabled, String servicePattern, String routePattern) { - this.enabled = enabled; - this.servicePattern = servicePattern; - this.routePattern = routePattern; - } - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public String getServicePattern() { - return servicePattern; - } - - public void setServicePattern(String servicePattern) { - this.servicePattern = servicePattern; - } - - public String getRoutePattern() { - return routePattern; - } - - public void setRoutePattern(String routePattern) { - this.routePattern = routePattern; - } - } - private RegexMapper regexMapper = new RegexMapper(); @Before @@ -128,8 +83,8 @@ public class DiscoveryClientRouteLocatorTests { this.properties.init(); routeLocator.getRoutes(); // force refresh Route route = routeLocator.getMatchingRoute("/foo/1"); - assertEquals("foo", route.getLocation()); - assertEquals("foo", route.getId()); + assertThat(route.getLocation()).isEqualTo("foo"); + assertThat(route.getId()).isEqualTo("foo"); } @Test @@ -141,8 +96,8 @@ public class DiscoveryClientRouteLocatorTests { this.properties.init(); routeLocator.getRoutes(); // force refresh Route route = routeLocator.getMatchingRoute("/proxy/foo/1"); - assertEquals("foo", route.getLocation()); - assertEquals("/1", route.getPath()); + assertThat(route.getLocation()).isEqualTo("foo"); + assertThat(route.getPath()).isEqualTo("/1"); } @Test @@ -156,8 +111,8 @@ public class DiscoveryClientRouteLocatorTests { this.properties.init(); routeLocator.getRoutes(); // force refresh Route route = routeLocator.getMatchingRoute("/app/foo/1"); - assertEquals("foo", route.getLocation()); - assertEquals("/1", route.getPath()); + assertThat(route.getLocation()).isEqualTo("foo"); + assertThat(route.getPath()).isEqualTo("/1"); } @Test @@ -169,8 +124,8 @@ public class DiscoveryClientRouteLocatorTests { this.properties.init(); routeLocator.getRoutes(); // force refresh Route route = routeLocator.getMatchingRoute("/zuul/foo/1"); - assertEquals("foo", route.getLocation()); - assertEquals("/1", route.getPath()); + assertThat(route.getLocation()).isEqualTo("foo"); + assertThat(route.getPath()).isEqualTo("/1"); } @@ -184,8 +139,8 @@ public class DiscoveryClientRouteLocatorTests { this.properties.setPrefix("/proxy"); routeLocator.getRoutes(); // force refresh Route route = routeLocator.getMatchingRoute("/proxy/foo/1"); - assertEquals("foo", route.getLocation()); - assertEquals("/proxy/foo/1", route.getPath()); + assertThat(route.getLocation()).isEqualTo("foo"); + assertThat(route.getPath()).isEqualTo("/proxy/foo/1"); } @Test @@ -197,8 +152,8 @@ public class DiscoveryClientRouteLocatorTests { this.properties.setPrefix("/proxy"); routeLocator.getRoutes(); // force refresh Route route = routeLocator.getMatchingRoute("/proxy/foo/1"); - assertEquals("foo", route.getLocation()); - assertEquals("/proxy/1", route.getPath()); + assertThat(route.getLocation()).isEqualTo("foo"); + assertThat(route.getPath()).isEqualTo("/proxy/1"); } @Test @@ -210,8 +165,8 @@ public class DiscoveryClientRouteLocatorTests { this.properties.setPrefix("/proxy"); routeLocator.getRoutes(); // force refresh Route route = routeLocator.getMatchingRoute("/proxy/foo/1"); - assertEquals("foo", route.getLocation()); - assertEquals("/foo/1", route.getPath()); + assertThat(route.getLocation()).isEqualTo("foo"); + assertThat(route.getPath()).isEqualTo("/foo/1"); } @Test @@ -226,8 +181,8 @@ public class DiscoveryClientRouteLocatorTests { this.properties.setPrefix("/proxy"); routeLocator.getRoutes(); // force refresh Route route = routeLocator.getMatchingRoute("/app/proxy/foo/1"); - assertEquals("foo", route.getLocation()); - assertEquals("/foo/1", route.getPath()); + assertThat(route.getLocation()).isEqualTo("foo"); + assertThat(route.getPath()).isEqualTo("/foo/1"); } @Test @@ -241,8 +196,8 @@ public class DiscoveryClientRouteLocatorTests { this.properties.setPrefix("/proxy"); routeLocator.getRoutes(); // force refresh Route route = routeLocator.getMatchingRoute("/zuul/proxy/foo/1"); - assertEquals("foo", route.getLocation()); - assertEquals("/foo/1", route.getPath()); + assertThat(route.getLocation()).isEqualTo("foo"); + assertThat(route.getPath()).isEqualTo("/foo/1"); } @Test @@ -255,8 +210,8 @@ public class DiscoveryClientRouteLocatorTests { this.properties.init(); routeLocator.getRoutes(); // force refresh Route route = routeLocator.getMatchingRoute("/foo/1"); - assertEquals("foo", route.getLocation()); - assertEquals("/1", route.getPath()); + assertThat(route.getLocation()).isEqualTo("foo"); + assertThat(route.getPath()).isEqualTo("/1"); } @Test @@ -268,8 +223,8 @@ public class DiscoveryClientRouteLocatorTests { this.properties.init(); routeLocator.getRoutes(); // force refresh Route route = routeLocator.getMatchingRoute("/bar/1"); - assertEquals("bar", route.getLocation()); - assertEquals("bar", route.getId()); + assertThat(route.getLocation()).isEqualTo("bar"); + assertThat(route.getId()).isEqualTo("bar"); } @Test @@ -281,7 +236,7 @@ public class DiscoveryClientRouteLocatorTests { this.properties.init(); routeLocator.getRoutes(); // force refresh Route route = routeLocator.getMatchingRoute("/foo/1"); - assertNull("routes did not ignore " + IGNOREDPATTERN, route); + assertThat(route).as("routes did not ignore " + IGNOREDPATTERN).isNull(); } @Test @@ -295,8 +250,8 @@ public class DiscoveryClientRouteLocatorTests { this.properties.init(); routeLocator.getRoutes(); // force refresh Route route = routeLocator.getMatchingRoute("/proxy/foo/1"); - assertEquals("foo", route.getLocation()); - assertEquals("/1", route.getPath()); + assertThat(route.getLocation()).isEqualTo("foo"); + assertThat(route.getPath()).isEqualTo("/1"); } @Test @@ -309,7 +264,7 @@ public class DiscoveryClientRouteLocatorTests { this.properties.init(); routeLocator.getRoutes(); // force refresh Route route = routeLocator.getMatchingRoute("/app/foo/1"); - assertNull("routes did not ignore " + IGNOREDPATTERN, route); + assertThat(route).as("routes did not ignore " + IGNOREDPATTERN).isNull(); } @Test @@ -324,8 +279,8 @@ public class DiscoveryClientRouteLocatorTests { this.properties.setPrefix("/proxy"); routeLocator.getRoutes(); // force refresh Route route = routeLocator.getMatchingRoute("/proxy/foo/1"); - assertEquals("foo", route.getLocation()); - assertEquals("/proxy/foo/1", route.getPath()); + assertThat(route.getLocation()).isEqualTo("foo"); + assertThat(route.getPath()).isEqualTo("/proxy/foo/1"); } @Test @@ -341,7 +296,8 @@ public class DiscoveryClientRouteLocatorTests { this.properties.setPrefix("/proxy"); routeLocator.getRoutes(); // force refresh Route route = routeLocator.getMatchingRoute("/proxy/foo/1"); - assertNull("routes did not ignore " + "/proxy" + IGNOREDPATTERN, route); + assertThat(route).as("routes did not ignore " + "/proxy" + IGNOREDPATTERN) + .isNull(); } @Test @@ -355,8 +311,8 @@ public class DiscoveryClientRouteLocatorTests { this.properties.setPrefix("/proxy"); routeLocator.getRoutes(); // force refresh Route route = routeLocator.getMatchingRoute("/proxy/foo/1"); - assertEquals("foo", route.getLocation()); - assertEquals("/proxy/1", route.getPath()); + assertThat(route.getLocation()).isEqualTo("foo"); + assertThat(route.getPath()).isEqualTo("/proxy/1"); } @Test @@ -371,7 +327,8 @@ public class DiscoveryClientRouteLocatorTests { this.properties.setPrefix("/proxy"); routeLocator.getRoutes(); // force refresh Route route = routeLocator.getMatchingRoute("/proxy/foo/1"); - assertNull("routes did not ignore " + "/proxy" + IGNOREDPATTERN, route); + assertThat(route).as("routes did not ignore " + "/proxy" + IGNOREDPATTERN) + .isNull(); } @Test @@ -385,8 +342,8 @@ public class DiscoveryClientRouteLocatorTests { this.properties.setPrefix("/proxy"); routeLocator.getRoutes(); // force refresh Route route = routeLocator.getMatchingRoute("/proxy/foo/1"); - assertEquals("foo", route.getLocation()); - assertEquals("/foo/1", route.getPath()); + assertThat(route.getLocation()).isEqualTo("foo"); + assertThat(route.getPath()).isEqualTo("/foo/1"); } @Test @@ -401,7 +358,8 @@ public class DiscoveryClientRouteLocatorTests { this.properties.setPrefix("/proxy"); routeLocator.getRoutes(); // force refresh Route route = routeLocator.getMatchingRoute("/proxy/foo/1"); - assertNull("routes did not ignore " + "/proxy" + IGNOREDPATTERN, route); + assertThat(route).as("routes did not ignore " + "/proxy" + IGNOREDPATTERN) + .isNull(); } @Test @@ -416,7 +374,7 @@ public class DiscoveryClientRouteLocatorTests { this.properties.init(); routeLocator.getRoutes(); // force refresh Route route = routeLocator.getMatchingRoute("/foo/1"); - assertNull("routes did not ignore " + IGNOREDPATTERN, route); + assertThat(route).as("routes did not ignore " + IGNOREDPATTERN).isNull(); } @Test @@ -426,8 +384,8 @@ public class DiscoveryClientRouteLocatorTests { this.properties.getRoutes().put(ASERVICE, new ZuulRoute("/" + ASERVICE + "/**")); this.properties.init(); List routesMap = routeLocator.getRoutes(); - assertNotNull("routesMap was null", routesMap); - assertFalse("routesMap was empty", routesMap.isEmpty()); + assertThat(routesMap).as("routesMap was null").isNotNull(); + assertThat(routesMap.isEmpty()).as("routesMap was empty").isFalse(); assertMapping(routesMap, ASERVICE); } @@ -450,8 +408,8 @@ public class DiscoveryClientRouteLocatorTests { this.properties.getRoutes().put(ASERVICE, new ZuulRoute("/" + ASERVICE + "/**", "http://" + ASERVICE)); List routesMap = routeLocator.getRoutes(); - assertNotNull("routesMap was null", routesMap); - assertFalse("routesMap was empty", routesMap.isEmpty()); + assertThat(routesMap).as("routesMap was null").isNotNull(); + assertThat(routesMap.isEmpty()).as("routesMap was empty").isFalse(); assertMapping(routesMap, "http://" + ASERVICE, ASERVICE); } @@ -461,8 +419,8 @@ public class DiscoveryClientRouteLocatorTests { this.discovery, this.properties); this.properties.getRoutes().put(ASERVICE, new ZuulRoute("/**", ASERVICE)); List routesMap = routeLocator.getRoutes(); - assertNotNull("routesMap was null", routesMap); - assertFalse("routesMap was empty", routesMap.isEmpty()); + assertThat(routesMap).as("routesMap was null").isNotNull(); + assertThat(routesMap.isEmpty()).as("routesMap was empty").isFalse(); assertDefaultMapping(routesMap, ASERVICE); } @@ -473,8 +431,8 @@ public class DiscoveryClientRouteLocatorTests { this.properties.getRoutes().put(ASERVICE, new ZuulRoute("/**", "http://" + ASERVICE)); List routesMap = routeLocator.getRoutes(); - assertNotNull("routesMap was null", routesMap); - assertFalse("routesMap was empty", routesMap.isEmpty()); + assertThat(routesMap).as("routesMap was null").isNotNull(); + assertThat(routesMap.isEmpty()).as("routesMap was empty").isFalse(); assertDefaultMapping(routesMap, "http://" + ASERVICE); } @@ -486,8 +444,8 @@ public class DiscoveryClientRouteLocatorTests { given(this.discovery.getServices()) .willReturn(Collections.singletonList(IGNOREDSERVICE)); List routesMap = routeLocator.getRoutes(); - assertNull("routes did not ignore " + IGNOREDSERVICE, - getRoute(routesMap, getMapping(IGNOREDSERVICE))); + assertThat(getRoute(routesMap, getMapping(IGNOREDSERVICE))) + .as("routes did not ignore " + IGNOREDSERVICE).isNull(); } @Test @@ -498,8 +456,8 @@ public class DiscoveryClientRouteLocatorTests { given(this.discovery.getServices()) .willReturn(Collections.singletonList(IGNOREDSERVICE)); List routesMap = routeLocator.getRoutes(); - assertNull("routes did not ignore " + IGNOREDSERVICE, - getRoute(routesMap, getMapping(IGNOREDSERVICE))); + assertThat(getRoute(routesMap, getMapping(IGNOREDSERVICE))) + .as("routes did not ignore " + IGNOREDSERVICE).isNull(); } @Test @@ -510,8 +468,8 @@ public class DiscoveryClientRouteLocatorTests { given(this.discovery.getServices()) .willReturn(Collections.singletonList(IGNOREDSERVICE)); List routesMap = routeLocator.getRoutes(); - assertNull("routes did not ignore " + IGNOREDSERVICE, - getRoute(routesMap, getMapping(IGNOREDSERVICE))); + assertThat(getRoute(routesMap, getMapping(IGNOREDSERVICE))) + .as("routes did not ignore " + IGNOREDSERVICE).isNull(); } @Test @@ -522,7 +480,7 @@ public class DiscoveryClientRouteLocatorTests { this.properties.setIgnoredServices(Collections.singleton("*")); given(this.discovery.getServices()).willReturn(Collections.singletonList("foo")); List routesMap = routeLocator.getRoutes(); - assertNotNull("routes ignored foo", getRoute(routesMap, "/foo/**")); + assertThat(getRoute(routesMap, "/foo/**")).as("routes ignored foo").isNotNull(); } @Test @@ -537,9 +495,10 @@ public class DiscoveryClientRouteLocatorTests { given(this.discovery.getServices()).willReturn(Collections.singletonList("foo")); LinkedHashMap routes = routeLocator.locateRoutes(); ZuulRoute actual = routes.get("/foo/**"); - assertNotNull("routes ignored foo", actual); - assertTrue("stripPrefix is wrong", actual.isStripPrefix()); - assertEquals("retryable is wrong", Boolean.TRUE, actual.getRetryable()); + assertThat(actual).as("routes ignored foo").isNotNull(); + assertThat(actual.isStripPrefix()).as("stripPrefix is wrong").isTrue(); + assertThat(actual.getRetryable()).as("retryable is wrong") + .isEqualTo(Boolean.TRUE); } @Test @@ -555,10 +514,10 @@ public class DiscoveryClientRouteLocatorTests { given(this.discovery.getServices()).willReturn(Collections.singletonList("foo")); LinkedHashMap routes = routeLocator.locateRoutes(); ZuulRoute actual = routes.get("/**"); - assertNotNull("routes ignored foo", actual); - assertEquals("id is wrong", "foo", actual.getId()); - assertEquals("location is wrong", "foo", actual.getServiceId()); - assertEquals("path is wrong", "/**", actual.getPath()); + assertThat(actual).as("routes ignored foo").isNotNull(); + assertThat(actual.getId()).as("id is wrong").isEqualTo("foo"); + assertThat(actual.getServiceId()).as("location is wrong").isEqualTo("foo"); + assertThat(actual.getPath()).as("path is wrong").isEqualTo("/**"); } @Test @@ -570,7 +529,8 @@ public class DiscoveryClientRouteLocatorTests { this.properties.setIgnoredServices(Collections.singleton("*")); given(this.discovery.getServices()).willReturn(Collections.singletonList("bar")); List routesMap = routeLocator.getRoutes(); - assertNotNull("routes ignored foo", getRoute(routesMap, getMapping("foo"))); + assertThat(getRoute(routesMap, getMapping("foo"))).as("routes ignored foo") + .isNotNull(); } @Test @@ -580,8 +540,8 @@ public class DiscoveryClientRouteLocatorTests { given(this.discovery.getServices()) .willReturn(Collections.singletonList(MYSERVICE)); List routesMap = routeLocator.getRoutes(); - assertNotNull("routesMap was null", routesMap); - assertFalse("routesMap was empty", routesMap.isEmpty()); + assertThat(routesMap).as("routesMap was null").isNotNull(); + assertThat(routesMap.isEmpty()).as("routesMap was empty").isFalse(); assertMapping(routesMap, MYSERVICE); } @@ -595,8 +555,8 @@ public class DiscoveryClientRouteLocatorTests { given(this.discovery.getServices()) .willReturn(Collections.singletonList(MYSERVICE)); List routesMap = routeLocator.getRoutes(); - assertNotNull("routesMap was null", routesMap); - assertFalse("routesMap was empty", routesMap.isEmpty()); + assertThat(routesMap).as("routesMap was null").isNotNull(); + assertThat(routesMap.isEmpty()).as("routesMap was empty").isFalse(); assertMapping(routesMap, "http://example.com/" + MYSERVICE, MYSERVICE); } @@ -641,11 +601,11 @@ public class DiscoveryClientRouteLocatorTests { LinkedHashMap routes = routeLocator.locateRoutes(); ZuulRoute actual = routes.get("/**"); - assertNull("routes didn't ignore " + MYSERVICE, actual); + assertThat(actual).as("routes didn't ignore " + MYSERVICE).isNull(); List routesMap = routeLocator.getRoutes(); - assertNotNull("routesMap was null", routesMap); - assertTrue("routesMap was empty", routesMap.isEmpty()); + assertThat(routesMap).as("routesMap was null").isNotNull(); + assertThat(routesMap.isEmpty()).as("routesMap was empty").isTrue(); } @Test @@ -659,8 +619,8 @@ public class DiscoveryClientRouteLocatorTests { this.discovery, this.properties); List routesMap = routeLocator.getRoutes(); - assertNotNull("routesMap was null", routesMap); - assertFalse("routesMap was empty", routesMap.isEmpty()); + assertThat(routesMap).as("routesMap was null").isNotNull(); + assertThat(routesMap.isEmpty()).as("routesMap was empty").isFalse(); assertMapping(routesMap, MYSERVICE); } @@ -669,7 +629,7 @@ public class DiscoveryClientRouteLocatorTests { given(this.discovery.getServices()).willReturn(Collections.emptyList()); DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", - this.discovery, this.properties, (Registration)null); + this.discovery, this.properties, (Registration) null); // if no exception is thrown in constructor, this is a success routeLocator.locateRoutes(); @@ -685,8 +645,8 @@ public class DiscoveryClientRouteLocatorTests { DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", this.discovery, this.properties, regExServiceRouteMapper); List routesMap = routeLocator.getRoutes(); - assertNotNull("routesMap was null", routesMap); - assertFalse("routesMap was empty", routesMap.isEmpty()); + assertThat(routesMap).as("routesMap was null").isNotNull(); + assertThat(routesMap.isEmpty()).as("routesMap was empty").isFalse(); assertMapping(routesMap, MYSERVICE); } @@ -700,8 +660,8 @@ public class DiscoveryClientRouteLocatorTests { DiscoveryClientRouteLocator routeLocator = new DiscoveryClientRouteLocator("/", this.discovery, this.properties, regExServiceRouteMapper); List routesMap = routeLocator.getRoutes(); - assertNotNull("routesMap was null", routesMap); - assertFalse("routesMap was empty", routesMap.isEmpty()); + assertThat(routesMap).as("routesMap was null").isNotNull(); + assertThat(routesMap.isEmpty()).as("routesMap was empty").isFalse(); assertMapping(routesMap, "rest-service-v1", "v1/rest-service"); } @@ -713,9 +673,10 @@ public class DiscoveryClientRouteLocatorTests { String key) { String mapping = getMapping(key); Route route = getRoute(routesMap, mapping); - assertNotNull("Could not find route for " + key, route); + assertThat(route).as("Could not find route for " + key).isNotNull(); String location = route.getLocation(); - assertEquals("routesMap had wrong value for " + mapping, expectedRoute, location); + assertThat(location).as("routesMap had wrong value for " + mapping) + .isEqualTo(expectedRoute); } private String getMapping(String serviceId) { @@ -725,7 +686,8 @@ public class DiscoveryClientRouteLocatorTests { protected void assertDefaultMapping(List routesMap, String expectedRoute) { String mapping = "/**"; String route = getRoute(routesMap, mapping).getLocation(); - assertEquals("routesMap had wrong value for " + mapping, expectedRoute, route); + assertThat(route).as("routesMap had wrong value for " + mapping) + .isEqualTo(expectedRoute); } private Route getRoute(List routes, String path) { @@ -742,4 +704,48 @@ public class DiscoveryClientRouteLocatorTests { RequestContext context = new RequestContext(); RequestContext.testSetCurrentContext(context); } + + public static class RegexMapper { + + private boolean enabled = false; + + private String servicePattern = "(?.*)-(?v.*$)"; + + private String routePattern = "${version}/${name}"; + + public RegexMapper() { + } + + public RegexMapper(boolean enabled, String servicePattern, String routePattern) { + this.enabled = enabled; + this.servicePattern = servicePattern; + this.routePattern = routePattern; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public String getServicePattern() { + return servicePattern; + } + + public void setServicePattern(String servicePattern) { + this.servicePattern = servicePattern; + } + + public String getRoutePattern() { + return routePattern; + } + + public void setRoutePattern(String routePattern) { + this.routePattern = routePattern; + } + + } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/discovery/PatternServiceRouteMapperIntegrationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/discovery/PatternServiceRouteMapperIntegrationTests.java index f40793ea6..a298550e3 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/discovery/PatternServiceRouteMapperIntegrationTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/discovery/PatternServiceRouteMapperIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.filters.discovery; @@ -20,10 +19,14 @@ package org.springframework.cloud.netflix.zuul.filters.discovery; import java.util.ArrayList; import java.util.List; +import com.netflix.loadbalancer.Server; +import com.netflix.loadbalancer.ServerList; +import com.netflix.zuul.context.RequestContext; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -49,11 +52,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerList; -import com.netflix.zuul.context.RequestContext; - -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; @@ -62,8 +61,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Stéphane Leroy */ @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(webEnvironment = RANDOM_PORT, - properties = { "spring.application.name=regex-test-application", "spring.jmx.enabled=false", +@SpringBootTest(webEnvironment = RANDOM_PORT, properties = { + "spring.application.name=regex-test-application", "spring.jmx.enabled=false", "eureka.client.enabled=false" }) @DirtiesContext public class PatternServiceRouteMapperIntegrationTests { @@ -96,8 +95,8 @@ public class PatternServiceRouteMapperIntegrationTests { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/v1/domain/service/get/1", HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Get 1", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Get 1"); } @Test @@ -107,40 +106,40 @@ public class PatternServiceRouteMapperIntegrationTests { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/self/get/1", HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Get 1", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Get 1"); } @SpringBootConfiguration - @EnableAutoConfiguration - @RestController - @EnableZuulProxy - @RibbonClient(value = SERVICE_ID, configuration = SimpleRibbonClientConfiguration.class) + @EnableAutoConfiguration + @RestController + @EnableZuulProxy + @RibbonClient(value = SERVICE_ID, configuration = SimpleRibbonClientConfiguration.class) @Import(NoSecurityConfiguration.class) - protected static class SampleCustomZuulProxyApplication { + protected static class SampleCustomZuulProxyApplication { - @Bean - public DiscoveryClient discoveryClient() { - DiscoveryClient discoveryClient = mock(DiscoveryClient.class); - List services = new ArrayList<>(); - services.add(SERVICE_ID); - when(discoveryClient.getServices()).thenReturn(services); - return discoveryClient; - } + @Bean + public DiscoveryClient discoveryClient() { + DiscoveryClient discoveryClient = mock(DiscoveryClient.class); + List services = new ArrayList<>(); + services.add(SERVICE_ID); + when(discoveryClient.getServices()).thenReturn(services); + return discoveryClient; + } - @RequestMapping(value = "/get/{id}", method = RequestMethod.GET) - public String get(@PathVariable String id) { - return "Get " + id; - } + @RequestMapping(value = "/get/{id}", method = RequestMethod.GET) + public String get(@PathVariable String id) { + return "Get " + id; + } - @Bean - public PatternServiceRouteMapper serviceRouteMapper() { - return new PatternServiceRouteMapper( - "(?^.+)-(?.+)-(?v.+$)", - "${version}/${domain}/${name}"); - } + @Bean + public PatternServiceRouteMapper serviceRouteMapper() { + return new PatternServiceRouteMapper( + "(?^.+)-(?.+)-(?v.+$)", + "${version}/${domain}/${name}"); + } - } + } protected static class SimpleRibbonClientConfiguration { @@ -151,5 +150,7 @@ public class PatternServiceRouteMapperIntegrationTests { public ServerList ribbonServerList() { return new StaticServerList<>(new Server("localhost", this.port)); } + } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/discovery/PatternServiceRouteMapperTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/discovery/PatternServiceRouteMapperTests.java index afca60b93..74ec4c85a 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/discovery/PatternServiceRouteMapperTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/discovery/PatternServiceRouteMapperTests.java @@ -1,12 +1,27 @@ +/* + * Copyright 2015-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.springframework.cloud.netflix.zuul.filters.discovery; import com.netflix.zuul.context.RequestContext; - import org.junit.After; import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Stéphane Leroy @@ -18,6 +33,7 @@ public class PatternServiceRouteMapperTests { * optional */ public static final String SERVICE_PATTERN = "(?^\\w+)(-(?\\w+)-|-)(?v\\d+$)"; + public static final String ROUTE_PATTERN = "${version}/${domain}/${name}"; @Before @@ -36,8 +52,8 @@ public class PatternServiceRouteMapperTests { PatternServiceRouteMapper toTest = new PatternServiceRouteMapper(SERVICE_PATTERN, ROUTE_PATTERN); - assertEquals("service version convention", "v1/rest/service", - toTest.apply("rest-service-v1")); + assertThat(toTest.apply("rest-service-v1")).as("service version convention") + .isEqualTo("v1/rest/service"); } @Test @@ -46,8 +62,8 @@ public class PatternServiceRouteMapperTests { ROUTE_PATTERN); // No version here - assertEquals("No matches for this service id", "rest-service", - toTest.apply("rest-service")); + assertThat(toTest.apply("rest-service")).as("No matches for this service id") + .isEqualTo("rest-service"); } @Test @@ -56,9 +72,10 @@ public class PatternServiceRouteMapperTests { PatternServiceRouteMapper toTest = new PatternServiceRouteMapper( SERVICE_PATTERN + "(?.)?", "/${version}/${nevermatch}/${domain}/${name}/"); - assertEquals("No matches for this service id", "v1/domain/service", - toTest.apply("domain-service-v1")); - assertEquals("No matches for this service id", "v1/domain", - toTest.apply("domain-v1")); + assertThat(toTest.apply("domain-service-v1")).as("No matches for this service id") + .isEqualTo("v1/domain/service"); + assertThat(toTest.apply("domain-v1")).as("No matches for this service id") + .isEqualTo("v1/domain"); } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/LocationRewriteFilterIntegrationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/LocationRewriteFilterIntegrationTests.java index 70938ac84..86a5300d8 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/LocationRewriteFilterIntegrationTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/LocationRewriteFilterIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,17 +12,19 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.filters.post; +import java.util.List; + import com.netflix.loadbalancer.Server; import com.netflix.loadbalancer.ServerList; import com.netflix.zuul.context.RequestContext; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -41,8 +43,6 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.bind.annotation.RequestMapping; -import java.util.List; - import static org.assertj.core.api.Assertions.assertThat; /** @@ -102,6 +102,7 @@ public class LocationRewriteFilterIntegrationTests { } public static class RibbonConfig { + @LocalServerPort private int port; @@ -111,4 +112,5 @@ public class LocationRewriteFilterIntegrationTests { } } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/LocationRewriteFilterTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/LocationRewriteFilterTests.java index adf9f314f..a58b0e9d0 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/LocationRewriteFilterTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/LocationRewriteFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,24 +12,24 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.filters.post; +import java.util.Collections; + import com.netflix.util.Pair; import com.netflix.zuul.context.RequestContext; import org.junit.After; import org.junit.Before; import org.junit.Test; + import org.springframework.cloud.netflix.zuul.filters.Route; import org.springframework.cloud.netflix.zuul.filters.RouteLocator; import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; -import java.util.Collections; - import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -41,14 +41,20 @@ import static org.mockito.Mockito.when; public class LocationRewriteFilterTests { private final String ZUUL_HOST = "myzuul.com"; + private final String ZUUL_SCHEME = "https"; + private final int ZUUL_PORT = 8443; + private final String ZUUL_BASE_URL = String.format("%s://%s:%d", ZUUL_SCHEME, ZUUL_HOST, ZUUL_PORT); private final String SERVER_HOST = "someserver.com"; + private final String SERVER_SCHEME = "http"; + private final int SERVER_PORT = 8564; + private final String SERVER_BASE_URL = String.format("%s://%s:%d", SERVER_SCHEME, SERVER_HOST, SERVER_PORT); @@ -58,7 +64,6 @@ public class LocationRewriteFilterTests { RequestContext.testSetCurrentContext(context); } - @After public void reset() { RequestContext.getCurrentContext().clear(); @@ -182,4 +187,5 @@ public class LocationRewriteFilterTests { } return null; } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/SendErrorFilterIntegrationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/SendErrorFilterIntegrationTests.java index e9f82b738..06edfc3d7 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/SendErrorFilterIntegrationTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/SendErrorFilterIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.filters.post; @@ -65,6 +64,7 @@ import static org.springframework.cloud.netflix.zuul.filters.support.FilterConst @SpringBootTest(properties = "zuul.routes.filtertest:/filtertest/**", webEnvironment = RANDOM_PORT) @DirtiesContext public class SendErrorFilterIntegrationTests { + @Autowired private MeterRegistry meterRegistry; @@ -93,7 +93,8 @@ public class SendErrorFilterIntegrationTests { } private void assertMetrics(String filterType) { - Double count = meterRegistry.counter("ZUUL::EXCEPTION:"+ filterType +"::500").count(); + Double count = meterRegistry.counter("ZUUL::EXCEPTION:" + filterType + "::500") + .count(); assertThat(count.longValue()).isEqualTo(1L); count = meterRegistry.counter("ZUUL::EXCEPTION:null:500").count(); assertThat(count.longValue()).isEqualTo(0L); @@ -116,7 +117,7 @@ public class SendErrorFilterIntegrationTests { String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); - //FIXME: 2.1.0 assertMetrics("post"); + // FIXME: 2.1.0 assertMetrics("post"); } @SpringBootConfiguration @@ -166,10 +167,12 @@ public class SendErrorFilterIntegrationTests { public MeterRegistry meterRegistry() { return new SimpleMeterRegistry(SimpleConfig.DEFAULT, new MockClock()); } + } @Configuration private static class RibbonConfig { + @LocalServerPort private int port; @@ -181,6 +184,7 @@ public class SendErrorFilterIntegrationTests { } private abstract static class FailureFilter extends ZuulFilter { + @Override public int filterOrder() { return Integer.MIN_VALUE; @@ -200,5 +204,7 @@ public class SendErrorFilterIntegrationTests { } return null; } + } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/SendErrorFilterTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/SendErrorFilterTests.java index bd3daa56d..9f6b98a56 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/SendErrorFilterTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/SendErrorFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,20 +18,18 @@ package org.springframework.cloud.netflix.zuul.filters.post; import javax.servlet.http.HttpServletRequest; +import com.netflix.zuul.context.RequestContext; import com.netflix.zuul.exception.ZuulException; import com.netflix.zuul.monitoring.MonitoringHelper; import org.junit.After; import org.junit.Before; import org.junit.Test; + import org.springframework.http.HttpStatus; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; -import com.netflix.zuul.context.RequestContext; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -54,7 +52,7 @@ public class SendErrorFilterTests { @Test public void runsNormally() { SendErrorFilter filter = createSendErrorFilter(new MockHttpServletRequest()); - assertTrue("shouldFilter returned false", filter.shouldFilter()); + assertThat(filter.shouldFilter()).as("shouldFilter returned false").isTrue(); filter.run(); } @@ -62,7 +60,8 @@ public class SendErrorFilterTests { RequestContext context = new RequestContext(); context.setRequest(request); context.setResponse(new MockHttpServletResponse()); - context.setThrowable(new ZuulException(new RuntimeException(), HttpStatus.NOT_FOUND.value(), null)); + context.setThrowable(new ZuulException(new RuntimeException(), + HttpStatus.NOT_FOUND.value(), null)); RequestContext.testSetCurrentContext(context); SendErrorFilter filter = new SendErrorFilter(); filter.setErrorPath("/error"); @@ -72,16 +71,16 @@ public class SendErrorFilterTests { @Test public void noRequestDispatcher() { SendErrorFilter filter = createSendErrorFilter(mock(HttpServletRequest.class)); - assertTrue("shouldFilter returned false", filter.shouldFilter()); + assertThat(filter.shouldFilter()).as("shouldFilter returned false").isTrue(); filter.run(); } @Test public void doesNotRunTwice() { SendErrorFilter filter = createSendErrorFilter(new MockHttpServletRequest()); - assertTrue("shouldFilter returned false", filter.shouldFilter()); + assertThat(filter.shouldFilter()).as("shouldFilter returned false").isTrue(); filter.run(); - assertFalse("shouldFilter returned true", filter.shouldFilter()); + assertThat(filter.shouldFilter()).as("shouldFilter returned true").isFalse(); } @Test @@ -93,7 +92,10 @@ public class SendErrorFilterTests { int resCode = ctx.getResponse().getStatus(); int ctxCode = ctx.getResponseStatusCode(); - assertEquals("invalid response code: " + resCode, HttpStatus.NOT_FOUND.value(), resCode); - assertEquals("invalid response code in RequestContext: " + ctxCode, resCode, ctxCode); + assertThat(resCode).as("invalid response code: " + resCode) + .isEqualTo(HttpStatus.NOT_FOUND.value()); + assertThat(ctxCode).as("invalid response code in RequestContext: " + ctxCode) + .isEqualTo(resCode); } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/SendResponseFilterTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/SendResponseFilterTests.java index 3957fd4d8..0ac90d32f 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/SendResponseFilterTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/SendResponseFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,20 +16,6 @@ package org.springframework.cloud.netflix.zuul.filters.post; -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.X_ZUUL_DEBUG_HEADER; - import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -46,18 +32,28 @@ import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import com.netflix.zuul.constants.ZuulHeaders; +import com.netflix.zuul.context.Debug; +import com.netflix.zuul.context.RequestContext; import org.junit.After; import org.junit.Before; import org.junit.Test; + import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; import org.springframework.http.HttpStatus; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.web.util.WebUtils; -import com.netflix.zuul.constants.ZuulHeaders; -import com.netflix.zuul.context.Debug; -import com.netflix.zuul.context.RequestContext; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.X_ZUUL_DEBUG_HEADER; /** * @author Spencer Gibb @@ -70,7 +66,7 @@ public class SendResponseFilterTests { context.setRequest(new MockHttpServletRequest()); context.setResponse(new MockHttpServletResponse()); context.setResponseGZipped(false); - + RequestContext.testSetCurrentContext(context); } @@ -103,13 +99,14 @@ public class SendResponseFilterTests { ZuulProperties properties = new ZuulProperties(); properties.setIncludeDebugHeader(true); - SendResponseFilter filter = createFilter(properties, "hello", null, new MockHttpServletResponse(), false); + SendResponseFilter filter = createFilter(properties, "hello", null, + new MockHttpServletResponse(), false); Debug.addRoutingDebug("test"); filter.run(); String debugHeader = RequestContext.getCurrentContext().getResponse() .getHeader(X_ZUUL_DEBUG_HEADER); - assertThat("wrong debug header", debugHeader, equalTo("[[[test]]]")); + assertThat(debugHeader).as("wrong debug header").isEqualTo("[[[test]]]"); } /* @@ -120,18 +117,20 @@ public class SendResponseFilterTests { ZuulProperties properties = new ZuulProperties(); properties.setSetContentLength(true); - SendResponseFilter filter = createFilter(properties, "hello", null, new MockHttpServletResponse(), false); + SendResponseFilter filter = createFilter(properties, "hello", null, + new MockHttpServletResponse(), false); RequestContext.getCurrentContext().setOriginContentLength(6L); // for test RequestContext.getCurrentContext().setResponseGZipped(false); filter.run(); String contentLength = RequestContext.getCurrentContext().getResponse() .getHeader("Content-Length"); - assertThat("wrong origin content length", contentLength, equalTo("6")); + assertThat(contentLength).as("wrong origin content length").isEqualTo("6"); } /* - * GZip requested and GZip response -> Content-Length forwarded asis, response compressed + * GZip requested and GZip response -> Content-Length forwarded asis, response + * compressed */ @Test public void runWithOriginContentLength_gzipRequested_gzipResponse() throws Exception { @@ -139,52 +138,65 @@ public class SendResponseFilterTests { properties.setSetContentLength(true); SendResponseFilter filter = new SendResponseFilter(properties); - + byte[] gzipData = gzipData("hello"); - - RequestContext.getCurrentContext().setOriginContentLength((long) gzipData.length); // for test + + RequestContext.getCurrentContext().setOriginContentLength((long) gzipData.length); // for + // test RequestContext.getCurrentContext().setResponseGZipped(true); - RequestContext.getCurrentContext().setResponseDataStream( new ByteArrayInputStream(gzipData) ); - ((MockHttpServletRequest) RequestContext.getCurrentContext().getRequest()).addHeader(ZuulHeaders.ACCEPT_ENCODING, "gzip"); - + RequestContext.getCurrentContext() + .setResponseDataStream(new ByteArrayInputStream(gzipData)); + ((MockHttpServletRequest) RequestContext.getCurrentContext().getRequest()) + .addHeader(ZuulHeaders.ACCEPT_ENCODING, "gzip"); + filter.run(); - MockHttpServletResponse response = (MockHttpServletResponse) RequestContext.getCurrentContext().getResponse(); - assertThat(response.getHeader("Content-Length")).isEqualTo(Integer.toString(gzipData.length)); + MockHttpServletResponse response = (MockHttpServletResponse) RequestContext + .getCurrentContext().getResponse(); + assertThat(response.getHeader("Content-Length")) + .isEqualTo(Integer.toString(gzipData.length)); assertThat(response.getHeader("Content-Encoding")).isEqualTo("gzip"); assertThat(response.getContentAsByteArray()).isEqualTo(gzipData); - - BufferedReader reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(new ByteArrayInputStream(response.getContentAsByteArray())))); + + BufferedReader reader = new BufferedReader( + new InputStreamReader(new GZIPInputStream( + new ByteArrayInputStream(response.getContentAsByteArray())))); assertThat(reader.readLine()).isEqualTo("hello"); } - + /* - * GZip NOT requested and GZip response -> Content-Length discarded and response uncompressed + * GZip NOT requested and GZip response -> Content-Length discarded and response + * uncompressed */ @Test - public void runWithOriginContentLength_gzipNotRequested_gzipResponse() throws Exception { + public void runWithOriginContentLength_gzipNotRequested_gzipResponse() + throws Exception { ZuulProperties properties = new ZuulProperties(); properties.setSetContentLength(true); SendResponseFilter filter = new SendResponseFilter(properties); - + byte[] gzipData = gzipData("hello"); - - RequestContext.getCurrentContext().setOriginContentLength((long) gzipData.length); // for test + + RequestContext.getCurrentContext().setOriginContentLength((long) gzipData.length); // for + // test RequestContext.getCurrentContext().setResponseGZipped(true); - RequestContext.getCurrentContext().setResponseDataStream( new ByteArrayInputStream(gzipData) ); - + RequestContext.getCurrentContext() + .setResponseDataStream(new ByteArrayInputStream(gzipData)); + filter.run(); - MockHttpServletResponse response = (MockHttpServletResponse) RequestContext.getCurrentContext().getResponse(); + MockHttpServletResponse response = (MockHttpServletResponse) RequestContext + .getCurrentContext().getResponse(); assertThat(response.getHeader("Content-Length")).isNull(); assertThat(response.getHeader("Content-Encoding")).isNull(); - assertThat("wrong content", response.getContentAsString(), equalTo("hello")); + assertThat(response.getContentAsString()).as("wrong content").isEqualTo("hello"); } - + /* - * Origin sends a non gzip response with Content-Encoding: gzip - * Request does not support GZIP -> filter fails to uncompress and send stream "asis". Content-Length is NOT preserved. + * Origin sends a non gzip response with Content-Encoding: gzip Request does not + * support GZIP -> filter fails to uncompress and send stream "asis". Content-Length + * is NOT preserved. */ @Test public void invalidGzipResponseFromOrigin() throws Exception { @@ -192,24 +204,31 @@ public class SendResponseFilterTests { properties.setSetContentLength(true); SendResponseFilter filter = new SendResponseFilter(properties); - + byte[] gzipData = "hello".getBytes(); - - RequestContext.getCurrentContext().setOriginContentLength((long) gzipData.length); // for test - RequestContext.getCurrentContext().setResponseGZipped(true); // say it is GZipped although not the case - RequestContext.getCurrentContext().setResponseDataStream( new ByteArrayInputStream(gzipData) ); - + + RequestContext.getCurrentContext().setOriginContentLength((long) gzipData.length); // for + // test + RequestContext.getCurrentContext().setResponseGZipped(true); // say it is GZipped + // although not + // the case + RequestContext.getCurrentContext() + .setResponseDataStream(new ByteArrayInputStream(gzipData)); + filter.run(); - MockHttpServletResponse response = (MockHttpServletResponse) RequestContext.getCurrentContext().getResponse(); + MockHttpServletResponse response = (MockHttpServletResponse) RequestContext + .getCurrentContext().getResponse(); assertThat(response.getHeader("Content-Length")).isNull(); assertThat(response.getHeader("Content-Encoding")).isNull(); - assertThat("wrong content", response.getContentAsString(), equalTo("hello")); // response sent "asis" + assertThat(response.getContentAsString()).as("wrong content").isEqualTo("hello"); // response + // sent + // "asis" } - + /* - * Empty response from origin with Content-Encoding: gzip - * Request does not support GZIP -> filter should not fail in decoding the *empty* response stream + * Empty response from origin with Content-Encoding: gzip Request does not support + * GZIP -> filter should not fail in decoding the *empty* response stream */ @Test public void emptyGzipResponseFromOrigin() throws Exception { @@ -217,25 +236,27 @@ public class SendResponseFilterTests { properties.setSetContentLength(true); SendResponseFilter filter = new SendResponseFilter(properties); - + byte[] gzipData = new byte[] {}; - + RequestContext.getCurrentContext().setResponseGZipped(true); - RequestContext.getCurrentContext().setResponseDataStream( new ByteArrayInputStream(gzipData) ); - + RequestContext.getCurrentContext() + .setResponseDataStream(new ByteArrayInputStream(gzipData)); + filter.run(); - MockHttpServletResponse response = (MockHttpServletResponse) RequestContext.getCurrentContext().getResponse(); + MockHttpServletResponse response = (MockHttpServletResponse) RequestContext + .getCurrentContext().getResponse(); assertThat(response.getHeader("Content-Length")).isNull(); assertThat(response.getHeader("Content-Encoding")).isNull(); - assertThat(response.getContentAsByteArray(), equalTo(gzipData)); + assertThat(response.getContentAsByteArray()).isEqualTo(gzipData); } - - + @Test public void closeResponseOutputStreamError() throws Exception { HttpServletResponse response = mock(HttpServletResponse.class); - InputStream mockStream = spy(new ByteArrayInputStream("Hello\n".getBytes("UTF-8"))); + InputStream mockStream = spy( + new ByteArrayInputStream("Hello\n".getBytes("UTF-8"))); RequestContext context = new RequestContext(); context.setRequest(new MockHttpServletRequest()); @@ -249,14 +270,17 @@ public class SendResponseFilterTests { SendResponseFilter filter = new SendResponseFilter(); ServletOutputStream zuuloutputstream = mock(ServletOutputStream.class); - doThrow(new IOException("Response to client closed")).when(zuuloutputstream).write(isA(byte[].class), anyInt(), anyInt()); + doThrow(new IOException("Response to client closed")).when(zuuloutputstream) + .write(isA(byte[].class), anyInt(), anyInt()); when(response.getOutputStream()).thenReturn(zuuloutputstream); try { filter.run(); - } catch (UndeclaredThrowableException ex) { - assertThat(ex.getUndeclaredThrowable().getMessage(), is("Response to client closed")); + } + catch (UndeclaredThrowableException ex) { + assertThat(ex.getUndeclaredThrowable().getMessage()) + .isEqualTo("Response to client closed"); } verify(zuulResponse).close(); @@ -266,7 +290,8 @@ public class SendResponseFilterTests { @Test public void testCloseResponseDataStream() throws Exception { HttpServletResponse response = mock(HttpServletResponse.class); - InputStream mockStream = spy(new ByteArrayInputStream("Hello\n".getBytes("UTF-8"))); + InputStream mockStream = spy( + new ByteArrayInputStream("Hello\n".getBytes("UTF-8"))); RequestContext context = new RequestContext(); context.setRequest(new MockHttpServletRequest()); @@ -286,22 +311,30 @@ public class SendResponseFilterTests { verify(mockStream).close(); } - private void runFilter(String characterEncoding, String content, boolean streamContent) throws Exception { + private void runFilter(String characterEncoding, String content, + boolean streamContent) throws Exception { MockHttpServletResponse response = new MockHttpServletResponse(); - SendResponseFilter filter = createFilter(content, characterEncoding, response, streamContent); - assertTrue("shouldFilter returned false", filter.shouldFilter()); + SendResponseFilter filter = createFilter(content, characterEncoding, response, + streamContent); + assertThat(filter.shouldFilter()).as("shouldFilter returned false").isTrue(); filter.run(); - String encoding = RequestContext.getCurrentContext().getResponse().getCharacterEncoding(); - String expectedEncoding = characterEncoding != null ? characterEncoding : WebUtils.DEFAULT_CHARACTER_ENCODING; - assertThat("wrong character encoding", encoding, equalTo(expectedEncoding)); - assertThat("wrong content", response.getContentAsString(), equalTo(content)); + String encoding = RequestContext.getCurrentContext().getResponse() + .getCharacterEncoding(); + String expectedEncoding = characterEncoding != null ? characterEncoding + : WebUtils.DEFAULT_CHARACTER_ENCODING; + assertThat(encoding).as("wrong character encoding").isEqualTo(expectedEncoding); + assertThat(response.getContentAsString()).as("wrong content").isEqualTo(content); } - private SendResponseFilter createFilter(String content, String characterEncoding, MockHttpServletResponse response, boolean streamContent) throws Exception { - return createFilter(new ZuulProperties(), content, characterEncoding, response, streamContent); - } + private SendResponseFilter createFilter(String content, String characterEncoding, + MockHttpServletResponse response, boolean streamContent) throws Exception { + return createFilter(new ZuulProperties(), content, characterEncoding, response, + streamContent); + } - private SendResponseFilter createFilter(ZuulProperties properties, String content, String characterEncoding, MockHttpServletResponse response, boolean streamContent) throws Exception { + private SendResponseFilter createFilter(ZuulProperties properties, String content, + String characterEncoding, MockHttpServletResponse response, + boolean streamContent) throws Exception { HttpServletRequest request = new MockHttpServletRequest(); RequestContext context = new RequestContext(); context.setRequest(request); @@ -312,8 +345,10 @@ public class SendResponseFilterTests { } if (streamContent) { - context.setResponseDataStream(new ByteArrayInputStream(content.getBytes(characterEncoding))); - } else { + context.setResponseDataStream( + new ByteArrayInputStream(content.getBytes(characterEncoding))); + } + else { context.setResponseBody(content); } @@ -330,7 +365,8 @@ public class SendResponseFilterTests { gzip.print(content); gzip.flush(); gzip.close(); - + return bos.toByteArray(); } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/pre/FormBodyWrapperFilterTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/pre/FormBodyWrapperFilterTests.java index 10ef5b4e3..2cbb97229 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/pre/FormBodyWrapperFilterTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/pre/FormBodyWrapperFilterTests.java @@ -1,7 +1,20 @@ -package org.springframework.cloud.netflix.zuul.filters.pre; +/* + * Copyright 2016-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +package org.springframework.cloud.netflix.zuul.filters.pre; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -14,20 +27,22 @@ import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.Part; +import com.netflix.zuul.context.RequestContext; import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Test; + import org.springframework.mock.web.MockMultipartHttpServletRequest; -import com.netflix.zuul.context.RequestContext; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Michael Hartle */ public class FormBodyWrapperFilterTests { - + private FormBodyWrapperFilter filter; - + private MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest(); @Before @@ -37,79 +52,97 @@ public class FormBodyWrapperFilterTests { ctx.clear(); ctx.setRequest(this.request); } - + @Test - public void multiplePartNamesWithMultipleParts() throws IOException, ServletException { + public void multiplePartNamesWithMultipleParts() + throws IOException, ServletException { this.request.setRequestURI("/api/foo/1"); this.request.setRemoteAddr("5.6.7.8"); - + final Map> firstPartHeaders = new HashMap<>(); final byte[] firstPartBody = "{ \"u\" : 1 }".getBytes(); - final Part firstPart = new MockPart("a", "application/json", null, firstPartHeaders, firstPartBody); + final Part firstPart = new MockPart("a", "application/json", null, + firstPartHeaders, firstPartBody); this.request.addPart(firstPart); final Map> secondPartHeaders = new HashMap<>(); final byte[] secondPartBody = "%PDF...1".getBytes(); - final Part secondPart = new MockPart("b", "application/pdf", "document.pdf", secondPartHeaders, secondPartBody); + final Part secondPart = new MockPart("b", "application/pdf", "document.pdf", + secondPartHeaders, secondPartBody); this.request.addPart(secondPart); - + final Map> thirdPartHeaders = new HashMap<>(); final byte[] thirdPartBody = "%PDF...2".getBytes(); - final Part thirdPart = new MockPart("c", "application/pdf", "attachment1.pdf", thirdPartHeaders, thirdPartBody); + final Part thirdPart = new MockPart("c", "application/pdf", "attachment1.pdf", + thirdPartHeaders, thirdPartBody); this.request.addPart(thirdPart); - + final Map> fourthPartHeaders = new HashMap<>(); final byte[] fourthPartBody = "%PDF...3".getBytes(); - final Part fourthPart = new MockPart("c", "application/pdf", "attachment2.pdf", fourthPartHeaders, fourthPartBody); + final Part fourthPart = new MockPart("c", "application/pdf", "attachment2.pdf", + fourthPartHeaders, fourthPartBody); this.request.addPart(fourthPart); final Map> fifthPartHeaders = new HashMap<>(); final byte[] fifthPartBody = "%PDF...4".getBytes(); - final Part fifthPart = new MockPart("c", "application/pdf", "attachment3.pdf", fifthPartHeaders, fifthPartBody); + final Part fifthPart = new MockPart("c", "application/pdf", "attachment3.pdf", + fifthPartHeaders, fifthPartBody); this.request.addPart(fifthPart); - - this.filter.run(); - - final RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("/api/foo/1", ctx.getRequest().getRequestURI()); - assertEquals("5.6.7.8", ctx.getRequest().getRemoteAddr()); - assertEquals(5, ctx.getRequest().getParts().size()); - - final Part[] parts = ctx.getRequest().getParts().toArray(new Part[0]); - assertEquals("a", parts[0].getName()); - assertEquals(null, parts[0].getSubmittedFileName()); - assertEquals("application/json", parts[0].getContentType()); - assertArrayEquals(firstPartBody, IOUtils.toByteArray(parts[0].getInputStream())); - - assertEquals("b", parts[1].getName()); - assertEquals("document.pdf", parts[1].getSubmittedFileName()); - assertEquals("application/pdf", parts[1].getContentType()); - assertArrayEquals(secondPartBody, IOUtils.toByteArray(parts[1].getInputStream())); - - assertEquals("c", parts[2].getName()); - assertEquals("attachment1.pdf", parts[2].getSubmittedFileName()); - assertEquals("application/pdf", parts[2].getContentType()); - assertArrayEquals(thirdPartBody, IOUtils.toByteArray(parts[2].getInputStream())); - - assertEquals("c", parts[3].getName()); - assertEquals("attachment2.pdf", parts[3].getSubmittedFileName()); - assertEquals("application/pdf", parts[3].getContentType()); - assertArrayEquals(fourthPartBody, IOUtils.toByteArray(parts[3].getInputStream())); - assertEquals("c", parts[4].getName()); - assertEquals("attachment3.pdf", parts[4].getSubmittedFileName()); - assertEquals("application/pdf", parts[4].getContentType()); - assertArrayEquals(fifthPartBody, IOUtils.toByteArray(parts[4].getInputStream())); + this.filter.run(); + + final RequestContext ctx = RequestContext.getCurrentContext(); + assertThat(ctx.getRequest().getRequestURI()).isEqualTo("/api/foo/1"); + assertThat(ctx.getRequest().getRemoteAddr()).isEqualTo("5.6.7.8"); + assertThat(ctx.getRequest().getParts().size()).isEqualTo(5); + + final Part[] parts = ctx.getRequest().getParts().toArray(new Part[0]); + assertThat(parts[0].getName()).isEqualTo("a"); + assertThat(parts[0].getSubmittedFileName()).isEqualTo(null); + assertThat(parts[0].getContentType()).isEqualTo("application/json"); + assertThat(IOUtils.toByteArray(parts[0].getInputStream())) + .isEqualTo(firstPartBody); + + assertThat(parts[1].getName()).isEqualTo("b"); + assertThat(parts[1].getSubmittedFileName()).isEqualTo("document.pdf"); + assertThat(parts[1].getContentType()).isEqualTo("application/pdf"); + assertThat(IOUtils.toByteArray(parts[1].getInputStream())) + .isEqualTo(secondPartBody); + + assertThat(parts[2].getName()).isEqualTo("c"); + assertThat(parts[2].getSubmittedFileName()).isEqualTo("attachment1.pdf"); + assertThat(parts[2].getContentType()).isEqualTo("application/pdf"); + assertThat(IOUtils.toByteArray(parts[2].getInputStream())) + .isEqualTo(thirdPartBody); + + assertThat(parts[3].getName()).isEqualTo("c"); + assertThat(parts[3].getSubmittedFileName()).isEqualTo("attachment2.pdf"); + assertThat(parts[3].getContentType()).isEqualTo("application/pdf"); + assertThat(IOUtils.toByteArray(parts[3].getInputStream())) + .isEqualTo(fourthPartBody); + + assertThat(parts[4].getName()).isEqualTo("c"); + assertThat(parts[4].getSubmittedFileName()).isEqualTo("attachment3.pdf"); + assertThat(parts[4].getContentType()).isEqualTo("application/pdf"); + assertThat(IOUtils.toByteArray(parts[4].getInputStream())) + .isEqualTo(fifthPartBody); } - + private class MockPart implements Part { + private final String name; + private final String contentType; + private final String submittedFileName; + private final Map> headers; + private final byte[] body; - - public MockPart(final String name, final String contentType, final String submittedFileName, final Map> headers, final byte[] body) { + + MockPart(final String name, final String contentType, + final String submittedFileName, final Map> headers, + final byte[] body) { this.name = name; this.contentType = contentType; this.submittedFileName = submittedFileName; @@ -163,7 +196,7 @@ public class FormBodyWrapperFilterTests { if (values == null || values.size() == 0) { return null; } - + return values.get(0); } @@ -172,7 +205,7 @@ public class FormBodyWrapperFilterTests { if (this.headers == null) { return null; } - + return this.headers.get(name); } @@ -184,5 +217,7 @@ public class FormBodyWrapperFilterTests { return this.headers.keySet(); } + } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/pre/PreDecorationFilterTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/pre/PreDecorationFilterTests.java index 59407f6a3..b287d7111 100755 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/pre/PreDecorationFilterTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/pre/PreDecorationFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,6 @@ import java.util.Set; import com.netflix.util.Pair; import com.netflix.zuul.context.RequestContext; - import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -42,9 +41,6 @@ import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.util.MultiValueMap; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; import static org.mockito.MockitoAnnotations.initMocks; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.FORWARD_TO_KEY; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE; @@ -55,9 +51,10 @@ import static org.springframework.cloud.netflix.zuul.filters.support.FilterConst * @author Dave Syer */ @RunWith(ModifiedClassPathRunner.class) -//This is needed for sensitiveHeadersOverrideEmpty, if Spring Security is on the classpath -//then sensitive headers will always be present. -@ClassPathExclusions({"spring-security-*.jar"}) +// This is needed for sensitiveHeadersOverrideEmpty, if Spring Security is on the +// classpath +// then sensitive headers will always be present. +@ClassPathExclusions({ "spring-security-*.jar" }) public class PreDecorationFilterTests { private PreDecorationFilter filter; @@ -94,21 +91,21 @@ public class PreDecorationFilterTests { @Test public void basicProperties() throws Exception { - assertEquals(5, this.filter.filterOrder()); - assertEquals(true, this.filter.shouldFilter()); - assertEquals(PRE_TYPE, this.filter.filterType()); + assertThat(this.filter.filterOrder()).isEqualTo(5); + assertThat(this.filter.shouldFilter()).isEqualTo(true); + assertThat(this.filter.filterType()).isEqualTo(PRE_TYPE); } @Test public void skippedIfServiceIdSet() throws Exception { RequestContext.getCurrentContext().set(SERVICE_ID_KEY, "myservice"); - assertEquals(false, this.filter.shouldFilter()); + assertThat(this.filter.shouldFilter()).isEqualTo(false); } @Test public void skippedIfForwardToSet() throws Exception { RequestContext.getCurrentContext().set(FORWARD_TO_KEY, "myconteext"); - assertEquals(false, this.filter.shouldFilter()); + assertThat(this.filter.shouldFilter()).isEqualTo(false); } @Test @@ -121,8 +118,8 @@ public class PreDecorationFilterTests { new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); this.filter.run(); RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("localhost:8080", - ctx.getZuulRequestHeaders().get("x-forwarded-host")); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-host")) + .isEqualTo("localhost:8080"); } @Test @@ -137,10 +134,12 @@ public class PreDecorationFilterTests { new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); this.filter.run(); RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("example.com,localhost:8080", - ctx.getZuulRequestHeaders().get("x-forwarded-host")); - assertEquals("443,8080", ctx.getZuulRequestHeaders().get("x-forwarded-port")); - assertEquals("https,http", ctx.getZuulRequestHeaders().get("x-forwarded-proto")); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-host")) + .isEqualTo("example.com,localhost:8080"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-port")) + .isEqualTo("443,8080"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-proto")) + .isEqualTo("https,http"); } @Test @@ -154,10 +153,11 @@ public class PreDecorationFilterTests { new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); this.filter.run(); RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("example.com,localhost:8080", - ctx.getZuulRequestHeaders().get("x-forwarded-host")); - assertEquals("8080", ctx.getZuulRequestHeaders().get("x-forwarded-port")); - assertEquals("http", ctx.getZuulRequestHeaders().get("x-forwarded-proto")); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-host")) + .isEqualTo("example.com,localhost:8080"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-port")).isEqualTo("8080"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-proto")) + .isEqualTo("http"); } @Test @@ -171,10 +171,12 @@ public class PreDecorationFilterTests { new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); this.filter.run(); RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("localhost:8080", - ctx.getZuulRequestHeaders().get("x-forwarded-host")); - assertEquals("443,8080", ctx.getZuulRequestHeaders().get("x-forwarded-port")); - assertEquals("https,http", ctx.getZuulRequestHeaders().get("x-forwarded-proto")); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-host")) + .isEqualTo("localhost:8080"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-port")) + .isEqualTo("443,8080"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-proto")) + .isEqualTo("https,http"); } @Test @@ -188,10 +190,12 @@ public class PreDecorationFilterTests { new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); this.filter.run(); RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("localhost:8080", - ctx.getZuulRequestHeaders().get("x-forwarded-host")); - assertEquals("80,8080", ctx.getZuulRequestHeaders().get("x-forwarded-port")); - assertEquals("http,http", ctx.getZuulRequestHeaders().get("x-forwarded-proto")); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-host")) + .isEqualTo("localhost:8080"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-port")) + .isEqualTo("80,8080"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-proto")) + .isEqualTo("http,http"); } @Test @@ -205,10 +209,12 @@ public class PreDecorationFilterTests { new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); this.filter.run(); RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("localhost:8080", - ctx.getZuulRequestHeaders().get("x-forwarded-host")); - assertEquals("456,8080", ctx.getZuulRequestHeaders().get("x-forwarded-port")); - assertEquals("http", ctx.getZuulRequestHeaders().get("x-forwarded-proto")); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-host")) + .isEqualTo("localhost:8080"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-port")) + .isEqualTo("456,8080"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-proto")) + .isEqualTo("http"); } @Test @@ -223,10 +229,12 @@ public class PreDecorationFilterTests { new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); this.filter.run(); RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("localhost:8080", - ctx.getZuulRequestHeaders().get("x-forwarded-host")); - assertEquals("456,8080", ctx.getZuulRequestHeaders().get("x-forwarded-port")); - assertEquals("https,http", ctx.getZuulRequestHeaders().get("x-forwarded-proto")); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-host")) + .isEqualTo("localhost:8080"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-port")) + .isEqualTo("456,8080"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-proto")) + .isEqualTo("https,http"); } @Test @@ -240,9 +248,9 @@ public class PreDecorationFilterTests { new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); this.filter.run(); RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("localhost:8080", - ctx.getZuulRequestHeaders().get("x-forwarded-host")); - assertEquals("localhost:8080", ctx.getZuulRequestHeaders().get("host")); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-host")) + .isEqualTo("localhost:8080"); + assertThat(ctx.getZuulRequestHeaders().get("host")).isEqualTo("localhost:8080"); } @Test @@ -256,15 +264,18 @@ public class PreDecorationFilterTests { new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); this.filter.run(); RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("/foo/1", ctx.get(REQUEST_URI_KEY)); - assertEquals("localhost", ctx.getZuulRequestHeaders().get("x-forwarded-host")); - assertEquals("80", ctx.getZuulRequestHeaders().get("x-forwarded-port")); - assertEquals("http", ctx.getZuulRequestHeaders().get("x-forwarded-proto")); - assertEquals("/api", ctx.getZuulRequestHeaders().get("x-forwarded-prefix")); - assertEquals("1.2.3.4, 5.6.7.8", - ctx.getZuulRequestHeaders().get("x-forwarded-for")); - assertEquals("foo", - getHeader(ctx.getOriginResponseHeaders(), "x-zuul-serviceid")); + assertThat(ctx.get(REQUEST_URI_KEY)).isEqualTo("/foo/1"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-host")) + .isEqualTo("localhost"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-port")).isEqualTo("80"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-proto")) + .isEqualTo("http"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-prefix")) + .isEqualTo("/api"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-for")) + .isEqualTo("1.2.3.4, 5.6.7.8"); + assertThat(getHeader(ctx.getOriginResponseHeaders(), "x-zuul-serviceid")) + .isEqualTo("foo"); } @Test @@ -279,16 +290,18 @@ public class PreDecorationFilterTests { new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); this.filter.run(); RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("/foo/1", ctx.get(REQUEST_URI_KEY)); - assertEquals("localhost", ctx.getZuulRequestHeaders().get("x-forwarded-host")); - assertEquals("80", ctx.getZuulRequestHeaders().get("x-forwarded-port")); - assertEquals("http", ctx.getZuulRequestHeaders().get("x-forwarded-proto")); - assertEquals("/prefix/api", - ctx.getZuulRequestHeaders().get("x-forwarded-prefix")); - assertEquals("1.2.3.4, 5.6.7.8", - ctx.getZuulRequestHeaders().get("x-forwarded-for")); - assertEquals("foo", - getHeader(ctx.getOriginResponseHeaders(), "x-zuul-serviceid")); + assertThat(ctx.get(REQUEST_URI_KEY)).isEqualTo("/foo/1"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-host")) + .isEqualTo("localhost"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-port")).isEqualTo("80"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-proto")) + .isEqualTo("http"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-prefix")) + .isEqualTo("/prefix/api"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-for")) + .isEqualTo("1.2.3.4, 5.6.7.8"); + assertThat(getHeader(ctx.getOriginResponseHeaders(), "x-zuul-serviceid")) + .isEqualTo("foo"); } @Test @@ -300,14 +313,16 @@ public class PreDecorationFilterTests { new ZuulRoute("foo", "/api/foo/**", "foo", null, false, null, null)); this.filter.run(); RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("/api/foo/1", ctx.get(REQUEST_URI_KEY)); - assertEquals("localhost", ctx.getZuulRequestHeaders().get("x-forwarded-host")); - assertEquals("80", ctx.getZuulRequestHeaders().get("x-forwarded-port")); - assertEquals("http", ctx.getZuulRequestHeaders().get("x-forwarded-proto")); - assertEquals("/context-path", - ctx.getZuulRequestHeaders().get("x-forwarded-prefix")); - assertEquals("foo", - getHeader(ctx.getOriginResponseHeaders(), "x-zuul-serviceid")); + assertThat(ctx.get(REQUEST_URI_KEY)).isEqualTo("/api/foo/1"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-host")) + .isEqualTo("localhost"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-port")).isEqualTo("80"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-proto")) + .isEqualTo("http"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-prefix")) + .isEqualTo("/context-path"); + assertThat(getHeader(ctx.getOriginResponseHeaders(), "x-zuul-serviceid")) + .isEqualTo("foo"); } @Test @@ -320,14 +335,16 @@ public class PreDecorationFilterTests { new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); this.filter.run(); RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("/foo/1", ctx.get(REQUEST_URI_KEY)); - assertEquals("localhost", ctx.getZuulRequestHeaders().get("x-forwarded-host")); - assertEquals("80", ctx.getZuulRequestHeaders().get("x-forwarded-port")); - assertEquals("http", ctx.getZuulRequestHeaders().get("x-forwarded-proto")); - assertEquals("/context-path/api", - ctx.getZuulRequestHeaders().get("x-forwarded-prefix")); - assertEquals("foo", - getHeader(ctx.getOriginResponseHeaders(), "x-zuul-serviceid")); + assertThat(ctx.get(REQUEST_URI_KEY)).isEqualTo("/foo/1"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-host")) + .isEqualTo("localhost"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-port")).isEqualTo("80"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-proto")) + .isEqualTo("http"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-prefix")) + .isEqualTo("/context-path/api"); + assertThat(getHeader(ctx.getOriginResponseHeaders(), "x-zuul-serviceid")) + .isEqualTo("foo"); } @Test @@ -343,7 +360,7 @@ public class PreDecorationFilterTests { this.proxyRequestHelper); this.filter.run(); RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("/foo/encoded%2Fpath", ctx.get(REQUEST_URI_KEY)); + assertThat(ctx.get(REQUEST_URI_KEY)).isEqualTo("/foo/encoded%2Fpath"); } @Test @@ -356,13 +373,16 @@ public class PreDecorationFilterTests { new ZuulRoute("foo", "/api/foo/**", "foo", null, false, null, null)); this.filter.run(); RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("/api/foo/1", ctx.get(REQUEST_URI_KEY)); - assertEquals("localhost", ctx.getZuulRequestHeaders().get("x-forwarded-host")); - assertEquals("80", ctx.getZuulRequestHeaders().get("x-forwarded-port")); - assertEquals("http", ctx.getZuulRequestHeaders().get("x-forwarded-proto")); - assertEquals("/prefix", ctx.getZuulRequestHeaders().get("x-forwarded-prefix")); - assertEquals("foo", - getHeader(ctx.getOriginResponseHeaders(), "x-zuul-serviceid")); + assertThat(ctx.get(REQUEST_URI_KEY)).isEqualTo("/api/foo/1"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-host")) + .isEqualTo("localhost"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-port")).isEqualTo("80"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-proto")) + .isEqualTo("http"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-prefix")) + .isEqualTo("/prefix"); + assertThat(getHeader(ctx.getOriginResponseHeaders(), "x-zuul-serviceid")) + .isEqualTo("foo"); } @Test @@ -376,14 +396,16 @@ public class PreDecorationFilterTests { new ZuulRoute("foo", "/foo/**", "foo", null, false, null, null)); this.filter.run(); RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("/foo/1", ctx.get(REQUEST_URI_KEY)); - assertEquals("localhost", ctx.getZuulRequestHeaders().get("x-forwarded-host")); - assertEquals("80", ctx.getZuulRequestHeaders().get("x-forwarded-port")); - assertEquals("http", ctx.getZuulRequestHeaders().get("x-forwarded-proto")); - assertEquals("/prefix/api", - ctx.getZuulRequestHeaders().get("x-forwarded-prefix")); - assertEquals("foo", - getHeader(ctx.getOriginResponseHeaders(), "x-zuul-serviceid")); + assertThat(ctx.get(REQUEST_URI_KEY)).isEqualTo("/foo/1"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-host")) + .isEqualTo("localhost"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-port")).isEqualTo("80"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-proto")) + .isEqualTo("http"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-prefix")) + .isEqualTo("/prefix/api"); + assertThat(getHeader(ctx.getOriginResponseHeaders(), "x-zuul-serviceid")) + .isEqualTo("foo"); } @Test @@ -395,7 +417,7 @@ public class PreDecorationFilterTests { new ZuulRoute("foo", "/foo/**", null, "forward:/foo", true, null, null)); this.filter.run(); RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("/foo/1", ctx.get(FORWARD_TO_KEY)); + assertThat(ctx.get(FORWARD_TO_KEY)).isEqualTo("/foo/1"); } @Test @@ -405,7 +427,7 @@ public class PreDecorationFilterTests { new ZuulRoute("foo", "/foo/**", null, "forward:/bar", false, null, null)); this.filter.run(); RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("/bar/foo/1", ctx.get(FORWARD_TO_KEY)); + assertThat(ctx.get(FORWARD_TO_KEY)).isEqualTo("/bar/foo/1"); } @Test @@ -416,12 +438,15 @@ public class PreDecorationFilterTests { this.routeLocator.addRoute("/foo/**", "foo"); this.filter.run(); RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("/1", ctx.get(REQUEST_URI_KEY)); - assertEquals("localhost", ctx.getZuulRequestHeaders().get("x-forwarded-host")); - assertEquals("http", ctx.getZuulRequestHeaders().get("x-forwarded-proto")); - assertEquals("/api/foo", ctx.getZuulRequestHeaders().get("x-forwarded-prefix")); - assertEquals("foo", - getHeader(ctx.getOriginResponseHeaders(), "x-zuul-serviceid")); + assertThat(ctx.get(REQUEST_URI_KEY)).isEqualTo("/1"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-host")) + .isEqualTo("localhost"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-proto")) + .isEqualTo("http"); + assertThat(ctx.getZuulRequestHeaders().get("x-forwarded-prefix")) + .isEqualTo("/api/foo"); + assertThat(getHeader(ctx.getOriginResponseHeaders(), "x-zuul-serviceid")) + .isEqualTo("foo"); } @Test @@ -435,7 +460,7 @@ public class PreDecorationFilterTests { this.filter.run(); RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("/api/bar/1", ctx.get(FORWARD_TO_KEY)); + assertThat(ctx.get(FORWARD_TO_KEY)).isEqualTo("/api/bar/1"); } @Test @@ -453,7 +478,7 @@ public class PreDecorationFilterTests { this.filter.run(); RequestContext ctx = RequestContext.getCurrentContext(); - assertEquals("/special/api/bar/1", ctx.get(FORWARD_TO_KEY)); + assertThat(ctx.get(FORWARD_TO_KEY)).isEqualTo("/special/api/bar/1"); } @Test @@ -472,7 +497,7 @@ public class PreDecorationFilterTests { this.filter.run(); - assertEquals("/api/bar/1", ctx.get(FORWARD_TO_KEY)); + assertThat(ctx.get(FORWARD_TO_KEY)).isEqualTo("/api/bar/1"); } @Test @@ -494,7 +519,7 @@ public class PreDecorationFilterTests { this.filter.run(); - assertEquals("/special/api/bar/1", ctx.get(FORWARD_TO_KEY)); + assertThat(ctx.get(FORWARD_TO_KEY)).isEqualTo("/special/api/bar/1"); } @Test @@ -517,7 +542,7 @@ public class PreDecorationFilterTests { this.filter.run(); - assertEquals("/special/api/bar/1", ctx.get(FORWARD_TO_KEY)); + assertThat(ctx.get(FORWARD_TO_KEY)).isEqualTo("/special/api/bar/1"); } @Test @@ -534,10 +559,10 @@ public class PreDecorationFilterTests { @SuppressWarnings("unchecked") Set sensitiveHeaders = (Set) ctx .get(ProxyRequestHelper.IGNORED_HEADERS); - assertTrue("sensitiveHeaders is wrong: " + sensitiveHeaders, - sensitiveHeaders.containsAll(Collections.singletonList("x-foo"))); - assertFalse("sensitiveHeaders is wrong: " + sensitiveHeaders, - sensitiveHeaders.contains("Cookie")); + assertThat(sensitiveHeaders.containsAll(Collections.singletonList("x-foo"))) + .as("sensitiveHeaders is wrong: " + sensitiveHeaders).isTrue(); + assertThat(sensitiveHeaders.contains("Cookie")) + .as("sensitiveHeaders is wrong: " + sensitiveHeaders).isFalse(); } @Test @@ -554,8 +579,8 @@ public class PreDecorationFilterTests { @SuppressWarnings("unchecked") Set sensitiveHeaders = (Set) ctx .get(ProxyRequestHelper.IGNORED_HEADERS); - assertTrue("sensitiveHeaders is wrong: " + sensitiveHeaders, - sensitiveHeaders.isEmpty()); + assertThat(sensitiveHeaders.isEmpty()) + .as("sensitiveHeaders is wrong: " + sensitiveHeaders).isTrue(); } @Test @@ -570,9 +595,10 @@ public class PreDecorationFilterTests { @SuppressWarnings("unchecked") Set sensitiveHeaders = (Set) ctx .get(ProxyRequestHelper.IGNORED_HEADERS); - assertTrue("sensitiveHeaders is wrong: " + sensitiveHeaders, - sensitiveHeaders.containsAll(Collections.singletonList("x-bar"))); - assertFalse("sensitiveHeaders is wrong", sensitiveHeaders.contains("Cookie")); + assertThat(sensitiveHeaders.containsAll(Collections.singletonList("x-bar"))) + .as("sensitiveHeaders is wrong: " + sensitiveHeaders).isTrue(); + assertThat(sensitiveHeaders.contains("Cookie")).as("sensitiveHeaders is wrong") + .isFalse(); } @Test @@ -587,8 +613,8 @@ public class PreDecorationFilterTests { @SuppressWarnings("unchecked") Set sensitiveHeaders = (Set) ctx .get(ProxyRequestHelper.IGNORED_HEADERS); - assertTrue("sensitiveHeaders is wrong: " + sensitiveHeaders, - sensitiveHeaders.containsAll(Collections.singletonList("x-bar"))); + assertThat(sensitiveHeaders.containsAll(Collections.singletonList("x-bar"))) + .as("sensitiveHeaders is wrong: " + sensitiveHeaders).isTrue(); } @Test @@ -605,8 +631,8 @@ public class PreDecorationFilterTests { @SuppressWarnings("unchecked") Set sensitiveHeaders = (Set) ctx .get(ProxyRequestHelper.IGNORED_HEADERS); - assertTrue("sensitiveHeaders is wrong: " + sensitiveHeaders, - sensitiveHeaders.containsAll(Collections.singletonList("x-foo"))); + assertThat(sensitiveHeaders.containsAll(Collections.singletonList("x-foo"))) + .as("sensitiveHeaders is wrong: " + sensitiveHeaders).isTrue(); } @Test @@ -624,8 +650,8 @@ public class PreDecorationFilterTests { @SuppressWarnings("unchecked") Set sensitiveHeaders = (Set) ctx .get(ProxyRequestHelper.IGNORED_HEADERS); - assertTrue("sensitiveHeaders is wrong: " + sensitiveHeaders, - sensitiveHeaders.containsAll(Arrays.asList("x-bar", "x-foo"))); + assertThat(sensitiveHeaders.containsAll(Arrays.asList("x-bar", "x-foo"))) + .as("sensitiveHeaders is wrong: " + sensitiveHeaders).isTrue(); } @Test @@ -638,7 +664,7 @@ public class PreDecorationFilterTests { RequestContext ctx = RequestContext.getCurrentContext(); this.filter.run(); String decodedRequestURI = (String) ctx.get(REQUEST_URI_KEY); - assertTrue(decodedRequestURI.equals("/oléדרעק")); + assertThat(decodedRequestURI.equals("/oléדרעק")).isTrue(); } @Test @@ -651,9 +677,9 @@ public class PreDecorationFilterTests { MultiValueMap result = proxyRequestHelper .buildZuulRequestHeaders(request); - assertTrue(result.containsKey("x-forwarded-proto")); - assertFalse(result.containsKey("x-forwarded-host")); - assertFalse(result.containsKey("x-forwarded-port")); + assertThat(result.containsKey("x-forwarded-proto")).isTrue(); + assertThat(result.containsKey("x-forwarded-host")).isFalse(); + assertThat(result.containsKey("x-forwarded-port")).isFalse(); } @Test diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/EagerLoadOfZuulConfigurationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/EagerLoadOfZuulConfigurationTests.java index 56f5b8948..93af2e80b 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/EagerLoadOfZuulConfigurationTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/EagerLoadOfZuulConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,14 +14,16 @@ * limitations under the License. */ - package org.springframework.cloud.netflix.zuul.filters.route; +import java.util.concurrent.atomic.AtomicInteger; + import com.netflix.zuul.context.RequestContext; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.netflix.ribbon.RibbonClient; @@ -32,8 +34,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; -import java.util.concurrent.atomic.AtomicInteger; - import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @@ -52,6 +52,7 @@ public class EagerLoadOfZuulConfigurationTests { public void clear() { RequestContext.getCurrentContext().clear(); } + @Test public void testEagerLoading() { // Child context FooConfig should have been eagerly instantiated.. @@ -67,15 +68,17 @@ public class EagerLoadOfZuulConfigurationTests { } static class Foo { + private static final AtomicInteger INSTANCE_COUNT = new AtomicInteger(); - public Foo() { + Foo() { INSTANCE_COUNT.incrementAndGet(); } public static int getInstanceCount() { return INSTANCE_COUNT.get(); } + } static class FooConfig { @@ -86,4 +89,5 @@ public class EagerLoadOfZuulConfigurationTests { } } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/LazyLoadOfZuulConfigurationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/LazyLoadOfZuulConfigurationTests.java index 9b3453738..195b84da2 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/LazyLoadOfZuulConfigurationTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/LazyLoadOfZuulConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.filters.route; @@ -51,7 +50,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = RANDOM_PORT, properties = { "zuul.routes.lazyroute.service-id=lazy", "zuul.routes.lazyroute.path=/lazy/**", - "zuul.ribbon.eager-load.enabled=false"}) + "zuul.ribbon.eager-load.enabled=false" }) @DirtiesContext public class LazyLoadOfZuulConfigurationTests { @@ -99,18 +98,21 @@ public class LazyLoadOfZuulConfigurationTests { public String sampleEndpoint() { return "sample"; } + } static class Foo { + private static final AtomicInteger INSTANCE_COUNT = new AtomicInteger(); - public Foo() { + Foo() { INSTANCE_COUNT.incrementAndGet(); } public static int getInstanceCount() { return INSTANCE_COUNT.get(); } + } static class FooConfig { diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/RestClientRibbonCommandTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/RestClientRibbonCommandTests.java index 1f5cd8b95..1a379ea39 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/RestClientRibbonCommandTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/RestClientRibbonCommandTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,18 +12,10 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.filters.route; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.startsWith; -import static org.hamcrest.core.IsNull.nullValue; -import static org.junit.Assert.assertThat; - import java.io.ByteArrayInputStream; import java.io.InputStream; import java.net.URI; @@ -31,16 +23,18 @@ import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collections; +import com.netflix.client.http.HttpRequest; +import com.netflix.client.http.HttpRequest.Verb; import org.junit.Before; import org.junit.Test; + import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; import org.springframework.cloud.netflix.ribbon.support.RibbonRequestCustomizer; import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.StreamUtils; -import com.netflix.client.http.HttpRequest; -import com.netflix.client.http.HttpRequest.Verb; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Spencer Gibb @@ -48,14 +42,15 @@ import com.netflix.client.http.HttpRequest.Verb; public class RestClientRibbonCommandTests { private ZuulProperties zuulProperties; - + @Before - public void setUp() { + public void setUp() { zuulProperties = new ZuulProperties(); } - + /** - * Tests old constructors kept for backwards compatibility with Spring Cloud Sleuth 1.x versions + * Tests old constructors kept for backwards compatibility with Spring Cloud Sleuth + * 1.x versions */ @Test @Deprecated @@ -65,27 +60,29 @@ public class RestClientRibbonCommandTests { headers.add("my-header", "my-value"); LinkedMultiValueMap params = new LinkedMultiValueMap<>(); params.add("myparam", "myparamval"); - RestClientRibbonCommand command = - new RestClientRibbonCommand("cmd", null,Verb.GET ,uri, false, headers, params, null); + RestClientRibbonCommand command = new RestClientRibbonCommand("cmd", null, + Verb.GET, uri, false, headers, params, null); HttpRequest request = command.createRequest(); - assertThat("uri is wrong", request.getUri().toString(), startsWith(uri)); - assertThat("my-header is wrong", request.getHttpHeaders().getFirstValue("my-header"), is(equalTo("my-value"))); - assertThat("myparam is missing", request.getQueryParams().get("myparam").iterator().next(), is(equalTo("myparamval"))); - - command = - new RestClientRibbonCommand("cmd", null, - new RibbonCommandContext("example", "GET", uri, false, headers, params, null), - zuulProperties); + assertThat(request.getUri().toString()).as("uri is wrong").startsWith(uri); + assertThat(request.getHttpHeaders().getFirstValue("my-header")) + .as("my-header is wrong").isEqualTo("my-value"); + assertThat(request.getQueryParams().get("myparam").iterator().next()) + .as("myparam is missing").isEqualTo("myparamval"); + + command = new RestClientRibbonCommand("cmd", null, new RibbonCommandContext( + "example", "GET", uri, false, headers, params, null), zuulProperties); request = command.createRequest(); - assertThat("uri is wrong", request.getUri().toString(), startsWith(uri)); - assertThat("my-header is wrong", request.getHttpHeaders().getFirstValue("my-header"), is(equalTo("my-value"))); - assertThat("myparam is missing", request.getQueryParams().get("myparam").iterator().next(), is(equalTo("myparamval"))); + assertThat(request.getUri().toString()).as("uri is wrong").startsWith(uri); + assertThat(request.getHttpHeaders().getFirstValue("my-header")) + .as("my-header is wrong").isEqualTo("my-value"); + assertThat(request.getQueryParams().get("myparam").iterator().next()) + .as("myparam is missing").isEqualTo("myparamval"); } - + @Test public void testNullEntity() throws Exception { String uri = "http://example.com"; @@ -93,38 +90,45 @@ public class RestClientRibbonCommandTests { headers.add("my-header", "my-value"); LinkedMultiValueMap params = new LinkedMultiValueMap<>(); params.add("myparam", "myparamval"); - RestClientRibbonCommand command = - new RestClientRibbonCommand("cmd", null, - new RibbonCommandContext("example", "GET", uri, false, headers, params, null, new ArrayList()), + RestClientRibbonCommand command = new RestClientRibbonCommand( + "cmd", null, new RibbonCommandContext("example", "GET", uri, false, + headers, params, null, new ArrayList()), zuulProperties); HttpRequest request = command.createRequest(); - assertThat("uri is wrong", request.getUri().toString(), startsWith(uri)); - assertThat("my-header is wrong", request.getHttpHeaders().getFirstValue("my-header"), is(equalTo("my-value"))); - assertThat("myparam is missing", request.getQueryParams().get("myparam").iterator().next(), is(equalTo("myparamval"))); + assertThat(request.getUri().toString()).as("uri is wrong").startsWith(uri); + assertThat(request.getHttpHeaders().getFirstValue("my-header")) + .as("my-header is wrong").isEqualTo("my-value"); + assertThat(request.getQueryParams().get("myparam").iterator().next()) + .as("myparam is missing").isEqualTo("myparamval"); } @Test - // this situation happens, see https://github.com/spring-cloud/spring-cloud-netflix/issues/1042#issuecomment-227723877 + // this situation happens, see + // https://github.com/spring-cloud/spring-cloud-netflix/issues/1042#issuecomment-227723877 public void testEmptyEntityGet() throws Exception { String entityValue = ""; - testEntity(entityValue, new ByteArrayInputStream(entityValue.getBytes()), false, "GET"); + testEntity(entityValue, new ByteArrayInputStream(entityValue.getBytes()), false, + "GET"); } @Test public void testNonEmptyEntityPost() throws Exception { String entityValue = "abcd"; - testEntity(entityValue, new ByteArrayInputStream(entityValue.getBytes()), true, "POST"); + testEntity(entityValue, new ByteArrayInputStream(entityValue.getBytes()), true, + "POST"); } @Test public void testNonEmptyEntityDelete() throws Exception { String entityValue = "abcd"; - testEntity(entityValue, new ByteArrayInputStream(entityValue.getBytes()), true, "DELETE"); + testEntity(entityValue, new ByteArrayInputStream(entityValue.getBytes()), true, + "DELETE"); } - void testEntity(String entityValue, ByteArrayInputStream requestEntity, boolean addContentLengthHeader, String method) throws Exception { + void testEntity(String entityValue, ByteArrayInputStream requestEntity, + boolean addContentLengthHeader, String method) throws Exception { String lengthString = String.valueOf(entityValue.length()); Long length = null; URI uri = URI.create("http://example.com"); @@ -149,27 +153,31 @@ public class RestClientRibbonCommandTests { uri.toString(), false, headers, new LinkedMultiValueMap(), requestEntity, Collections.singletonList(requestCustomizer)); context.setContentLength(length); - RestClientRibbonCommand command = new RestClientRibbonCommand("cmd", null, context, zuulProperties); + RestClientRibbonCommand command = new RestClientRibbonCommand("cmd", null, + context, zuulProperties); HttpRequest request = command.createRequest(); - assertThat("uri is wrong", request.getUri().toString(), startsWith(uri.toString())); + assertThat(request.getUri().toString()).as("uri is wrong") + .startsWith(uri.toString()); if (addContentLengthHeader) { - assertThat("Content-Length is wrong", request.getHttpHeaders().getFirstValue("Content-Length"), - is(equalTo(lengthString))); + assertThat(request.getHttpHeaders().getFirstValue("Content-Length")) + .as("Content-Length is wrong").isEqualTo(lengthString); } - assertThat("from-customizer is wrong", request.getHttpHeaders().getFirstValue("from-customizer"), - is(equalTo("foo"))); - + assertThat(request.getHttpHeaders().getFirstValue("from-customizer")) + .as("from-customizer is wrong").isEqualTo("foo"); if (method.equalsIgnoreCase("DELETE")) { - assertThat("entity is was non-null", request.getEntity(), is(nullValue())); - } else { - assertThat("entity is missing", request.getEntity(), is(notNullValue())); - assertThat("entity is wrong type", InputStream.class.isAssignableFrom(request.getEntity().getClass()), is(true)); + assertThat(request.getEntity()).as("entity is was non-null").isNull(); + } + else { + assertThat(request.getEntity()).as("entity is missing").isNotNull(); + assertThat(InputStream.class.isAssignableFrom(request.getEntity().getClass())) + .as("entity is wrong type").isTrue(); InputStream entity = (InputStream) request.getEntity(); String string = StreamUtils.copyToString(entity, Charset.forName("UTF-8")); - assertThat("content is wrong", string, is(equalTo(entityValue))); + assertThat(string).as("content is wrong").isEqualTo(entityValue); } } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonRoutingFilterLoadBalancerKeyIntegrationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonRoutingFilterLoadBalancerKeyIntegrationTests.java index 620fa1722..65627b9d9 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonRoutingFilterLoadBalancerKeyIntegrationTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonRoutingFilterLoadBalancerKeyIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,11 +12,12 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.filters.route; +import javax.servlet.http.HttpServletRequest; + import com.netflix.loadbalancer.AvailabilityFilteringRule; import com.netflix.loadbalancer.IRule; import com.netflix.loadbalancer.Server; @@ -27,6 +28,7 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -39,16 +41,18 @@ import org.springframework.cloud.netflix.zuul.test.NoSecurityConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; -import org.springframework.http.*; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; -import javax.servlet.http.HttpServletRequest; - -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.LOAD_BALANCER_KEY; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE; @@ -56,9 +60,8 @@ import static org.springframework.cloud.netflix.zuul.filters.support.FilterConst * @author Yongsung Yoon */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = CanaryTestZuulProxyApplication.class, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - value = { "zuul.routes.simple.path: /simple/**" }) +@SpringBootTest(classes = CanaryTestZuulProxyApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, value = { + "zuul.routes.simple.path: /simple/**" }) @DirtiesContext public class RibbonRoutingFilterLoadBalancerKeyIntegrationTests { @@ -81,19 +84,20 @@ public class RibbonRoutingFilterLoadBalancerKeyIntegrationTests { HttpHeaders headers = new HttpHeaders(); headers.set("X-Canary-Test", "true"); - ResponseEntity result = testRestTemplate.exchange("/simple/hello", HttpMethod.GET, - new HttpEntity<>(headers), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("canary", result.getBody()); + ResponseEntity result = testRestTemplate.exchange("/simple/hello", + HttpMethod.GET, new HttpEntity<>(headers), String.class); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("canary"); } @Test public void invokeWithoutUserDefinedCanaryHeader() { HttpHeaders headers = new HttpHeaders(); - ResponseEntity result = testRestTemplate.exchange("/simple/hello", HttpMethod.GET, - new HttpEntity<>(headers), String.class); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, result.getStatusCode()); + ResponseEntity result = testRestTemplate.exchange("/simple/hello", + HttpMethod.GET, new HttpEntity<>(headers), String.class); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); } + } @Configuration @@ -116,14 +120,16 @@ class CanaryTestZuulProxyApplication { public Object run() { RequestContext context = RequestContext.getCurrentContext(); if (checkIfCanaryRequest(context)) { - context.set(LOAD_BALANCER_KEY, "canary"); // set loadBalancerKey for IRule + context.set(LOAD_BALANCER_KEY, "canary"); // set loadBalancerKey for + // IRule } return null; } private boolean checkIfCanaryRequest(RequestContext context) { HttpServletRequest request = context.getRequest(); - String canaryHeader = request.getHeader("X-Canary-Test"); // user defined header + String canaryHeader = request.getHeader("X-Canary-Test"); // user defined + // header if ((canaryHeader != null) && (canaryHeader.equalsIgnoreCase("true"))) { return true; @@ -147,36 +153,43 @@ class CanaryTestZuulProxyApplication { } }; } + } @Configuration class CanaryTestRibbonClientConfiguration { @LocalServerPort - private int port; + private int port; private static Server testCanaryInstance; @Bean public ServerList ribbonServerList() { - return new StaticServerList<>(new Server("normal-routing-notexist-localhost", this.port)); + return new StaticServerList<>( + new Server("normal-routing-notexist-localhost", this.port)); } @Bean public IRule canaryTestRule() { if (testCanaryInstance == null) { - testCanaryInstance = new Server("localhost", port); // use test server as a canary instance + testCanaryInstance = new Server("localhost", port); // use test server as a + // canary instance } return new TestCanaryRule(); } public static class TestCanaryRule extends AvailabilityFilteringRule { + @Override public Server choose(Object key) { if ((key != null) && (key.equals("canary"))) { - return testCanaryInstance; // choose test canary server instead of normal servers. + return testCanaryInstance; // choose test canary server instead of normal + // servers. } return super.choose(key); // normal routing } + } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonRoutingFilterTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonRoutingFilterTests.java index 568fcdb4d..f0ee3fde1 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonRoutingFilterTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonRoutingFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.filters.route; @@ -22,10 +21,13 @@ import java.io.IOException; import java.io.InputStream; import java.util.Collections; +import javax.servlet.http.HttpServletResponse; + import com.netflix.zuul.context.RequestContext; import org.junit.After; import org.junit.Before; import org.junit.Test; + import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; import org.springframework.cloud.netflix.ribbon.support.RibbonRequestCustomizer; import org.springframework.cloud.netflix.zuul.filters.ProxyRequestHelper; @@ -37,8 +39,6 @@ import org.springframework.http.client.ClientHttpResponse; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; -import javax.servlet.http.HttpServletResponse; - import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.LOAD_BALANCER_KEY; @@ -52,6 +52,7 @@ import static org.springframework.cloud.netflix.zuul.filters.support.FilterConst public class RibbonRoutingFilterTests { private RequestContext requestContext; + private RibbonRoutingFilter filter; @Before @@ -115,7 +116,8 @@ public class RibbonRoutingFilterTests { private void setupRibbonRoutingFilter() { RibbonCommandFactory factory = mock(RibbonCommandFactory.class); - filter = new RibbonRoutingFilter(new ProxyRequestHelper(new ZuulProperties()), factory, Collections.emptyList()); + filter = new RibbonRoutingFilter(new ProxyRequestHelper(new ZuulProperties()), + factory, Collections.emptyList()); } private ClientHttpResponse createClientHttpResponseWithNonStatus() { @@ -189,4 +191,5 @@ public class RibbonRoutingFilterTests { } }; } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/SendForwardFilterTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/SendForwardFilterTests.java index f25c953de..6261c4622 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/SendForwardFilterTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/SendForwardFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,6 @@ package org.springframework.cloud.netflix.zuul.filters.route; import javax.servlet.http.HttpServletRequest; import com.netflix.zuul.context.RequestContext; - import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -27,8 +26,7 @@ import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.FORWARD_TO_KEY; /** @@ -50,7 +48,7 @@ public class SendForwardFilterTests { @Test public void runsNormally() { SendForwardFilter filter = createSendForwardFilter(new MockHttpServletRequest()); - assertTrue("shouldFilter returned false", filter.shouldFilter()); + assertThat(filter.shouldFilter()).as("shouldFilter returned false").isTrue(); filter.run(); } @@ -67,8 +65,9 @@ public class SendForwardFilterTests { @Test public void doesNotRunTwice() { SendForwardFilter filter = createSendForwardFilter(new MockHttpServletRequest()); - assertTrue("shouldFilter returned false", filter.shouldFilter()); + assertThat(filter.shouldFilter()).as("shouldFilter returned false").isTrue(); filter.run(); - assertFalse("shouldFilter returned true", filter.shouldFilter()); + assertThat(filter.shouldFilter()).as("shouldFilter returned true").isFalse(); } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/SimpleHostRoutingFilterIntegrationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/SimpleHostRoutingFilterIntegrationTests.java index a4bd92d82..e52ae842f 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/SimpleHostRoutingFilterIntegrationTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/SimpleHostRoutingFilterIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.filters.route; @@ -54,430 +53,314 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Gang Li */ @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = RANDOM_PORT, - properties = {"server.servlet.context-path: /app"}) +@SpringBootTest(webEnvironment = RANDOM_PORT, properties = { + "server.servlet.context-path: /app" }) @DirtiesContext public class SimpleHostRoutingFilterIntegrationTests { @LocalServerPort private int port; -/* - @Autowired - private SimpleHostRoutingFilter filter; - @Before - public void setup() { - CounterFactory.initialize(new EmptyCounterFactory()); - RequestContext.testSetCurrentContext(new RequestContext()); - } - - @After - public void clear() { - CounterFactory.initialize(null); - - RequestContext.testSetCurrentContext(null); - RequestContext.getCurrentContext().clear(); - } - - @Test - public void contentLengthNegativeTest() throws IOException { - contentLengthTest(-1000L); - } - - @Test - public void contentLengthNegativeOneTest() throws IOException { - contentLengthTest(-1L); - } - - @Test - public void contentLengthZeroTest() throws IOException { - contentLengthTest(0L); - } - - @Test - public void contentLengthOneTest() throws IOException { - contentLengthTest(1L); - } - - @Test - public void contentLength1KbTest() throws IOException { - contentLengthTest(1000L); - } - - @Test - public void contentLength1MbTest() throws IOException { - contentLengthTest(1000000L); - } - - @Test - public void contentLength1GbTest() throws IOException { - contentLengthTest(1000000000L); - } - - @Test - public void contentLength2GbTest() throws IOException { - contentLengthTest(2000000000L); - } - - @Test - public void contentLength3GbTest() throws IOException { - contentLengthTest(3000000000L); - } - - @Test - public void contentLength4GbTest() throws IOException { - contentLengthTest(4000000000L); - } - - @Test - public void contentLength5GbTest() throws IOException { - contentLengthTest(5000000000L); - } - - @Test - public void contentLength6GbTest() throws IOException { - contentLengthTest(6000000000L); - } - - @Test - public void contentLengthServlet30WithHeaderNegativeTest() throws IOException { - contentLengthServlet30WithHeaderTest(-1000L); - } - - @Test - public void contentLengthServlet30WithHeaderNegativeOneTest() throws IOException { - contentLengthServlet30WithHeaderTest(-1L); - } - - @Test - public void contentLengthServlet30WithHeaderZeroTest() throws IOException { - contentLengthServlet30WithHeaderTest(0L); - } - - @Test - public void contentLengthServlet30WithHeaderOneTest() throws IOException { - contentLengthServlet30WithHeaderTest(1L); - } - - @Test - public void contentLengthServlet30WithHeader1KbTest() throws IOException { - contentLengthServlet30WithHeaderTest(1000L); - } - - @Test - public void contentLengthServlet30WithHeader1MbTest() throws IOException { - contentLengthServlet30WithHeaderTest(1000000L); - } - - @Test - public void contentLengthServlet30WithHeader1GbTest() throws IOException { - contentLengthServlet30WithHeaderTest(1000000000L); - } - - @Test - public void contentLengthServlet30WithHeader2GbTest() throws IOException { - contentLengthServlet30WithHeaderTest(2000000000L); - } - - @Test - public void contentLengthServlet30WithHeader3GbTest() throws IOException { - contentLengthServlet30WithHeaderTest(3000000000L); - } - - @Test - public void contentLengthServlet30WithHeader4GbTest() throws IOException { - contentLengthServlet30WithHeaderTest(4000000000L); - } - - @Test - public void contentLengthServlet30WithHeader5GbTest() throws IOException { - contentLengthServlet30WithHeaderTest(5000000000L); - } - - @Test - public void contentLengthServlet30WithHeader6GbTest() throws IOException { - contentLengthServlet30WithHeaderTest(6000000000L); - } - - @Test - public void contentLengthServlet30WithInvalidLongHeaderTest() throws IOException { - setupContext(); - MockMultipartHttpServletRequest request = getMockedReqest(-1L); - request.addHeader(HttpHeaders.CONTENT_LENGTH, "InvalidLong"); - contentLengthTest(-1L, getServlet30Filter(), request); - } - - @Test - public void contentLengthServlet30WithoutHeaderNegativeTest() throws IOException { - contentLengthServlet30WithoutHeaderTest(-1000L); - } - - @Test - public void contentLengthServlet30WithoutHeaderNegativeOneTest() throws IOException { - contentLengthServlet30WithoutHeaderTest(-1L); - } - - @Test - public void contentLengthServlet30WithoutHeaderZeroTest() throws IOException { - contentLengthServlet30WithoutHeaderTest(0L); - } - - @Test - public void contentLengthServlet30WithoutHeaderOneTest() throws IOException { - contentLengthServlet30WithoutHeaderTest(1L); - } - - @Test - public void contentLengthServlet30WithoutHeader1KbTest() throws IOException { - contentLengthServlet30WithoutHeaderTest(1000L); - } - - @Test - public void contentLengthServlet30WithoutHeader1MbTest() throws IOException { - contentLengthServlet30WithoutHeaderTest(1000000L); - } - - @Test - public void contentLengthServlet30WithoutHeader1GbTest() throws IOException { - contentLengthServlet30WithoutHeaderTest(1000000000L); - } - - @Test - public void contentLengthServlet30WithoutHeader2GbTest() throws IOException { - contentLengthServlet30WithoutHeaderTest(2000000000L); - } - - @Test - public void contentLengthServlet30WithoutHeader3GbTest() throws IOException { - contentLengthServlet30WithoutHeaderTest(3000000000L); - } - - @Test - public void contentLengthServlet30WithoutHeader4GbTest() throws IOException { - contentLengthServlet30WithoutHeaderTest(4000000000L); - } - - @Test - public void contentLengthServlet30WithoutHeader5GbTest() throws IOException { - contentLengthServlet30WithoutHeaderTest(5000000000L); - } - - @Test - public void contentLengthServlet30WithoutHeader6GbTest() throws IOException { - contentLengthServlet30WithoutHeaderTest(6000000000L); - } - - public void contentLengthTest(Long contentLength) throws IOException { - setupContext(); - - contentLengthTest(contentLength, getFilter(), getMockedReqest(contentLength)); - } - - public void contentLengthServlet30WithHeaderTest(Long contentLength) throws IOException { - setupContext(); - MockMultipartHttpServletRequest request = getMockedReqest(contentLength); - request.addHeader(HttpHeaders.CONTENT_LENGTH, contentLength); - contentLengthTest(contentLength, getServlet30Filter(), request); - } - - public void contentLengthServlet30WithoutHeaderTest(Long contentLength) throws IOException { - setupContext(); - - //Although contentLength.intValue is not always equals to contentLength, that's the expected result when calling - // request.getContentLength() from servlet 3.0 implementation. - contentLengthTest(Long.parseLong("" + contentLength.intValue()), getServlet30Filter(), getMockedReqest(contentLength)); - } - - public MockMultipartHttpServletRequest getMockedReqest(final Long contentLength) throws IOException { - - MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest() { - @Override - public int getContentLength() { - return contentLength.intValue(); - } - - @Override - public long getContentLengthLong() { - return contentLength; - } - }; - - return request; - } - - public void contentLengthTest(Long expectedContentLength, SimpleHostRoutingFilter filter, MockMultipartHttpServletRequest request) throws IOException { - byte[] data = "poprqwueproqiwuerpoqweiurpo".getBytes(); - MockMultipartFile file = new MockMultipartFile("test.zip", "test.zip", - "application/zip", data); - String boundary = "q1w2e3r4t5y6u7i8o9"; - request.setContentType("multipart/form-data; boundary=" + boundary); - request.setContent( - createFileContent(data, boundary, "application/zip", "test.zip")); - request.addFile(file); - request.setMethod("POST"); - request.setParameter("variant", "php"); - request.setParameter("os", "mac"); - request.setParameter("version", "3.4"); - request.setRequestURI("/app/echo"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - RequestContext.getCurrentContext().setRequest(request); - RequestContext.getCurrentContext().setResponse(response); - URL url = new URL("http://localhost:" + this.port); - RequestContext.getCurrentContext().set("routeHost", url); - filter.run(); - - CloseableHttpResponse httpResponse = (CloseableHttpResponse) RequestContext.getCurrentContext() - .get("zuulResponse"); - assertThat(httpResponse.getStatusLine().getStatusCode(), equalTo(200)); - InputStream zuulResponse = httpResponse.getEntity().getContent(); - assertThat(zuulResponse, not(instanceOf(EmptyInputStream.class))); - String responseString = IOUtils.toString(new GZIPInputStream( - zuulResponse)); - assertTrue(!responseString.isEmpty()); - if (expectedContentLength < 0) { - assertThat(responseString, containsString("\"" - + HttpHeaders.TRANSFER_ENCODING.toLowerCase() + "\":\"chunked\"")); - assertThat(responseString, - not(containsString(HttpHeaders.CONTENT_LENGTH.toLowerCase()))); - } - else { - assertThat(responseString, - containsString("\"" + HttpHeaders.CONTENT_LENGTH.toLowerCase() - + "\":\"" + expectedContentLength + "\"")); - } - } - - public byte[] createFileContent(byte[] data, String boundary, String contentType, - String fileName) { - String start = "--" + boundary - + "\r\n Content-Disposition: form-data; name=\"file\"; filename=\"" - + fileName + "\"\r\n" + "Content-type: " + contentType + "\r\n\r\n"; - ; - - String end = "\r\n--" + boundary + "--"; // correction suggested @butfly - return ArrayUtils.addAll(start.getBytes(), - ArrayUtils.addAll(data, end.getBytes())); - } - - @Test - public void httpClientDoesNotDecompressEncodedData() throws Exception { - setupContext(); - InputStreamEntity inputStreamEntity = new InputStreamEntity(new ByteArrayInputStream(new byte[]{1})); - HttpRequest httpRequest = getFilter().buildHttpRequest("GET", "/app/compressed/get/1", inputStreamEntity, - new LinkedMultiValueMap<>(), new LinkedMultiValueMap<>(), new MockHttpServletRequest()); - - CloseableHttpResponse response = getFilter().newClient().execute(new HttpHost("localhost", this.port), httpRequest); - assertEquals(200, response.getStatusLine().getStatusCode()); - byte[] responseBytes = copyToByteArray(response.getEntity().getContent()); - assertTrue(Arrays.equals(GZIPCompression.compress("Get 1"), responseBytes)); - } - - @Test - public void httpClientPreservesUnencodedData() throws Exception { - setupContext(); - InputStreamEntity inputStreamEntity = new InputStreamEntity(new ByteArrayInputStream(new byte[]{1})); - HttpRequest httpRequest = getFilter().buildHttpRequest("GET", "/app/get/1", inputStreamEntity, - new LinkedMultiValueMap<>(), new LinkedMultiValueMap<>(), new MockHttpServletRequest()); - - CloseableHttpResponse response = getFilter().newClient().execute(new HttpHost("localhost", this.port), httpRequest); - assertEquals(200, response.getStatusLine().getStatusCode()); - String responseString = copyToString(response.getEntity().getContent(), Charset.forName("UTF-8")); - assertTrue("Get 1".equals(responseString)); - } - - @Test - public void redirectTest() throws IOException { - setupContext(); - InputStreamEntity inputStreamEntity = new InputStreamEntity(new ByteArrayInputStream(new byte[]{})); - HttpRequest httpRequest = getFilter().buildHttpRequest("GET", "/app/redirect", inputStreamEntity, - new LinkedMultiValueMap<>(), new LinkedMultiValueMap<>(), new MockHttpServletRequest()); - - CloseableHttpResponse response = getFilter().newClient().execute(new HttpHost("localhost", this.port), httpRequest); - assertEquals(302, response.getStatusLine().getStatusCode()); - String responseString = copyToString(response.getEntity().getContent(), Charset.forName("UTF-8")); - assertTrue(response.getLastHeader("Location").getValue().contains("/app/get/5")); - } - - @Test(expected = ZuulRuntimeException.class) - public void run() throws Exception { - setupContext(); - MockHttpServletRequest request = new MockHttpServletRequest("POST", "/"); - request.setContent("{1}".getBytes()); - request.addHeader("singleName", "singleValue"); - request.addHeader("multiName", "multiValue1"); - request.addHeader("multiName", "multiValue2"); - RequestContext.getCurrentContext().setRequest(request); - URL url = new URL("http://localhost:8080"); - RequestContext.getCurrentContext().set("routeHost", url); - getFilter().run(); - } - - private void setupContext() { - } - - private SimpleHostRoutingFilter getFilter() { - return this.filter; - } - - private SimpleHostRoutingFilter getServlet30Filter() { - SimpleHostRoutingFilter filter = getFilter(); - filter.setUseServlet31(false); - return filter; - } -*/ - /*@Configuration - @EnableConfigurationProperties - protected static class TestConfiguration { - @Bean - ZuulProperties zuulProperties() { - return new ZuulProperties(); - } - - @Bean - ApacheHttpClientFactory clientFactory() {return new DefaultApacheHttpClientFactory(HttpClientBuilder.create()); } - - @Bean - ApacheHttpClientConnectionManagerFactory connectionManagerFactory() { return new DefaultApacheHttpClientConnectionManagerFactory(); } - - @Bean - SimpleHostRoutingFilter simpleHostRoutingFilter(ZuulProperties zuulProperties, - ApacheHttpClientConnectionManagerFactory connectionManagerFactory, - ApacheHttpClientFactory clientFactory) { - return new SimpleHostRoutingFilter(new ProxyRequestHelper(), zuulProperties, connectionManagerFactory, clientFactory); - } - }*/ + /* + * @Autowired private SimpleHostRoutingFilter filter; + * + * @Before public void setup() { CounterFactory.initialize(new EmptyCounterFactory()); + * RequestContext.testSetCurrentContext(new RequestContext()); } + * + * @After public void clear() { CounterFactory.initialize(null); + * + * RequestContext.testSetCurrentContext(null); + * RequestContext.getCurrentContext().clear(); } + * + * @Test public void contentLengthNegativeTest() throws IOException { + * contentLengthTest(-1000L); } + * + * @Test public void contentLengthNegativeOneTest() throws IOException { + * contentLengthTest(-1L); } + * + * @Test public void contentLengthZeroTest() throws IOException { + * contentLengthTest(0L); } + * + * @Test public void contentLengthOneTest() throws IOException { + * contentLengthTest(1L); } + * + * @Test public void contentLength1KbTest() throws IOException { + * contentLengthTest(1000L); } + * + * @Test public void contentLength1MbTest() throws IOException { + * contentLengthTest(1000000L); } + * + * @Test public void contentLength1GbTest() throws IOException { + * contentLengthTest(1000000000L); } + * + * @Test public void contentLength2GbTest() throws IOException { + * contentLengthTest(2000000000L); } + * + * @Test public void contentLength3GbTest() throws IOException { + * contentLengthTest(3000000000L); } + * + * @Test public void contentLength4GbTest() throws IOException { + * contentLengthTest(4000000000L); } + * + * @Test public void contentLength5GbTest() throws IOException { + * contentLengthTest(5000000000L); } + * + * @Test public void contentLength6GbTest() throws IOException { + * contentLengthTest(6000000000L); } + * + * @Test public void contentLengthServlet30WithHeaderNegativeTest() throws IOException + * { contentLengthServlet30WithHeaderTest(-1000L); } + * + * @Test public void contentLengthServlet30WithHeaderNegativeOneTest() throws + * IOException { contentLengthServlet30WithHeaderTest(-1L); } + * + * @Test public void contentLengthServlet30WithHeaderZeroTest() throws IOException { + * contentLengthServlet30WithHeaderTest(0L); } + * + * @Test public void contentLengthServlet30WithHeaderOneTest() throws IOException { + * contentLengthServlet30WithHeaderTest(1L); } + * + * @Test public void contentLengthServlet30WithHeader1KbTest() throws IOException { + * contentLengthServlet30WithHeaderTest(1000L); } + * + * @Test public void contentLengthServlet30WithHeader1MbTest() throws IOException { + * contentLengthServlet30WithHeaderTest(1000000L); } + * + * @Test public void contentLengthServlet30WithHeader1GbTest() throws IOException { + * contentLengthServlet30WithHeaderTest(1000000000L); } + * + * @Test public void contentLengthServlet30WithHeader2GbTest() throws IOException { + * contentLengthServlet30WithHeaderTest(2000000000L); } + * + * @Test public void contentLengthServlet30WithHeader3GbTest() throws IOException { + * contentLengthServlet30WithHeaderTest(3000000000L); } + * + * @Test public void contentLengthServlet30WithHeader4GbTest() throws IOException { + * contentLengthServlet30WithHeaderTest(4000000000L); } + * + * @Test public void contentLengthServlet30WithHeader5GbTest() throws IOException { + * contentLengthServlet30WithHeaderTest(5000000000L); } + * + * @Test public void contentLengthServlet30WithHeader6GbTest() throws IOException { + * contentLengthServlet30WithHeaderTest(6000000000L); } + * + * @Test public void contentLengthServlet30WithInvalidLongHeaderTest() throws + * IOException { setupContext(); MockMultipartHttpServletRequest request = + * getMockedReqest(-1L); request.addHeader(HttpHeaders.CONTENT_LENGTH, "InvalidLong"); + * contentLengthTest(-1L, getServlet30Filter(), request); } + * + * @Test public void contentLengthServlet30WithoutHeaderNegativeTest() throws + * IOException { contentLengthServlet30WithoutHeaderTest(-1000L); } + * + * @Test public void contentLengthServlet30WithoutHeaderNegativeOneTest() throws + * IOException { contentLengthServlet30WithoutHeaderTest(-1L); } + * + * @Test public void contentLengthServlet30WithoutHeaderZeroTest() throws IOException + * { contentLengthServlet30WithoutHeaderTest(0L); } + * + * @Test public void contentLengthServlet30WithoutHeaderOneTest() throws IOException { + * contentLengthServlet30WithoutHeaderTest(1L); } + * + * @Test public void contentLengthServlet30WithoutHeader1KbTest() throws IOException { + * contentLengthServlet30WithoutHeaderTest(1000L); } + * + * @Test public void contentLengthServlet30WithoutHeader1MbTest() throws IOException { + * contentLengthServlet30WithoutHeaderTest(1000000L); } + * + * @Test public void contentLengthServlet30WithoutHeader1GbTest() throws IOException { + * contentLengthServlet30WithoutHeaderTest(1000000000L); } + * + * @Test public void contentLengthServlet30WithoutHeader2GbTest() throws IOException { + * contentLengthServlet30WithoutHeaderTest(2000000000L); } + * + * @Test public void contentLengthServlet30WithoutHeader3GbTest() throws IOException { + * contentLengthServlet30WithoutHeaderTest(3000000000L); } + * + * @Test public void contentLengthServlet30WithoutHeader4GbTest() throws IOException { + * contentLengthServlet30WithoutHeaderTest(4000000000L); } + * + * @Test public void contentLengthServlet30WithoutHeader5GbTest() throws IOException { + * contentLengthServlet30WithoutHeaderTest(5000000000L); } + * + * @Test public void contentLengthServlet30WithoutHeader6GbTest() throws IOException { + * contentLengthServlet30WithoutHeaderTest(6000000000L); } + * + * public void contentLengthTest(Long contentLength) throws IOException { + * setupContext(); + * + * contentLengthTest(contentLength, getFilter(), getMockedReqest(contentLength)); } + * + * public void contentLengthServlet30WithHeaderTest(Long contentLength) throws + * IOException { setupContext(); MockMultipartHttpServletRequest request = + * getMockedReqest(contentLength); request.addHeader(HttpHeaders.CONTENT_LENGTH, + * contentLength); contentLengthTest(contentLength, getServlet30Filter(), request); } + * + * public void contentLengthServlet30WithoutHeaderTest(Long contentLength) throws + * IOException { setupContext(); + * + * //Although contentLength.intValue is not always equals to contentLength, that's the + * expected result when calling // request.getContentLength() from servlet 3.0 + * implementation. contentLengthTest(Long.parseLong("" + contentLength.intValue()), + * getServlet30Filter(), getMockedReqest(contentLength)); } + * + * public MockMultipartHttpServletRequest getMockedReqest(final Long contentLength) + * throws IOException { + * + * MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest() { + * + * @Override public int getContentLength() { return contentLength.intValue(); } + * + * @Override public long getContentLengthLong() { return contentLength; } }; + * + * return request; } + * + * public void contentLengthTest(Long expectedContentLength, SimpleHostRoutingFilter + * filter, MockMultipartHttpServletRequest request) throws IOException { byte[] data = + * "poprqwueproqiwuerpoqweiurpo".getBytes(); MockMultipartFile file = new + * MockMultipartFile("test.zip", "test.zip", "application/zip", data); String boundary + * = "q1w2e3r4t5y6u7i8o9"; request.setContentType("multipart/form-data; boundary=" + + * boundary); request.setContent( createFileContent(data, boundary, "application/zip", + * "test.zip")); request.addFile(file); request.setMethod("POST"); + * request.setParameter("variant", "php"); request.setParameter("os", "mac"); + * request.setParameter("version", "3.4"); request.setRequestURI("/app/echo"); + * + * MockHttpServletResponse response = new MockHttpServletResponse(); + * RequestContext.getCurrentContext().setRequest(request); + * RequestContext.getCurrentContext().setResponse(response); URL url = new + * URL("http://localhost:" + this.port); + * RequestContext.getCurrentContext().set("routeHost", url); filter.run(); + * + * CloseableHttpResponse httpResponse = (CloseableHttpResponse) + * RequestContext.getCurrentContext() .get("zuulResponse"); + * assertThat(httpResponse.getStatusLine().getStatusCode(), equalTo(200)); InputStream + * zuulResponse = httpResponse.getEntity().getContent(); assertThat(zuulResponse, + * not(instanceOf(EmptyInputStream.class))); String responseString = + * IOUtils.toString(new GZIPInputStream( zuulResponse)); + * assertTrue(!responseString.isEmpty()); if (expectedContentLength < 0) { + * assertThat(responseString, containsString("\"" + + * HttpHeaders.TRANSFER_ENCODING.toLowerCase() + "\":\"chunked\"")); + * assertThat(responseString, + * not(containsString(HttpHeaders.CONTENT_LENGTH.toLowerCase()))); } else { + * assertThat(responseString, containsString("\"" + + * HttpHeaders.CONTENT_LENGTH.toLowerCase() + "\":\"" + expectedContentLength + + * "\"")); } } + * + * public byte[] createFileContent(byte[] data, String boundary, String contentType, + * String fileName) { String start = "--" + boundary + + * "\r\n Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + + * "\"\r\n" + "Content-type: " + contentType + "\r\n\r\n"; ; + * + * String end = "\r\n--" + boundary + "--"; // correction suggested @butfly return + * ArrayUtils.addAll(start.getBytes(), ArrayUtils.addAll(data, end.getBytes())); } + * + * @Test public void httpClientDoesNotDecompressEncodedData() throws Exception { + * setupContext(); InputStreamEntity inputStreamEntity = new InputStreamEntity(new + * ByteArrayInputStream(new byte[]{1})); HttpRequest httpRequest = + * getFilter().buildHttpRequest("GET", "/app/compressed/get/1", inputStreamEntity, new + * LinkedMultiValueMap<>(), new LinkedMultiValueMap<>(), new + * MockHttpServletRequest()); + * + * CloseableHttpResponse response = getFilter().newClient().execute(new + * HttpHost("localhost", this.port), httpRequest); assertEquals(200, + * response.getStatusLine().getStatusCode()); byte[] responseBytes = + * copyToByteArray(response.getEntity().getContent()); + * assertTrue(Arrays.equals(GZIPCompression.compress("Get 1"), responseBytes)); } + * + * @Test public void httpClientPreservesUnencodedData() throws Exception { + * setupContext(); InputStreamEntity inputStreamEntity = new InputStreamEntity(new + * ByteArrayInputStream(new byte[]{1})); HttpRequest httpRequest = + * getFilter().buildHttpRequest("GET", "/app/get/1", inputStreamEntity, new + * LinkedMultiValueMap<>(), new LinkedMultiValueMap<>(), new + * MockHttpServletRequest()); + * + * CloseableHttpResponse response = getFilter().newClient().execute(new + * HttpHost("localhost", this.port), httpRequest); assertEquals(200, + * response.getStatusLine().getStatusCode()); String responseString = + * copyToString(response.getEntity().getContent(), Charset.forName("UTF-8")); + * assertTrue("Get 1".equals(responseString)); } + * + * @Test public void redirectTest() throws IOException { setupContext(); + * InputStreamEntity inputStreamEntity = new InputStreamEntity(new + * ByteArrayInputStream(new byte[]{})); HttpRequest httpRequest = + * getFilter().buildHttpRequest("GET", "/app/redirect", inputStreamEntity, new + * LinkedMultiValueMap<>(), new LinkedMultiValueMap<>(), new + * MockHttpServletRequest()); + * + * CloseableHttpResponse response = getFilter().newClient().execute(new + * HttpHost("localhost", this.port), httpRequest); assertEquals(302, + * response.getStatusLine().getStatusCode()); String responseString = + * copyToString(response.getEntity().getContent(), Charset.forName("UTF-8")); + * assertTrue(response.getLastHeader("Location").getValue().contains("/app/get/5")); } + * + * @Test(expected = ZuulRuntimeException.class) public void run() throws Exception { + * setupContext(); MockHttpServletRequest request = new MockHttpServletRequest("POST", + * "/"); request.setContent("{1}".getBytes()); request.addHeader("singleName", + * "singleValue"); request.addHeader("multiName", "multiValue1"); + * request.addHeader("multiName", "multiValue2"); + * RequestContext.getCurrentContext().setRequest(request); URL url = new + * URL("http://localhost:8080"); RequestContext.getCurrentContext().set("routeHost", + * url); getFilter().run(); } + * + * private void setupContext() { } + * + * private SimpleHostRoutingFilter getFilter() { return this.filter; } + * + * private SimpleHostRoutingFilter getServlet30Filter() { SimpleHostRoutingFilter + * filter = getFilter(); filter.setUseServlet31(false); return filter; } + */ + /* + * @Configuration + * + * @EnableConfigurationProperties protected static class TestConfiguration { + * + * @Bean ZuulProperties zuulProperties() { return new ZuulProperties(); } + * + * @Bean ApacheHttpClientFactory clientFactory() {return new + * DefaultApacheHttpClientFactory(HttpClientBuilder.create()); } + * + * @Bean ApacheHttpClientConnectionManagerFactory connectionManagerFactory() { return + * new DefaultApacheHttpClientConnectionManagerFactory(); } + * + * @Bean SimpleHostRoutingFilter simpleHostRoutingFilter(ZuulProperties + * zuulProperties, ApacheHttpClientConnectionManagerFactory connectionManagerFactory, + * ApacheHttpClientFactory clientFactory) { return new SimpleHostRoutingFilter(new + * ProxyRequestHelper(), zuulProperties, connectionManagerFactory, clientFactory); } } + */ @Test public void test() { } - @SpringBootConfiguration + @SpringBootConfiguration @EnableAutoConfiguration - @RestController + @RestController @Import(NoSecurityConfiguration.class) - static class SampleApplication { + static class SampleApplication { - @RequestMapping(value = "/compressed/get/{id}", method = RequestMethod.GET) - public byte[] getCompressed(@PathVariable String id, HttpServletResponse response) throws IOException { - response.setHeader("content-encoding", "gzip"); - return GZIPCompression.compress("Get " + id); - } + @RequestMapping(value = "/compressed/get/{id}", method = RequestMethod.GET) + public byte[] getCompressed(@PathVariable String id, HttpServletResponse response) + throws IOException { + response.setHeader("content-encoding", "gzip"); + return GZIPCompression.compress("Get " + id); + } - @RequestMapping(value = "/get/{id}", method = RequestMethod.GET) - public String getString(@PathVariable String id, HttpServletResponse response) throws IOException { - return "Get " + id; - } + @RequestMapping(value = "/get/{id}", method = RequestMethod.GET) + public String getString(@PathVariable String id, HttpServletResponse response) + throws IOException { + return "Get " + id; + } - @RequestMapping(value = "/redirect", method = RequestMethod.GET) - public String redirect(HttpServletResponse response) throws IOException { - response.sendRedirect("/app/get/5"); - return null; - } + @RequestMapping(value = "/redirect", method = RequestMethod.GET) + public String redirect(HttpServletResponse response) throws IOException { + response.sendRedirect("/app/get/5"); + return null; + } - @RequestMapping(value = "/echo") - public Map echoRequestAttributes(@RequestHeader HttpHeaders httpHeaders, HttpServletRequest request) throws IOException { + @RequestMapping("/echo") + public Map echoRequestAttributes( + @RequestHeader HttpHeaders httpHeaders, HttpServletRequest request) + throws IOException { Map result = new HashMap<>(); result.put("headers", httpHeaders.toSingleValueMap()); @@ -486,23 +369,25 @@ public class SimpleHostRoutingFilterIntegrationTests { @Bean MultipartConfigElement multipartConfigElement() { - long maxSize = 10l * 1024 * 1024 * 1024; + long maxSize = 10L * 1024 * 1024 * 1024; return new MultipartConfigElement("", maxSize, maxSize, 0); } - } - static class GZIPCompression { + } - public static byte[] compress(final String str) throws IOException { - if ((str == null) || (str.length() == 0)) { - return null; - } - ByteArrayOutputStream obj = new ByteArrayOutputStream(); - GZIPOutputStream gzip = new GZIPOutputStream(obj); - gzip.write(str.getBytes("UTF-8")); - gzip.close(); - return obj.toByteArray(); - } - } + static class GZIPCompression { + + public static byte[] compress(final String str) throws IOException { + if ((str == null) || (str.length() == 0)) { + return null; + } + ByteArrayOutputStream obj = new ByteArrayOutputStream(); + GZIPOutputStream gzip = new GZIPOutputStream(obj); + gzip.write(str.getBytes("UTF-8")); + gzip.close(); + return obj.toByteArray(); + } + + } } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/SimpleHostRoutingFilterTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/SimpleHostRoutingFilterTests.java index 276f85a2b..476fa613a 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/SimpleHostRoutingFilterTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/SimpleHostRoutingFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.filters.route; @@ -60,9 +59,7 @@ import org.springframework.test.util.ReflectionTestUtils; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.ReflectionUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.util.StreamUtils.copyToByteArray; /** @@ -93,16 +90,18 @@ public class SimpleHostRoutingFilterTests { @Test public void timeoutPropertiesAreApplied() { - TestPropertyValues.of("zuul.host.socket-timeout-millis=11000", - "zuul.host.connect-timeout-millis=2100", "zuul.host.connection-request-timeout-millis=2500") + TestPropertyValues + .of("zuul.host.socket-timeout-millis=11000", + "zuul.host.connect-timeout-millis=2100", + "zuul.host.connection-request-timeout-millis=2500") .applyTo(this.context); setupContext(); CloseableHttpClient httpClient = getFilter().newClient(); Assertions.assertThat(httpClient).isInstanceOf(Configurable.class); RequestConfig config = ((Configurable) httpClient).getConfig(); - assertEquals(11000, config.getSocketTimeout()); - assertEquals(2100, config.getConnectTimeout()); - assertEquals(2500, config.getConnectionRequestTimeout()); + assertThat(config.getSocketTimeout()).isEqualTo(11000); + assertThat(config.getConnectTimeout()).isEqualTo(2100); + assertThat(config.getConnectionRequestTimeout()).isEqualTo(2500); } @Test @@ -111,14 +110,15 @@ public class SimpleHostRoutingFilterTests { "zuul.host.maxPerRouteConnections=10", "zuul.host.timeToLive=5", "zuul.host.timeUnit=SECONDS").applyTo(this.context); setupContext(); - PoolingHttpClientConnectionManager connMgr = (PoolingHttpClientConnectionManager) getFilter().getConnectionManager(); - assertEquals(100, connMgr.getMaxTotal()); - assertEquals(10, connMgr.getDefaultMaxPerRoute()); + PoolingHttpClientConnectionManager connMgr = (PoolingHttpClientConnectionManager) getFilter() + .getConnectionManager(); + assertThat(connMgr.getMaxTotal()).isEqualTo(100); + assertThat(connMgr.getDefaultMaxPerRoute()).isEqualTo(10); Object pool = getField(connMgr, "pool"); Long timeToLive = getField(pool, "timeToLive"); TimeUnit timeUnit = getField(pool, "tunit"); - assertEquals(new Long(5), timeToLive); - assertEquals(TimeUnit.SECONDS, timeUnit); + assertThat(timeToLive).isEqualTo(new Long(5)); + assertThat(timeUnit).isEqualTo(TimeUnit.SECONDS); } protected T getField(Object target, String name) { @@ -131,48 +131,54 @@ public class SimpleHostRoutingFilterTests { @Test public void validateSslHostnamesByDefault() { setupContext(); - assertTrue("Hostname verification should be enabled by default", - getFilter().isSslHostnameValidationEnabled()); + assertThat(getFilter().isSslHostnameValidationEnabled()) + .as("Hostname verification should be enabled by default").isTrue(); } @Test public void validationOfSslHostnamesCanBeDisabledViaProperty() { - TestPropertyValues.of("zuul.sslHostnameValidationEnabled=false").applyTo(this.context); + TestPropertyValues.of("zuul.sslHostnameValidationEnabled=false") + .applyTo(this.context); setupContext(); - assertFalse("Hostname verification should be disabled via property", - getFilter().isSslHostnameValidationEnabled()); + assertThat(getFilter().isSslHostnameValidationEnabled()) + .as("Hostname verification should be disabled via property").isFalse(); } @Test public void defaultPropertiesAreApplied() { setupContext(); - PoolingHttpClientConnectionManager connMgr = (PoolingHttpClientConnectionManager) getFilter().getConnectionManager(); + PoolingHttpClientConnectionManager connMgr = (PoolingHttpClientConnectionManager) getFilter() + .getConnectionManager(); - assertEquals(200, connMgr.getMaxTotal()); - assertEquals(20, connMgr.getDefaultMaxPerRoute()); + assertThat(connMgr.getMaxTotal()).isEqualTo(200); + assertThat(connMgr.getDefaultMaxPerRoute()).isEqualTo(20); } @Test public void deleteRequestBuiltWithBody() { setupContext(); - InputStreamEntity inputStreamEntity = new InputStreamEntity(new ByteArrayInputStream(new byte[]{1})); - HttpRequest httpRequest = getFilter().buildHttpRequest("DELETE", "uri", inputStreamEntity, - new LinkedMultiValueMap<>(), new LinkedMultiValueMap<>(), new MockHttpServletRequest()); + InputStreamEntity inputStreamEntity = new InputStreamEntity( + new ByteArrayInputStream(new byte[] { 1 })); + HttpRequest httpRequest = getFilter().buildHttpRequest("DELETE", "uri", + inputStreamEntity, new LinkedMultiValueMap<>(), + new LinkedMultiValueMap<>(), new MockHttpServletRequest()); - assertTrue(httpRequest instanceof HttpEntityEnclosingRequest); + assertThat(httpRequest instanceof HttpEntityEnclosingRequest).isTrue(); HttpEntityEnclosingRequest httpEntityEnclosingRequest = (HttpEntityEnclosingRequest) httpRequest; - assertTrue(httpEntityEnclosingRequest.getEntity() != null); + assertThat(httpEntityEnclosingRequest.getEntity() != null).isTrue(); } - @Test public void zuulHostKeysUpdateHttpClient() { setupContext(); SimpleHostRoutingFilter filter = getFilter(); - CloseableHttpClient httpClient = (CloseableHttpClient) ReflectionTestUtils.getField(filter, "httpClient"); - EnvironmentChangeEvent event = new EnvironmentChangeEvent(Collections.singleton("zuul.host.mykey")); + CloseableHttpClient httpClient = (CloseableHttpClient) ReflectionTestUtils + .getField(filter, "httpClient"); + EnvironmentChangeEvent event = new EnvironmentChangeEvent( + Collections.singleton("zuul.host.mykey")); filter.onPropertyChange(event); - CloseableHttpClient newhttpClient = (CloseableHttpClient) ReflectionTestUtils.getField(filter, "httpClient"); + CloseableHttpClient newhttpClient = (CloseableHttpClient) ReflectionTestUtils + .getField(filter, "httpClient"); Assertions.assertThat(httpClient).isNotEqualTo(newhttpClient); } @@ -186,62 +192,70 @@ public class SimpleHostRoutingFilterTests { request.addHeader("multiName", "multiValue2"); RequestContext.getCurrentContext().setRequest(request); InputStream inputStream = getFilter().getRequestBody(request); - assertTrue(Arrays.equals("{1}".getBytes(), copyToByteArray(inputStream))); + assertThat(Arrays.equals("{1}".getBytes(), copyToByteArray(inputStream))) + .isTrue(); } @Test public void putRequestBuiltWithBody() { setupContext(); - InputStreamEntity inputStreamEntity = new InputStreamEntity(new ByteArrayInputStream(new byte[]{1})); - HttpRequest httpRequest = getFilter().buildHttpRequest("PUT", "uri", inputStreamEntity, - new LinkedMultiValueMap<>(), new LinkedMultiValueMap<>(), new MockHttpServletRequest()); + InputStreamEntity inputStreamEntity = new InputStreamEntity( + new ByteArrayInputStream(new byte[] { 1 })); + HttpRequest httpRequest = getFilter().buildHttpRequest("PUT", "uri", + inputStreamEntity, new LinkedMultiValueMap<>(), + new LinkedMultiValueMap<>(), new MockHttpServletRequest()); - assertTrue(httpRequest instanceof HttpEntityEnclosingRequest); + assertThat(httpRequest instanceof HttpEntityEnclosingRequest).isTrue(); HttpEntityEnclosingRequest httpEntityEnclosingRequest = (HttpEntityEnclosingRequest) httpRequest; - assertTrue(httpEntityEnclosingRequest.getEntity() != null); + assertThat(httpEntityEnclosingRequest.getEntity() != null).isTrue(); } @Test public void postRequestBuiltWithBody() { setupContext(); - InputStreamEntity inputStreamEntity = new InputStreamEntity(new ByteArrayInputStream(new byte[]{1})); - HttpRequest httpRequest = getFilter().buildHttpRequest("POST", "uri", inputStreamEntity, - new LinkedMultiValueMap<>(), new LinkedMultiValueMap<>(), new MockHttpServletRequest()); + InputStreamEntity inputStreamEntity = new InputStreamEntity( + new ByteArrayInputStream(new byte[] { 1 })); + HttpRequest httpRequest = getFilter().buildHttpRequest("POST", "uri", + inputStreamEntity, new LinkedMultiValueMap<>(), + new LinkedMultiValueMap<>(), new MockHttpServletRequest()); - assertTrue(httpRequest instanceof HttpEntityEnclosingRequest); + assertThat(httpRequest instanceof HttpEntityEnclosingRequest).isTrue(); HttpEntityEnclosingRequest httpEntityEnclosingRequest = (HttpEntityEnclosingRequest) httpRequest; - assertTrue(httpEntityEnclosingRequest.getEntity() != null); + assertThat(httpEntityEnclosingRequest.getEntity() != null).isTrue(); } @Test public void pathRequestBuiltWithBody() { setupContext(); - InputStreamEntity inputStreamEntity = new InputStreamEntity(new ByteArrayInputStream(new byte[]{1})); - HttpRequest httpRequest = getFilter().buildHttpRequest("PATCH", "uri", inputStreamEntity, - new LinkedMultiValueMap<>(), new LinkedMultiValueMap<>(), new MockHttpServletRequest()); + InputStreamEntity inputStreamEntity = new InputStreamEntity( + new ByteArrayInputStream(new byte[] { 1 })); + HttpRequest httpRequest = getFilter().buildHttpRequest("PATCH", "uri", + inputStreamEntity, new LinkedMultiValueMap<>(), + new LinkedMultiValueMap<>(), new MockHttpServletRequest()); HttpPatch basicHttpRequest = (HttpPatch) httpRequest; - assertTrue(basicHttpRequest.getEntity() != null); + assertThat(basicHttpRequest.getEntity() != null).isTrue(); } @Test public void shouldFilterFalse() { setupContext(); - assertEquals(false, getFilter().shouldFilter()); + assertThat(getFilter().shouldFilter()).isEqualTo(false); } @Test public void shouldFilterTrue() throws Exception { setupContext(); - RequestContext.getCurrentContext().set("routeHost", new URL("http://localhost:8080")); + RequestContext.getCurrentContext().set("routeHost", + new URL("http://localhost:8080")); RequestContext.getCurrentContext().set("sendZuulResponse", true); - assertEquals(true, getFilter().shouldFilter()); + assertThat(getFilter().shouldFilter()).isEqualTo(true); } @Test public void filterOrder() { setupContext(); - assertEquals(100, getFilter().filterOrder()); + assertThat(getFilter().filterOrder()).isEqualTo(100); } private void setupContext() { @@ -257,6 +271,7 @@ public class SimpleHostRoutingFilterTests { @Configuration @EnableConfigurationProperties protected static class TestConfiguration { + @Bean ZuulProperties zuulProperties() { return new ZuulProperties(); @@ -274,9 +289,12 @@ public class SimpleHostRoutingFilterTests { @Bean SimpleHostRoutingFilter simpleHostRoutingFilter(ZuulProperties zuulProperties, - ApacheHttpClientConnectionManagerFactory connectionManagerFactory, - ApacheHttpClientFactory clientFactory) { - return new SimpleHostRoutingFilter(new ProxyRequestHelper(zuulProperties), zuulProperties, connectionManagerFactory, clientFactory); + ApacheHttpClientConnectionManagerFactory connectionManagerFactory, + ApacheHttpClientFactory clientFactory) { + return new SimpleHostRoutingFilter(new ProxyRequestHelper(zuulProperties), + zuulProperties, connectionManagerFactory, clientFactory); } + } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommandFactoryTest.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommandFactoryTest.java index b2dc24817..757aa83ee 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommandFactoryTest.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommandFactoryTest.java @@ -1,22 +1,39 @@ +/* + * Copyright 2017-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.springframework.cloud.netflix.zuul.filters.route.apache; import java.util.HashSet; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.cloud.netflix.ribbon.SpringClientFactory; -import org.springframework.cloud.netflix.ribbon.apache.RibbonLoadBalancingHttpClient; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; -import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey; import com.netflix.config.ConfigurationManager; import com.netflix.hystrix.strategy.properties.HystrixPropertiesFactory; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; -import static org.junit.Assert.assertEquals; +import org.springframework.cloud.netflix.ribbon.SpringClientFactory; +import org.springframework.cloud.netflix.ribbon.apache.RibbonLoadBalancingHttpClient; +import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; +import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; +import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider; + +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doReturn; @@ -29,19 +46,24 @@ import static org.mockito.Mockito.mock; public class HttpClientRibbonCommandFactoryTest { SpringClientFactory springClientFactory; + ZuulProperties zuulProperties; + HttpClientRibbonCommandFactory ribbonCommandFactory; @Before public void setup() { this.springClientFactory = mock(SpringClientFactory.class); this.zuulProperties = new ZuulProperties(); - RibbonLoadBalancingHttpClient loadBalancingHttpClient = mock(RibbonLoadBalancingHttpClient.class); + RibbonLoadBalancingHttpClient loadBalancingHttpClient = mock( + RibbonLoadBalancingHttpClient.class); IClientConfig clientConfig = new DefaultClientConfigImpl(); - doReturn(loadBalancingHttpClient).when(this.springClientFactory).getClient(anyString(), - eq(RibbonLoadBalancingHttpClient.class)); - doReturn(clientConfig).when(this.springClientFactory).getClientConfig(anyString()); - this.ribbonCommandFactory = new HttpClientRibbonCommandFactory(springClientFactory, zuulProperties, new HashSet()); + doReturn(loadBalancingHttpClient).when(this.springClientFactory) + .getClient(anyString(), eq(RibbonLoadBalancingHttpClient.class)); + doReturn(clientConfig).when(this.springClientFactory) + .getClientConfig(anyString()); + this.ribbonCommandFactory = new HttpClientRibbonCommandFactory( + springClientFactory, zuulProperties, new HashSet()); } @After @@ -55,239 +77,315 @@ public class HttpClientRibbonCommandFactoryTest { RibbonCommandContext context = mock(RibbonCommandContext.class); doReturn("service").when(context).getServiceId(); HttpClientRibbonCommand ribbonCommand = this.ribbonCommandFactory.create(context); - assertEquals(4000, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); + assertThat(ribbonCommand.getProperties().executionTimeoutInMilliseconds().get() + .intValue()).isEqualTo(4000); } @Test public void testHystrixTimeoutValueSetting() throws Exception { - ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds", 50); + ConfigurationManager.getConfigInstance().setProperty( + "hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds", + 50); RibbonCommandContext context = mock(RibbonCommandContext.class); doReturn("service").when(context).getServiceId(); HttpClientRibbonCommand ribbonCommand = this.ribbonCommandFactory.create(context); - assertEquals(50, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); + assertThat(ribbonCommand.getProperties().executionTimeoutInMilliseconds().get() + .intValue()).isEqualTo(50); } @Test public void testHystrixTimeoutValueCommandSetting() throws Exception { - ConfigurationManager.getConfigInstance().setProperty("hystrix.command.service.execution.isolation.thread.timeoutInMilliseconds", 50); + ConfigurationManager.getConfigInstance().setProperty( + "hystrix.command.service.execution.isolation.thread.timeoutInMilliseconds", + 50); RibbonCommandContext context = mock(RibbonCommandContext.class); doReturn("service").when(context).getServiceId(); HttpClientRibbonCommand ribbonCommand = this.ribbonCommandFactory.create(context); - assertEquals(50, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); + assertThat(ribbonCommand.getProperties().executionTimeoutInMilliseconds().get() + .intValue()).isEqualTo(50); } @Test public void testHystrixTimeoutValueCommandAndDefaultSetting() throws Exception { - ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds", 30); - ConfigurationManager.getConfigInstance().setProperty("hystrix.command.service.execution.isolation.thread.timeoutInMilliseconds", 50); + ConfigurationManager.getConfigInstance().setProperty( + "hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds", + 30); + ConfigurationManager.getConfigInstance().setProperty( + "hystrix.command.service.execution.isolation.thread.timeoutInMilliseconds", + 50); RibbonCommandContext context = mock(RibbonCommandContext.class); doReturn("service").when(context).getServiceId(); HttpClientRibbonCommand ribbonCommand = this.ribbonCommandFactory.create(context); - assertEquals(50, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); + assertThat(ribbonCommand.getProperties().executionTimeoutInMilliseconds().get() + .intValue()).isEqualTo(50); } @Test public void testHystrixTimeoutValueRibbonTimeouts() throws Exception { SpringClientFactory springClientFactory = mock(SpringClientFactory.class); ZuulProperties zuulProperties = new ZuulProperties(); - RibbonLoadBalancingHttpClient loadBalancingHttpClient = mock(RibbonLoadBalancingHttpClient.class); + RibbonLoadBalancingHttpClient loadBalancingHttpClient = mock( + RibbonLoadBalancingHttpClient.class); IClientConfig clientConfig = new DefaultClientConfigImpl(); clientConfig.set(IClientConfigKey.Keys.ConnectTimeout, 100); clientConfig.set(IClientConfigKey.Keys.ReadTimeout, 500); doReturn(loadBalancingHttpClient).when(springClientFactory).getClient(anyString(), - eq(RibbonLoadBalancingHttpClient.class)); + eq(RibbonLoadBalancingHttpClient.class)); doReturn(clientConfig).when(springClientFactory).getClientConfig(anyString()); - HttpClientRibbonCommandFactory ribbonCommandFactory = new HttpClientRibbonCommandFactory(springClientFactory, zuulProperties, new HashSet()); + HttpClientRibbonCommandFactory ribbonCommandFactory = new HttpClientRibbonCommandFactory( + springClientFactory, zuulProperties, new HashSet()); RibbonCommandContext context = mock(RibbonCommandContext.class); doReturn("service").when(context).getServiceId(); HttpClientRibbonCommand ribbonCommand = ribbonCommandFactory.create(context); - assertEquals(1200, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); + assertThat(ribbonCommand.getProperties().executionTimeoutInMilliseconds().get() + .intValue()).isEqualTo(1200); } @Test public void testHystrixDefaultAndRibbonSetting() throws Exception { - ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds", 30); - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ConnectTimeout", 1000); - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ReadTimeout", 1000); - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.MaxAutoRetries", 1); - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.MaxAutoRetriesNextServer", 2); + ConfigurationManager.getConfigInstance().setProperty( + "hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds", + 30); + ConfigurationManager.getConfigInstance() + .setProperty("service.ribbon.ConnectTimeout", 1000); + ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ReadTimeout", + 1000); + ConfigurationManager.getConfigInstance() + .setProperty("service.ribbon.MaxAutoRetries", 1); + ConfigurationManager.getConfigInstance() + .setProperty("service.ribbon.MaxAutoRetriesNextServer", 2); SpringClientFactory springClientFactory = mock(SpringClientFactory.class); ZuulProperties zuulProperties = new ZuulProperties(); - RibbonLoadBalancingHttpClient loadBalancingHttpClient = mock(RibbonLoadBalancingHttpClient.class); + RibbonLoadBalancingHttpClient loadBalancingHttpClient = mock( + RibbonLoadBalancingHttpClient.class); IClientConfig clientConfig = new DefaultClientConfigImpl(); clientConfig.set(IClientConfigKey.Keys.ConnectTimeout, 100); clientConfig.set(IClientConfigKey.Keys.ReadTimeout, 500); doReturn(loadBalancingHttpClient).when(springClientFactory).getClient(anyString(), - eq(RibbonLoadBalancingHttpClient.class)); + eq(RibbonLoadBalancingHttpClient.class)); doReturn(clientConfig).when(springClientFactory).getClientConfig(anyString()); - HttpClientRibbonCommandFactory ribbonCommandFactory = new HttpClientRibbonCommandFactory(springClientFactory, zuulProperties, new HashSet()); + HttpClientRibbonCommandFactory ribbonCommandFactory = new HttpClientRibbonCommandFactory( + springClientFactory, zuulProperties, new HashSet()); RibbonCommandContext context = mock(RibbonCommandContext.class); doReturn("service").when(context).getServiceId(); HttpClientRibbonCommand ribbonCommand = ribbonCommandFactory.create(context); - assertEquals(30, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); + assertThat(ribbonCommand.getProperties().executionTimeoutInMilliseconds().get() + .intValue()).isEqualTo(30); } @Test public void testHystrixCommandAndRibbonSetting() throws Exception { - ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds", 30); - ConfigurationManager.getConfigInstance().setProperty("hystrix.command.service.execution.isolation.thread.timeoutInMilliseconds", 50); - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ConnectTimeout", 1000); - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ReadTimeout", 1000); - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.MaxAutoRetries", 1); - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.MaxAutoRetriesNextServer", 2); + ConfigurationManager.getConfigInstance().setProperty( + "hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds", + 30); + ConfigurationManager.getConfigInstance().setProperty( + "hystrix.command.service.execution.isolation.thread.timeoutInMilliseconds", + 50); + ConfigurationManager.getConfigInstance() + .setProperty("service.ribbon.ConnectTimeout", 1000); + ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ReadTimeout", + 1000); + ConfigurationManager.getConfigInstance() + .setProperty("service.ribbon.MaxAutoRetries", 1); + ConfigurationManager.getConfigInstance() + .setProperty("service.ribbon.MaxAutoRetriesNextServer", 2); SpringClientFactory springClientFactory = mock(SpringClientFactory.class); ZuulProperties zuulProperties = new ZuulProperties(); - RibbonLoadBalancingHttpClient loadBalancingHttpClient = mock(RibbonLoadBalancingHttpClient.class); + RibbonLoadBalancingHttpClient loadBalancingHttpClient = mock( + RibbonLoadBalancingHttpClient.class); IClientConfig clientConfig = new DefaultClientConfigImpl(); clientConfig.set(IClientConfigKey.Keys.ConnectTimeout, 100); clientConfig.set(IClientConfigKey.Keys.ReadTimeout, 500); doReturn(loadBalancingHttpClient).when(springClientFactory).getClient(anyString(), - eq(RibbonLoadBalancingHttpClient.class)); + eq(RibbonLoadBalancingHttpClient.class)); doReturn(clientConfig).when(springClientFactory).getClientConfig(anyString()); - HttpClientRibbonCommandFactory ribbonCommandFactory = new HttpClientRibbonCommandFactory(springClientFactory, zuulProperties, new HashSet()); + HttpClientRibbonCommandFactory ribbonCommandFactory = new HttpClientRibbonCommandFactory( + springClientFactory, zuulProperties, new HashSet()); RibbonCommandContext context = mock(RibbonCommandContext.class); doReturn("service").when(context).getServiceId(); HttpClientRibbonCommand ribbonCommand = ribbonCommandFactory.create(context); - assertEquals(50, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); + assertThat(ribbonCommand.getProperties().executionTimeoutInMilliseconds().get() + .intValue()).isEqualTo(50); } @Test public void testDefaultRibbonSetting() throws Exception { SpringClientFactory springClientFactory = mock(SpringClientFactory.class); ZuulProperties zuulProperties = new ZuulProperties(); - RibbonLoadBalancingHttpClient loadBalancingHttpClient = mock(RibbonLoadBalancingHttpClient.class); + RibbonLoadBalancingHttpClient loadBalancingHttpClient = mock( + RibbonLoadBalancingHttpClient.class); IClientConfig clientConfig = new DefaultClientConfigImpl(); doReturn(loadBalancingHttpClient).when(springClientFactory).getClient(anyString(), - eq(RibbonLoadBalancingHttpClient.class)); + eq(RibbonLoadBalancingHttpClient.class)); doReturn(clientConfig).when(springClientFactory).getClientConfig(anyString()); - HttpClientRibbonCommandFactory commandFactory = new HttpClientRibbonCommandFactory(springClientFactory, zuulProperties, new HashSet()); + HttpClientRibbonCommandFactory commandFactory = new HttpClientRibbonCommandFactory( + springClientFactory, zuulProperties, new HashSet()); RibbonCommandContext context = mock(RibbonCommandContext.class); doReturn("service").when(context).getServiceId(); HttpClientRibbonCommand ribbonCommand = commandFactory.create(context); - assertEquals(4000, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); + assertThat(ribbonCommand.getProperties().executionTimeoutInMilliseconds().get() + .intValue()).isEqualTo(4000); } @Test - public void testRibbonTimeoutAndRibbonRetriesDefaultAndNameSpaceSetting() throws Exception { - ConfigurationManager.getConfigInstance().setProperty("service.test.ConnectTimeout", 1000); - ConfigurationManager.getConfigInstance().setProperty("service.test.ReadTimeout", 1000); + public void testRibbonTimeoutAndRibbonRetriesDefaultAndNameSpaceSetting() + throws Exception { + ConfigurationManager.getConfigInstance() + .setProperty("service.test.ConnectTimeout", 1000); + ConfigurationManager.getConfigInstance().setProperty("service.test.ReadTimeout", + 1000); SpringClientFactory springClientFactory = mock(SpringClientFactory.class); ZuulProperties zuulProperties = new ZuulProperties(); - RibbonLoadBalancingHttpClient loadBalancingHttpClient = mock(RibbonLoadBalancingHttpClient.class); + RibbonLoadBalancingHttpClient loadBalancingHttpClient = mock( + RibbonLoadBalancingHttpClient.class); IClientConfig clientConfig = new DefaultClientConfigImpl(); clientConfig.set(IClientConfigKey.Keys.ConnectTimeout, 100); clientConfig.set(IClientConfigKey.Keys.ReadTimeout, 500); doReturn(loadBalancingHttpClient).when(springClientFactory).getClient(anyString(), - eq(RibbonLoadBalancingHttpClient.class)); + eq(RibbonLoadBalancingHttpClient.class)); doReturn(clientConfig).when(springClientFactory).getClientConfig(anyString()); - HttpClientRibbonCommandFactory ribbonCommandFactory = new HttpClientRibbonCommandFactory(springClientFactory, zuulProperties, new HashSet()); + HttpClientRibbonCommandFactory ribbonCommandFactory = new HttpClientRibbonCommandFactory( + springClientFactory, zuulProperties, new HashSet()); RibbonCommandContext context = mock(RibbonCommandContext.class); doReturn("service").when(context).getServiceId(); HttpClientRibbonCommand ribbonCommand = ribbonCommandFactory.create(context); - assertEquals(1200, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); + assertThat(ribbonCommand.getProperties().executionTimeoutInMilliseconds().get() + .intValue()).isEqualTo(1200); } @Test - public void testRibbonTimeoutAndRibbonRetriesDefaultAndDefaultSpaceSetting() throws Exception { - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ConnectTimeout", 1000); - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ReadTimeout", 1000); + public void testRibbonTimeoutAndRibbonRetriesDefaultAndDefaultSpaceSetting() + throws Exception { + ConfigurationManager.getConfigInstance() + .setProperty("service.ribbon.ConnectTimeout", 1000); + ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ReadTimeout", + 1000); SpringClientFactory springClientFactory = mock(SpringClientFactory.class); ZuulProperties zuulProperties = new ZuulProperties(); - RibbonLoadBalancingHttpClient loadBalancingHttpClient = mock(RibbonLoadBalancingHttpClient.class); + RibbonLoadBalancingHttpClient loadBalancingHttpClient = mock( + RibbonLoadBalancingHttpClient.class); IClientConfig clientConfig = new DefaultClientConfigImpl(); clientConfig.set(IClientConfigKey.Keys.ConnectTimeout, 100); clientConfig.set(IClientConfigKey.Keys.ReadTimeout, 500); doReturn(loadBalancingHttpClient).when(springClientFactory).getClient(anyString(), - eq(RibbonLoadBalancingHttpClient.class)); + eq(RibbonLoadBalancingHttpClient.class)); doReturn(clientConfig).when(springClientFactory).getClientConfig(anyString()); - HttpClientRibbonCommandFactory ribbonCommandFactory = new HttpClientRibbonCommandFactory(springClientFactory, zuulProperties, new HashSet()); + HttpClientRibbonCommandFactory ribbonCommandFactory = new HttpClientRibbonCommandFactory( + springClientFactory, zuulProperties, new HashSet()); RibbonCommandContext context = mock(RibbonCommandContext.class); doReturn("service").when(context).getServiceId(); HttpClientRibbonCommand ribbonCommand = ribbonCommandFactory.create(context); - assertEquals(4000, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); + assertThat(ribbonCommand.getProperties().executionTimeoutInMilliseconds().get() + .intValue()).isEqualTo(4000); } @Test - public void testRibbonTimeoutAndRibbonNameSpaceRetriesDefaultAndDefaultSpaceSetting() throws Exception { - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ConnectTimeout", 1000); - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ReadTimeout", 1000); - ConfigurationManager.getConfigInstance().setProperty("service.test.MaxAutoRetriesNextServer", 2); + public void testRibbonTimeoutAndRibbonNameSpaceRetriesDefaultAndDefaultSpaceSetting() + throws Exception { + ConfigurationManager.getConfigInstance() + .setProperty("service.ribbon.ConnectTimeout", 1000); + ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ReadTimeout", + 1000); + ConfigurationManager.getConfigInstance() + .setProperty("service.test.MaxAutoRetriesNextServer", 2); SpringClientFactory springClientFactory = mock(SpringClientFactory.class); ZuulProperties zuulProperties = new ZuulProperties(); - RibbonLoadBalancingHttpClient loadBalancingHttpClient = mock(RibbonLoadBalancingHttpClient.class); + RibbonLoadBalancingHttpClient loadBalancingHttpClient = mock( + RibbonLoadBalancingHttpClient.class); IClientConfig clientConfig = new DefaultClientConfigImpl(); clientConfig.set(IClientConfigKey.Keys.ConnectTimeout, 100); clientConfig.set(IClientConfigKey.Keys.ReadTimeout, 500); doReturn(loadBalancingHttpClient).when(springClientFactory).getClient(anyString(), - eq(RibbonLoadBalancingHttpClient.class)); + eq(RibbonLoadBalancingHttpClient.class)); doReturn(clientConfig).when(springClientFactory).getClientConfig(anyString()); - HttpClientRibbonCommandFactory ribbonCommandFactory = new HttpClientRibbonCommandFactory(springClientFactory, zuulProperties, new HashSet()); + HttpClientRibbonCommandFactory ribbonCommandFactory = new HttpClientRibbonCommandFactory( + springClientFactory, zuulProperties, new HashSet()); RibbonCommandContext context = mock(RibbonCommandContext.class); doReturn("service").when(context).getServiceId(); HttpClientRibbonCommand ribbonCommand = ribbonCommandFactory.create(context); - assertEquals(4000, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); + assertThat(ribbonCommand.getProperties().executionTimeoutInMilliseconds().get() + .intValue()).isEqualTo(4000); } @Test public void testRibbonRetriesAndRibbonTimeoutSetting() throws Exception { - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.MaxAutoRetries", 1); - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.MaxAutoRetriesNextServer", 2); + ConfigurationManager.getConfigInstance() + .setProperty("service.ribbon.MaxAutoRetries", 1); + ConfigurationManager.getConfigInstance() + .setProperty("service.ribbon.MaxAutoRetriesNextServer", 2); SpringClientFactory springClientFactory = mock(SpringClientFactory.class); ZuulProperties zuulProperties = new ZuulProperties(); - RibbonLoadBalancingHttpClient loadBalancingHttpClient = mock(RibbonLoadBalancingHttpClient.class); + RibbonLoadBalancingHttpClient loadBalancingHttpClient = mock( + RibbonLoadBalancingHttpClient.class); IClientConfig clientConfig = new DefaultClientConfigImpl(); clientConfig.set(IClientConfigKey.Keys.ConnectTimeout, 100); clientConfig.set(IClientConfigKey.Keys.ReadTimeout, 500); doReturn(loadBalancingHttpClient).when(springClientFactory).getClient(anyString(), - eq(RibbonLoadBalancingHttpClient.class)); + eq(RibbonLoadBalancingHttpClient.class)); doReturn(clientConfig).when(springClientFactory).getClientConfig(anyString()); - HttpClientRibbonCommandFactory ribbonCommandFactory = new HttpClientRibbonCommandFactory(springClientFactory, zuulProperties, new HashSet()); + HttpClientRibbonCommandFactory ribbonCommandFactory = new HttpClientRibbonCommandFactory( + springClientFactory, zuulProperties, new HashSet()); RibbonCommandContext context = mock(RibbonCommandContext.class); doReturn("service").when(context).getServiceId(); HttpClientRibbonCommand ribbonCommand = ribbonCommandFactory.create(context); - assertEquals(3600, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); + assertThat(ribbonCommand.getProperties().executionTimeoutInMilliseconds().get() + .intValue()).isEqualTo(3600); } @Test - public void testRibbonCommandRetriesAndRibbonCommandTimeoutSetting() throws Exception { - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ConnectTimeout", 1000); - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ReadTimeout", 1000); - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.MaxAutoRetries", 1); - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.MaxAutoRetriesNextServer", 2); + public void testRibbonCommandRetriesAndRibbonCommandTimeoutSetting() + throws Exception { + ConfigurationManager.getConfigInstance() + .setProperty("service.ribbon.ConnectTimeout", 1000); + ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ReadTimeout", + 1000); + ConfigurationManager.getConfigInstance() + .setProperty("service.ribbon.MaxAutoRetries", 1); + ConfigurationManager.getConfigInstance() + .setProperty("service.ribbon.MaxAutoRetriesNextServer", 2); SpringClientFactory springClientFactory = mock(SpringClientFactory.class); ZuulProperties zuulProperties = new ZuulProperties(); - RibbonLoadBalancingHttpClient loadBalancingHttpClient = mock(RibbonLoadBalancingHttpClient.class); + RibbonLoadBalancingHttpClient loadBalancingHttpClient = mock( + RibbonLoadBalancingHttpClient.class); IClientConfig clientConfig = new DefaultClientConfigImpl(); clientConfig.set(IClientConfigKey.Keys.ConnectTimeout, 100); clientConfig.set(IClientConfigKey.Keys.ReadTimeout, 500); doReturn(loadBalancingHttpClient).when(springClientFactory).getClient(anyString(), - eq(RibbonLoadBalancingHttpClient.class)); + eq(RibbonLoadBalancingHttpClient.class)); doReturn(clientConfig).when(springClientFactory).getClientConfig(anyString()); - HttpClientRibbonCommandFactory ribbonCommandFactory = new HttpClientRibbonCommandFactory(springClientFactory, zuulProperties, new HashSet()); + HttpClientRibbonCommandFactory ribbonCommandFactory = new HttpClientRibbonCommandFactory( + springClientFactory, zuulProperties, new HashSet()); RibbonCommandContext context = mock(RibbonCommandContext.class); doReturn("service").when(context).getServiceId(); HttpClientRibbonCommand ribbonCommand = ribbonCommandFactory.create(context); - assertEquals(12000, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); + assertThat(ribbonCommand.getProperties().executionTimeoutInMilliseconds().get() + .intValue()).isEqualTo(12000); } @Test - public void testRibbonCommandRetriesAndRibbonCommandTimeoutPartOfSetting() throws Exception { - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ConnectTimeout", 1000); - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.MaxAutoRetries", 1); + public void testRibbonCommandRetriesAndRibbonCommandTimeoutPartOfSetting() + throws Exception { + ConfigurationManager.getConfigInstance() + .setProperty("service.ribbon.ConnectTimeout", 1000); + ConfigurationManager.getConfigInstance() + .setProperty("service.ribbon.MaxAutoRetries", 1); SpringClientFactory springClientFactory = mock(SpringClientFactory.class); ZuulProperties zuulProperties = new ZuulProperties(); - RibbonLoadBalancingHttpClient loadBalancingHttpClient = mock(RibbonLoadBalancingHttpClient.class); + RibbonLoadBalancingHttpClient loadBalancingHttpClient = mock( + RibbonLoadBalancingHttpClient.class); IClientConfig clientConfig = new DefaultClientConfigImpl(); clientConfig.set(IClientConfigKey.Keys.ConnectTimeout, 100); clientConfig.set(IClientConfigKey.Keys.ReadTimeout, 500); doReturn(loadBalancingHttpClient).when(springClientFactory).getClient(anyString(), - eq(RibbonLoadBalancingHttpClient.class)); + eq(RibbonLoadBalancingHttpClient.class)); doReturn(clientConfig).when(springClientFactory).getClientConfig(anyString()); - HttpClientRibbonCommandFactory ribbonCommandFactory = new HttpClientRibbonCommandFactory(springClientFactory, zuulProperties, new HashSet()); + HttpClientRibbonCommandFactory ribbonCommandFactory = new HttpClientRibbonCommandFactory( + springClientFactory, zuulProperties, new HashSet()); RibbonCommandContext context = mock(RibbonCommandContext.class); doReturn("service").when(context).getServiceId(); HttpClientRibbonCommand ribbonCommand = ribbonCommandFactory.create(context); - assertEquals(6000, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); + assertThat(ribbonCommand.getProperties().executionTimeoutInMilliseconds().get() + .intValue()).isEqualTo(6000); } -} \ No newline at end of file +} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommandFallbackTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommandFallbackTests.java index bfc1f86dc..fd411c0ea 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommandFallbackTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommandFallbackTests.java @@ -1,25 +1,22 @@ /* + * Copyright 2016-2019 the original author or authors. * - * * Copyright 2013-2016 the original author or authors. - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.netflix.zuul.filters.route.apache; import com.netflix.zuul.context.RequestContext; - import org.junit.Before; import org.junit.runner.RunWith; diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommandIntegrationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommandIntegrationTests.java index 2a0a3cef7..61cedee50 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommandIntegrationTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonCommandIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,16 +12,10 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.filters.route.apache; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.springframework.http.HttpHeaders.SET_COOKIE; - import java.util.Collections; import java.util.Set; @@ -29,9 +23,15 @@ import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import com.netflix.client.RetryHandler; +import com.netflix.client.config.IClientConfig; +import com.netflix.loadbalancer.ILoadBalancer; +import com.netflix.loadbalancer.Server; +import com.netflix.loadbalancer.ServerList; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -67,11 +67,8 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.util.WebUtils; -import com.netflix.client.RetryHandler; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.ILoadBalancer; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.http.HttpHeaders.SET_COOKIE; /** * @author Spencer Gibb @@ -96,8 +93,8 @@ public class HttpClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/simple/local/1", HttpMethod.PATCH, new HttpEntity<>("TestPatch"), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Patched 1!", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Patched 1!"); } @Test @@ -105,8 +102,8 @@ public class HttpClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/simple/local/1", HttpMethod.POST, new HttpEntity<>("TestPost"), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted 1!", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Posted 1!"); } @Test @@ -114,8 +111,8 @@ public class HttpClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/simple/local/1", HttpMethod.DELETE, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Deleted 1!", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Deleted 1!"); } @Test @@ -123,9 +120,9 @@ public class HttpClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/simple/downstream_cookie", HttpMethod.POST, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Cookie 434354454!", result.getBody()); - assertNull(result.getHeaders().getFirst(SET_COOKIE)); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Cookie 434354454!"); + assertThat(result.getHeaders().getFirst(SET_COOKIE)).isNull(); // if new instance of RibbonLoadBalancingHttpClient is getting created every time // and HttpClient is not reused then there are no concerns for the shared cookie @@ -135,21 +132,22 @@ public class HttpClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/singleton/downstream_cookie", HttpMethod.POST, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Cookie 434354454!", result.getBody()); - assertEquals("jsessionid=434354454", result.getHeaders().getFirst(SET_COOKIE)); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Cookie 434354454!"); + assertThat(result.getHeaders().getFirst(SET_COOKIE)) + .isEqualTo("jsessionid=434354454"); result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/singleton/downstream_cookie", HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Cookie null!", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Cookie null!"); } @Test public void ribbonCommandFactoryOverridden() { - assertTrue("ribbonCommandFactory not a HttpClientRibbonCommandFactory", - this.ribbonCommandFactory instanceof HttpClientRibbonCommandFactory); + assertThat(this.ribbonCommandFactory instanceof HttpClientRibbonCommandFactory) + .as("ribbonCommandFactory not a HttpClientRibbonCommandFactory").isTrue(); } // Don't use @SpringBootApplication because we don't want to component scan @@ -197,6 +195,7 @@ public class HttpClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { ErrorAttributes errorAttributes) { return new ZuulProxyTestBase.MyErrorController(errorAttributes); } + } // Load balancer with fixed server list and defined ribbon rest client @@ -214,12 +213,13 @@ public class HttpClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { @Bean public RibbonLoadBalancingHttpClient ribbonClient(IClientConfig config, ILoadBalancer loadBalancer, RetryHandler retryHandler) { - final RibbonLoadBalancingHttpClient client = new RibbonLoadBalancingHttpClient(config, - new DefaultServerIntrospector()); + final RibbonLoadBalancingHttpClient client = new RibbonLoadBalancingHttpClient( + config, new DefaultServerIntrospector()); client.setLoadBalancer(loadBalancer); client.setRetryHandler(retryHandler); return client; } } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonRetryIntegrationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonRetryIntegrationTests.java index d7d737b39..a47ef3b71 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonRetryIntegrationTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/apache/HttpClientRibbonRetryIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,12 +12,12 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.filters.route.apache; import org.junit.runner.RunWith; + import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.netflix.zuul.filters.route.support.RibbonRetryIntegrationTestBase; import org.springframework.test.annotation.DirtiesContext; @@ -29,12 +29,17 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Ryan Baxter */ @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = RibbonRetryIntegrationTestBase.RetryableTestConfig.class, - webEnvironment = RANDOM_PORT, - properties = { +@SpringBootTest(classes = RibbonRetryIntegrationTestBase.RetryableTestConfig.class, webEnvironment = RANDOM_PORT, properties = { "zuul.retryable: false", /* Disable retry by default, have each route enable it */ - "hystrix.command.default.execution.timeout.enabled: false", /* Disable hystrix so its timeout doesnt get in the way */ - "ribbon.ReadTimeout: 1000", /* Make sure ribbon will timeout before the thread is done sleeping */ + "hystrix.command.default.execution.timeout.enabled: false", /* + * Disable hystrix so + * its timeout doesnt + * get in the way + */ + "ribbon.ReadTimeout: 1000", /* + * Make sure ribbon will timeout before the thread is + * done sleeping + */ "zuul.routes.retryable.id: retryable", "zuul.routes.retryable.path: /retryable/**", "zuul.routes.retryable.retryable: true", @@ -54,8 +59,9 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen "zuul.routes.globalretrydisabled: /globalretrydisabled/**", "globalretrydisabled.ribbon.MaxAutoRetries: 1", "globalretrydisabled.ribbon.MaxAutoRetriesNextServer: 1", - "retryable.ribbon.retryableStatusCodes: 404,403" -}) + "retryable.ribbon.retryableStatusCodes: 404,403" }) @DirtiesContext -public class HttpClientRibbonRetryIntegrationTests extends RibbonRetryIntegrationTestBase { +public class HttpClientRibbonRetryIntegrationTests + extends RibbonRetryIntegrationTestBase { + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommandFactoryTest.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommandFactoryTest.java index 6959bd836..4c3ad5e25 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommandFactoryTest.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommandFactoryTest.java @@ -1,22 +1,39 @@ +/* + * Copyright 2017-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.springframework.cloud.netflix.zuul.filters.route.okhttp; import java.util.HashSet; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.cloud.netflix.ribbon.SpringClientFactory; -import org.springframework.cloud.netflix.ribbon.okhttp.OkHttpLoadBalancingClient; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; -import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey; import com.netflix.config.ConfigurationManager; import com.netflix.hystrix.strategy.properties.HystrixPropertiesFactory; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; -import static org.junit.Assert.assertEquals; +import org.springframework.cloud.netflix.ribbon.SpringClientFactory; +import org.springframework.cloud.netflix.ribbon.okhttp.OkHttpLoadBalancingClient; +import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext; +import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; +import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider; + +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doReturn; @@ -29,19 +46,24 @@ import static org.mockito.Mockito.mock; public class OkHttpRibbonCommandFactoryTest { SpringClientFactory springClientFactory; + ZuulProperties zuulProperties; + OkHttpRibbonCommandFactory commandFactory; @Before public void setup() { this.springClientFactory = mock(SpringClientFactory.class); this.zuulProperties = new ZuulProperties(); - OkHttpLoadBalancingClient loadBalancingHttpClient = mock(OkHttpLoadBalancingClient.class); + OkHttpLoadBalancingClient loadBalancingHttpClient = mock( + OkHttpLoadBalancingClient.class); IClientConfig clientConfig = new DefaultClientConfigImpl(); - doReturn(loadBalancingHttpClient).when(this.springClientFactory).getClient(anyString(), - eq(OkHttpLoadBalancingClient.class)); - doReturn(clientConfig).when(this.springClientFactory).getClientConfig(anyString()); - commandFactory = new OkHttpRibbonCommandFactory(springClientFactory, zuulProperties, new HashSet()); + doReturn(loadBalancingHttpClient).when(this.springClientFactory) + .getClient(anyString(), eq(OkHttpLoadBalancingClient.class)); + doReturn(clientConfig).when(this.springClientFactory) + .getClientConfig(anyString()); + commandFactory = new OkHttpRibbonCommandFactory(springClientFactory, + zuulProperties, new HashSet()); } @After @@ -55,235 +77,311 @@ public class OkHttpRibbonCommandFactoryTest { RibbonCommandContext context = mock(RibbonCommandContext.class); doReturn("service").when(context).getServiceId(); OkHttpRibbonCommand ribbonCommand = this.commandFactory.create(context); - assertEquals(4000, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); + assertThat(ribbonCommand.getProperties().executionTimeoutInMilliseconds().get() + .intValue()).isEqualTo(4000); } @Test public void testHystrixTimeoutValueSetting() throws Exception { - ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds", 50); + ConfigurationManager.getConfigInstance().setProperty( + "hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds", + 50); RibbonCommandContext context = mock(RibbonCommandContext.class); doReturn("service").when(context).getServiceId(); OkHttpRibbonCommand ribbonCommand = this.commandFactory.create(context); - assertEquals(50, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); + assertThat(ribbonCommand.getProperties().executionTimeoutInMilliseconds().get() + .intValue()).isEqualTo(50); } @Test public void testHystrixTimeoutValueCommandSetting() throws Exception { - ConfigurationManager.getConfigInstance().setProperty("hystrix.command.service.execution.isolation.thread.timeoutInMilliseconds", 50); + ConfigurationManager.getConfigInstance().setProperty( + "hystrix.command.service.execution.isolation.thread.timeoutInMilliseconds", + 50); RibbonCommandContext context = mock(RibbonCommandContext.class); doReturn("service").when(context).getServiceId(); OkHttpRibbonCommand ribbonCommand = this.commandFactory.create(context); - assertEquals(50, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); + assertThat(ribbonCommand.getProperties().executionTimeoutInMilliseconds().get() + .intValue()).isEqualTo(50); } @Test public void testHystrixTimeoutValueCommandAndDefaultSetting() throws Exception { - ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds", 30); - ConfigurationManager.getConfigInstance().setProperty("hystrix.command.service.execution.isolation.thread.timeoutInMilliseconds", 50); + ConfigurationManager.getConfigInstance().setProperty( + "hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds", + 30); + ConfigurationManager.getConfigInstance().setProperty( + "hystrix.command.service.execution.isolation.thread.timeoutInMilliseconds", + 50); RibbonCommandContext context = mock(RibbonCommandContext.class); doReturn("service").when(context).getServiceId(); OkHttpRibbonCommand ribbonCommand = this.commandFactory.create(context); - assertEquals(50, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); + assertThat(ribbonCommand.getProperties().executionTimeoutInMilliseconds().get() + .intValue()).isEqualTo(50); } @Test public void testHystrixDefaultAndRibbonSetting() throws Exception { - ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds", 30); - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ConnectTimeout", 1000); - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ReadTimeout", 1000); - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.MaxAutoRetries", 1); - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.MaxAutoRetriesNextServer", 2); + ConfigurationManager.getConfigInstance().setProperty( + "hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds", + 30); + ConfigurationManager.getConfigInstance() + .setProperty("service.ribbon.ConnectTimeout", 1000); + ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ReadTimeout", + 1000); + ConfigurationManager.getConfigInstance() + .setProperty("service.ribbon.MaxAutoRetries", 1); + ConfigurationManager.getConfigInstance() + .setProperty("service.ribbon.MaxAutoRetriesNextServer", 2); SpringClientFactory springClientFactory = mock(SpringClientFactory.class); ZuulProperties zuulProperties = new ZuulProperties(); - OkHttpLoadBalancingClient loadBalancingHttpClient = mock(OkHttpLoadBalancingClient.class); + OkHttpLoadBalancingClient loadBalancingHttpClient = mock( + OkHttpLoadBalancingClient.class); IClientConfig clientConfig = new DefaultClientConfigImpl(); doReturn(loadBalancingHttpClient).when(springClientFactory).getClient(anyString(), - eq(OkHttpLoadBalancingClient.class)); + eq(OkHttpLoadBalancingClient.class)); doReturn(clientConfig).when(springClientFactory).getClientConfig(anyString()); - OkHttpRibbonCommandFactory commandFactory = new OkHttpRibbonCommandFactory(springClientFactory, zuulProperties, new HashSet()); + OkHttpRibbonCommandFactory commandFactory = new OkHttpRibbonCommandFactory( + springClientFactory, zuulProperties, new HashSet()); RibbonCommandContext context = mock(RibbonCommandContext.class); doReturn("service").when(context).getServiceId(); OkHttpRibbonCommand ribbonCommand = commandFactory.create(context); - assertEquals(30, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); + assertThat(ribbonCommand.getProperties().executionTimeoutInMilliseconds().get() + .intValue()).isEqualTo(30); } @Test public void testHystrixCommandAndRibbonSetting() throws Exception { - ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds", 30); - ConfigurationManager.getConfigInstance().setProperty("hystrix.command.service.execution.isolation.thread.timeoutInMilliseconds", 50); - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ConnectTimeout", 1000); - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ReadTimeout", 1000); - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.MaxAutoRetries", 1); - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.MaxAutoRetriesNextServer", 2); + ConfigurationManager.getConfigInstance().setProperty( + "hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds", + 30); + ConfigurationManager.getConfigInstance().setProperty( + "hystrix.command.service.execution.isolation.thread.timeoutInMilliseconds", + 50); + ConfigurationManager.getConfigInstance() + .setProperty("service.ribbon.ConnectTimeout", 1000); + ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ReadTimeout", + 1000); + ConfigurationManager.getConfigInstance() + .setProperty("service.ribbon.MaxAutoRetries", 1); + ConfigurationManager.getConfigInstance() + .setProperty("service.ribbon.MaxAutoRetriesNextServer", 2); SpringClientFactory springClientFactory = mock(SpringClientFactory.class); ZuulProperties zuulProperties = new ZuulProperties(); - OkHttpLoadBalancingClient loadBalancingHttpClient = mock(OkHttpLoadBalancingClient.class); + OkHttpLoadBalancingClient loadBalancingHttpClient = mock( + OkHttpLoadBalancingClient.class); IClientConfig clientConfig = new DefaultClientConfigImpl(); doReturn(loadBalancingHttpClient).when(springClientFactory).getClient(anyString(), - eq(OkHttpLoadBalancingClient.class)); + eq(OkHttpLoadBalancingClient.class)); doReturn(clientConfig).when(springClientFactory).getClientConfig(anyString()); - OkHttpRibbonCommandFactory commandFactory = new OkHttpRibbonCommandFactory(springClientFactory, zuulProperties, new HashSet()); + OkHttpRibbonCommandFactory commandFactory = new OkHttpRibbonCommandFactory( + springClientFactory, zuulProperties, new HashSet()); RibbonCommandContext context = mock(RibbonCommandContext.class); doReturn("service").when(context).getServiceId(); OkHttpRibbonCommand ribbonCommand = commandFactory.create(context); - assertEquals(50, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); + assertThat(ribbonCommand.getProperties().executionTimeoutInMilliseconds().get() + .intValue()).isEqualTo(50); } @Test public void testDefaultRibbonSetting() throws Exception { SpringClientFactory springClientFactory = mock(SpringClientFactory.class); ZuulProperties zuulProperties = new ZuulProperties(); - OkHttpLoadBalancingClient loadBalancingHttpClient = mock(OkHttpLoadBalancingClient.class); + OkHttpLoadBalancingClient loadBalancingHttpClient = mock( + OkHttpLoadBalancingClient.class); IClientConfig clientConfig = new DefaultClientConfigImpl(); doReturn(loadBalancingHttpClient).when(springClientFactory).getClient(anyString(), - eq(OkHttpLoadBalancingClient.class)); + eq(OkHttpLoadBalancingClient.class)); doReturn(clientConfig).when(springClientFactory).getClientConfig(anyString()); - OkHttpRibbonCommandFactory commandFactory = new OkHttpRibbonCommandFactory(springClientFactory, zuulProperties, new HashSet()); + OkHttpRibbonCommandFactory commandFactory = new OkHttpRibbonCommandFactory( + springClientFactory, zuulProperties, new HashSet()); RibbonCommandContext context = mock(RibbonCommandContext.class); doReturn("service").when(context).getServiceId(); OkHttpRibbonCommand ribbonCommand = commandFactory.create(context); - assertEquals(4000, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); + assertThat(ribbonCommand.getProperties().executionTimeoutInMilliseconds().get() + .intValue()).isEqualTo(4000); } @Test public void testRibbonAndRibbonRetriesDefaultSetting() throws Exception { SpringClientFactory springClientFactory = mock(SpringClientFactory.class); ZuulProperties zuulProperties = new ZuulProperties(); - OkHttpLoadBalancingClient loadBalancingHttpClient = mock(OkHttpLoadBalancingClient.class); + OkHttpLoadBalancingClient loadBalancingHttpClient = mock( + OkHttpLoadBalancingClient.class); IClientConfig clientConfig = new DefaultClientConfigImpl(); clientConfig.set(IClientConfigKey.Keys.ConnectTimeout, 100); clientConfig.set(IClientConfigKey.Keys.ReadTimeout, 500); doReturn(loadBalancingHttpClient).when(springClientFactory).getClient(anyString(), eq(OkHttpLoadBalancingClient.class)); doReturn(clientConfig).when(springClientFactory).getClientConfig(anyString()); - OkHttpRibbonCommandFactory commandFactory = new OkHttpRibbonCommandFactory(springClientFactory, zuulProperties, new HashSet()); + OkHttpRibbonCommandFactory commandFactory = new OkHttpRibbonCommandFactory( + springClientFactory, zuulProperties, new HashSet()); RibbonCommandContext context = mock(RibbonCommandContext.class); doReturn("service").when(context).getServiceId(); OkHttpRibbonCommand ribbonCommand = commandFactory.create(context); - assertEquals(1200, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); + assertThat(ribbonCommand.getProperties().executionTimeoutInMilliseconds().get() + .intValue()).isEqualTo(1200); } @Test - public void testRibbonTimeoutAndRibbonRetriesDefaultAndNameSpaceSetting() throws Exception { - ConfigurationManager.getConfigInstance().setProperty("service.test.ConnectTimeout", 1000); - ConfigurationManager.getConfigInstance().setProperty("service.test.ReadTimeout", 1000); + public void testRibbonTimeoutAndRibbonRetriesDefaultAndNameSpaceSetting() + throws Exception { + ConfigurationManager.getConfigInstance() + .setProperty("service.test.ConnectTimeout", 1000); + ConfigurationManager.getConfigInstance().setProperty("service.test.ReadTimeout", + 1000); SpringClientFactory springClientFactory = mock(SpringClientFactory.class); ZuulProperties zuulProperties = new ZuulProperties(); - OkHttpLoadBalancingClient loadBalancingHttpClient = mock(OkHttpLoadBalancingClient.class); + OkHttpLoadBalancingClient loadBalancingHttpClient = mock( + OkHttpLoadBalancingClient.class); IClientConfig clientConfig = new DefaultClientConfigImpl("test"); clientConfig.set(IClientConfigKey.Keys.ConnectTimeout, 100); clientConfig.set(IClientConfigKey.Keys.ReadTimeout, 500); doReturn(loadBalancingHttpClient).when(springClientFactory).getClient(anyString(), - eq(OkHttpLoadBalancingClient.class)); + eq(OkHttpLoadBalancingClient.class)); doReturn(clientConfig).when(springClientFactory).getClientConfig(anyString()); - OkHttpRibbonCommandFactory commandFactory = new OkHttpRibbonCommandFactory(springClientFactory, zuulProperties, new HashSet()); + OkHttpRibbonCommandFactory commandFactory = new OkHttpRibbonCommandFactory( + springClientFactory, zuulProperties, new HashSet()); RibbonCommandContext context = mock(RibbonCommandContext.class); doReturn("service").when(context).getServiceId(); OkHttpRibbonCommand ribbonCommand = commandFactory.create(context); - assertEquals(4000, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); + assertThat(ribbonCommand.getProperties().executionTimeoutInMilliseconds().get() + .intValue()).isEqualTo(4000); } @Test - public void testRibbonTimeoutAndRibbonRetriesDefaultAndDefaultSpaceSetting() throws Exception { - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ConnectTimeout", 1000); - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ReadTimeout", 1000); + public void testRibbonTimeoutAndRibbonRetriesDefaultAndDefaultSpaceSetting() + throws Exception { + ConfigurationManager.getConfigInstance() + .setProperty("service.ribbon.ConnectTimeout", 1000); + ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ReadTimeout", + 1000); SpringClientFactory springClientFactory = mock(SpringClientFactory.class); ZuulProperties zuulProperties = new ZuulProperties(); - OkHttpLoadBalancingClient loadBalancingHttpClient = mock(OkHttpLoadBalancingClient.class); + OkHttpLoadBalancingClient loadBalancingHttpClient = mock( + OkHttpLoadBalancingClient.class); IClientConfig clientConfig = new DefaultClientConfigImpl(); clientConfig.set(IClientConfigKey.Keys.ConnectTimeout, 100); clientConfig.set(IClientConfigKey.Keys.ReadTimeout, 500); doReturn(loadBalancingHttpClient).when(springClientFactory).getClient(anyString(), - eq(OkHttpLoadBalancingClient.class)); + eq(OkHttpLoadBalancingClient.class)); doReturn(clientConfig).when(springClientFactory).getClientConfig(anyString()); - OkHttpRibbonCommandFactory commandFactory = new OkHttpRibbonCommandFactory(springClientFactory, zuulProperties, new HashSet()); + OkHttpRibbonCommandFactory commandFactory = new OkHttpRibbonCommandFactory( + springClientFactory, zuulProperties, new HashSet()); RibbonCommandContext context = mock(RibbonCommandContext.class); doReturn("service").when(context).getServiceId(); OkHttpRibbonCommand ribbonCommand = commandFactory.create(context); - assertEquals(4000, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); + assertThat(ribbonCommand.getProperties().executionTimeoutInMilliseconds().get() + .intValue()).isEqualTo(4000); } @Test - public void testRibbonTimeoutAndRibbonNameSpaceRetriesDefaultAndDefaultSpaceSetting() throws Exception { - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ConnectTimeout", 1000); - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ReadTimeout", 1000); - ConfigurationManager.getConfigInstance().setProperty("service.test.MaxAutoRetriesNextServer", 2); + public void testRibbonTimeoutAndRibbonNameSpaceRetriesDefaultAndDefaultSpaceSetting() + throws Exception { + ConfigurationManager.getConfigInstance() + .setProperty("service.ribbon.ConnectTimeout", 1000); + ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ReadTimeout", + 1000); + ConfigurationManager.getConfigInstance() + .setProperty("service.test.MaxAutoRetriesNextServer", 2); SpringClientFactory springClientFactory = mock(SpringClientFactory.class); ZuulProperties zuulProperties = new ZuulProperties(); - OkHttpLoadBalancingClient loadBalancingHttpClient = mock(OkHttpLoadBalancingClient.class); + OkHttpLoadBalancingClient loadBalancingHttpClient = mock( + OkHttpLoadBalancingClient.class); IClientConfig clientConfig = new DefaultClientConfigImpl("test"); clientConfig.set(IClientConfigKey.Keys.ConnectTimeout, 100); clientConfig.set(IClientConfigKey.Keys.ReadTimeout, 500); doReturn(loadBalancingHttpClient).when(springClientFactory).getClient(anyString(), - eq(OkHttpLoadBalancingClient.class)); + eq(OkHttpLoadBalancingClient.class)); doReturn(clientConfig).when(springClientFactory).getClientConfig(anyString()); - OkHttpRibbonCommandFactory commandFactory = new OkHttpRibbonCommandFactory(springClientFactory, zuulProperties, new HashSet()); + OkHttpRibbonCommandFactory commandFactory = new OkHttpRibbonCommandFactory( + springClientFactory, zuulProperties, new HashSet()); RibbonCommandContext context = mock(RibbonCommandContext.class); doReturn("service").when(context).getServiceId(); OkHttpRibbonCommand ribbonCommand = commandFactory.create(context); - assertEquals(1800, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); + assertThat(ribbonCommand.getProperties().executionTimeoutInMilliseconds().get() + .intValue()).isEqualTo(1800); } @Test public void testRibbonRetriesAndRibbonTimeoutSetting() throws Exception { - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.MaxAutoRetries", 1); - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.MaxAutoRetriesNextServer", 2); + ConfigurationManager.getConfigInstance() + .setProperty("service.ribbon.MaxAutoRetries", 1); + ConfigurationManager.getConfigInstance() + .setProperty("service.ribbon.MaxAutoRetriesNextServer", 2); SpringClientFactory springClientFactory = mock(SpringClientFactory.class); ZuulProperties zuulProperties = new ZuulProperties(); - OkHttpLoadBalancingClient loadBalancingHttpClient = mock(OkHttpLoadBalancingClient.class); + OkHttpLoadBalancingClient loadBalancingHttpClient = mock( + OkHttpLoadBalancingClient.class); IClientConfig clientConfig = new DefaultClientConfigImpl(); clientConfig.set(IClientConfigKey.Keys.ConnectTimeout, 100); clientConfig.set(IClientConfigKey.Keys.ReadTimeout, 500); doReturn(loadBalancingHttpClient).when(springClientFactory).getClient(anyString(), - eq(OkHttpLoadBalancingClient.class)); + eq(OkHttpLoadBalancingClient.class)); doReturn(clientConfig).when(springClientFactory).getClientConfig(anyString()); - OkHttpRibbonCommandFactory commandFactory = new OkHttpRibbonCommandFactory(springClientFactory, zuulProperties, new HashSet()); + OkHttpRibbonCommandFactory commandFactory = new OkHttpRibbonCommandFactory( + springClientFactory, zuulProperties, new HashSet()); RibbonCommandContext context = mock(RibbonCommandContext.class); doReturn("service").when(context).getServiceId(); OkHttpRibbonCommand ribbonCommand = commandFactory.create(context); - assertEquals(3600, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); + assertThat(ribbonCommand.getProperties().executionTimeoutInMilliseconds().get() + .intValue()).isEqualTo(3600); } @Test - public void testRibbonCommandRetriesAndRibbonCommandTimeoutSetting() throws Exception { - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ConnectTimeout", 1000); - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ReadTimeout", 1000); - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.MaxAutoRetries", 1); - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.MaxAutoRetriesNextServer", 2); + public void testRibbonCommandRetriesAndRibbonCommandTimeoutSetting() + throws Exception { + ConfigurationManager.getConfigInstance() + .setProperty("service.ribbon.ConnectTimeout", 1000); + ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ReadTimeout", + 1000); + ConfigurationManager.getConfigInstance() + .setProperty("service.ribbon.MaxAutoRetries", 1); + ConfigurationManager.getConfigInstance() + .setProperty("service.ribbon.MaxAutoRetriesNextServer", 2); SpringClientFactory springClientFactory = mock(SpringClientFactory.class); ZuulProperties zuulProperties = new ZuulProperties(); - OkHttpLoadBalancingClient loadBalancingHttpClient = mock(OkHttpLoadBalancingClient.class); + OkHttpLoadBalancingClient loadBalancingHttpClient = mock( + OkHttpLoadBalancingClient.class); IClientConfig clientConfig = new DefaultClientConfigImpl(); clientConfig.set(IClientConfigKey.Keys.ConnectTimeout, 100); clientConfig.set(IClientConfigKey.Keys.ReadTimeout, 500); doReturn(loadBalancingHttpClient).when(springClientFactory).getClient(anyString(), - eq(OkHttpLoadBalancingClient.class)); + eq(OkHttpLoadBalancingClient.class)); doReturn(clientConfig).when(springClientFactory).getClientConfig(anyString()); - OkHttpRibbonCommandFactory commandFactory = new OkHttpRibbonCommandFactory(springClientFactory, zuulProperties, new HashSet()); + OkHttpRibbonCommandFactory commandFactory = new OkHttpRibbonCommandFactory( + springClientFactory, zuulProperties, new HashSet()); RibbonCommandContext context = mock(RibbonCommandContext.class); doReturn("service").when(context).getServiceId(); OkHttpRibbonCommand ribbonCommand = commandFactory.create(context); - assertEquals(12000, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); + assertThat(ribbonCommand.getProperties().executionTimeoutInMilliseconds().get() + .intValue()).isEqualTo(12000); } @Test - public void testRibbonCommandRetriesAndRibbonCommandTimeoutPartOfSetting() throws Exception { - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.ConnectTimeout", 1000); - ConfigurationManager.getConfigInstance().setProperty("service.ribbon.MaxAutoRetries", 1); + public void testRibbonCommandRetriesAndRibbonCommandTimeoutPartOfSetting() + throws Exception { + ConfigurationManager.getConfigInstance() + .setProperty("service.ribbon.ConnectTimeout", 1000); + ConfigurationManager.getConfigInstance() + .setProperty("service.ribbon.MaxAutoRetries", 1); SpringClientFactory springClientFactory = mock(SpringClientFactory.class); ZuulProperties zuulProperties = new ZuulProperties(); - OkHttpLoadBalancingClient loadBalancingHttpClient = mock(OkHttpLoadBalancingClient.class); + OkHttpLoadBalancingClient loadBalancingHttpClient = mock( + OkHttpLoadBalancingClient.class); IClientConfig clientConfig = new DefaultClientConfigImpl(); clientConfig.set(IClientConfigKey.Keys.ConnectTimeout, 100); clientConfig.set(IClientConfigKey.Keys.ReadTimeout, 500); doReturn(loadBalancingHttpClient).when(springClientFactory).getClient(anyString(), - eq(OkHttpLoadBalancingClient.class)); + eq(OkHttpLoadBalancingClient.class)); doReturn(clientConfig).when(springClientFactory).getClientConfig(anyString()); - OkHttpRibbonCommandFactory commandFactory = new OkHttpRibbonCommandFactory(springClientFactory, zuulProperties, new HashSet()); + OkHttpRibbonCommandFactory commandFactory = new OkHttpRibbonCommandFactory( + springClientFactory, zuulProperties, new HashSet()); RibbonCommandContext context = mock(RibbonCommandContext.class); doReturn("service").when(context).getServiceId(); OkHttpRibbonCommand ribbonCommand = commandFactory.create(context); - assertEquals(6000, ribbonCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); + assertThat(ribbonCommand.getProperties().executionTimeoutInMilliseconds().get() + .intValue()).isEqualTo(6000); } -} \ No newline at end of file +} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommandFallbackTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommandFallbackTests.java index 219c15b95..1cc719eb7 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommandFallbackTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommandFallbackTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,13 +12,11 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.filters.route.okhttp; import com.netflix.zuul.context.RequestContext; - import org.junit.Before; import org.junit.runner.RunWith; @@ -39,8 +37,10 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @DirtiesContext @Import(NoSecurityConfiguration.class) public class OkHttpRibbonCommandFallbackTests extends RibbonCommandFallbackTests { + @Before public void init() { RequestContext.getCurrentContext().clear(); } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommandIntegrationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommandIntegrationTests.java index 8855f8430..edde4bd8b 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommandIntegrationTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonCommandIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.filters.route.okhttp; @@ -20,11 +19,15 @@ package org.springframework.cloud.netflix.zuul.filters.route.okhttp; import java.util.Collections; import java.util.Set; +import com.netflix.client.DefaultLoadBalancerRetryHandler; +import com.netflix.client.config.DefaultClientConfigImpl; +import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.Server; import com.netflix.loadbalancer.ZoneAwareLoadBalancer; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -52,12 +55,8 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.bind.annotation.RestController; -import com.netflix.client.DefaultLoadBalancerRetryHandler; -import com.netflix.client.config.DefaultClientConfigImpl; -import com.netflix.client.config.IClientConfig; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = OkHttpRibbonCommandIntegrationTests.TestConfig.class, webEnvironment = WebEnvironment.RANDOM_PORT, value = { @@ -76,8 +75,8 @@ public class OkHttpRibbonCommandIntegrationTests extends ZuulProxyTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/simple/local/1", HttpMethod.PATCH, new HttpEntity<>("TestPatch"), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Patched 1!", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Patched 1!"); } @Test @@ -85,8 +84,8 @@ public class OkHttpRibbonCommandIntegrationTests extends ZuulProxyTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/simple/local/1", HttpMethod.POST, new HttpEntity<>("TestPost"), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted 1!", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Posted 1!"); } @Test @@ -94,14 +93,14 @@ public class OkHttpRibbonCommandIntegrationTests extends ZuulProxyTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/simple/local/1", HttpMethod.DELETE, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Deleted 1!", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Deleted 1!"); } @Test public void ribbonCommandFactoryOverridden() { - assertTrue("ribbonCommandFactory not a OkHttpRibbonCommandFactory", - this.ribbonCommandFactory instanceof OkHttpRibbonCommandFactory); + assertThat(this.ribbonCommandFactory instanceof OkHttpRibbonCommandFactory) + .as("ribbonCommandFactory not a OkHttpRibbonCommandFactory").isTrue(); } // Don't use @SpringBootApplication because we don't want to component scan @@ -143,8 +142,11 @@ public class OkHttpRibbonCommandIntegrationTests extends ZuulProxyTestBase { client.setRetryHandler(new DefaultLoadBalancerRetryHandler()); return client; } + } static class TestLoadBalancer extends ZoneAwareLoadBalancer { + } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonRetryIntegrationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonRetryIntegrationTests.java index f56830f4c..dcc34abcc 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonRetryIntegrationTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/okhttp/OkHttpRibbonRetryIntegrationTests.java @@ -1,24 +1,23 @@ /* + * Copyright 2017-2019 the original author or authors. * - * * Copyright 2013-2016 the original author or authors. - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.netflix.zuul.filters.route.okhttp; import org.junit.runner.RunWith; + import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.netflix.zuul.filters.route.support.RibbonRetryIntegrationTestBase; import org.springframework.test.annotation.DirtiesContext; @@ -31,8 +30,15 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @SpringBootTest(classes = RibbonRetryIntegrationTestBase.RetryableTestConfig.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, value = { "zuul.retryable: false", /* Disable retry by default, have each route enable it */ "ribbon.okhttp.enabled: true", - "hystrix.command.default.execution.timeout.enabled: false", /* Disable hystrix so its timeout doesnt get in the way */ - "ribbon.ReadTimeout: 1000", /* Make sure ribbon will timeout before the thread is done sleeping */ + "hystrix.command.default.execution.timeout.enabled: false", /* + * Disable hystrix so + * its timeout doesnt + * get in the way + */ + "ribbon.ReadTimeout: 1000", /* + * Make sure ribbon will timeout before the thread is + * done sleeping + */ "zuul.routes.retryable.id: retryable", "zuul.routes.retryable.path: /retryable/**", "zuul.routes.retryable.retryable: true", @@ -52,8 +58,8 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; "disableretry.ribbon.MaxAutoRetriesNextServer: 1", "zuul.routes.globalretrydisabled: /globalretrydisabled/**", "globalretrydisabled.ribbon.MaxAutoRetries: 1", - "globalretrydisabled.ribbon.MaxAutoRetriesNextServer: 1" -}) + "globalretrydisabled.ribbon.MaxAutoRetriesNextServer: 1" }) @DirtiesContext public class OkHttpRibbonRetryIntegrationTests extends RibbonRetryIntegrationTestBase { + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/restclient/RestClientRibbonCommandFallbackTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/restclient/RestClientRibbonCommandFallbackTests.java index ff7d3cd70..43419d33f 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/restclient/RestClientRibbonCommandFallbackTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/restclient/RestClientRibbonCommandFallbackTests.java @@ -1,25 +1,22 @@ /* + * Copyright 2013-2019 the original author or authors. * - * * Copyright 2013-2016 the original author or authors. - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.netflix.zuul.filters.route.restclient; import com.netflix.zuul.context.RequestContext; - import org.junit.Before; import org.junit.runner.RunWith; @@ -37,8 +34,10 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; "ribbon.ReadTimeout: 1" }) @DirtiesContext public class RestClientRibbonCommandFallbackTests extends RibbonCommandFallbackTests { + @Before public void init() { RequestContext.getCurrentContext().clear(); } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/restclient/RestClientRibbonCommandIntegrationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/restclient/RestClientRibbonCommandIntegrationTests.java index 1e09d7a2b..90fbba571 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/restclient/RestClientRibbonCommandIntegrationTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/restclient/RestClientRibbonCommandIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.filters.route.restclient; @@ -83,13 +82,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import static org.hamcrest.CoreMatchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = RestClientRibbonCommandIntegrationTests.TestConfig.class, webEnvironment = WebEnvironment.RANDOM_PORT, value = { @@ -97,7 +90,7 @@ import static org.junit.Assert.assertTrue; "zuul.routes.another: /another/twolevel/**", "zuul.routes.simple: /simple/**", "zuul.routes.badhost: /badhost/**", "zuul.ignored-headers: X-Header", "zuul.routes.rnd: /rnd/**", "rnd.ribbon.listOfServers: ${random.value}", - "zuul.remove-semicolon-content: false", "ribbon.restclient.enabled=true"}) + "zuul.remove-semicolon-content: false", "ribbon.restclient.enabled=true" }) @DirtiesContext public class RestClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { @@ -121,9 +114,9 @@ public class RestClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/self/trailing-slash", HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("/trailing-slash", result.getBody()); - assertFalse(this.myErrorController.wasControllerUsed()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("/trailing-slash"); + assertThat(this.myErrorController.wasControllerUsed()).isFalse(); } @Test @@ -135,8 +128,8 @@ public class RestClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + uri, HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.NOT_FOUND, result.getStatusCode()); - assertFalse(this.myErrorController.wasControllerUsed()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + assertThat(this.myErrorController.wasControllerUsed()).isFalse(); } @Test @@ -146,8 +139,8 @@ public class RestClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/self/add-header", HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertNull(result.getHeaders().get("X-Header")); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getHeaders().get("X-Header")).isNull(); } @Test @@ -157,10 +150,10 @@ public class RestClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/self/add-header", HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); List headers = result.getHeaders().get("X-Application-Context"); - assertNotNull("header was null", headers); - assertEquals("[application-1]", headers.toString()); + assertThat(headers).as("header was null").isNotNull(); + assertThat(headers.toString()).isEqualTo("[application-1]"); } @Test @@ -170,8 +163,8 @@ public class RestClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/self/query?foo=bar", HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("/query?foo=bar", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("/query?foo=bar"); } @Test @@ -181,8 +174,8 @@ public class RestClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/self/matrix/my;q=2;p=1/more;x=2", HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("my=1-2;more=2", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("my=1-2;more=2"); } @Test @@ -192,8 +185,8 @@ public class RestClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/self/query?foo={foo}", HttpMethod.GET, new HttpEntity<>((Void) null), String.class, "weird#chars"); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("/query?foo=weird#chars", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("/query?foo=weird#chars"); } @Test @@ -201,10 +194,12 @@ public class RestClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { this.routes.addRoute("/self/**", "http://localhost:" + this.port + "/"); this.endpoint.reset(); ResponseEntity result = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/self/colonquery?foo:bar={foobar0}&foobar={foobar1}", HttpMethod.GET, - new HttpEntity<>((Void) null), String.class, "baz", "bam"); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("/colonquery?foo:bar=baz&foobar=bam", result.getBody()); + "http://localhost:" + this.port + + "/self/colonquery?foo:bar={foobar0}&foobar={foobar1}", + HttpMethod.GET, new HttpEntity<>((Void) null), String.class, "baz", + "bam"); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("/colonquery?foo:bar=baz&foobar=bam"); } @Test @@ -214,8 +209,8 @@ public class RestClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/self/content-type", HttpMethod.POST, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo(""); } @Test @@ -223,7 +218,7 @@ public class RestClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/simple/throwexception/403", HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.FORBIDDEN, result.getStatusCode()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } @Test @@ -231,7 +226,7 @@ public class RestClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/simple/throwexception/503", HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.SERVICE_UNAVAILABLE, result.getStatusCode()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); } @Test @@ -239,9 +234,9 @@ public class RestClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/badhost/1", HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, result.getStatusCode()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); // JSON response - assertThat(result.getBody(), containsString("\"status\":500")); + assertThat(result.getBody()).contains("\"status\":500"); } @Test @@ -249,15 +244,15 @@ public class RestClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/rnd/1", HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, result.getStatusCode()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); // JSON response - assertThat(result.getBody(), containsString("\"status\":500")); + assertThat(result.getBody()).contains("\"status\":500"); } @Test public void ribbonCommandFactoryOverridden() { - assertTrue("ribbonCommandFactory not a MyRibbonCommandFactory", - this.ribbonCommandFactory instanceof TestConfig.MyRibbonCommandFactory); + assertThat(this.ribbonCommandFactory instanceof TestConfig.MyRibbonCommandFactory) + .as("ribbonCommandFactory not a MyRibbonCommandFactory").isTrue(); } @Override @@ -274,14 +269,15 @@ public class RestClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { map.add("foo", "(bar)"); ResponseEntity result = testRestTemplate.postForEntity( "http://localhost:" + this.port + "/simple/local", map, String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted [(bar)] and Content-Length was: -1!", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()) + .isEqualTo("Posted [(bar)] and Content-Length was: -1!"); } @Test public void routeLocatorOverridden() { - assertTrue("routeLocator not a MyRouteLocator", - this.routeLocator instanceof TestConfig.MyRouteLocator); + assertThat(this.routeLocator instanceof TestConfig.MyRouteLocator) + .as("routeLocator not a MyRouteLocator").isTrue(); } // Don't use @SpringBootApplication because we don't want to component scan @@ -314,8 +310,8 @@ public class RestClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { public ResponseEntity addHeader(HttpServletRequest request) { HttpHeaders headers = new HttpHeaders(); headers.set("X-Header", "FOO"); - ResponseEntity result = new ResponseEntity<>( - request.getRequestURI(), headers, HttpStatus.OK); + ResponseEntity result = new ResponseEntity<>(request.getRequestURI(), + headers, HttpStatus.OK); return result; } @@ -325,7 +321,9 @@ public class RestClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { } @RequestMapping("/colonquery") - public String colonQuery(HttpServletRequest request, @RequestParam(name = "foo:bar") String foobar0, @RequestParam(name = "foobar") String foobar1) { + public String colonQuery(HttpServletRequest request, + @RequestParam(name = "foo:bar") String foobar0, + @RequestParam(name = "foobar") String foobar1) { return request.getRequestURI() + "?foo:bar=" + foobar0 + "&foobar=" + foobar1; } @@ -346,8 +344,7 @@ public class RestClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { @Bean public DiscoveryClientRouteLocator discoveryRouteLocator( - DiscoveryClient discoveryClient, - ZuulProperties zuulProperties) { + DiscoveryClient discoveryClient, ZuulProperties zuulProperties) { return new MyRouteLocator("/", discoveryClient, zuulProperties); } @@ -371,8 +368,8 @@ public class RestClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { private SpringClientFactory clientFactory; - public MyRibbonCommandFactory(SpringClientFactory clientFactory, - Set fallbackProviders) { + MyRibbonCommandFactory(SpringClientFactory clientFactory, + Set fallbackProviders) { super(clientFactory, new ZuulProperties(), fallbackProviders); this.clientFactory = clientFactory; } @@ -390,13 +387,14 @@ public class RestClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { } return super.create(context); } + } static class MyCommand extends RestClientRibbonCommand { private int errorCode; - public MyCommand(int errorCode, String commandKey, RestClient restClient, + MyCommand(int errorCode, String commandKey, RestClient restClient, RibbonCommandContext context) { super(commandKey, restClient, context, new ZuulProperties()); this.errorCode = errorCode; @@ -410,11 +408,13 @@ public class RestClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { return new MockClientHttpResponse(new byte[0], HttpStatus.valueOf(this.errorCode)); } + } // Load balancer with fixed server list for "simple" pointing to bad host @Configuration static class BadHostRibbonClientConfiguration { + @Bean public ServerList ribbonServerList() { return new StaticServerList<>( @@ -423,11 +423,14 @@ public class RestClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { } - //This is needed to allow semicolon separators used in matrix variables + // This is needed to allow semicolon separators used in matrix variables @Configuration - static class CustomHttpFirewallConfig implements WebSecurityConfigurer { + static class CustomHttpFirewallConfig + implements WebSecurityConfigurer { + @Override - public void init(WebSecurity webSecurity) throws Exception {} + public void init(WebSecurity webSecurity) throws Exception { + } @Override public void configure(WebSecurity builder) throws Exception { @@ -435,14 +438,18 @@ public class RestClientRibbonCommandIntegrationTests extends ZuulProxyTestBase { firewall.setAllowSemicolon(true); builder.httpFirewall(firewall); } + } static class MyRouteLocator extends DiscoveryClientRouteLocator { - public MyRouteLocator(String servletPath, DiscoveryClient discovery, + MyRouteLocator(String servletPath, DiscoveryClient discovery, ZuulProperties properties) { super(servletPath, discovery, properties); } + } + } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/NoEncodingFormHttpMessageConverter.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/NoEncodingFormHttpMessageConverter.java index 3f54c9098..3c29a2da9 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/NoEncodingFormHttpMessageConverter.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/NoEncodingFormHttpMessageConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.filters.route.support; @@ -34,14 +33,17 @@ public class NoEncodingFormHttpMessageConverter extends FormHttpMessageConverter @SuppressWarnings("unchecked") @Override - public void write(MultiValueMap map, MediaType contentType, HttpOutputMessage outputMessage) + public void write(MultiValueMap map, MediaType contentType, + HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { MultiValueMap form = (MultiValueMap) map; StringBuilder builder = new StringBuilder(); - for (Iterator nameIterator = form.keySet().iterator(); nameIterator.hasNext();) { + for (Iterator nameIterator = form.keySet().iterator(); nameIterator + .hasNext();) { String name = nameIterator.next(); - for (Iterator valueIterator = form.get(name).iterator(); valueIterator.hasNext();) { + for (Iterator valueIterator = form.get(name).iterator(); valueIterator + .hasNext();) { String value = valueIterator.next(); builder.append(name); if (value != null) { @@ -56,10 +58,12 @@ public class NoEncodingFormHttpMessageConverter extends FormHttpMessageConverter builder.append('&'); } } - final byte[] bytes = builder.toString().getBytes(FormHttpMessageConverter.DEFAULT_CHARSET); + final byte[] bytes = builder.toString() + .getBytes(FormHttpMessageConverter.DEFAULT_CHARSET); outputMessage.getHeaders().setContentLength(bytes.length); outputMessage.getHeaders().setContentType(MediaType.APPLICATION_FORM_URLENCODED); StreamUtils.copy(bytes, outputMessage.getBody()); } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/RibbonCommandCauseFallbackPropagationTest.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/RibbonCommandCauseFallbackPropagationTest.java index c4b2162f4..a92cd2da5 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/RibbonCommandCauseFallbackPropagationTest.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/RibbonCommandCauseFallbackPropagationTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.filters.route.support; @@ -32,7 +31,6 @@ import com.netflix.client.config.IClientConfig; import com.netflix.client.http.HttpResponse; import com.netflix.hystrix.HystrixCommandProperties; import com.netflix.hystrix.exception.HystrixTimeoutException; - import org.junit.Before; import org.junit.Test; @@ -62,8 +60,8 @@ public class RibbonCommandCauseFallbackPropagationTest { @Test public void providerIsCalledInCaseOfException() throws Exception { - FallbackProvider provider = new TestFallbackProvider(getClientHttpResponse( - HttpStatus.INTERNAL_SERVER_ERROR)); + FallbackProvider provider = new TestFallbackProvider( + getClientHttpResponse(HttpStatus.INTERNAL_SERVER_ERROR)); RuntimeException exception = new RuntimeException("Failed!"); TestRibbonCommand testCommand = new TestRibbonCommand(new TestClient(exception), provider, context); @@ -139,102 +137,6 @@ public class RibbonCommandCauseFallbackPropagationTest { .isEqualTo(HystrixTimeoutException.class); } - public static class TestRibbonCommand extends - AbstractRibbonCommand, ClientRequest, HttpResponse> { - - public TestRibbonCommand( - AbstractLoadBalancerAwareClient client, - FallbackProvider fallbackProvider, RibbonCommandContext context) { - this(client, new ZuulProperties(), fallbackProvider, context); - } - - public TestRibbonCommand( - AbstractLoadBalancerAwareClient client, - ZuulProperties zuulProperties, FallbackProvider fallbackProvider, RibbonCommandContext context) { - super("testCommand" + UUID.randomUUID(), client, context, zuulProperties, - fallbackProvider); - } - - public TestRibbonCommand( - AbstractLoadBalancerAwareClient client, - FallbackProvider fallbackProvider, int timeout, RibbonCommandContext context) { - // different name is used because of properties caching - super(getSetter("testCommand" + UUID.randomUUID(), new ZuulProperties(), new DefaultClientConfigImpl()) - .andCommandPropertiesDefaults(defauts(timeout)), client, context, - fallbackProvider, null); - } - - private static HystrixCommandProperties.Setter defauts(final int timeout) { - return HystrixCommandProperties.Setter().withExecutionTimeoutEnabled(true) - .withExecutionIsolationStrategy( - HystrixCommandProperties.ExecutionIsolationStrategy.THREAD) - .withExecutionTimeoutInMilliseconds(timeout); - } - - @Override - protected ClientRequest createRequest() throws Exception { - return null; - } - } - - @SuppressWarnings("rawtypes") - public static class TestClient extends AbstractLoadBalancerAwareClient { - - private final RuntimeException exception; - - public TestClient(RuntimeException exception) { - super(null); - this.exception = exception; - } - - @Override - public IResponse executeWithLoadBalancer(final ClientRequest request, - final IClientConfig requestConfig) throws ClientException { - throw exception; - } - - @Override - public RequestSpecificRetryHandler getRequestSpecificRetryHandler( - final ClientRequest clientRequest, final IClientConfig iClientConfig) { - return null; - } - - @Override - public IResponse execute(final ClientRequest clientRequest, - final IClientConfig iClientConfig) throws Exception { - return null; - } - } - - public static class TestFallbackProvider implements FallbackProvider { - - private final ClientHttpResponse response; - private Throwable cause; - - public TestFallbackProvider(final ClientHttpResponse response) { - this.response = response; - } - - @Override - public ClientHttpResponse fallbackResponse(String route, final Throwable cause) { - this.cause = cause; - return response; - } - - @Override - public String getRoute() { - return "test-route"; - } - - public Throwable getCause() { - return cause; - } - - public static TestFallbackProvider withResponse(final HttpStatus status) { - return new TestFallbackProvider(getClientHttpResponse(status)); - } - } - private static ClientHttpResponse getClientHttpResponse(final HttpStatus status) { return new ClientHttpResponse() { @Override @@ -267,4 +169,108 @@ public class RibbonCommandCauseFallbackPropagationTest { } }; } + + public static class TestFallbackProvider implements FallbackProvider { + + private final ClientHttpResponse response; + + private Throwable cause; + + public TestFallbackProvider(final ClientHttpResponse response) { + this.response = response; + } + + @Override + public ClientHttpResponse fallbackResponse(String route, final Throwable cause) { + this.cause = cause; + return response; + } + + @Override + public String getRoute() { + return "test-route"; + } + + public Throwable getCause() { + return cause; + } + + public static TestFallbackProvider withResponse(final HttpStatus status) { + return new TestFallbackProvider(getClientHttpResponse(status)); + } + + } + + @SuppressWarnings("rawtypes") + public static class TestClient extends AbstractLoadBalancerAwareClient { + + private final RuntimeException exception; + + public TestClient(RuntimeException exception) { + super(null); + this.exception = exception; + } + + @Override + public IResponse executeWithLoadBalancer(final ClientRequest request, + final IClientConfig requestConfig) throws ClientException { + throw exception; + } + + @Override + public RequestSpecificRetryHandler getRequestSpecificRetryHandler( + final ClientRequest clientRequest, final IClientConfig iClientConfig) { + return null; + } + + @Override + public IResponse execute(final ClientRequest clientRequest, + final IClientConfig iClientConfig) throws Exception { + return null; + } + + } + + public static class TestRibbonCommand extends + AbstractRibbonCommand, ClientRequest, HttpResponse> { + + public TestRibbonCommand( + AbstractLoadBalancerAwareClient client, + FallbackProvider fallbackProvider, RibbonCommandContext context) { + this(client, new ZuulProperties(), fallbackProvider, context); + } + + public TestRibbonCommand( + AbstractLoadBalancerAwareClient client, + ZuulProperties zuulProperties, FallbackProvider fallbackProvider, + RibbonCommandContext context) { + super("testCommand" + UUID.randomUUID(), client, context, zuulProperties, + fallbackProvider); + } + + public TestRibbonCommand( + AbstractLoadBalancerAwareClient client, + FallbackProvider fallbackProvider, int timeout, + RibbonCommandContext context) { + // different name is used because of properties caching + super(getSetter("testCommand" + UUID.randomUUID(), new ZuulProperties(), + new DefaultClientConfigImpl()).andCommandPropertiesDefaults( + defauts(timeout)), + client, context, fallbackProvider, null); + } + + private static HystrixCommandProperties.Setter defauts(final int timeout) { + return HystrixCommandProperties.Setter().withExecutionTimeoutEnabled(true) + .withExecutionIsolationStrategy( + HystrixCommandProperties.ExecutionIsolationStrategy.THREAD) + .withExecutionTimeoutInMilliseconds(timeout); + } + + @Override + protected ClientRequest createRequest() throws Exception { + return null; + } + + } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/RibbonCommandFallbackTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/RibbonCommandFallbackTests.java index 7330da753..ceebac84d 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/RibbonCommandFallbackTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/RibbonCommandFallbackTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.filters.route.support; @@ -24,6 +23,7 @@ import java.util.Collections; import java.util.Set; import org.junit.Test; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.web.client.TestRestTemplate; @@ -50,7 +50,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.http.client.ClientHttpResponse; import org.springframework.web.bind.annotation.RestController; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Ryan Baxter @@ -66,8 +66,8 @@ public abstract class RibbonCommandFallbackTests { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + uri, HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("fallback", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("fallback"); } @Test @@ -76,8 +76,8 @@ public abstract class RibbonCommandFallbackTests { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + uri, HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("default fallback", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("default fallback"); } // Don't use @SpringBootApplication because we don't want to component scan @@ -87,14 +87,14 @@ public abstract class RibbonCommandFallbackTests { @EnableZuulProxy @RibbonClients({ @RibbonClient(name = "simple", configuration = ZuulProxyTestBase.SimpleRibbonClientConfiguration.class), - @RibbonClient(name = "another", configuration = ZuulProxyTestBase.AnotherRibbonClientConfiguration.class)}) + @RibbonClient(name = "another", configuration = ZuulProxyTestBase.AnotherRibbonClientConfiguration.class) }) @Import(NoSecurityConfiguration.class) - public static class TestConfig extends ZuulProxyTestBase.AbstractZuulProxyApplication { + public static class TestConfig + extends ZuulProxyTestBase.AbstractZuulProxyApplication { @Autowired(required = false) private Set zuulFallbackProviders = Collections.emptySet(); - @Bean public RibbonCommandFactory ribbonCommandFactory( final SpringClientFactory clientFactory) { @@ -112,6 +112,7 @@ public abstract class RibbonCommandFallbackTests { public FallbackProvider defaultFallbackProvider() { return new DefaultFallbackProvider(); } + } public static class DefaultFallbackProvider implements FallbackProvider { @@ -131,7 +132,7 @@ public abstract class RibbonCommandFallbackTests { @Override public int getRawStatusCode() throws IOException { - if(route.equals("another")) { + if (route.equals("another")) { return 200; } return 500; @@ -160,5 +161,7 @@ public abstract class RibbonCommandFallbackTests { } }; } + } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/RibbonCommandHystrixThreadPoolKeyTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/RibbonCommandHystrixThreadPoolKeyTests.java index 2003c5aed..0a6b68a8e 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/RibbonCommandHystrixThreadPoolKeyTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/RibbonCommandHystrixThreadPoolKeyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,6 @@ import com.netflix.client.ClientRequest; import com.netflix.client.http.HttpResponse; import com.netflix.hystrix.HystrixCommandProperties; import com.netflix.hystrix.strategy.HystrixPlugins; - import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -122,6 +121,7 @@ public class RibbonCommandHystrixThreadPoolKeyTests { public static class TestRibbonCommand extends AbstractRibbonCommand, ClientRequest, HttpResponse> { + public TestRibbonCommand(String commandKey, ZuulProperties zuulProperties) { super(commandKey, null, null, zuulProperties); } @@ -130,5 +130,7 @@ public class RibbonCommandHystrixThreadPoolKeyTests { protected ClientRequest createRequest() throws Exception { return null; } + } -} \ No newline at end of file + +} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/RibbonRetryIntegrationTestBase.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/RibbonRetryIntegrationTestBase.java index 9125f7237..0384854a8 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/RibbonRetryIntegrationTestBase.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/RibbonRetryIntegrationTestBase.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.filters.route.support; @@ -20,7 +19,6 @@ package org.springframework.cloud.netflix.zuul.filters.route.support; import com.netflix.loadbalancer.Server; import com.netflix.loadbalancer.ServerList; import com.netflix.zuul.context.RequestContext; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Before; @@ -34,8 +32,8 @@ import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicy; import org.springframework.cloud.client.loadbalancer.ServiceInstanceChooser; import org.springframework.cloud.netflix.ribbon.RibbonClient; import org.springframework.cloud.netflix.ribbon.RibbonClients; -import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancedRetryPolicy; import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancedRetryFactory; +import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancedRetryPolicy; import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerContext; import org.springframework.cloud.netflix.ribbon.SpringClientFactory; import org.springframework.cloud.netflix.ribbon.StaticServerList; @@ -53,7 +51,7 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Ryan Baxter @@ -79,7 +77,7 @@ public abstract class RibbonRetryIntegrationTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + uri, HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test @@ -88,7 +86,7 @@ public abstract class RibbonRetryIntegrationTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + uri, HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test @@ -97,7 +95,7 @@ public abstract class RibbonRetryIntegrationTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + uri, HttpMethod.POST, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test @@ -106,7 +104,7 @@ public abstract class RibbonRetryIntegrationTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + uri, HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test @@ -115,7 +113,7 @@ public abstract class RibbonRetryIntegrationTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + uri, HttpMethod.POST, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, result.getStatusCode()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); } @Test @@ -125,7 +123,7 @@ public abstract class RibbonRetryIntegrationTestBase { "http://localhost:" + this.port + uri, HttpMethod.GET, new HttpEntity<>((Void) null), String.class); LOG.info("Response Body: " + result.getBody()); - assertEquals(HttpStatus.GATEWAY_TIMEOUT, result.getStatusCode()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.GATEWAY_TIMEOUT); } @Test @@ -135,7 +133,7 @@ public abstract class RibbonRetryIntegrationTestBase { "http://localhost:" + this.port + uri, HttpMethod.GET, new HttpEntity<>((Void) null), String.class); LOG.info("Response Body: " + result.getBody()); - assertEquals(HttpStatus.GATEWAY_TIMEOUT, result.getStatusCode()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.GATEWAY_TIMEOUT); } // Don't use @SpringBootApplication because we don't want to component scan @@ -205,6 +203,7 @@ public abstract class RibbonRetryIntegrationTestBase { public ServerList ribbonServerList() { return new StaticServerList<>(new Server("localhost", this.port)); } + } @Configuration @@ -217,8 +216,7 @@ public abstract class RibbonRetryIntegrationTestBase { return new MyRibbonRetryFactory(factory); } - public static class MyRibbonRetryFactory - extends RibbonLoadBalancedRetryFactory { + public static class MyRibbonRetryFactory extends RibbonLoadBalancedRetryFactory { private SpringClientFactory factory; @@ -238,7 +236,7 @@ public abstract class RibbonRetryIntegrationTestBase { class MyLoadBalancedRetryPolicy extends RibbonLoadBalancedRetryPolicy { - public MyLoadBalancedRetryPolicy(String serviceId, + MyLoadBalancedRetryPolicy(String serviceId, RibbonLoadBalancerContext context, ServiceInstanceChooser loadBalanceChooser) { super(serviceId, context, loadBalanceChooser); @@ -251,7 +249,11 @@ public abstract class RibbonRetryIntegrationTestBase { } return super.retryableStatusCode(statusCode); } + } + } + } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/ZuulProxyTestBase.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/ZuulProxyTestBase.java index 96ae29881..d91fbdce1 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/ZuulProxyTestBase.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/route/support/ZuulProxyTestBase.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.filters.route.support; @@ -30,11 +29,16 @@ import java.util.concurrent.atomic.AtomicBoolean; import javax.servlet.http.HttpServletRequest; +import com.netflix.loadbalancer.Server; +import com.netflix.loadbalancer.ServerList; +import com.netflix.zuul.ZuulFilter; +import com.netflix.zuul.context.RequestContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.After; import org.junit.Before; import org.junit.Test; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.web.ErrorProperties; @@ -72,14 +76,8 @@ import org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfigu import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerList; -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.context.RequestContext; - +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; import static org.junit.Assume.assumeThat; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE; @@ -145,12 +143,12 @@ public abstract class ZuulProxyTestBase { @Test public void bindRouteUsingPhysicalRoute() { - assertEquals("http://localhost:7777/local", getRoute("/test/**")); + assertThat(getRoute("/test/**")).isEqualTo("http://localhost:7777/local"); } @Test public void bindRouteUsingOnlyPath() { - assertEquals("simple", getRoute("/simple/**")); + assertThat(getRoute("/simple/**")).isEqualTo("simple"); } @Test @@ -158,8 +156,8 @@ public abstract class ZuulProxyTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/simple/local/1", HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Gotten 1!", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Gotten 1!"); } @Test @@ -169,8 +167,8 @@ public abstract class ZuulProxyTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/self/1", HttpMethod.DELETE, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Deleted 1!", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Deleted 1!"); } @Test @@ -181,9 +179,9 @@ public abstract class ZuulProxyTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/strip", HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); // Prefix not stripped to it goes to /local/strip - assertEquals("Gotten strip!", result.getBody()); + assertThat(result.getBody()).isEqualTo("Gotten strip!"); } @Test @@ -191,7 +189,7 @@ public abstract class ZuulProxyTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/simple/local/notfound", HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.NOT_FOUND, result.getStatusCode()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } @Test @@ -199,7 +197,7 @@ public abstract class ZuulProxyTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/myinvalidpath", HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.NOT_FOUND, result.getStatusCode()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } @Test @@ -207,8 +205,8 @@ public abstract class ZuulProxyTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/another/twolevel/local/1", HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Gotten 1!", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Gotten 1!"); } @Test @@ -218,9 +216,9 @@ public abstract class ZuulProxyTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + uri, HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Hello space", result.getBody()); - assertFalse(myErrorController.wasControllerUsed()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Hello space"); + assertThat(myErrorController.wasControllerUsed()).isFalse(); } @Test @@ -229,12 +227,12 @@ public abstract class ZuulProxyTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/simple/deletewithbody", HttpMethod.DELETE, new HttpEntity<>("deleterequestbody"), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); if (supportsDeleteWithBody()) { - assertEquals("Deleted deleterequestbody", result.getBody()); + assertThat(result.getBody()).isEqualTo("Deleted deleterequestbody"); } else { - assertEquals("Deleted null", result.getBody()); + assertThat(result.getBody()).isEqualTo("Deleted null"); } } @@ -245,8 +243,8 @@ public abstract class ZuulProxyTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + uri, HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.NOT_FOUND, result.getStatusCode()); - assertFalse(myErrorController.wasControllerUsed()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + assertThat(myErrorController.wasControllerUsed()).isFalse(); } @Test @@ -257,8 +255,8 @@ public abstract class ZuulProxyTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/self/spa ce", HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Hello space", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Hello space"); } @Test @@ -270,8 +268,8 @@ public abstract class ZuulProxyTestBase { "http://localhost:" + this.port + "/self/qstring?original=value1&original=value2", HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Received {original=[value1, value2]}", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Received {original=[value1, value2]}"); } @Test @@ -283,8 +281,8 @@ public abstract class ZuulProxyTestBase { "http://localhost:" + this.port + "/self/qstring?override=true&different=key", HttpMethod.GET, new HttpEntity<>((Void) null), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Received {key=[overridden]}", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Received {key=[overridden]}"); } @Test @@ -297,8 +295,8 @@ public abstract class ZuulProxyTestBase { ResponseEntity result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/self/1", HttpMethod.PATCH, new HttpEntity<>("TestPatch"), String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Patched 1!", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("Patched 1!"); } @SuppressWarnings("deprecation") @@ -314,8 +312,9 @@ public abstract class ZuulProxyTestBase { map.add("foo", "(bar)"); ResponseEntity result = testRestTemplate.postForEntity( "http://localhost:" + this.port + "/simple/local", map, String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Posted [(bar)] and Content-Length was: 13!", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()) + .isEqualTo("Posted [(bar)] and Content-Length was: 13!"); } public static abstract class AbstractZuulProxyApplication @@ -369,7 +368,7 @@ public abstract class ZuulProxyTestBase { return "Posted " + id + "!"; } - @RequestMapping(value = "/qstring") + @RequestMapping("/qstring") public String qstring(@RequestParam MultiValueMap params) { return "Received " + params.toString(); } @@ -486,6 +485,7 @@ public abstract class ZuulProxyTestBase { } }; } + } @Configuration @@ -501,6 +501,7 @@ public abstract class ZuulProxyTestBase { converters.add(converter); super.configureMessageConverters(converters); } + } // Load balancer with fixed server list for "simple" pointing to localhost @@ -531,6 +532,7 @@ public abstract class ZuulProxyTestBase { } public static class MyErrorController extends BasicErrorController { + ThreadLocal uriToMatch = new ThreadLocal<>(); AtomicBoolean controllerUsed = new AtomicBoolean(); @@ -562,5 +564,7 @@ public abstract class ZuulProxyTestBase { public void clear() { this.controllerUsed.set(false); } + } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/metrics/DefaultCounterFactoryTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/metrics/DefaultCounterFactoryTests.java index 95e74f043..6c8bff3b8 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/metrics/DefaultCounterFactoryTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/metrics/DefaultCounterFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,9 +16,7 @@ package org.springframework.cloud.netflix.zuul.metrics; - import com.netflix.zuul.monitoring.CounterFactory; - import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.MeterRegistry; import org.junit.Test; @@ -43,4 +41,5 @@ public class DefaultCounterFactoryTests { verify(counter).increment(); } -} \ No newline at end of file + +} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/metrics/ZuulEmptyMetricsApplicationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/metrics/ZuulEmptyMetricsApplicationTests.java index 5f184ec45..644fedc66 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/metrics/ZuulEmptyMetricsApplicationTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/metrics/ZuulEmptyMetricsApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.metrics; @@ -36,20 +35,20 @@ import org.springframework.cloud.test.ModifiedClassPathRunner; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Configuration; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(ModifiedClassPathRunner.class) -@ClassPathExclusions({ "spring-boot-starter-actuator-*.jar", - "spring-boot-actuator-*.jar", "micrometer-core-*.jar" }) +@ClassPathExclusions({ "spring-boot-starter-actuator-*.jar", "spring-boot-actuator-*.jar", + "micrometer-core-*.jar" }) public class ZuulEmptyMetricsApplicationTests { private ConfigurableApplicationContext context; @Before public void setUp() throws Exception { - ConfigurableApplicationContext context = new SpringApplicationBuilder(ZuulEmptyMetricsApplicationTestsConfiguration.class) - .web(WebApplicationType.NONE) - .run("--debug"); + ConfigurableApplicationContext context = new SpringApplicationBuilder( + ZuulEmptyMetricsApplicationTestsConfiguration.class) + .web(WebApplicationType.NONE).run("--debug"); this.context = context; } @@ -65,14 +64,14 @@ public class ZuulEmptyMetricsApplicationTests { throws Exception { CounterFactory factory = this.context.getBean(CounterFactory.class); - assertEquals(EmptyCounterFactory.class, factory.getClass()); + assertThat(factory.getClass()).isEqualTo(EmptyCounterFactory.class); } @Test public void shouldSetupEmptyTracerFactory() throws Exception { TracerFactory factory = this.context.getBean(TracerFactory.class); - assertEquals(EmptyTracerFactory.class, factory.getClass()); + assertThat(factory.getClass()).isEqualTo(EmptyTracerFactory.class); } @EnableAutoConfiguration(exclude = TestAutoConfiguration.class) @@ -83,4 +82,5 @@ public class ZuulEmptyMetricsApplicationTests { static class ZuulEmptyMetricsApplicationTestsConfiguration { } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/metrics/ZuulMetricsApplicationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/metrics/ZuulMetricsApplicationTests.java index 8f5efe537..24061a216 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/metrics/ZuulMetricsApplicationTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/metrics/ZuulMetricsApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,13 +12,20 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.metrics; +import com.netflix.zuul.exception.ZuulException; +import com.netflix.zuul.monitoring.CounterFactory; +import com.netflix.zuul.monitoring.TracerFactory; +import io.micrometer.core.instrument.MeterRegistry; +import io.micrometer.core.instrument.MockClock; +import io.micrometer.core.instrument.simple.SimpleConfig; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -29,18 +36,9 @@ import org.springframework.context.annotation.Configuration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; -import com.netflix.zuul.exception.ZuulException; -import com.netflix.zuul.monitoring.CounterFactory; -import com.netflix.zuul.monitoring.TracerFactory; - -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; -import io.micrometer.core.instrument.MeterRegistry; -import io.micrometer.core.instrument.MockClock; -import io.micrometer.core.instrument.simple.SimpleConfig; -import io.micrometer.core.instrument.simple.SimpleMeterRegistry; - @RunWith(SpringRunner.class) @SpringBootTest(classes = { ZuulMetricsApplicationTests.ZuulMetricsApplicationTestsConfiguration.class, @@ -50,20 +48,22 @@ public class ZuulMetricsApplicationTests { @Autowired private CounterFactory counterFactory; + @Autowired private TracerFactory tracerFactory; + @Autowired private MeterRegistry meterRegistry; @Test public void shouldSetupDefaultCounterFactoryIfCounterServiceIsPresent() throws Exception { - assertEquals(DefaultCounterFactory.class, counterFactory.getClass()); + assertThat(counterFactory.getClass()).isEqualTo(DefaultCounterFactory.class); } @Test public void shouldSetupEmptyTracerFactory() throws Exception { - assertEquals(EmptyTracerFactory.class, tracerFactory.getClass()); + assertThat(tracerFactory.getClass()).isEqualTo(EmptyTracerFactory.class); } @Test @@ -72,20 +72,20 @@ public class ZuulMetricsApplicationTests { new ZuulRuntimeException(new Exception()); Double count = meterRegistry.counter("ZUUL::EXCEPTION:null:500").count(); - assertEquals(count.longValue(), 0L); + assertThat(0L).isEqualTo(count.longValue()); new ZuulException("any", 500, "cause"); new ZuulException("any", 500, "cause"); count = meterRegistry.counter("ZUUL::EXCEPTION:cause:500").count(); - assertEquals(count.longValue(), 2L); + assertThat(2L).isEqualTo(count.longValue()); new ZuulException("any", 404, "cause2"); new ZuulException("any", 404, "cause2"); new ZuulException("any", 404, "cause2"); count = meterRegistry.counter("ZUUL::EXCEPTION:cause2:404").count(); - assertEquals(count.longValue(), 3L); + assertThat(3L).isEqualTo(count.longValue()); } // Don't use @SpringBootApplication because we don't want to component scan @@ -103,5 +103,7 @@ public class ZuulMetricsApplicationTests { public MeterRegistry meterRegistry() { return new SimpleMeterRegistry(SimpleConfig.DEFAULT, new MockClock()); } + } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/AdhocTestSuite.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/AdhocTestSuite.java index b248d167f..aea509894 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/AdhocTestSuite.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/AdhocTestSuite.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.test; @@ -21,6 +20,7 @@ import org.junit.Ignore; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; + import org.springframework.cloud.netflix.zuul.filters.route.SimpleHostRoutingFilterIntegrationTests; /** @@ -30,64 +30,62 @@ import org.springframework.cloud.netflix.zuul.filters.route.SimpleHostRoutingFil */ @RunWith(Suite.class) @SuiteClasses({ - org.springframework.cloud.netflix.zuul.ZuulServerAutoConfigurationTests.class, - org.springframework.cloud.netflix.zuul.RoutesEndpointTests.class, - org.springframework.cloud.netflix.zuul.FormZuulServletProxyApplicationTests.class, - org.springframework.cloud.netflix.zuul.metrics.DefaultCounterFactoryTests.class, - org.springframework.cloud.netflix.zuul.metrics.ZuulEmptyMetricsApplicationTests.class, - org.springframework.cloud.netflix.zuul.metrics.ZuulMetricsApplicationTests.class, - org.springframework.cloud.netflix.zuul.web.ZuulHandlerMappingTests.class, - org.springframework.cloud.netflix.zuul.ZuulProxyAutoConfigurationTests.class, - org.springframework.cloud.netflix.zuul.RetryableZuulProxyApplicationTests.class, - org.springframework.cloud.netflix.zuul.ServletPathZuulProxyApplicationTests.class, - org.springframework.cloud.netflix.zuul.FormZuulProxyApplicationTests.class, - org.springframework.cloud.netflix.zuul.filters.CompositeRouteLocatorTests.class, - org.springframework.cloud.netflix.zuul.filters.route.apache.HttpClientRibbonCommandIntegrationTests.class, - org.springframework.cloud.netflix.zuul.filters.route.apache.HttpClientRibbonCommandFallbackTests.class, - org.springframework.cloud.netflix.zuul.filters.route.apache.HttpClientRibbonCommandFactoryTest.class, - org.springframework.cloud.netflix.zuul.filters.route.apache.HttpClientRibbonRetryIntegrationTests.class, - org.springframework.cloud.netflix.zuul.filters.route.LazyLoadOfZuulConfigurationTests.class, - org.springframework.cloud.netflix.zuul.filters.route.EagerLoadOfZuulConfigurationTests.class, - org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilterTests.class, - org.springframework.cloud.netflix.zuul.filters.route.SendForwardFilterTests.class, - org.springframework.cloud.netflix.zuul.filters.route.RestClientRibbonCommandTests.class, - org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilterLoadBalancerKeyIntegrationTests.class, - org.springframework.cloud.netflix.zuul.filters.route.okhttp.OkHttpRibbonCommandFallbackTests.class, - org.springframework.cloud.netflix.zuul.filters.route.okhttp.OkHttpRibbonRetryIntegrationTests.class, - org.springframework.cloud.netflix.zuul.filters.route.okhttp.OkHttpRibbonCommandIntegrationTests.class, - org.springframework.cloud.netflix.zuul.filters.route.okhttp.OkHttpRibbonCommandFactoryTest.class, - org.springframework.cloud.netflix.zuul.filters.route.restclient.RestClientRibbonCommandIntegrationTests.class, - org.springframework.cloud.netflix.zuul.filters.route.restclient.RestClientRibbonCommandFallbackTests.class, - org.springframework.cloud.netflix.zuul.filters.route.support.RibbonCommandCauseFallbackPropagationTest.class, - org.springframework.cloud.netflix.zuul.filters.route.support.RibbonCommandHystrixThreadPoolKeyTests.class, - SimpleHostRoutingFilterIntegrationTests.class, - org.springframework.cloud.netflix.zuul.filters.ProxyRequestHelperTests.class, - org.springframework.cloud.netflix.zuul.filters.SimpleRouteLocatorTests.class, - org.springframework.cloud.netflix.zuul.filters.ZuulPropertiesTests.class, - org.springframework.cloud.netflix.zuul.filters.CustomHostRoutingFilterTests.class, - org.springframework.cloud.netflix.zuul.filters.discovery.PatternServiceRouteMapperIntegrationTests.class, - org.springframework.cloud.netflix.zuul.filters.discovery.PatternServiceRouteMapperTests.class, - org.springframework.cloud.netflix.zuul.filters.discovery.DiscoveryClientRouteLocatorTests.class, - org.springframework.cloud.netflix.zuul.filters.pre.PreDecorationFilterTests.class, - org.springframework.cloud.netflix.zuul.filters.pre.FormBodyWrapperFilterTests.class, - org.springframework.cloud.netflix.zuul.filters.post.LocationRewriteFilterTests.class, - org.springframework.cloud.netflix.zuul.filters.post.SendResponseFilterTests.class, - org.springframework.cloud.netflix.zuul.filters.post.SendErrorFilterIntegrationTests.class, - org.springframework.cloud.netflix.zuul.filters.post.LocationRewriteFilterIntegrationTests.class, - org.springframework.cloud.netflix.zuul.filters.post.SendErrorFilterTests.class, - org.springframework.cloud.netflix.zuul.RoutesEndpointDetailsTests.class, - org.springframework.cloud.netflix.zuul.ZuulProxyConfigurationTests.class, - org.springframework.cloud.netflix.zuul.ZuulProxyApplicationTests.class, - org.springframework.cloud.netflix.zuul.SimpleZuulProxyApplicationTests.class, - org.springframework.cloud.netflix.zuul.ZuulFilterInitializerTests.class, - org.springframework.cloud.netflix.zuul.RoutesEndpointIntegrationTests.class, - org.springframework.cloud.netflix.zuul.test.ZuulApacheHttpClientConfigurationTests.class, - org.springframework.cloud.netflix.zuul.test.ZuulOkHttpClientConfigurationTests.class, - org.springframework.cloud.netflix.zuul.ContextPathZuulProxyApplicationTests.class, - org.springframework.cloud.netflix.zuul.SimpleZuulServerApplicationTests.class, - org.springframework.cloud.netflix.zuul.FiltersEndpointTests.class, - -}) + org.springframework.cloud.netflix.zuul.ZuulServerAutoConfigurationTests.class, + org.springframework.cloud.netflix.zuul.RoutesEndpointTests.class, + org.springframework.cloud.netflix.zuul.FormZuulServletProxyApplicationTests.class, + org.springframework.cloud.netflix.zuul.metrics.DefaultCounterFactoryTests.class, + org.springframework.cloud.netflix.zuul.metrics.ZuulEmptyMetricsApplicationTests.class, + org.springframework.cloud.netflix.zuul.metrics.ZuulMetricsApplicationTests.class, + org.springframework.cloud.netflix.zuul.web.ZuulHandlerMappingTests.class, + org.springframework.cloud.netflix.zuul.ZuulProxyAutoConfigurationTests.class, + org.springframework.cloud.netflix.zuul.RetryableZuulProxyApplicationTests.class, + org.springframework.cloud.netflix.zuul.ServletPathZuulProxyApplicationTests.class, + org.springframework.cloud.netflix.zuul.FormZuulProxyApplicationTests.class, + org.springframework.cloud.netflix.zuul.filters.CompositeRouteLocatorTests.class, + org.springframework.cloud.netflix.zuul.filters.route.apache.HttpClientRibbonCommandIntegrationTests.class, + org.springframework.cloud.netflix.zuul.filters.route.apache.HttpClientRibbonCommandFallbackTests.class, + org.springframework.cloud.netflix.zuul.filters.route.apache.HttpClientRibbonCommandFactoryTest.class, + org.springframework.cloud.netflix.zuul.filters.route.apache.HttpClientRibbonRetryIntegrationTests.class, + org.springframework.cloud.netflix.zuul.filters.route.LazyLoadOfZuulConfigurationTests.class, + org.springframework.cloud.netflix.zuul.filters.route.EagerLoadOfZuulConfigurationTests.class, + org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilterTests.class, + org.springframework.cloud.netflix.zuul.filters.route.SendForwardFilterTests.class, + org.springframework.cloud.netflix.zuul.filters.route.RestClientRibbonCommandTests.class, + org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilterLoadBalancerKeyIntegrationTests.class, + org.springframework.cloud.netflix.zuul.filters.route.okhttp.OkHttpRibbonCommandFallbackTests.class, + org.springframework.cloud.netflix.zuul.filters.route.okhttp.OkHttpRibbonRetryIntegrationTests.class, + org.springframework.cloud.netflix.zuul.filters.route.okhttp.OkHttpRibbonCommandIntegrationTests.class, + org.springframework.cloud.netflix.zuul.filters.route.okhttp.OkHttpRibbonCommandFactoryTest.class, + org.springframework.cloud.netflix.zuul.filters.route.restclient.RestClientRibbonCommandIntegrationTests.class, + org.springframework.cloud.netflix.zuul.filters.route.restclient.RestClientRibbonCommandFallbackTests.class, + org.springframework.cloud.netflix.zuul.filters.route.support.RibbonCommandCauseFallbackPropagationTest.class, + org.springframework.cloud.netflix.zuul.filters.route.support.RibbonCommandHystrixThreadPoolKeyTests.class, + SimpleHostRoutingFilterIntegrationTests.class, + org.springframework.cloud.netflix.zuul.filters.ProxyRequestHelperTests.class, + org.springframework.cloud.netflix.zuul.filters.SimpleRouteLocatorTests.class, + org.springframework.cloud.netflix.zuul.filters.ZuulPropertiesTests.class, + org.springframework.cloud.netflix.zuul.filters.CustomHostRoutingFilterTests.class, + org.springframework.cloud.netflix.zuul.filters.discovery.PatternServiceRouteMapperIntegrationTests.class, + org.springframework.cloud.netflix.zuul.filters.discovery.PatternServiceRouteMapperTests.class, + org.springframework.cloud.netflix.zuul.filters.discovery.DiscoveryClientRouteLocatorTests.class, + org.springframework.cloud.netflix.zuul.filters.pre.PreDecorationFilterTests.class, + org.springframework.cloud.netflix.zuul.filters.pre.FormBodyWrapperFilterTests.class, + org.springframework.cloud.netflix.zuul.filters.post.LocationRewriteFilterTests.class, + org.springframework.cloud.netflix.zuul.filters.post.SendResponseFilterTests.class, + org.springframework.cloud.netflix.zuul.filters.post.SendErrorFilterIntegrationTests.class, + org.springframework.cloud.netflix.zuul.filters.post.LocationRewriteFilterIntegrationTests.class, + org.springframework.cloud.netflix.zuul.filters.post.SendErrorFilterTests.class, + org.springframework.cloud.netflix.zuul.RoutesEndpointDetailsTests.class, + org.springframework.cloud.netflix.zuul.ZuulProxyConfigurationTests.class, + org.springframework.cloud.netflix.zuul.ZuulProxyApplicationTests.class, + org.springframework.cloud.netflix.zuul.SimpleZuulProxyApplicationTests.class, + org.springframework.cloud.netflix.zuul.ZuulFilterInitializerTests.class, + org.springframework.cloud.netflix.zuul.RoutesEndpointIntegrationTests.class, + org.springframework.cloud.netflix.zuul.test.ZuulApacheHttpClientConfigurationTests.class, + org.springframework.cloud.netflix.zuul.test.ZuulOkHttpClientConfigurationTests.class, + org.springframework.cloud.netflix.zuul.ContextPathZuulProxyApplicationTests.class, + org.springframework.cloud.netflix.zuul.SimpleZuulServerApplicationTests.class, + org.springframework.cloud.netflix.zuul.FiltersEndpointTests.class }) @Ignore public class AdhocTestSuite { diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/AdhocZuulTestSuite.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/AdhocZuulTestSuite.java index 2eb9206f0..f20b524df 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/AdhocZuulTestSuite.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/AdhocZuulTestSuite.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.test; @@ -21,6 +20,7 @@ import org.junit.Ignore; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; + import org.springframework.cloud.netflix.zuul.filters.route.SimpleHostRoutingFilterIntegrationTests; /** @@ -30,7 +30,7 @@ import org.springframework.cloud.netflix.zuul.filters.route.SimpleHostRoutingFil */ @RunWith(Suite.class) @SuiteClasses({ -org.springframework.cloud.netflix.zuul.ContextPathZuulProxyApplicationTests.class, + org.springframework.cloud.netflix.zuul.ContextPathZuulProxyApplicationTests.class, org.springframework.cloud.netflix.zuul.filters.CompositeRouteLocatorTests.class, org.springframework.cloud.netflix.zuul.filters.CustomHostRoutingFilterTests.class, org.springframework.cloud.netflix.zuul.filters.discovery.DiscoveryClientRouteLocatorTests.class, @@ -84,8 +84,7 @@ org.springframework.cloud.netflix.zuul.ContextPathZuulProxyApplicationTests.clas org.springframework.cloud.netflix.zuul.ZuulProxyApplicationTests.class, org.springframework.cloud.netflix.zuul.ZuulProxyAutoConfigurationTests.class, org.springframework.cloud.netflix.zuul.ZuulProxyConfigurationTests.class, - org.springframework.cloud.netflix.zuul.ZuulServerAutoConfigurationTests.class, -}) + org.springframework.cloud.netflix.zuul.ZuulServerAutoConfigurationTests.class }) @Ignore public class AdhocZuulTestSuite { diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/NoSecurityConfiguration.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/NoSecurityConfiguration.java index cfeafbed8..e2d54b4fe 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/NoSecurityConfiguration.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/NoSecurityConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,7 +12,6 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.test; @@ -23,11 +22,10 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur @Configuration public class NoSecurityConfiguration extends WebSecurityConfigurerAdapter { + @Override protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests() - .anyRequest().permitAll() - .and() - .csrf().disable(); + http.authorizeRequests().anyRequest().permitAll().and().csrf().disable(); } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/TestAutoConfiguration.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/TestAutoConfiguration.java index a048e9708..eb5278779 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/TestAutoConfiguration.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/TestAutoConfiguration.java @@ -1,11 +1,11 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -32,14 +32,14 @@ import org.springframework.security.web.firewall.StrictHttpFirewall; * @author Spencer Gibb */ @Configuration -@Import({NoopDiscoveryClientAutoConfiguration.class}) +@Import({ NoopDiscoveryClientAutoConfiguration.class }) @AutoConfigureBefore(SecurityAutoConfiguration.class) public class TestAutoConfiguration { @Configuration @Order(Ordered.HIGHEST_PRECEDENCE) - protected static class TestSecurityConfiguration extends WebSecurityConfigurerAdapter { - + protected static class TestSecurityConfiguration + extends WebSecurityConfigurerAdapter { TestSecurityConfiguration() { super(true); @@ -55,11 +55,10 @@ public class TestAutoConfiguration { @Override protected void configure(HttpSecurity http) throws Exception { // super.configure(http); - http.antMatcher("/proxy-username") - .httpBasic() - .and() - .authorizeRequests().antMatchers("/**").permitAll(); + http.antMatcher("/proxy-username").httpBasic().and().authorizeRequests() + .antMatchers("/**").permitAll(); } } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/ZuulApacheHttpClientConfigurationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/ZuulApacheHttpClientConfigurationTests.java index 9f477ebe2..e16f21196 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/ZuulApacheHttpClientConfigurationTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/ZuulApacheHttpClientConfigurationTests.java @@ -1,11 +1,11 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -31,6 +31,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockingDetails; import org.mockito.Mockito; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -49,7 +50,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.ReflectionUtils; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; @@ -59,8 +60,7 @@ import static org.mockito.Mockito.mockingDetails; * @author Ryan Baxter */ @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(properties = { - "ribbon.eureka.enabled = false"}) +@SpringBootTest(properties = { "ribbon.eureka.enabled = false" }) @DirtiesContext public class ZuulApacheHttpClientConfigurationTests { @@ -70,24 +70,23 @@ public class ZuulApacheHttpClientConfigurationTests { @Autowired HttpClientRibbonCommandFactory httpClientRibbonCommandFactory; - @Test public void testHttpClientSimpleHostRoutingFilter() { CloseableHttpClient httpClient = getField(simpleHostRoutingFilter, "httpClient"); MockingDetails httpClientDetails = mockingDetails(httpClient); - assertTrue(httpClientDetails.isMock()); + assertThat(httpClientDetails.isMock()); } @Test public void testRibbonLoadBalancingHttpClient() { - RibbonCommandContext context = new RibbonCommandContext("foo"," GET", "http://localhost", - false, new LinkedMultiValueMap<>(), new LinkedMultiValueMap<>(), - null, new ArrayList<>(), 0l); + RibbonCommandContext context = new RibbonCommandContext("foo", " GET", + "http://localhost", false, new LinkedMultiValueMap<>(), + new LinkedMultiValueMap<>(), null, new ArrayList<>(), 0L); HttpClientRibbonCommand command = httpClientRibbonCommandFactory.create(context); RibbonLoadBalancingHttpClient ribbonClient = command.getClient(); CloseableHttpClient httpClient = getField(ribbonClient, "delegate"); MockingDetails httpClientDetails = mockingDetails(httpClient); - assertTrue(httpClientDetails.isMock()); + assertThat(httpClientDetails.isMock()); } @SuppressWarnings("unchecked") @@ -95,7 +94,12 @@ public class ZuulApacheHttpClientConfigurationTests { Field field = ReflectionUtils.findField(target.getClass(), name); ReflectionUtils.makeAccessible(field); Object value = ReflectionUtils.getField(field, target); - return (T)value; + return (T) value; + } + + @Bean + public ApacheHttpClientFactory apacheHttpClientFactory(HttpClientBuilder builder) { + return new TestConfig.MyApacheHttpClientFactory(builder); } @SpringBootConfiguration @@ -104,13 +108,14 @@ public class ZuulApacheHttpClientConfigurationTests { static class TestConfig { static class MyApacheHttpClientFactory extends DefaultApacheHttpClientFactory { - public MyApacheHttpClientFactory(HttpClientBuilder builder) { + + MyApacheHttpClientFactory(HttpClientBuilder builder) { super(builder); } @Override public HttpClientBuilder createBuilder() { - CloseableHttpClient client = mock(CloseableHttpClient.class); + CloseableHttpClient client = mock(CloseableHttpClient.class); CloseableHttpResponse response = mock(CloseableHttpResponse.class); StatusLine statusLine = mock(StatusLine.class); doReturn(200).when(statusLine).getStatusCode(); @@ -118,21 +123,19 @@ public class ZuulApacheHttpClientConfigurationTests { Header[] headers = new BasicHeader[0]; doReturn(headers).when(response).getAllHeaders(); try { - Mockito.doReturn(response).when(client).execute(any(HttpUriRequest.class)); - } catch (IOException e) { + Mockito.doReturn(response).when(client) + .execute(any(HttpUriRequest.class)); + } + catch (IOException e) { e.printStackTrace(); } HttpClientBuilder builder = mock(HttpClientBuilder.class); Mockito.doReturn(client).when(builder).build(); return builder; } + } - @Bean - public ApacheHttpClientFactory apacheHttpClientFactory(HttpClientBuilder builder) { - return new MyApacheHttpClientFactory(builder); - } } } - diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/ZuulOkHttpClientConfigurationTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/ZuulOkHttpClientConfigurationTests.java index 0f973d50e..3e42eb290 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/ZuulOkHttpClientConfigurationTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/test/ZuulOkHttpClientConfigurationTests.java @@ -1,11 +1,11 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -19,9 +19,11 @@ package org.springframework.cloud.netflix.zuul.test; import java.lang.reflect.Field; import java.util.ArrayList; +import okhttp3.OkHttpClient; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockingDetails; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -39,18 +41,15 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.ReflectionUtils; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockingDetails; -import okhttp3.OkHttpClient; - /** * @author Ryan Baxter */ @RunWith(SpringRunner.class) -@SpringBootTest(properties = { - "spring.cloud.httpclientfactories.ok.enabled: true", +@SpringBootTest(properties = { "spring.cloud.httpclientfactories.ok.enabled: true", "ribbon.eureka.enabled = false", "ribbon.okhttp.enabled: true", "ribbon.httpclient.enabled: false" }) @DirtiesContext @@ -69,13 +68,12 @@ public class ZuulOkHttpClientConfigurationTests { public void testOkHttpLoadBalancingHttpClient() { RibbonCommandContext context = new RibbonCommandContext("foo", " GET", "http://localhost", false, new LinkedMultiValueMap<>(), - new LinkedMultiValueMap<>(), null, - new ArrayList<>(), 0l); + new LinkedMultiValueMap<>(), null, new ArrayList<>(), 0L); OkHttpRibbonCommand command = okHttpRibbonCommandFactory.create(context); OkHttpLoadBalancingClient ribbonClient = command.getClient(); OkHttpClient httpClient = getField(ribbonClient, "delegate"); MockingDetails httpClientDetails = mockingDetails(httpClient); - assertTrue(httpClientDetails.isMock()); + assertThat(httpClientDetails.isMock()).isTrue(); } protected T getField(Object target, String name) { @@ -89,10 +87,12 @@ public class ZuulOkHttpClientConfigurationTests { @EnableAutoConfiguration @EnableZuulProxy static class TestConfig { + @Bean public OkHttpClient client() { return mock(OkHttpClient.class); } } + } diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/util/RequestContentDataExtractorTest.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/util/RequestContentDataExtractorTest.java index d7bc919c9..d043d0072 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/util/RequestContentDataExtractorTest.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/util/RequestContentDataExtractorTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,28 +16,28 @@ package org.springframework.cloud.netflix.zuul.util; -import static java.util.Arrays.asList; -import static org.hamcrest.Matchers.hasEntry; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.beans.HasPropertyWithValue.hasProperty; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.when; - import java.util.HashMap; import java.util.List; import java.util.Map; +import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; + import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.multipart.MultipartHttpServletRequest; +import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.beans.HasPropertyWithValue.hasProperty; +import static org.mockito.Mockito.when; + /** * Created by Dmitrii_Priporov on 01.07.18. */ @@ -66,12 +66,13 @@ public class RequestContentDataExtractorTest { .extract(request); // then - assertThat(result, notNullValue()); - assertThat(result.size(), equalTo(1)); - assertThat(result.get("uid"), notNullValue()); - assertThat(result.get("uid"), hasSize(1)); - assertThat(result.get("uid"), hasItem(hasProperty("body", equalTo("65")))); - assertThat(result.get("uid"), hasItem(hasProperty("headers", notNullValue()))); + assertThat(result).isNotNull(); + assertThat(result.size()).isEqualTo(1); + assertThat(result.get("uid")).isNotNull(); + assertThat(result.get("uid")).hasSize(1); + Assert.assertThat(result.get("uid"), hasItem(hasProperty("body", equalTo("65")))); + Assert.assertThat(result.get("uid"), + hasItem(hasProperty("headers", notNullValue()))); } @Test @@ -93,8 +94,8 @@ public class RequestContentDataExtractorTest { .extract(request); // then - assertThat(result, notNullValue()); - assertThat(result.size(), equalTo(0)); + assertThat(result).isNotNull(); + assertThat(result.size()).isEqualTo(0); } @Test @@ -107,8 +108,8 @@ public class RequestContentDataExtractorTest { .findQueryParamsGroupedByName(request); // then - assertThat(result, hasEntry("uid", asList("12", "34"))); - assertThat(result.size(), equalTo(1)); + assertThat(result).containsEntry("uid", asList("12", "34")); + assertThat(result.size()).isEqualTo(1); } @Test @@ -121,8 +122,8 @@ public class RequestContentDataExtractorTest { .findQueryParamsGroupedByName(request); // then - assertThat(result, notNullValue()); - assertThat(result.size(), equalTo(0)); + assertThat(result).isNotNull(); + assertThat(result.size()).isEqualTo(0); } @Test @@ -135,8 +136,8 @@ public class RequestContentDataExtractorTest { .findQueryParamsGroupedByName(request); // then - assertThat(result, notNullValue()); - assertThat(result.size(), equalTo(0)); + assertThat(result).isNotNull(); + assertThat(result.size()).isEqualTo(0); } -} \ No newline at end of file +} diff --git a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/web/ZuulHandlerMappingTests.java b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/web/ZuulHandlerMappingTests.java index fc1a02c99..525c6589a 100644 --- a/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/web/ZuulHandlerMappingTests.java +++ b/spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/web/ZuulHandlerMappingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,26 +12,25 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ package org.springframework.cloud.netflix.zuul.web; -import static org.assertj.core.api.Assertions.assertThat; - import java.util.Arrays; import java.util.Collections; import java.util.List; +import com.netflix.zuul.context.RequestContext; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; + import org.springframework.boot.web.servlet.error.ErrorController; import org.springframework.cloud.netflix.zuul.filters.Route; import org.springframework.cloud.netflix.zuul.filters.RouteLocator; import org.springframework.mock.web.MockHttpServletRequest; -import com.netflix.zuul.context.RequestContext; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -68,7 +67,6 @@ public class ZuulHandlerMappingTests { public void defaultPath() throws Exception { Mockito.when(this.locator.getRoutes()).thenReturn(Collections .singletonList(new Route("default", "/**", "foo", "", null, null))); - ; this.request.setServletPath("/"); this.mapping.setDirty(true); assertThat(this.mapping.getHandler(this.request)).isNotNull(); @@ -91,26 +89,28 @@ public class ZuulHandlerMappingTests { assertThat(mappingWithIgnoredPathsAndRoutes(Arrays.asList("/p1/**/p3/"), new Route("p1", "/p1/**/p3", "p1", "", null, null)) - .getHandler(requestForAPath("/p1/p2/p3"))).isNull(); + .getHandler(requestForAPath("/p1/p2/p3"))).isNull(); assertThat(mappingWithIgnoredPathsAndRoutes(Arrays.asList("/p1/**/p3/**"), new Route("p1", "/p1/**/p3", "p1", "", null, null)) - .getHandler(requestForAPath("/p1/p2/p3"))).isNull(); + .getHandler(requestForAPath("/p1/p2/p3"))).isNull(); assertThat(mappingWithIgnoredPathsAndRoutes(Arrays.asList("/p1/**/p4/"), new Route("p1", "/p1/**/p4/", "p1", "", null, null)) - .getHandler(requestForAPath("/p1/p2/p3/p4"))).isNull(); + .getHandler(requestForAPath("/p1/p2/p3/p4"))).isNull(); } - - private ZuulHandlerMapping mappingWithIgnoredPathsAndRoutes(List ignoredPaths, Route route) { + + private ZuulHandlerMapping mappingWithIgnoredPathsAndRoutes(List ignoredPaths, + Route route) { RouteLocator routeLocator = Mockito.mock(RouteLocator.class); - Mockito.when(routeLocator.getIgnoredPaths()) - .thenReturn(ignoredPaths); - Mockito.when(routeLocator.getRoutes()).thenReturn(Collections.singletonList(route)); - ZuulHandlerMapping zuulHandlerMapping = new ZuulHandlerMapping(routeLocator, new ZuulController()); + Mockito.when(routeLocator.getIgnoredPaths()).thenReturn(ignoredPaths); + Mockito.when(routeLocator.getRoutes()) + .thenReturn(Collections.singletonList(route)); + ZuulHandlerMapping zuulHandlerMapping = new ZuulHandlerMapping(routeLocator, + new ZuulController()); return zuulHandlerMapping; } - + private MockHttpServletRequest requestForAPath(String path) { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServletPath(path); diff --git a/src/checkstyle/checkstyle-suppressions.xml b/src/checkstyle/checkstyle-suppressions.xml new file mode 100644 index 000000000..e0aa83956 --- /dev/null +++ b/src/checkstyle/checkstyle-suppressions.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file