diff --git a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/AbstractZookeeperPropertySource.java b/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/AbstractZookeeperPropertySource.java index c5d11b88..e3ecb55b 100644 --- a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/AbstractZookeeperPropertySource.java +++ b/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/AbstractZookeeperPropertySource.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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,16 +17,18 @@ package org.springframework.cloud.zookeeper.config; import org.apache.curator.framework.CuratorFramework; + import org.springframework.core.env.EnumerablePropertySource; /** - * A {@link EnumerablePropertySource} that has a notion of a context which is - * the root folder in Zookeeper. + * A {@link EnumerablePropertySource} that has a notion of a context which is the root + * folder in Zookeeper. * * @author Spencer Gibb * @since 1.0.0 */ -public abstract class AbstractZookeeperPropertySource extends EnumerablePropertySource { +public abstract class AbstractZookeeperPropertySource + extends EnumerablePropertySource { private String context; @@ -45,4 +47,5 @@ public abstract class AbstractZookeeperPropertySource extends EnumerableProperty public String getContext() { return this.context; } + } diff --git a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ConfigWatcher.java b/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ConfigWatcher.java index 5083960f..2b01d74a 100644 --- a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ConfigWatcher.java +++ b/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ConfigWatcher.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -16,13 +16,14 @@ package org.springframework.cloud.zookeeper.config; -import javax.annotation.PostConstruct; import java.io.Closeable; import java.nio.charset.Charset; import java.util.HashMap; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; +import javax.annotation.PostConstruct; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.curator.framework.CuratorFramework; @@ -30,6 +31,7 @@ import org.apache.curator.framework.recipes.cache.TreeCache; import org.apache.curator.framework.recipes.cache.TreeCacheEvent; import org.apache.curator.framework.recipes.cache.TreeCacheListener; import org.apache.zookeeper.KeeperException; + import org.springframework.cloud.endpoint.event.RefreshEvent; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; @@ -39,20 +41,25 @@ import static org.apache.curator.framework.recipes.cache.TreeCacheEvent.Type.NOD import static org.apache.curator.framework.recipes.cache.TreeCacheEvent.Type.NODE_UPDATED; /** - * Class that registers a {@link TreeCache} for each context. - * It publishes events upon element change in Zookeeper. + * Class that registers a {@link TreeCache} for each context. It publishes events upon + * element change in Zookeeper. * * @author Spencer Gibb * @since 1.0.0 */ -public class ConfigWatcher implements Closeable, TreeCacheListener, ApplicationEventPublisherAware{ +public class ConfigWatcher + implements Closeable, TreeCacheListener, ApplicationEventPublisherAware { private static final Log log = LogFactory.getLog(ConfigWatcher.class); private AtomicBoolean running = new AtomicBoolean(false); + private List contexts; + private CuratorFramework source; + private ApplicationEventPublisher publisher; + private HashMap caches; public ConfigWatcher(List contexts, CuratorFramework source) { @@ -80,9 +87,11 @@ public class ConfigWatcher implements Closeable, TreeCacheListener, ApplicationE this.caches.put(context, cache); // no race condition since ZookeeperAutoConfiguration.curatorFramework // calls curator.blockUntilConnected - } catch (KeeperException.NoNodeException e) { + } + catch (KeeperException.NoNodeException e) { // no node, ignore - } catch (Exception e) { + } + catch (Exception e) { log.error("Error initializing listener for context " + context, e); } } @@ -100,10 +109,13 @@ public class ConfigWatcher implements Closeable, TreeCacheListener, ApplicationE } @Override - public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception { + public void childEvent(CuratorFramework client, TreeCacheEvent event) + throws Exception { TreeCacheEvent.Type eventType = event.getType(); - if (eventType == NODE_ADDED || eventType == NODE_REMOVED || eventType == NODE_UPDATED) { - this.publisher.publishEvent(new RefreshEvent(this, event, getEventDesc(event))); + if (eventType == NODE_ADDED || eventType == NODE_REMOVED + || eventType == NODE_UPDATED) { + this.publisher + .publishEvent(new RefreshEvent(this, event, getEventDesc(event))); } } @@ -117,4 +129,5 @@ public class ConfigWatcher implements Closeable, TreeCacheListener, ApplicationE } return out.toString(); } + } diff --git a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigAutoConfiguration.java b/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigAutoConfiguration.java index 979d177b..6e6d2043 100644 --- a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigAutoConfiguration.java +++ b/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -17,6 +17,7 @@ package org.springframework.cloud.zookeeper.config; import org.apache.curator.framework.CuratorFramework; + import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.cloud.endpoint.RefreshEndpoint; @@ -25,8 +26,8 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** - * {@link org.springframework.boot.autoconfigure.EnableAutoConfiguration Auto-configuration} - * that registers a Zookeeper configuration watcher. + * {@link org.springframework.boot.autoconfigure.EnableAutoConfiguration + * Auto-configuration} that registers a Zookeeper configuration watcher. * * @author Spencer Gibb * @since 1.0.0 @@ -39,11 +40,14 @@ public class ZookeeperConfigAutoConfiguration { @Configuration @ConditionalOnClass(RefreshEndpoint.class) protected static class ZkRefreshConfiguration { + @Bean @ConditionalOnProperty(name = "spring.cloud.zookeeper.config.watcher.enabled", matchIfMissing = true) public ConfigWatcher configWatcher(ZookeeperPropertySourceLocator locator, CuratorFramework curator) { return new ConfigWatcher(locator.getContexts(), curator); } + } + } diff --git a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigBootstrapConfiguration.java b/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigBootstrapConfiguration.java index 298d4df5..040de986 100644 --- a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigBootstrapConfiguration.java +++ b/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigBootstrapConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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.zookeeper.config; import org.apache.curator.framework.CuratorFramework; + import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.cloud.zookeeper.ConditionalOnZookeeperEnabled; import org.springframework.cloud.zookeeper.ZookeeperAutoConfiguration; @@ -25,7 +26,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; /** - * Bootstrap Configuration for Zookeeper Configuration + * Bootstrap Configuration for Zookeeper Configuration. * * @author Spencer Gibb * @since 1.0.0 @@ -47,4 +48,5 @@ public class ZookeeperConfigBootstrapConfiguration { public ZookeeperConfigProperties zookeeperConfigProperties() { return new ZookeeperConfigProperties(); } + } diff --git a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigProperties.java b/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigProperties.java index f5703abc..75d1f93f 100644 --- a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigProperties.java +++ b/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -16,7 +16,8 @@ package org.springframework.cloud.zookeeper.config; -import org.hibernate.validator.constraints.NotEmpty; +import javax.validation.constraints.NotEmpty; + import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; @@ -25,27 +26,27 @@ import org.springframework.validation.annotation.Validated; * * @author Spencer Gibb * @since 1.0.0 - * * @see ZookeeperPropertySourceLocator */ @Validated @ConfigurationProperties("spring.cloud.zookeeper.config") public class ZookeeperConfigProperties { + private boolean enabled = true; /** - * Root folder where the configuration for Zookeeper is kept + * Root folder where the configuration for Zookeeper is kept. */ private String root = "config"; /** - * The name of the default context + * The name of the default context. */ @NotEmpty private String defaultContext = "application"; /** - * Separator for profile appended to the application name + * Separator for profile appended to the application name. */ @NotEmpty private String profileSeparator = ","; @@ -94,4 +95,5 @@ public class ZookeeperConfigProperties { public void setFailFast(boolean failFast) { this.failFast = failFast; } + } diff --git a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySource.java b/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySource.java index 4695cfcb..7b87527b 100644 --- a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySource.java +++ b/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySource.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -26,11 +26,12 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.curator.framework.CuratorFramework; import org.apache.zookeeper.KeeperException; + import org.springframework.util.ReflectionUtils; /** - * {@link org.springframework.core.env.PropertySource} that stores properties - * from Zookeeper inside a map. Properties are loaded upon class initialization. + * {@link org.springframework.core.env.PropertySource} that stores properties from + * Zookeeper inside a map. Properties are loaded upon class initialization. * * @author Spencer Gibb * @since 1.0.0 @@ -56,13 +57,15 @@ public class ZookeeperPropertySource extends AbstractZookeeperPropertySource { byte[] bytes = null; try { bytes = this.getSource().getData().forPath(fullPath); - } catch (KeeperException e) { + } + catch (KeeperException e) { if (e.code() != KeeperException.Code.NONODE) { // not found throw e; } } return bytes; - } catch (Exception exception) { + } + catch (Exception exception) { ReflectionUtils.rethrowRuntimeException(exception); } return null; @@ -92,15 +95,18 @@ public class ZookeeperPropertySource extends AbstractZookeeperPropertySource { if (childPathChildren == null || childPathChildren.isEmpty()) { registerKeyValue(childPath, ""); } - } else { - registerKeyValue(childPath, new String(bytes, Charset.forName("UTF-8"))); + } + else { + registerKeyValue(childPath, + new String(bytes, Charset.forName("UTF-8"))); } // Check children even if we have found a value for the current znode findProperties(childPath, childPathChildren); } log.trace("leaving findProperties for path: " + path); - } catch (Exception exception) { + } + catch (Exception exception) { ReflectionUtils.rethrowRuntimeException(exception); } } @@ -114,7 +120,8 @@ public class ZookeeperPropertySource extends AbstractZookeeperPropertySource { List children = null; try { children = this.getSource().getChildren().forPath(path); - } catch (KeeperException e) { + } + catch (KeeperException e) { if (e.code() != KeeperException.Code.NONODE) { // not found throw e; } diff --git a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySourceLocator.java b/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySourceLocator.java index 5805d423..b9e84fe9 100644 --- a/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySourceLocator.java +++ b/spring-cloud-zookeeper-config/src/main/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySourceLocator.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -16,15 +16,17 @@ package org.springframework.cloud.zookeeper.config; -import javax.annotation.PreDestroy; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; +import javax.annotation.PreDestroy; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.curator.framework.CuratorFramework; + import org.springframework.cloud.bootstrap.config.PropertySourceLocator; import org.springframework.core.env.CompositePropertySource; import org.springframework.core.env.ConfigurableEnvironment; @@ -33,13 +35,17 @@ import org.springframework.core.env.PropertySource; import org.springframework.util.ReflectionUtils; /** - * Zookeeper provides a hierarchical namespace that allows - * clients to store arbitrary data, such as configuration data. Spring Cloud Zookeeper Config is an alternative to the - * Config Server and Client. Configuration is loaded into the Spring Environment during - * the special "bootstrap" phase. Configuration is stored in the {@code /config} namespace by default. Multiple - * {@code PropertySource} instances are created based on the application's name and the active profiles that mimicks the Spring Cloud Config - * order of resolving properties. For example, an application with the name "testApp" and with the "dev" profile will have the following property sources - * created: + * Zookeeper provides a hierarchical + * namespace that allows clients to store arbitrary data, such as configuration data. + * Spring Cloud Zookeeper Config is an alternative to the + * Config Server and + * Client. Configuration is loaded into the Spring Environment during the special + * "bootstrap" phase. Configuration is stored in the {@code /config} namespace by default. + * Multiple {@code PropertySource} instances are created based on the application's name + * and the active profiles that mimicks the Spring Cloud Config order of resolving + * properties. For example, an application with the name "testApp" and with the "dev" + * profile will have the following property sources created: * *
{@code
  * config/testApp,dev
@@ -48,11 +54,11 @@ import org.springframework.util.ReflectionUtils;
  * config/application
  * }
* - *

- * The most specific property source is at the top, with the least specific at the - * bottom. Properties is the {@code config/application} namespace are applicable to all applications - * using zookeeper for configuration. Properties in the {@code config/testApp} namespace are only available - * to the instances of the service named "testApp". + * The most specific property source is at the top, with the least specific at the bottom. + * Properties is the {@code config/application} namespace are applicable to all + * applications using zookeeper for configuration. Properties in the + * {@code config/testApp} namespace are only available to the instances of the service + * named "testApp". * * @author Spencer Gibb * @since 1.0.0 @@ -65,9 +71,11 @@ public class ZookeeperPropertySourceLocator implements PropertySourceLocator { private List contexts; - private static final Log log = LogFactory.getLog(ZookeeperPropertySourceLocator.class); + private static final Log log = LogFactory + .getLog(ZookeeperPropertySourceLocator.class); - public ZookeeperPropertySourceLocator(CuratorFramework curator, ZookeeperConfigProperties properties) { + public ZookeeperPropertySourceLocator(CuratorFramework curator, + ZookeeperConfigProperties properties) { this.curator = curator; this.properties = properties; } @@ -84,7 +92,8 @@ public class ZookeeperPropertySourceLocator implements PropertySourceLocator { if (appName == null) { // use default "application" (which config client does) appName = "application"; - log.warn("spring.application.name is not set. Using default of 'application'"); + log.warn( + "spring.application.name is not set. Using default of 'application'"); } List profiles = Arrays.asList(env.getActiveProfiles()); @@ -112,11 +121,14 @@ public class ZookeeperPropertySourceLocator implements PropertySourceLocator { PropertySource propertySource = create(propertySourceContext); composite.addPropertySource(propertySource); // TODO: howto call close when /refresh - } catch (Exception e) { + } + catch (Exception e) { if (this.properties.isFailFast()) { ReflectionUtils.rethrowRuntimeException(e); - } else { - log.warn("Unable to load zookeeper config from " + propertySourceContext, e); + } + else { + log.warn("Unable to load zookeeper config from " + + propertySourceContext, e); } } } @@ -140,4 +152,5 @@ public class ZookeeperPropertySourceLocator implements PropertySourceLocator { contexts.add(baseContext + this.properties.getProfileSeparator() + profile); } } + } diff --git a/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigAutoConfigurationTests.java b/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigAutoConfigurationTests.java index be69b2de..5aed5e34 100644 --- a/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigAutoConfigurationTests.java +++ b/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperConfigAutoConfigurationTests.java @@ -1,79 +1,93 @@ +/* + * 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.zookeeper.config; +import java.net.ConnectException; -import org.junit.*; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; import org.junit.rules.ExpectedException; + import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.ConfigurableApplicationContext; -import java.net.ConnectException; - /** * @author Cesar Aguilera */ public class ZookeeperConfigAutoConfigurationTests { - @Rule - public ExpectedException expectedException; + @Rule + public ExpectedException expectedException; - @Before - public void setUp() throws Exception { - expectedException = ExpectedException.none(); - // makes Curator fail faster, otherwise it takes 15 seconds to trigger a retry - System.setProperty("curator-default-connection-timeout", "0"); - } + @Before + public void setUp() throws Exception { + expectedException = ExpectedException.none(); + // makes Curator fail faster, otherwise it takes 15 seconds to trigger a retry + System.setProperty("curator-default-connection-timeout", "0"); + } - @After - public void tearDown() throws Exception { - System.clearProperty("curator-default-connection-timeout"); - } + @After + public void tearDown() throws Exception { + System.clearProperty("curator-default-connection-timeout"); + } - @Test(expected = NoSuchBeanDefinitionException.class) - public void testConfigEnabledFalseDoesNotLoadZookeeperConfigAutoConfiguration() throws Exception { - ConfigurableApplicationContext context = new SpringApplicationBuilder() - .sources(Config.class) - .web(WebApplicationType.NONE) - .run( - "--spring.application.name=testZookeeperConfigEnabledSetToFalse", - "--spring.jmx.default-domain=testZookeeperConfigEnabledSetToFalse", - "--spring.cloud.zookeeper.config.connectString=localhost:2188", - "--spring.cloud.zookeeper.baseSleepTimeMs=0", - "--spring.cloud.zookeeper.maxRetries=0", - "--spring.cloud.zookeeper.maxSleepMs=0", - "--spring.cloud.zookeeper.blockUntilConnectedWait=0", - "--spring.cloud.zookeeper.config.failFast=false", - "--spring.cloud.zookeeper.config.enabled=false" - ); + @Test(expected = NoSuchBeanDefinitionException.class) + public void testConfigEnabledFalseDoesNotLoadZookeeperConfigAutoConfiguration() + throws Exception { + ConfigurableApplicationContext context = new SpringApplicationBuilder() + .sources(Config.class).web(WebApplicationType.NONE) + .run("--spring.application.name=testZookeeperConfigEnabledSetToFalse", + "--spring.jmx.default-domain=testZookeeperConfigEnabledSetToFalse", + "--spring.cloud.zookeeper.config.connectString=localhost:2188", + "--spring.cloud.zookeeper.baseSleepTimeMs=0", + "--spring.cloud.zookeeper.maxRetries=0", + "--spring.cloud.zookeeper.maxSleepMs=0", + "--spring.cloud.zookeeper.blockUntilConnectedWait=0", + "--spring.cloud.zookeeper.config.failFast=false", + "--spring.cloud.zookeeper.config.enabled=false"); + context.getBean(ZookeeperConfigAutoConfiguration.class); + } - context.getBean(ZookeeperConfigAutoConfiguration.class); - } + @Test + public void testConfigEnabledTrueLoadsZookeeperConfigAutoConfiguration() + throws Exception { + expectedException.expect(ConnectException.class); + new SpringApplicationBuilder().sources(Config.class).web(WebApplicationType.NONE) + .run("--spring.application.name=testZookeeperConfigEnabledSetToTrue", + "--spring.jmx.default-domain=testZookeeperConfigEnabledSetToTrue", + "--spring.cloud.zookeeper.config.connectString=localhost:2188", + "--spring.cloud.zookeeper.baseSleepTimeMs=0", + "--spring.cloud.zookeeper.maxRetries=0", + "--spring.cloud.zookeeper.maxSleepMs=0", + "--spring.cloud.zookeeper.blockUntilConnectedWait=0", + "--spring.cloud.zookeeper.config.failFast=false", + "--spring.cloud.zookeeper.config.enabled=true"); + } - @Test - public void testConfigEnabledTrueLoadsZookeeperConfigAutoConfiguration() throws Exception { - expectedException.expect(ConnectException.class); + @SpringBootApplication + static class Config { - new SpringApplicationBuilder() - .sources(Config.class) - .web(WebApplicationType.NONE) - .run( - "--spring.application.name=testZookeeperConfigEnabledSetToTrue", - "--spring.jmx.default-domain=testZookeeperConfigEnabledSetToTrue", - "--spring.cloud.zookeeper.config.connectString=localhost:2188", - "--spring.cloud.zookeeper.baseSleepTimeMs=0", - "--spring.cloud.zookeeper.maxRetries=0", - "--spring.cloud.zookeeper.maxSleepMs=0", - "--spring.cloud.zookeeper.blockUntilConnectedWait=0", - "--spring.cloud.zookeeper.config.failFast=false", - "--spring.cloud.zookeeper.config.enabled=true" - ); - } + } - @SpringBootApplication - static class Config { - } } diff --git a/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySourceLocatorFailFastTests.java b/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySourceLocatorFailFastTests.java index 6ed2bbda..09919ade 100644 --- a/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySourceLocatorFailFastTests.java +++ b/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySourceLocatorFailFastTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -21,6 +21,7 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; + import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; @@ -29,12 +30,14 @@ import org.springframework.boot.builder.SpringApplicationBuilder; * @author Enrique Recarte Llorens */ public class ZookeeperPropertySourceLocatorFailFastTests { + @Rule public ExpectedException expectedException = ExpectedException.none(); @Before public void setUp() throws Exception { - // This system property makes Curator fail faster, otherwise it takes 15 seconds to trigger a retry + // This system property makes Curator fail faster, otherwise it takes 15 seconds + // to trigger a retry System.setProperty("curator-default-connection-timeout", "0"); } @@ -45,39 +48,33 @@ public class ZookeeperPropertySourceLocatorFailFastTests { @Test public void testFailFastFalseLoadsTheApplicationContext() throws Exception { - new SpringApplicationBuilder() - .sources(Config.class) - .web(WebApplicationType.NONE) - .run( - "--spring.application.name=testZookeeperPropertySourceLocatorFailFast", - "--spring.cloud.zookeeper.config.connectString=localhost:2188", - "--spring.cloud.zookeeper.baseSleepTimeMs=0", - "--spring.cloud.zookeeper.maxRetries=0", - "--spring.cloud.zookeeper.maxSleepMs=0", - "--spring.cloud.zookeeper.blockUntilConnectedWait=0", - "--spring.cloud.zookeeper.config.failFast=false" - ); + new SpringApplicationBuilder().sources(Config.class).web(WebApplicationType.NONE) + .run("--spring.application.name=testZookeeperPropertySourceLocatorFailFast", + "--spring.cloud.zookeeper.config.connectString=localhost:2188", + "--spring.cloud.zookeeper.baseSleepTimeMs=0", + "--spring.cloud.zookeeper.maxRetries=0", + "--spring.cloud.zookeeper.maxSleepMs=0", + "--spring.cloud.zookeeper.blockUntilConnectedWait=0", + "--spring.cloud.zookeeper.config.failFast=false"); } @Test public void testFailFastTrueDoesNotLoadTheApplicationContext() throws Exception { expectedException.expect(Exception.class); - new SpringApplicationBuilder() - .sources(Config.class) - .web(WebApplicationType.NONE) - .run( - "--spring.application.name=testZookeeperPropertySourceLocatorFailFast", - "--spring.cloud.zookeeper.config.connectString=localhost:2188", - "--spring.cloud.zookeeper.baseSleepTimeMs=0", - "--spring.cloud.zookeeper.maxRetries=0", - "--spring.cloud.zookeeper.maxSleepMs=0", - "--spring.cloud.zookeeper.blockUntilConnectedWait=0", - "--spring.cloud.zookeeper.config.failFast=true" - ); + new SpringApplicationBuilder().sources(Config.class).web(WebApplicationType.NONE) + .run("--spring.application.name=testZookeeperPropertySourceLocatorFailFast", + "--spring.cloud.zookeeper.config.connectString=localhost:2188", + "--spring.cloud.zookeeper.baseSleepTimeMs=0", + "--spring.cloud.zookeeper.maxRetries=0", + "--spring.cloud.zookeeper.maxSleepMs=0", + "--spring.cloud.zookeeper.blockUntilConnectedWait=0", + "--spring.cloud.zookeeper.config.failFast=true"); } @SpringBootApplication static class Config { + } -} \ No newline at end of file + +} diff --git a/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySourceLocatorNoApplicationNameTests.java b/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySourceLocatorNoApplicationNameTests.java index 715d9a30..a4101715 100644 --- a/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySourceLocatorNoApplicationNameTests.java +++ b/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySourceLocatorNoApplicationNameTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -19,9 +19,7 @@ package org.springframework.cloud.zookeeper.config; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.GetChildrenBuilder; import org.junit.Test; -import org.mockito.Mockito; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.annotation.Configuration; + import org.springframework.mock.env.MockEnvironment; import static org.mockito.Mockito.mock; @@ -36,7 +34,9 @@ public class ZookeeperPropertySourceLocatorNoApplicationNameTests { public void defaultSpringApplicationNameWorks() { CuratorFramework curator = mock(CuratorFramework.class); when(curator.getChildren()).thenReturn(mock(GetChildrenBuilder.class)); - ZookeeperPropertySourceLocator locator = new ZookeeperPropertySourceLocator(curator, new ZookeeperConfigProperties()); + ZookeeperPropertySourceLocator locator = new ZookeeperPropertySourceLocator( + curator, new ZookeeperConfigProperties()); locator.locate(new MockEnvironment()); } + } diff --git a/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySourceLocatorTests.java b/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySourceLocatorTests.java index 3d3b878d..5633b291 100644 --- a/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySourceLocatorTests.java +++ b/spring-cloud-zookeeper-config/src/test/java/org/springframework/cloud/zookeeper/config/ZookeeperPropertySourceLocatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -45,66 +45,54 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.util.SocketUtils; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.isEmptyString; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Spencer Gibb */ public class ZookeeperPropertySourceLocatorTests { - private static final Log log = LogFactory.getLog(ZookeeperPropertySourceLocatorTests.class); + private static final Log log = LogFactory + .getLog(ZookeeperPropertySourceLocatorTests.class); public static final String PREFIX = "test__config__"; + public static final String ROOT = "/" + PREFIX + UUID.randomUUID(); + public static final String CONTEXT = ROOT + "/application/"; public static final String KEY_BASIC = "testProp"; + public static final String KEY_BASIC_PATH = CONTEXT + KEY_BASIC; + public static final String VAL_BASIC = "testPropVal"; public static final String KEY_WITH_DOT = "testProp.dot"; + public static final String KEY_WITH_DOT_PATH = CONTEXT + KEY_WITH_DOT; + public static final String VAL_WITH_DOT = "withDotVal"; public static final String KEY_NESTED = "testProp.nested"; + public static final String KEY_NESTED_PATH = CONTEXT + KEY_NESTED.replace('.', '/'); + public static final String VAL_NESTED = "nestedVal"; public static final String KEY_WITHOUT_VALUE = "testProp.novalue"; + public static final String KEY_WITHOUT_VALUE_PATH = CONTEXT + KEY_WITHOUT_VALUE; private ConfigurableEnvironment environment; + private ConfigurableApplicationContext context; + private TestingServer testingServer; + private CuratorFramework curator; + private ZookeeperConfigProperties properties; - @Configuration - @EnableAutoConfiguration - static class Config implements ApplicationListener { - @Bean - public CountDownLatch countDownLatch() { - return new CountDownLatch(1); - } - - @Bean - public ContextRefresher contextRefresher(ConfigurableApplicationContext context, - RefreshScope scope) { - return new ContextRefresher(context, scope); - } - - @Override - public void onApplicationEvent(EnvironmentChangeEvent event) { - log.debug("Event keys: " + event.getKeys()); - if (event.getKeys().contains(KEY_BASIC)) { - countDownLatch().countDown(); - } - } - } - @Before public void setup() throws Exception { int port = SocketUtils.findAvailableTcpPort(); @@ -133,10 +121,12 @@ public class ZookeeperPropertySourceLocatorTests { this.curator.close(); System.out.println(create); - this.context = new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE).run( - "--spring.cloud.zookeeper.connectString=" + connectString, - "--spring.application.name=testZkPropertySource", "--logging.level.org.springframework.cloud.zookeeper=DEBUG", - "--spring.cloud.zookeeper.config.root=" + ROOT); + this.context = new SpringApplicationBuilder(Config.class) + .web(WebApplicationType.NONE) + .run("--spring.cloud.zookeeper.connectString=" + connectString, + "--spring.application.name=testZkPropertySource", + "--logging.level.org.springframework.cloud.zookeeper=DEBUG", + "--spring.cloud.zookeeper.config.root=" + ROOT); this.curator = this.context.getBean(CuratorFramework.class); this.properties = this.context.getBean(ZookeeperConfigProperties.class); @@ -168,31 +158,57 @@ public class ZookeeperPropertySourceLocatorTests { @Test public void checkKeyValues() throws Exception { String propValue = this.environment.getProperty(KEY_BASIC); - assertThat(KEY_BASIC + " was wrong", propValue, is(equalTo(VAL_BASIC))); + assertThat(propValue).as(KEY_BASIC + " was wrong").isEqualTo(VAL_BASIC); propValue = this.environment.getProperty(KEY_NESTED); - assertThat(VAL_NESTED + " was wrong", propValue, is(equalTo(VAL_NESTED))); + assertThat(propValue).as(VAL_NESTED + " was wrong").isEqualTo(VAL_NESTED); propValue = this.environment.getProperty(KEY_WITH_DOT); - assertThat(VAL_WITH_DOT + " was wrong", propValue, is(equalTo(VAL_WITH_DOT))); + assertThat(propValue).as(VAL_WITH_DOT + " was wrong").isEqualTo(VAL_WITH_DOT); propValue = this.environment.getProperty(KEY_WITHOUT_VALUE); - assertThat(KEY_WITHOUT_VALUE + " was wrong", propValue, is(isEmptyString())); + assertThat(propValue).as(KEY_WITHOUT_VALUE + " was wrong").isEmpty(); } @Test public void propertyLoadedAndUpdated() throws Exception { String testProp = this.environment.getProperty(KEY_BASIC); - assertThat("testProp was wrong", testProp, is(equalTo(VAL_BASIC))); + assertThat(testProp).as("testProp was wrong").isEqualTo(VAL_BASIC); this.curator.setData().forPath(KEY_BASIC_PATH, "testPropValUpdate".getBytes()); CountDownLatch latch = this.context.getBean(CountDownLatch.class); boolean receivedEvent = latch.await(15, TimeUnit.SECONDS); - assertThat("listener didn't receive event", receivedEvent, is(true)); + assertThat(receivedEvent).as("listener didn't receive event").isTrue(); testProp = this.environment.getProperty(KEY_BASIC); - assertThat("testProp was wrong after update", testProp, - is(equalTo("testPropValUpdate"))); + assertThat(testProp).as("testProp was wrong after update") + .isEqualTo("testPropValUpdate"); } + + @Configuration + @EnableAutoConfiguration + static class Config implements ApplicationListener { + + @Bean + public CountDownLatch countDownLatch() { + return new CountDownLatch(1); + } + + @Bean + public ContextRefresher contextRefresher(ConfigurableApplicationContext context, + RefreshScope scope) { + return new ContextRefresher(context, scope); + } + + @Override + public void onApplicationEvent(EnvironmentChangeEvent event) { + log.debug("Event keys: " + event.getKeys()); + if (event.getKeys().contains(KEY_BASIC)) { + countDownLatch().countDown(); + } + } + + } + } diff --git a/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ConditionalOnZookeeperEnabled.java b/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ConditionalOnZookeeperEnabled.java index 6a19e31b..111e18fc 100644 --- a/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ConditionalOnZookeeperEnabled.java +++ b/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ConditionalOnZookeeperEnabled.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -24,12 +24,14 @@ import java.lang.annotation.Target; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; /** - * Wrapper annotation to enable Zookeeper + * Wrapper annotation to enable Zookeeper. * + * @author Marcin Grzejszczak * @since 1.1.0 */ @Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE, ElementType.METHOD}) +@Target({ ElementType.TYPE, ElementType.METHOD }) @ConditionalOnProperty(value = "spring.cloud.zookeeper.enabled", matchIfMissing = true) public @interface ConditionalOnZookeeperEnabled { + } diff --git a/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ZookeeperAutoConfiguration.java b/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ZookeeperAutoConfiguration.java index a57162ab..a78e11e0 100644 --- a/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ZookeeperAutoConfiguration.java +++ b/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ZookeeperAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -23,6 +23,7 @@ import org.apache.curator.ensemble.EnsembleProvider; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; @@ -30,8 +31,8 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** - * {@link org.springframework.boot.autoconfigure.EnableAutoConfiguration Auto-configuration} - * that sets up Zookeeper discovery. + * {@link org.springframework.boot.autoconfigure.EnableAutoConfiguration + * Auto-configuration} that sets up Zookeeper discovery. * * @author Spencer Gibb * @since 1.0.0 @@ -52,20 +53,24 @@ public class ZookeeperAutoConfiguration { return new ZookeeperProperties(); } - @Bean(destroyMethod = "close") @ConditionalOnMissingBean - public CuratorFramework curatorFramework(RetryPolicy retryPolicy, ZookeeperProperties properties) throws Exception { + public CuratorFramework curatorFramework(RetryPolicy retryPolicy, + ZookeeperProperties properties) throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); if (this.ensembleProvider != null) { builder.ensembleProvider(this.ensembleProvider); - } else { + } + else { builder.connectString(properties.getConnectString()); } CuratorFramework curator = builder.retryPolicy(retryPolicy).build(); curator.start(); - log.trace("blocking until connected to zookeeper for " + properties.getBlockUntilConnectedWait() + properties.getBlockUntilConnectedUnit()); - curator.blockUntilConnected(properties.getBlockUntilConnectedWait(), properties.getBlockUntilConnectedUnit()); + log.trace("blocking until connected to zookeeper for " + + properties.getBlockUntilConnectedWait() + + properties.getBlockUntilConnectedUnit()); + curator.blockUntilConnected(properties.getBlockUntilConnectedWait(), + properties.getBlockUntilConnectedUnit()); log.trace("connected to zookeeper"); return curator; } @@ -74,7 +79,7 @@ public class ZookeeperAutoConfiguration { @ConditionalOnMissingBean public RetryPolicy exponentialBackoffRetry(ZookeeperProperties properties) { return new ExponentialBackoffRetry(properties.getBaseSleepTimeMs(), - properties.getMaxRetries(), - properties.getMaxSleepMs()); + properties.getMaxRetries(), properties.getMaxSleepMs()); } + } diff --git a/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ZookeeperHealthAutoConfiguration.java b/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ZookeeperHealthAutoConfiguration.java index 7c70ac45..7f1ae710 100644 --- a/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ZookeeperHealthAutoConfiguration.java +++ b/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ZookeeperHealthAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 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. @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.zookeeper; import org.apache.curator.framework.CuratorFramework; + import org.springframework.boot.actuate.autoconfigure.health.ConditionalOnEnabledHealthIndicator; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.autoconfigure.AutoConfigureAfter; @@ -28,8 +30,8 @@ import org.springframework.context.annotation.Configuration; /** * Auto {@link Configuration} for adding a Zookeeper health endpoint to actuator if * required. - * - * @author tgianos + * + * @author Tom Gianos * @since 2.0.1 */ @Configuration @@ -41,7 +43,6 @@ public class ZookeeperHealthAutoConfiguration { /** * If there is an active curator, if the zookeeper health endpoint is enabled and if a * health indicator hasn't already been added by a user add one. - * * @param curator The curator connection to zookeeper to use * @return An instance of {@link ZookeeperHealthIndicator} to add to actuator health * report @@ -53,4 +54,5 @@ public class ZookeeperHealthAutoConfiguration { public ZookeeperHealthIndicator zookeeperHealthIndicator(CuratorFramework curator) { return new ZookeeperHealthIndicator(curator); } + } diff --git a/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ZookeeperHealthIndicator.java b/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ZookeeperHealthIndicator.java index aeb77dd6..308e3ab7 100644 --- a/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ZookeeperHealthIndicator.java +++ b/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ZookeeperHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -18,6 +18,7 @@ package org.springframework.cloud.zookeeper; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.imps.CuratorFrameworkState; + import org.springframework.boot.actuate.health.AbstractHealthIndicator; import org.springframework.boot.actuate.health.Health; @@ -29,6 +30,7 @@ import org.springframework.boot.actuate.health.Health; * @since 1.0.0 */ public class ZookeeperHealthIndicator extends AbstractHealthIndicator { + private final CuratorFramework curator; public ZookeeperHealthIndicator(CuratorFramework curator) { @@ -56,4 +58,5 @@ public class ZookeeperHealthIndicator extends AbstractHealthIndicator { builder.down(e); } } + } diff --git a/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ZookeeperProperties.java b/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ZookeeperProperties.java index b84427a2..17cf86ff 100644 --- a/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ZookeeperProperties.java +++ b/spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ZookeeperProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -16,14 +16,15 @@ package org.springframework.cloud.zookeeper; -import javax.validation.constraints.NotNull; import java.util.concurrent.TimeUnit; +import javax.validation.constraints.NotNull; + import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; /** - * Properties related to connecting to Zookeeper + * Properties related to connecting to Zookeeper. * * @author Spencer Gibb * @since 1.0.0 @@ -33,38 +34,38 @@ import org.springframework.validation.annotation.Validated; public class ZookeeperProperties { /** - * Connection string to the Zookeeper cluster + * Connection string to the Zookeeper cluster. */ @NotNull private String connectString = "localhost:2181"; /** - * Is Zookeeper enabled + * Is Zookeeper enabled. */ private boolean enabled = true; /** - * Initial amount of time to wait between retries + * Initial amount of time to wait between retries. */ private Integer baseSleepTimeMs = 50; /** - * Max number of times to retry + * Max number of times to retry. */ private Integer maxRetries = 10; /** - * Max time in ms to sleep on each retry + * Max time in ms to sleep on each retry. */ private Integer maxSleepMs = 500; /** - * Wait time to block on connection to Zookeeper + * Wait time to block on connection to Zookeeper. */ private Integer blockUntilConnectedWait = 10; /** - * The unit of time related to blocking on connection to Zookeeper + * The unit of time related to blocking on connection to Zookeeper. */ private TimeUnit blockUntilConnectedUnit = TimeUnit.SECONDS; @@ -123,4 +124,5 @@ public class ZookeeperProperties { public void setBlockUntilConnectedUnit(TimeUnit blockUntilConnectedUnit) { this.blockUntilConnectedUnit = blockUntilConnectedUnit; } + } diff --git a/spring-cloud-zookeeper-core/src/test/java/org/springframework/cloud/zookeeper/ZookeeperAutoConfigurationEnsembleTests.java b/spring-cloud-zookeeper-core/src/test/java/org/springframework/cloud/zookeeper/ZookeeperAutoConfigurationEnsembleTests.java index 9a2283e0..b50621e1 100644 --- a/spring-cloud-zookeeper-core/src/test/java/org/springframework/cloud/zookeeper/ZookeeperAutoConfigurationEnsembleTests.java +++ b/spring-cloud-zookeeper-core/src/test/java/org/springframework/cloud/zookeeper/ZookeeperAutoConfigurationEnsembleTests.java @@ -1,7 +1,20 @@ -package org.springframework.cloud.zookeeper; +/* + * 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. + */ -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +package org.springframework.cloud.zookeeper; import org.apache.curator.ensemble.EnsembleProvider; import org.apache.curator.ensemble.fixed.FixedEnsembleProvider; @@ -9,26 +22,35 @@ import org.apache.curator.framework.CuratorFramework; import org.apache.curator.test.TestingServer; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Konrad Kamil DobrzyƄski */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { ZookeeperAutoConfigurationEnsembleTests.TestConfig.class, ZookeeperAutoConfiguration.class }) +@ContextConfiguration(classes = { + ZookeeperAutoConfigurationEnsembleTests.TestConfig.class, + ZookeeperAutoConfiguration.class }) public class ZookeeperAutoConfigurationEnsembleTests { - @Autowired(required = false) CuratorFramework curator; + @Autowired(required = false) + CuratorFramework curator; + + @Autowired + TestingServer testingServer; - @Autowired TestingServer testingServer; - @Test public void should_successfully_inject_Curator_with_ensemble_connection_string() { - assertEquals(testingServer.getConnectString(), curator.getZookeeperClient().getCurrentConnectionString()); - assertNotEquals(TestConfig.DUMMY_CONNECTION_STRING, curator.getZookeeperClient().getCurrentConnectionString()); + assertThat(curator.getZookeeperClient().getCurrentConnectionString()) + .isEqualTo(testingServer.getConnectString()); + assertThat(curator.getZookeeperClient().getCurrentConnectionString()) + .isNotEqualTo(TestConfig.DUMMY_CONNECTION_STRING); } static class TestConfig { @@ -36,7 +58,7 @@ public class ZookeeperAutoConfigurationEnsembleTests { static final String DUMMY_CONNECTION_STRING = "dummy-connection-string:2111"; @Bean - EnsembleProvider ensembleProvider(TestingServer testingServer){ + EnsembleProvider ensembleProvider(TestingServer testingServer) { return new FixedEnsembleProvider(testingServer.getConnectString()); } @@ -47,8 +69,11 @@ public class ZookeeperAutoConfigurationEnsembleTests { return properties; } - @Bean(destroyMethod = "close") TestingServer testingServer() throws Exception { + @Bean(destroyMethod = "close") + TestingServer testingServer() throws Exception { return new TestingServer(); } + } + } diff --git a/spring-cloud-zookeeper-core/src/test/java/org/springframework/cloud/zookeeper/ZookeeperAutoConfigurationTests.java b/spring-cloud-zookeeper-core/src/test/java/org/springframework/cloud/zookeeper/ZookeeperAutoConfigurationTests.java index 3662027d..e1dc0e20 100644 --- a/spring-cloud-zookeeper-core/src/test/java/org/springframework/cloud/zookeeper/ZookeeperAutoConfigurationTests.java +++ b/spring-cloud-zookeeper-core/src/test/java/org/springframework/cloud/zookeeper/ZookeeperAutoConfigurationTests.java @@ -1,40 +1,64 @@ +/* + * 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.zookeeper; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.test.TestingServer; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Marcin Grzejszczak */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { ZookeeperAutoConfigurationTests.TestConfig.class, ZookeeperAutoConfiguration.class }) +@ContextConfiguration(classes = { ZookeeperAutoConfigurationTests.TestConfig.class, + ZookeeperAutoConfiguration.class }) public class ZookeeperAutoConfigurationTests { - @Autowired(required = false) CuratorFramework curator; - + @Autowired(required = false) + CuratorFramework curator; + @Test public void should_successfully_inject_Curator_as_a_Spring_bean() { - assertNotNull(this.curator); + assertThat(this.curator).isNotNull(); } static class TestConfig { + @Bean - ZookeeperProperties zookeeperProperties(TestingServer testingServer) throws Exception { + ZookeeperProperties zookeeperProperties(TestingServer testingServer) + throws Exception { ZookeeperProperties properties = new ZookeeperProperties(); properties.setConnectString(testingServer.getConnectString()); return properties; } - @Bean(destroyMethod = "close") TestingServer testingServer() throws Exception { + @Bean(destroyMethod = "close") + TestingServer testingServer() throws Exception { return new TestingServer(); } + } + } diff --git a/spring-cloud-zookeeper-core/src/test/java/org/springframework/cloud/zookeeper/ZookeeperHealthAutoConfigurationTests.java b/spring-cloud-zookeeper-core/src/test/java/org/springframework/cloud/zookeeper/ZookeeperHealthAutoConfigurationTests.java index baf2d023..122059b8 100644 --- a/spring-cloud-zookeeper-core/src/test/java/org/springframework/cloud/zookeeper/ZookeeperHealthAutoConfigurationTests.java +++ b/spring-cloud-zookeeper-core/src/test/java/org/springframework/cloud/zookeeper/ZookeeperHealthAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 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. @@ -13,22 +13,25 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.zookeeper; import org.apache.curator.framework.CuratorFramework; import org.assertj.core.api.Assertions; import org.junit.Test; + import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; /** * Tests for {@link ZookeeperHealthAutoConfiguration}. - * - * @author tgianos + * + * @author Tom Gianos * @since 2.0.1 */ public class ZookeeperHealthAutoConfigurationTests { + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(ZookeeperAutoConfiguration.class, ZookeeperHealthAutoConfiguration.class)) @@ -61,10 +64,13 @@ public class ZookeeperHealthAutoConfigurationTests { } static class HealthIndicatorCustomConfig { + @Bean ZookeeperHealthIndicator customZookeeperHealthIndicator( CuratorFramework curatorFramework) { return new ZookeeperHealthIndicator(curatorFramework); } + } + } diff --git a/spring-cloud-zookeeper-dependencies/pom.xml b/spring-cloud-zookeeper-dependencies/pom.xml index 7a57f6bb..7845dbfd 100644 --- a/spring-cloud-zookeeper-dependencies/pom.xml +++ b/spring-cloud-zookeeper-dependencies/pom.xml @@ -15,6 +15,9 @@ Spring Cloud Zookeeper Dependencies 4.0.1 + true + true + true @@ -116,6 +119,27 @@ + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + io.spring.javaformat + spring-javaformat-maven-plugin + + + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + spring diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ConditionalOnRibbonZookeeper.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ConditionalOnRibbonZookeeper.java index 36425732..4b1b14ee 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ConditionalOnRibbonZookeeper.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ConditionalOnRibbonZookeeper.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -24,12 +24,14 @@ import java.lang.annotation.Target; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; /** - * Wrapper annotation to enable Ribbon for Zookeeper + * Wrapper annotation to enable Ribbon for Zookeeper. * - * @since 1.0.0 + * @author Marcin Grzejszczak + * * @since 1.0.0 */ @Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE, ElementType.METHOD}) +@Target({ ElementType.TYPE, ElementType.METHOD }) @ConditionalOnProperty(value = "ribbon.zookeeper.enabled", matchIfMissing = true) public @interface ConditionalOnRibbonZookeeper { + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ConditionalOnZookeeperDiscoveryEnabled.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ConditionalOnZookeeperDiscoveryEnabled.java index b47e8a4f..3f94b223 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ConditionalOnZookeeperDiscoveryEnabled.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ConditionalOnZookeeperDiscoveryEnabled.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -25,13 +25,15 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.cloud.zookeeper.ConditionalOnZookeeperEnabled; /** - * Wrapper annotation to enable Zookeeper Discovery + * Wrapper annotation to enable Zookeeper Discovery. * + * @author Marcin Grzejszczak * @since 1.1.0 */ @Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE, ElementType.METHOD}) +@Target({ ElementType.TYPE, ElementType.METHOD }) @ConditionalOnZookeeperEnabled @ConditionalOnProperty(value = "spring.cloud.zookeeper.discovery.enabled", matchIfMissing = true) public @interface ConditionalOnZookeeperDiscoveryEnabled { + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/DependencyPathUtils.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/DependencyPathUtils.java index 9744c801..6172d1a5 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/DependencyPathUtils.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/DependencyPathUtils.java @@ -1,17 +1,37 @@ +/* + * 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.zookeeper.discovery; /** - * Utils for correct dependency path format + * Utils for correct dependency path format. * * @author Denis Stepanov * @since 1.0.4 */ -public class DependencyPathUtils { +public final class DependencyPathUtils { + + private DependencyPathUtils() { + } /** - * Sanitizes path by ensuring that path starts with a slash and doesn't have one at the end - * @param path - * @return + * Sanitizes path by ensuring that path starts with a slash and doesn't have one at + * the end. + * @param path file path to sanitize. + * @return sanitized path. */ public static String sanitize(String path) { return withLeadingSlash(withoutSlashAtEnd(path)); diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/RibbonZookeeperAutoConfiguration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/RibbonZookeeperAutoConfiguration.java index 187cfa79..ac27c6ef 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/RibbonZookeeperAutoConfiguration.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/RibbonZookeeperAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -26,8 +26,8 @@ import org.springframework.cloud.zookeeper.ConditionalOnZookeeperEnabled; import org.springframework.context.annotation.Configuration; /** - * {@link org.springframework.boot.autoconfigure.EnableAutoConfiguration Auto-configuration} - * that sets up Ribbon for Zookeeper. + * {@link org.springframework.boot.autoconfigure.EnableAutoConfiguration + * Auto-configuration} that sets up Ribbon for Zookeeper. * * @author Dave Syer * @since 1.0.0 @@ -40,4 +40,5 @@ import org.springframework.context.annotation.Configuration; @AutoConfigureAfter(RibbonAutoConfiguration.class) @RibbonClients(defaultConfiguration = ZookeeperRibbonClientConfiguration.class) public class RibbonZookeeperAutoConfiguration { + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryAutoConfiguration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryAutoConfiguration.java index b14f7209..d566cf4e 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryAutoConfiguration.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -18,6 +18,7 @@ package org.springframework.cloud.zookeeper.discovery; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.x.discovery.ServiceDiscovery; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.autoconfigure.health.ConditionalOnEnabledHealthIndicator; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; @@ -40,8 +41,9 @@ import org.springframework.context.annotation.Configuration; @Configuration @ConditionalOnBean(ZookeeperDiscoveryClientConfiguration.Marker.class) @ConditionalOnZookeeperDiscoveryEnabled -@AutoConfigureBefore({CommonsClientAutoConfiguration.class, NoopDiscoveryClientAutoConfiguration.class}) -@AutoConfigureAfter({ZookeeperDiscoveryClientConfiguration.class}) +@AutoConfigureBefore({ CommonsClientAutoConfiguration.class, + NoopDiscoveryClientAutoConfiguration.class }) +@AutoConfigureAfter({ ZookeeperDiscoveryClientConfiguration.class }) public class ZookeeperDiscoveryAutoConfiguration { @Autowired(required = false) @@ -52,13 +54,15 @@ public class ZookeeperDiscoveryAutoConfiguration { @Bean @ConditionalOnMissingBean - public ZookeeperDiscoveryProperties zookeeperDiscoveryProperties(InetUtils inetUtils) { + public ZookeeperDiscoveryProperties zookeeperDiscoveryProperties( + InetUtils inetUtils) { return new ZookeeperDiscoveryProperties(inetUtils); } @Bean @ConditionalOnMissingBean - // currently means auto-registration is false. That will change when ZookeeperServiceDiscovery is gone + // currently means auto-registration is false. That will change when + // ZookeeperServiceDiscovery is gone public ZookeeperDiscoveryClient zookeeperDiscoveryClient( ServiceDiscovery serviceDiscovery, ZookeeperDiscoveryProperties zookeeperDiscoveryProperties) { @@ -66,10 +70,17 @@ public class ZookeeperDiscoveryAutoConfiguration { zookeeperDiscoveryProperties); } + @Bean + public ZookeeperServiceWatch zookeeperServiceWatch( + ZookeeperDiscoveryProperties zookeeperDiscoveryProperties) { + return new ZookeeperServiceWatch(this.curator, zookeeperDiscoveryProperties); + } + @Configuration @ConditionalOnEnabledHealthIndicator("zookeeper") @ConditionalOnClass(Endpoint.class) protected static class ZookeeperDiscoveryHealthConfig { + @Autowired(required = false) private ZookeeperDependencies zookeeperDependencies; @@ -82,11 +93,7 @@ public class ZookeeperDiscoveryAutoConfiguration { return new ZookeeperDiscoveryHealthIndicator(curatorFramework, serviceDiscovery, this.zookeeperDependencies, properties); } - } - @Bean - public ZookeeperServiceWatch zookeeperServiceWatch(ZookeeperDiscoveryProperties zookeeperDiscoveryProperties) { - return new ZookeeperServiceWatch(this.curator, zookeeperDiscoveryProperties); } } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryClient.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryClient.java index c374cf64..e304d72d 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryClient.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryClient.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -46,7 +46,9 @@ public class ZookeeperDiscoveryClient implements DiscoveryClient { private static final Log log = LogFactory.getLog(ZookeeperDiscoveryClient.class); private final ZookeeperDependencies zookeeperDependencies; + private final ServiceDiscovery serviceDiscovery; + private final ZookeeperDiscoveryProperties zookeeperDiscoveryProperties; public ZookeeperDiscoveryClient(ServiceDiscovery serviceDiscovery, @@ -62,7 +64,8 @@ public class ZookeeperDiscoveryClient implements DiscoveryClient { return "Spring Cloud Zookeeper Discovery Client"; } - private static org.springframework.cloud.client.ServiceInstance createServiceInstance(String serviceId, ServiceInstance serviceInstance) { + private static org.springframework.cloud.client.ServiceInstance createServiceInstance( + String serviceId, ServiceInstance serviceInstance) { return new ZookeeperServiceInstance(serviceId, serviceInstance); } @@ -74,19 +77,24 @@ public class ZookeeperDiscoveryClient implements DiscoveryClient { return Collections.EMPTY_LIST; } String serviceIdToQuery = getServiceIdToQuery(serviceId); - Collection> zkInstances = getServiceDiscovery().queryForInstances(serviceIdToQuery); + Collection> zkInstances = getServiceDiscovery() + .queryForInstances(serviceIdToQuery); List instances = new ArrayList<>(); for (ServiceInstance instance : zkInstances) { instances.add(createServiceInstance(serviceIdToQuery, instance)); } return instances; - } catch (KeeperException.NoNodeException e) { + } + catch (KeeperException.NoNodeException e) { if (log.isDebugEnabled()) { - log.debug("Error getting instances from zookeeper. Possibly, no service has registered.", e); + log.debug( + "Error getting instances from zookeeper. Possibly, no service has registered.", + e); } // this means that nothing has registered as a service yes return Collections.emptyList(); - } catch (Exception exception) { + } + catch (Exception exception) { rethrowRuntimeException(exception); } return new ArrayList<>(); @@ -97,7 +105,8 @@ public class ZookeeperDiscoveryClient implements DiscoveryClient { } private String getServiceIdToQuery(String serviceId) { - if (this.zookeeperDependencies != null && this.zookeeperDependencies.hasDependencies()) { + if (this.zookeeperDependencies != null + && this.zookeeperDependencies.hasDependencies()) { String pathForAlias = this.zookeeperDependencies.getPathForAlias(serviceId); return pathForAlias.isEmpty() ? serviceId : pathForAlias; } @@ -108,7 +117,8 @@ public class ZookeeperDiscoveryClient implements DiscoveryClient { public List getServices() { List services = null; if (getServiceDiscovery() == null) { - log.warn("Service Discovery is not yet ready - returning empty list of services"); + log.warn( + "Service Discovery is not yet ready - returning empty list of services"); return Collections.emptyList(); } try { @@ -120,7 +130,9 @@ public class ZookeeperDiscoveryClient implements DiscoveryClient { } catch (KeeperException.NoNodeException e) { if (log.isDebugEnabled()) { - log.debug("Error getting services from zookeeper. Possibly, no service has registered.", e); + log.debug( + "Error getting services from zookeeper. Possibly, no service has registered.", + e); } // this means that nothing has registered as a service yes return Collections.emptyList(); @@ -135,4 +147,5 @@ public class ZookeeperDiscoveryClient implements DiscoveryClient { public int getOrder() { return this.zookeeperDiscoveryProperties.getOrder(); } + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryClientConfiguration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryClientConfiguration.java index a561cba7..4a417751 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryClientConfiguration.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryClientConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -21,8 +21,8 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** - * {@link org.springframework.cloud.client.discovery.DiscoveryClient} configuration - * for Zookeeper. + * {@link org.springframework.cloud.client.discovery.DiscoveryClient} configuration for + * Zookeeper. * * @author Spencer Gibb * @since 1.0.0 @@ -31,11 +31,12 @@ import org.springframework.context.annotation.Configuration; @ConditionalOnProperty(value = "spring.cloud.zookeeper.discovery.enabled", matchIfMissing = true) public class ZookeeperDiscoveryClientConfiguration { - class Marker {} - @Bean public Marker zookeeperDiscoveryClientMarker() { return new Marker(); } + class Marker { + } + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryHealthIndicator.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryHealthIndicator.java index 7e1d52f6..845e2864 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryHealthIndicator.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -21,6 +21,7 @@ import org.apache.commons.logging.LogFactory; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.ServiceInstance; + import org.springframework.boot.actuate.health.Health; import org.springframework.cloud.client.discovery.health.DiscoveryHealthIndicator; import org.springframework.cloud.zookeeper.discovery.dependency.ZookeeperDependencies; @@ -38,8 +39,11 @@ public class ZookeeperDiscoveryHealthIndicator implements DiscoveryHealthIndicat .getLog(ZookeeperDiscoveryHealthIndicator.class); private CuratorFramework curatorFramework; + private ServiceDiscovery serviceDiscovery; + private final ZookeeperDependencies zookeeperDependencies; + private final ZookeeperDiscoveryProperties zookeeperDiscoveryProperties; public ZookeeperDiscoveryHealthIndicator(CuratorFramework curatorFramework, @@ -61,10 +65,9 @@ public class ZookeeperDiscoveryHealthIndicator implements DiscoveryHealthIndicat public Health health() { Health.Builder builder = Health.unknown(); try { - Iterable> allInstances = - new ZookeeperServiceInstances(this.curatorFramework, - this.serviceDiscovery, this.zookeeperDependencies, - this.zookeeperDiscoveryProperties); + Iterable> allInstances = new ZookeeperServiceInstances( + this.curatorFramework, this.serviceDiscovery, + this.zookeeperDependencies, this.zookeeperDiscoveryProperties); builder.up().withDetail("services", allInstances); } catch (Exception e) { diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryProperties.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryProperties.java index c30cd499..53dce3af 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryProperties.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -33,6 +33,9 @@ import org.springframework.util.StringUtils; @ConfigurationProperties("spring.cloud.zookeeper.discovery") public class ZookeeperDiscoveryProperties { + /** + * Default URI spec. + */ public static final String DEFAULT_URI_SPEC = "{scheme}://{address}:{port}"; private InetUtils.HostInfo hostInfo; @@ -40,12 +43,12 @@ public class ZookeeperDiscoveryProperties { private boolean enabled = true; /** - * Root Zookeeper folder in which all instances are registered + * Root Zookeeper folder in which all instances are registered. */ private String root = "/services"; /** - * The URI specification to resolve during service registration in Zookeeper + * The URI specification to resolve during service registration in Zookeeper. */ private String uriSpec = DEFAULT_URI_SPEC; @@ -58,16 +61,17 @@ public class ZookeeperDiscoveryProperties { */ private String instanceHost; - /** IP address to use when accessing service (must also set preferIpAddress - to use) */ + /** + * IP address to use when accessing service (must also set preferIpAddress to use). + */ private String instanceIpAddress; /** - * Use ip address rather than hostname during registration + * Use ip address rather than hostname during registration. */ private boolean preferIpAddress = false; - /** Port to register the service under (defaults to listening port) */ + /** Port to register the service under (defaults to listening port). */ private Integer instancePort; /** Ssl port of the registered service. */ @@ -85,17 +89,20 @@ public class ZookeeperDiscoveryProperties { private Map metadata = new HashMap<>(); /** - * The initial status of this instance (defaults to {@link StatusConstants#STATUS_UP}). + * The initial status of this instance (defaults to + * {@link StatusConstants#STATUS_UP}). */ private String initialStatus = StatusConstants.STATUS_UP; /** - * 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; // Visible for Testing - protected ZookeeperDiscoveryProperties() {} + protected ZookeeperDiscoveryProperties() { + } public ZookeeperDiscoveryProperties(InetUtils inetUtils) { this.hostInfo = inetUtils.findFirstNonLoopbackHostInfo(); @@ -206,17 +213,13 @@ public class ZookeeperDiscoveryProperties { @Override public String toString() { - return "ZookeeperDiscoveryProperties{" + "enabled=" + this.enabled + - ", root='" + this.root + '\'' + - ", uriSpec='" + this.uriSpec + '\'' + - ", instanceId='" + this.instanceId + '\'' + - ", instanceHost='" + this.instanceHost + '\'' + - ", instancePort='" + this.instancePort + '\'' + - ", instanceSslPort='" + this.instanceSslPort + '\'' + - ", metadata=" + this.metadata + - ", register=" + this.register + - ", initialStatus=" + this.initialStatus + - ", order=" + this.order + - '}'; + return "ZookeeperDiscoveryProperties{" + "enabled=" + this.enabled + ", root='" + + this.root + '\'' + ", uriSpec='" + this.uriSpec + '\'' + + ", instanceId='" + this.instanceId + '\'' + ", instanceHost='" + + this.instanceHost + '\'' + ", instancePort='" + this.instancePort + '\'' + + ", instanceSslPort='" + this.instanceSslPort + '\'' + ", metadata=" + + this.metadata + ", register=" + this.register + ", initialStatus=" + + this.initialStatus + ", order=" + this.order + '}'; } + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperInstance.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperInstance.java index c69580f5..d1a9cf63 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperInstance.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperInstance.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -26,8 +26,11 @@ import java.util.Map; * @since 1.0.0 */ public class ZookeeperInstance { + private String id; + private String name; + private Map metadata = new HashMap<>(); @SuppressWarnings("unused") @@ -66,9 +69,8 @@ public class ZookeeperInstance { @Override public String toString() { - return "ZookeeperInstance{" + "id='" + this.id + '\'' + - ", name='" + this.name + '\'' + - ", metadata=" + this.metadata + - '}'; + return "ZookeeperInstance{" + "id='" + this.id + '\'' + ", name='" + this.name + + '\'' + ", metadata=" + this.metadata + '}'; } + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperRibbonClientConfiguration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperRibbonClientConfiguration.java index b780f5fe..d7364135 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperRibbonClientConfiguration.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperRibbonClientConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -18,9 +18,18 @@ package org.springframework.cloud.zookeeper.discovery; import javax.annotation.PostConstruct; +import com.netflix.client.config.IClientConfig; +import com.netflix.config.ConfigurationManager; +import com.netflix.config.DynamicPropertyFactory; +import com.netflix.config.DynamicStringProperty; +import com.netflix.loadbalancer.ILoadBalancer; +import com.netflix.loadbalancer.IPing; +import com.netflix.loadbalancer.PingUrl; +import com.netflix.loadbalancer.ServerList; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.curator.x.discovery.ServiceDiscovery; + import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -32,15 +41,6 @@ import org.springframework.cloud.zookeeper.discovery.dependency.ZookeeperDepende import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import com.netflix.client.config.IClientConfig; -import com.netflix.config.ConfigurationManager; -import com.netflix.config.DynamicPropertyFactory; -import com.netflix.config.DynamicStringProperty; -import com.netflix.loadbalancer.ILoadBalancer; -import com.netflix.loadbalancer.IPing; -import com.netflix.loadbalancer.PingUrl; -import com.netflix.loadbalancer.ServerList; - import static com.netflix.client.config.CommonClientConfigKey.DeploymentContextBasedVipAddresses; import static com.netflix.client.config.CommonClientConfigKey.EnableZoneAffinity; @@ -56,9 +56,12 @@ import static com.netflix.client.config.CommonClientConfigKey.EnableZoneAffinity */ @Configuration public class ZookeeperRibbonClientConfiguration { - private static final Log log = LogFactory.getLog(ZookeeperRibbonClientConfiguration.class); + + private static final Log log = LogFactory + .getLog(ZookeeperRibbonClientConfiguration.class); protected static final String VALUE_NOT_SET = "__not__set__"; + protected static final String DEFAULT_NAMESPACE = "ribbon"; @Value("${ribbon.client.name}") @@ -75,7 +78,9 @@ public class ZookeeperRibbonClientConfiguration { ServiceDiscovery serviceDiscovery) { ZookeeperServerList serverList = new ZookeeperServerList(serviceDiscovery); serverList.initFromDependencies(config, zookeeperDependencies); - log.debug(String.format("Server list for Ribbon's dependencies based load balancing is [%s]", serverList)); + log.debug(String.format( + "Server list for Ribbon's dependencies based load balancing is [%s]", + serverList)); return serverList; } @@ -83,9 +88,11 @@ public class ZookeeperRibbonClientConfiguration { @ConditionalOnMissingBean @ConditionalOnDependenciesPassed @ConditionalOnProperty(value = "spring.cloud.zookeeper.dependency.ribbon.loadbalancer", matchIfMissing = true) - public ILoadBalancer dependenciesBasedLoadBalancer(ZookeeperDependencies zookeeperDependencies, - ServerList serverList, IClientConfig config, IPing iPing) { - return new DependenciesBasedLoadBalancer(zookeeperDependencies, serverList, config, iPing); + public ILoadBalancer dependenciesBasedLoadBalancer( + ZookeeperDependencies zookeeperDependencies, ServerList serverList, + IClientConfig config, IPing iPing) { + return new DependenciesBasedLoadBalancer(zookeeperDependencies, serverList, + config, iPing); } @Bean @@ -102,11 +109,12 @@ public class ZookeeperRibbonClientConfiguration { ServiceDiscovery serviceDiscovery) { ZookeeperServerList serverList = new ZookeeperServerList(serviceDiscovery); serverList.initWithNiwsConfig(config); - log.debug(String.format("Server list for Ribbon's non-dependency based load balancing is [%s]", serverList)); + log.debug(String.format( + "Server list for Ribbon's non-dependency based load balancing is [%s]", + serverList)); return serverList; } - @Bean public ServerIntrospector serverIntrospector() { return new ZookeeperServerIntrospector(); diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServer.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServer.java index 716644d2..49b9bc12 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServer.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServer.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -16,12 +16,11 @@ package org.springframework.cloud.zookeeper.discovery; +import com.netflix.loadbalancer.Server; import org.apache.curator.x.discovery.ServiceInstance; -import com.netflix.loadbalancer.Server; - /** - * A Zookeeper version of a {@link Server Ribbon Server} + * A Zookeeper version of a {@link Server Ribbon Server}. * * @author Spencer Gibb * @since 1.0.0 @@ -29,6 +28,7 @@ import com.netflix.loadbalancer.Server; public class ZookeeperServer extends Server { private final MetaInfo metaInfo; + private ServiceInstance instance; public ZookeeperServer(final ServiceInstance instance) { @@ -66,4 +66,5 @@ public class ZookeeperServer extends Server { public ServiceInstance getInstance() { return this.instance; } + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServerIntrospector.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServerIntrospector.java index c97db916..c65edb8c 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServerIntrospector.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServerIntrospector.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 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. @@ -16,16 +16,18 @@ package org.springframework.cloud.zookeeper.discovery; +import java.util.Map; + import com.netflix.loadbalancer.Server; import org.apache.curator.x.discovery.ServiceInstance; -import org.springframework.cloud.netflix.ribbon.DefaultServerIntrospector; -import java.util.Map; +import org.springframework.cloud.netflix.ribbon.DefaultServerIntrospector; /** * @author Spencer Gibb */ public class ZookeeperServerIntrospector extends DefaultServerIntrospector { + @Override public boolean isSecure(Server server) { if (server instanceof ZookeeperServer) { @@ -47,4 +49,5 @@ public class ZookeeperServerIntrospector extends DefaultServerIntrospector { } return super.getMetadata(server); } + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServerList.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServerList.java index 1a65c184..1925a005 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServerList.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServerList.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -21,22 +21,22 @@ import java.util.Collection; import java.util.Collections; import java.util.List; -import org.apache.curator.x.discovery.ServiceDiscovery; -import org.apache.curator.x.discovery.ServiceInstance; -import org.springframework.cloud.zookeeper.discovery.dependency.ZookeeperDependencies; -import org.springframework.util.StringUtils; - import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.AbstractServerList; +import org.apache.curator.x.discovery.ServiceDiscovery; +import org.apache.curator.x.discovery.ServiceInstance; + +import org.springframework.cloud.zookeeper.discovery.dependency.ZookeeperDependencies; +import org.springframework.util.StringUtils; import static org.springframework.cloud.zookeeper.support.StatusConstants.INSTANCE_STATUS_KEY; import static org.springframework.cloud.zookeeper.support.StatusConstants.STATUS_UP; import static org.springframework.util.ReflectionUtils.rethrowRuntimeException; /** - * Zookeeper version of {@link AbstractServerList} that returns the list of - * servers on which instances are ran. The implementation is capable of resolving - * the servers from {@link ZookeeperDependencies}. + * Zookeeper version of {@link AbstractServerList} that returns the list of servers on + * which instances are ran. The implementation is capable of resolving the servers from + * {@link ZookeeperDependencies}. * * @author Spencer Gibb * @author Marcin Grzejszczak @@ -45,6 +45,7 @@ import static org.springframework.util.ReflectionUtils.rethrowRuntimeException; public class ZookeeperServerList extends AbstractServerList { private String serviceId; + private final ServiceDiscovery serviceDiscovery; public ZookeeperServerList(ServiceDiscovery serviceDiscovery) { @@ -56,13 +57,18 @@ public class ZookeeperServerList extends AbstractServerList { this.serviceId = clientConfig.getClientName(); } - public void initFromDependencies(IClientConfig clientConfig, ZookeeperDependencies zookeeperDependencies) { - this.serviceId = getServiceIdFromDepsOrClientName(clientConfig, zookeeperDependencies); + public void initFromDependencies(IClientConfig clientConfig, + ZookeeperDependencies zookeeperDependencies) { + this.serviceId = getServiceIdFromDepsOrClientName(clientConfig, + zookeeperDependencies); } - private String getServiceIdFromDepsOrClientName(IClientConfig clientConfig, ZookeeperDependencies zookeeperDependencies) { - String serviceIdFromDeps = zookeeperDependencies.getPathForAlias(clientConfig.getClientName()); - return StringUtils.hasText(serviceIdFromDeps) ? serviceIdFromDeps : clientConfig.getClientName(); + private String getServiceIdFromDepsOrClientName(IClientConfig clientConfig, + ZookeeperDependencies zookeeperDependencies) { + String serviceIdFromDeps = zookeeperDependencies + .getPathForAlias(clientConfig.getClientName()); + return StringUtils.hasText(serviceIdFromDeps) ? serviceIdFromDeps + : clientConfig.getClientName(); } @Override @@ -89,8 +95,10 @@ public class ZookeeperServerList extends AbstractServerList { List servers = new ArrayList<>(); for (ServiceInstance instance : instances) { String instanceStatus = null; - if (instance.getPayload() != null && instance.getPayload().getMetadata() != null) { - instanceStatus = instance.getPayload().getMetadata().get(INSTANCE_STATUS_KEY); + if (instance.getPayload() != null + && instance.getPayload().getMetadata() != null) { + instanceStatus = instance.getPayload().getMetadata() + .get(INSTANCE_STATUS_KEY); } if (!StringUtils.hasText(instanceStatus) // backwards compatibility || instanceStatus.equalsIgnoreCase(STATUS_UP)) { @@ -104,4 +112,5 @@ public class ZookeeperServerList extends AbstractServerList { } return Collections.EMPTY_LIST; } + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServiceInstance.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServiceInstance.java index d43008a6..f127f178 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServiceInstance.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServiceInstance.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 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. @@ -23,27 +23,35 @@ import java.util.Map; import org.springframework.cloud.client.ServiceInstance; /** - * A specific {@link ServiceInstance} describing a zookeeper service instance + * A specific {@link ServiceInstance} describing a zookeeper service instance. * - * @author Reda.Housni-Alaoui + * @author Reda Housni-Alaoui * @author Tim Ysewyn * @since 1.1.0 */ public class ZookeeperServiceInstance implements ServiceInstance { private final String serviceId; + private final String host; + private final int port; + private final boolean secure; + private final URI uri; + private final Map metadata; + private final org.apache.curator.x.discovery.ServiceInstance serviceInstance; /** * @param serviceId The service id to be used - * @param serviceInstance The zookeeper service instance described by this service instance + * @param serviceInstance The zookeeper service instance described by this service + * instance */ - public ZookeeperServiceInstance(String serviceId, org.apache.curator.x.discovery.ServiceInstance serviceInstance) { + public ZookeeperServiceInstance(String serviceId, + org.apache.curator.x.discovery.ServiceInstance serviceInstance) { this.serviceId = serviceId; this.serviceInstance = serviceInstance; this.host = this.serviceInstance.getAddress(); @@ -56,7 +64,8 @@ public class ZookeeperServiceInstance implements ServiceInstance { this.uri = URI.create(serviceInstance.buildUriSpec()); if (serviceInstance.getPayload() != null) { this.metadata = serviceInstance.getPayload().getMetadata(); - } else { + } + else { this.metadata = new HashMap<>(); } } @@ -99,4 +108,5 @@ public class ZookeeperServiceInstance implements ServiceInstance { public org.apache.curator.x.discovery.ServiceInstance getServiceInstance() { return this.serviceInstance; } + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServiceInstances.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServiceInstances.java index 18d81377..8ab17e4e 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServiceInstances.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServiceInstances.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.zookeeper.discovery; import java.util.ArrayList; @@ -10,6 +26,7 @@ import org.apache.commons.logging.LogFactory; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.ServiceInstance; + import org.springframework.cloud.zookeeper.discovery.dependency.ZookeeperDependencies; import static org.springframework.cloud.zookeeper.discovery.DependencyPathUtils.sanitize; @@ -19,6 +36,7 @@ import static org.springframework.cloud.zookeeper.discovery.DependencyPathUtils. * {@link ZookeeperDependencies} it will return a list of registered Zookeeper instances * corresponding to the ones defined in the dependencies. * + * @author Marcin Grzejszczak * @since 1.0.0 */ public class ZookeeperServiceInstances @@ -27,9 +45,13 @@ public class ZookeeperServiceInstances private static final Log log = LogFactory.getLog(ZookeeperServiceInstances.class); private ServiceDiscovery serviceDiscovery; + private final ZookeeperDependencies zookeeperDependencies; + private final ZookeeperDiscoveryProperties zookeeperDiscoveryProperties; + private final List> allInstances; + private final CuratorFramework curator; public ZookeeperServiceInstances(CuratorFramework curator, @@ -74,9 +96,11 @@ public class ZookeeperServiceInstances try { List children = this.curator.getChildren().forPath(parentPath); return iterateOverChildren(accumulator, parentPath, children); - } catch (Exception e) { + } + catch (Exception e) { if (log.isTraceEnabled()) { - log.trace("Exception occurred while trying to retrieve children of [" + parentPath + "]", e); + log.trace("Exception occurred while trying to retrieve children of [" + + parentPath + "]", e); } return injectZookeeperServiceInstances(accumulator, parentPath); } @@ -90,8 +114,7 @@ public class ZookeeperServiceInstances private Collection> tryToGetInstances( String path) { try { - return getServiceDiscovery() - .queryForInstances(getPathWithoutRoot(path)); + return getServiceDiscovery().queryForInstances(getPathWithoutRoot(path)); } catch (Exception e) { log.trace("Exception occurred while trying to retrieve instances of [" + path @@ -111,7 +134,8 @@ public class ZookeeperServiceInstances private List> injectZookeeperServiceInstances( List> accumulator, String name) throws Exception { - Collection> instances = getServiceDiscovery().queryForInstances(name); + Collection> instances = getServiceDiscovery() + .queryForInstances(name); accumulator.addAll(convertCollectionToList(instances)); return accumulator; } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServiceWatch.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServiceWatch.java index 4ffa5e2f..9b08d8b6 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServiceWatch.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServiceWatch.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -16,13 +16,15 @@ package org.springframework.cloud.zookeeper.discovery; -import javax.annotation.PreDestroy; import java.util.concurrent.atomic.AtomicLong; +import javax.annotation.PreDestroy; + import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.cache.TreeCache; import org.apache.curator.framework.recipes.cache.TreeCacheEvent; import org.apache.curator.framework.recipes.cache.TreeCacheListener; + import org.springframework.cloud.client.discovery.event.HeartbeatEvent; import org.springframework.cloud.client.discovery.event.InstanceRegisteredEvent; import org.springframework.context.ApplicationEventPublisher; @@ -31,20 +33,24 @@ import org.springframework.context.ApplicationListener; import org.springframework.util.ReflectionUtils; /** - * A {@link TreeCacheListener} that sends {@link HeartbeatEvent} when an - * entry inside Zookeeper has changed. + * A {@link TreeCacheListener} that sends {@link HeartbeatEvent} when an entry inside + * Zookeeper has changed. * * @author Spencer Gibb * @since 1.0.0 */ -public class ZookeeperServiceWatch implements - ApplicationListener>, TreeCacheListener, +public class ZookeeperServiceWatch + implements ApplicationListener>, TreeCacheListener, ApplicationEventPublisherAware { private final CuratorFramework curator; + private final ZookeeperDiscoveryProperties properties; + private final AtomicLong cacheChange = new AtomicLong(0); + private ApplicationEventPublisher publisher; + private TreeCache cache; public ZookeeperServiceWatch(CuratorFramework curator, @@ -64,7 +70,8 @@ public class ZookeeperServiceWatch implements @Override public void onApplicationEvent(InstanceRegisteredEvent event) { - this.cache = TreeCache.newBuilder(this.curator, this.properties.getRoot()).build(); + this.cache = TreeCache.newBuilder(this.curator, this.properties.getRoot()) + .build(); this.cache.getListenable().addListener(this); try { this.cache.start(); @@ -82,7 +89,8 @@ public class ZookeeperServiceWatch implements } @Override - public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception { + public void childEvent(CuratorFramework client, TreeCacheEvent event) + throws Exception { if (event.getType().equals(TreeCacheEvent.Type.NODE_ADDED) || event.getType().equals(TreeCacheEvent.Type.NODE_REMOVED) || event.getType().equals(TreeCacheEvent.Type.NODE_UPDATED)) { @@ -90,4 +98,5 @@ public class ZookeeperServiceWatch implements this.publisher.publishEvent(new HeartbeatEvent(this, newCacheChange)); } } + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/configclient/ZookeeperDiscoveryClientConfigServiceBootstrapConfiguration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/configclient/ZookeeperDiscoveryClientConfigServiceBootstrapConfiguration.java index 0ff259b0..a8a6f966 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/configclient/ZookeeperDiscoveryClientConfigServiceBootstrapConfiguration.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/configclient/ZookeeperDiscoveryClientConfigServiceBootstrapConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -39,15 +39,19 @@ import org.springframework.core.annotation.Order; @ConditionalOnProperty(value = "spring.cloud.config.discovery.enabled", matchIfMissing = false) @Configuration @Import({ ZookeeperAutoConfiguration.class, ZookeeperDiscoveryClientConfiguration.class, - CuratorServiceDiscoveryAutoConfiguration.class, ZookeeperDiscoveryAutoConfiguration.class}) + CuratorServiceDiscoveryAutoConfiguration.class, + ZookeeperDiscoveryAutoConfiguration.class }) @Order(0) public class ZookeeperDiscoveryClientConfigServiceBootstrapConfiguration { @Bean - public ZookeeperDiscoveryProperties zookeeperDiscoveryProperties(InetUtils inetUtils) { - ZookeeperDiscoveryProperties properties = new ZookeeperDiscoveryProperties(inetUtils); + public ZookeeperDiscoveryProperties zookeeperDiscoveryProperties( + InetUtils inetUtils) { + ZookeeperDiscoveryProperties properties = new ZookeeperDiscoveryProperties( + inetUtils); // for bootstrap, registration is not needed, just discovery client properties.setRegister(false); return properties; } + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ConditionalOnDependenciesNotPassed.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ConditionalOnDependenciesNotPassed.java index 5a6fdbc8..a42baa91 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ConditionalOnDependenciesNotPassed.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ConditionalOnDependenciesNotPassed.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -24,13 +24,14 @@ import java.lang.annotation.Target; import org.springframework.context.annotation.Conditional; /** - * Annotation to turn off a feature if Zookeeper dependencies have NOT been passed + * Annotation to turn off a feature if Zookeeper dependencies have NOT been passed. * * @author Marcin Grzejszczak * @since 1.0.0 */ -@Target({ElementType.TYPE, ElementType.METHOD}) +@Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Conditional(DependenciesNotPassedCondition.class) public @interface ConditionalOnDependenciesNotPassed { + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ConditionalOnDependenciesPassed.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ConditionalOnDependenciesPassed.java index 2edd7ccc..9bf66459 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ConditionalOnDependenciesPassed.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ConditionalOnDependenciesPassed.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -24,14 +24,15 @@ import java.lang.annotation.Target; import org.springframework.context.annotation.Conditional; /** - * Annotation to turn on a feature if Zookeeper dependencies have been passed. - * Also checks if switch for zookeeper dependencies is turned on. + * Annotation to turn on a feature if Zookeeper dependencies have been passed. Also checks + * if switch for zookeeper dependencies is turned on. * * @author Marcin Grzejszczak * @since 1.0.0 */ -@Target({ElementType.TYPE, ElementType.METHOD}) +@Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Conditional(DependenciesPassedCondition.class) public @interface ConditionalOnDependenciesPassed { + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependenciesBasedLoadBalancer.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependenciesBasedLoadBalancer.java index e7d29edb..5f4f9e39 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependenciesBasedLoadBalancer.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependenciesBasedLoadBalancer.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -27,13 +27,12 @@ import com.netflix.loadbalancer.RandomRule; import com.netflix.loadbalancer.RoundRobinRule; import com.netflix.loadbalancer.Server; import com.netflix.loadbalancer.ServerList; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** - * LoadBalancer that delegates to other rules depending on the provided load balancing strategy - * in the {@link ZookeeperDependency#getLoadBalancerType()} + * LoadBalancer that delegates to other rules depending on the provided load balancing + * strategy in the {@link ZookeeperDependency#getLoadBalancerType()}. * * @author Marcin Grzejszczak * @since 1.0.0 @@ -46,7 +45,8 @@ public class DependenciesBasedLoadBalancer extends DynamicServerListLoadBalancer private final ZookeeperDependencies zookeeperDependencies; - public DependenciesBasedLoadBalancer(ZookeeperDependencies zookeeperDependencies, ServerList serverList, IClientConfig config, IPing iPing) { + public DependenciesBasedLoadBalancer(ZookeeperDependencies zookeeperDependencies, + ServerList serverList, IClientConfig config, IPing iPing) { super(config); this.zookeeperDependencies = zookeeperDependencies; setServersList(serverList.getInitialListOfServers()); @@ -59,17 +59,24 @@ public class DependenciesBasedLoadBalancer extends DynamicServerListLoadBalancer String keyAsString; if ("default".equals(key)) { // this is the default hint, use name instead keyAsString = getName(); - } else { + } + else { keyAsString = (String) key; } - ZookeeperDependency dependency = this.zookeeperDependencies.getDependencyForAlias(keyAsString); - log.debug(String.format("Current dependencies are [%s]", this.zookeeperDependencies)); + ZookeeperDependency dependency = this.zookeeperDependencies + .getDependencyForAlias(keyAsString); + log.debug(String.format("Current dependencies are [%s]", + this.zookeeperDependencies)); if (dependency == null) { - log.debug(String.format("No dependency found for alias [%s] - will use the default rule which is [%s]", keyAsString, this.rule)); + log.debug(String.format( + "No dependency found for alias [%s] - will use the default rule which is [%s]", + keyAsString, this.rule)); return this.rule.choose(key); } cacheEntryIfMissing(keyAsString, dependency); - log.debug(String.format("Will try to retrieve dependency for key [%s]. Current cache contents [%s]", keyAsString, this.ruleCache)); + log.debug(String.format( + "Will try to retrieve dependency for key [%s]. Current cache contents [%s]", + keyAsString, this.ruleCache)); updateListOfServers(); return this.ruleCache.get(keyAsString).choose(key); } @@ -77,20 +84,21 @@ public class DependenciesBasedLoadBalancer extends DynamicServerListLoadBalancer private void cacheEntryIfMissing(String keyAsString, ZookeeperDependency dependency) { if (!this.ruleCache.containsKey(keyAsString)) { log.debug(String.format("Cache doesn't contain entry for [%s]", keyAsString)); - this.ruleCache.put(keyAsString, chooseRuleForLoadBalancerType(dependency.getLoadBalancerType())); + this.ruleCache.put(keyAsString, + chooseRuleForLoadBalancerType(dependency.getLoadBalancerType())); } } private IRule chooseRuleForLoadBalancerType(LoadBalancerType type) { switch (type) { - case ROUND_ROBIN: - return getRoundRobinRule(); - case RANDOM: - return getRandomRule(); - case STICKY: - return getStickyRule(); - default: - throw new IllegalArgumentException("Unknown load balancer type " + type); + case ROUND_ROBIN: + return getRoundRobinRule(); + case RANDOM: + return getRandomRule(); + case STICKY: + return getStickyRule(); + default: + throw new IllegalArgumentException("Unknown load balancer type " + type); } } @@ -109,4 +117,5 @@ public class DependenciesBasedLoadBalancer extends DynamicServerListLoadBalancer stickyRule.setLoadBalancer(this); return stickyRule; } + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependenciesNotPassedCondition.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependenciesNotPassedCondition.java index 68d06f46..1f84eb46 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependenciesNotPassedCondition.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependenciesNotPassedCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.zookeeper.discovery.dependency; import org.springframework.boot.autoconfigure.condition.ConditionOutcome; @@ -20,7 +21,7 @@ import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; /** - * Inverse of the {@link ConditionalOnDependenciesPassed} condition. + * Inverse of the {@link ConditionalOnDependenciesPassed} condition. * * @author Marcin Grzejszczak * @since 1.0.0 @@ -28,7 +29,8 @@ import org.springframework.core.type.AnnotatedTypeMetadata; public class DependenciesNotPassedCondition extends DependenciesPassedCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, + AnnotatedTypeMetadata metadata) { ConditionOutcome propertiesSet = super.getMatchOutcome(context, metadata); return ConditionOutcome.inverse(propertiesSet); } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependenciesPassedCondition.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependenciesPassedCondition.java index 27e61a39..d8233660 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependenciesPassedCondition.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependenciesPassedCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.zookeeper.discovery.dependency; import java.util.Collections; @@ -26,8 +27,8 @@ import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; /** - * Condition that verifies if the Dependencies have been passed in an appropriate - * place in the application properties. + * Condition that verifies if the Dependencies have been passed in an appropriate place in + * the application properties. * * @author Marcin Grzejszczak * @since 1.0.0 @@ -36,21 +37,26 @@ public class DependenciesPassedCondition extends SpringBootCondition { private static final Bindable> STRING_STRING_MAP = Bindable .mapOf(String.class, String.class); + private static final String ZOOKEEPER_DEPENDENCIES_PROP = "spring.cloud.zookeeper.dependencies"; @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, + AnnotatedTypeMetadata metadata) { Map subProperties = Binder.get(context.getEnvironment()) - .bind(ZOOKEEPER_DEPENDENCIES_PROP, STRING_STRING_MAP).orElseGet(Collections::emptyMap); + .bind(ZOOKEEPER_DEPENDENCIES_PROP, STRING_STRING_MAP) + .orElseGet(Collections::emptyMap); if (!subProperties.isEmpty()) { return ConditionOutcome.match("Dependencies are defined in configuration"); } - Boolean dependenciesEnabled = context.getEnvironment() - .getProperty("spring.cloud.zookeeper.dependency.enabled", Boolean.class, false); + Boolean dependenciesEnabled = context.getEnvironment().getProperty( + "spring.cloud.zookeeper.dependency.enabled", Boolean.class, false); if (dependenciesEnabled) { - return ConditionOutcome.match("Dependencies are not defined in configuration, but switch is turned on"); + return ConditionOutcome.match( + "Dependencies are not defined in configuration, but switch is turned on"); } - return ConditionOutcome.noMatch("No dependencies have been passed for the service"); + return ConditionOutcome + .noMatch("No dependencies have been passed for the service"); } } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyEnvironmentPostProcessor.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyEnvironmentPostProcessor.java index 9a6d4788..ceae8dd3 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyEnvironmentPostProcessor.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyEnvironmentPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -27,10 +27,10 @@ import org.springframework.core.env.MapPropertySource; import org.springframework.util.StringUtils; /** - * EnvironmentPostProcessor that sets spring.application.name. - * Specifically, if spring.application.name doesn't contain a / and - * spring.cloud.zookeeper.prefix has text, it sets spring.application.name - * to /${spring.cloud.zookeeper.prefix}/${spring.application.name} + * EnvironmentPostProcessor that sets spring.application.name. Specifically, if + * spring.application.name doesn't contain a / and spring.cloud.zookeeper.prefix has text, + * it sets spring.application.name to + * /${spring.cloud.zookeeper.prefix}/${spring.application.name} * * @author Spencer Gibb * @since 1.0.0 @@ -41,11 +41,13 @@ public class DependencyEnvironmentPostProcessor // after ConfigFileEnvironmentPostProcessorr private int order = ConfigFileApplicationListener.DEFAULT_ORDER + 1; - @Override public int getOrder() { + @Override + public int getOrder() { return this.order; } - @Override public void postProcessEnvironment(ConfigurableEnvironment environment, + @Override + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { String appName = environment.getProperty("spring.application.name"); if (StringUtils.hasText(appName) && !appName.contains("/")) { @@ -61,11 +63,12 @@ public class DependencyEnvironmentPostProcessor } prefixedName.append(appName); MapPropertySource propertySource = new MapPropertySource( - "zookeeperDependencyEnvironment", Collections - .singletonMap("spring.application.name", + "zookeeperDependencyEnvironment", + Collections.singletonMap("spring.application.name", (Object) prefixedName.toString())); environment.getPropertySources().addFirst(propertySource); } } } + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyFeignClientAutoConfiguration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyFeignClientAutoConfiguration.java index 2781e354..dadeb9d5 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyFeignClientAutoConfiguration.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyFeignClientAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -23,27 +23,27 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; +import feign.Client; +import feign.Request; +import feign.Response; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration; +import org.springframework.cloud.netflix.ribbon.SpringClientFactory; import org.springframework.cloud.openfeign.ribbon.CachingSpringLoadBalancerFactory; import org.springframework.cloud.openfeign.ribbon.FeignRibbonClientAutoConfiguration; import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient; -import org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration; -import org.springframework.cloud.netflix.ribbon.SpringClientFactory; import org.springframework.cloud.zookeeper.ConditionalOnZookeeperEnabled; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; -import feign.Client; -import feign.Request; -import feign.Response; - /** - * Configuration for ensuring that headers are set for a given dependency when - * Feign is used. + * Configuration for ensuring that headers are set for a given dependency when Feign is + * used. * * @author Marcin Grzejszczak * @since 1.0.0 @@ -53,32 +53,40 @@ import feign.Response; @ConditionalOnZookeeperEnabled @ConditionalOnProperty(value = "spring.cloud.zookeeper.dependency.headers.enabled", matchIfMissing = true) @ConditionalOnClass({ Client.class, LoadBalancerFeignClient.class }) -@AutoConfigureAfter({ RibbonAutoConfiguration.class, FeignRibbonClientAutoConfiguration.class }) +@AutoConfigureAfter({ RibbonAutoConfiguration.class, + FeignRibbonClientAutoConfiguration.class }) public class DependencyFeignClientAutoConfiguration { - @Autowired(required = false) private LoadBalancerFeignClient ribbonClient; - @Autowired private ZookeeperDependencies zookeeperDependencies; - @Autowired private CachingSpringLoadBalancerFactory loadBalancerFactory; - @Autowired private SpringClientFactory springClientFactory; + + @Autowired(required = false) + private LoadBalancerFeignClient ribbonClient; + + @Autowired + private ZookeeperDependencies zookeeperDependencies; + + @Autowired + private CachingSpringLoadBalancerFactory loadBalancerFactory; + + @Autowired + private SpringClientFactory springClientFactory; @Bean @Primary Client dependencyBasedFeignClient() { - return new LoadBalancerFeignClient( - new Client.Default(null, null), this.loadBalancerFactory, this.springClientFactory) { + return new LoadBalancerFeignClient(new Client.Default(null, null), + this.loadBalancerFactory, this.springClientFactory) { @Override public Response execute(Request request, Request.Options options) throws IOException { URI asUri = URI.create(request.url()); String clientName = asUri.getHost(); - ZookeeperDependency dependencyForAlias = - DependencyFeignClientAutoConfiguration.this.zookeeperDependencies + ZookeeperDependency dependencyForAlias = DependencyFeignClientAutoConfiguration.this.zookeeperDependencies .getDependencyForAlias(clientName); Map> headers = getUpdatedHeadersIfPossible( request, dependencyForAlias); if (DependencyFeignClientAutoConfiguration.this.ribbonClient != null) { - return DependencyFeignClientAutoConfiguration.this.ribbonClient.execute( - request(request, headers), options); + return DependencyFeignClientAutoConfiguration.this.ribbonClient + .execute(request(request, headers), options); } return super.execute(request(request, headers), options); } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyRestTemplateAutoConfiguration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyRestTemplateAutoConfiguration.java index 9b86a6bb..43776054 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyRestTemplateAutoConfiguration.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyRestTemplateAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -22,6 +22,7 @@ import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; + import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; @@ -52,33 +53,45 @@ import org.springframework.web.client.RestTemplate; @AutoConfigureAfter(DependencyRibbonAutoConfiguration.class) public class DependencyRestTemplateAutoConfiguration { - @Autowired @LoadBalanced RestTemplate restTemplate; - @Autowired ZookeeperDependencies zookeeperDependencies; + @Autowired + @LoadBalanced + RestTemplate restTemplate; + + @Autowired + ZookeeperDependencies zookeeperDependencies; @PostConstruct void customizeRestTemplate() { this.restTemplate.getInterceptors().add(new ClientHttpRequestInterceptor() { @Override - public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { + public ClientHttpResponse intercept(HttpRequest request, byte[] body, + ClientHttpRequestExecution execution) throws IOException { String clientName = request.getURI().getHost(); - ZookeeperDependency dependencyForAlias = DependencyRestTemplateAutoConfiguration.this.zookeeperDependencies.getDependencyForAlias(clientName); - HttpHeaders headers = getUpdatedHeadersIfPossible(request, dependencyForAlias); + ZookeeperDependency dependencyForAlias = DependencyRestTemplateAutoConfiguration.this.zookeeperDependencies + .getDependencyForAlias(clientName); + HttpHeaders headers = getUpdatedHeadersIfPossible(request, + dependencyForAlias); request.getHeaders().putAll(headers); return execution.execute(request, body); } - private HttpHeaders getUpdatedHeadersIfPossible(HttpRequest request, ZookeeperDependency dependencyForAlias) { + private HttpHeaders getUpdatedHeadersIfPossible(HttpRequest request, + ZookeeperDependency dependencyForAlias) { HttpHeaders httpHeaders = new HttpHeaders(); if (dependencyForAlias != null) { - Map> updatedHeaders = dependencyForAlias.getUpdatedHeaders(convertHeadersFromListToCollection(request.getHeaders())); - httpHeaders.putAll(convertHeadersFromCollectionToList(updatedHeaders)); + Map> updatedHeaders = dependencyForAlias + .getUpdatedHeaders(convertHeadersFromListToCollection( + request.getHeaders())); + httpHeaders + .putAll(convertHeadersFromCollectionToList(updatedHeaders)); return httpHeaders; } httpHeaders.putAll(request.getHeaders()); return httpHeaders; } - private Map> convertHeadersFromListToCollection(HttpHeaders headers) { + private Map> convertHeadersFromListToCollection( + HttpHeaders headers) { Map> transformedHeaders = new HashMap<>(); for (Map.Entry> entry : headers.entrySet()) { transformedHeaders.put(entry.getKey(), entry.getValue()); @@ -86,10 +99,12 @@ public class DependencyRestTemplateAutoConfiguration { return transformedHeaders; } - private Map> convertHeadersFromCollectionToList(Map> headers) { + private Map> convertHeadersFromCollectionToList( + Map> headers) { Map> transformedHeaders = new HashMap<>(); for (Map.Entry> entry : headers.entrySet()) { - transformedHeaders.put(entry.getKey(), new ArrayList<>(entry.getValue())); + transformedHeaders.put(entry.getKey(), + new ArrayList<>(entry.getValue())); } return transformedHeaders; } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyRibbonAutoConfiguration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyRibbonAutoConfiguration.java index 3ee63a3b..810e8ce6 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyRibbonAutoConfiguration.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyRibbonAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -18,9 +18,9 @@ package org.springframework.cloud.zookeeper.discovery.dependency; import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.loadbalancer.Server; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; @@ -38,7 +38,7 @@ import org.springframework.context.annotation.Configuration; /** * * Provides LoadBalancerClient that at runtime can pick proper load balancing strategy - * basing on the Zookeeper dependencies from properties + * basing on the Zookeeper dependencies from properties. * * @author Marcin Grzejszczak * @since 1.0.0 @@ -50,25 +50,33 @@ import org.springframework.context.annotation.Configuration; @AutoConfigureBefore(RibbonAutoConfiguration.class) public class DependencyRibbonAutoConfiguration { - private static final Log log = LogFactory.getLog(DependencyRibbonAutoConfiguration.class); + private static final Log log = LogFactory + .getLog(DependencyRibbonAutoConfiguration.class); - @Autowired ApplicationContext applicationContext; + @Autowired + ApplicationContext applicationContext; @Bean @ConditionalOnMissingBean @ConditionalOnProperty(value = "spring.cloud.zookeeper.dependency.ribbon.enabled", matchIfMissing = true) - public LoadBalancerClient loadBalancerClient(SpringClientFactory springClientFactory) { + public LoadBalancerClient loadBalancerClient( + SpringClientFactory springClientFactory) { return new RibbonLoadBalancerClient(springClientFactory) { @Override protected Server getServer(String serviceId) { ILoadBalancer loadBalancer = this.getLoadBalancer(serviceId); - return loadBalancer == null ? null : chooseServerByServiceIdOrDefault(loadBalancer, serviceId); + return loadBalancer == null ? null + : chooseServerByServiceIdOrDefault(loadBalancer, serviceId); } - private Server chooseServerByServiceIdOrDefault(ILoadBalancer loadBalancer, String serviceId) { - log.debug(String.format("Dependencies are set - will try to load balance via provided load balancer [%s] for key [%s]", loadBalancer, serviceId)); + private Server chooseServerByServiceIdOrDefault(ILoadBalancer loadBalancer, + String serviceId) { + log.debug(String.format( + "Dependencies are set - will try to load balance via provided load balancer [%s] for key [%s]", + loadBalancer, serviceId)); Server server = loadBalancer.chooseServer(serviceId); - log.debug(String.format("Retrieved server [%s] via load balancer", server)); + log.debug( + String.format("Retrieved server [%s] via load balancer", server)); return server != null ? server : loadBalancer.chooseServer("default"); } }; diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/LoadBalancerType.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/LoadBalancerType.java index b8f209e3..0449a4cd 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/LoadBalancerType.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/LoadBalancerType.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.zookeeper.discovery.dependency; /** @@ -21,5 +22,10 @@ package org.springframework.cloud.zookeeper.discovery.dependency; * @since 1.0.0 */ public enum LoadBalancerType { + + /** + * Valid load balancer types. + */ STICKY, RANDOM, ROUND_ROBIN + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/StickyRule.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/StickyRule.java index ea8ff04b..0d99e37d 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/StickyRule.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/StickyRule.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -24,7 +24,6 @@ import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.AbstractLoadBalancerRule; import com.netflix.loadbalancer.IRule; import com.netflix.loadbalancer.Server; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -37,9 +36,13 @@ import org.apache.commons.logging.LogFactory; * @since 1.0.0 */ public class StickyRule extends AbstractLoadBalancerRule { + private static final Log log = LogFactory.getLog(StickyRule.class); + private final IRule masterStrategy; + private final AtomicReference ourInstance = new AtomicReference<>(null); + private final AtomicInteger instanceNumber = new AtomicInteger(-1); public StickyRule(IRule masterStrategy) { @@ -70,10 +73,10 @@ public class StickyRule extends AbstractLoadBalancerRule { } /** - * Each time a new instance is picked, an internal counter is incremented. This way you - * can track when/if the instance changes. The instance can change when the selected instance - * is not in the current list of instances returned by the instance provider - * + * Each time a new instance is picked, an internal counter is incremented. This way + * you can track when/if the instance changes. The instance can change when the + * selected instance is not in the current list of instances returned by the instance + * provider * @return instance number */ public int getInstanceNumber() { diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/StubsConfiguration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/StubsConfiguration.java index 234ac70e..bed3c700 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/StubsConfiguration.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/StubsConfiguration.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.zookeeper.discovery.dependency; import java.util.Arrays; @@ -12,29 +28,38 @@ import org.springframework.util.StringUtils; * @since 1.0.0 */ public class StubsConfiguration { + private static final String DEFAULT_STUBS_CLASSIFIER = "stubs"; + private static final String STUB_COLON_DELIMITER = ":"; + private static final String PATH_SLASH_DELIMITER = "/"; private final String stubsGroupId; + private final String stubsArtifactId; + private final String stubsClassifier; - public StubsConfiguration(String stubsGroupId, String stubsArtifactId, String stubsClassifier) { + public StubsConfiguration(String stubsGroupId, String stubsArtifactId, + String stubsClassifier) { this.stubsGroupId = stubsGroupId; this.stubsArtifactId = stubsArtifactId; - this.stubsClassifier = StringUtils.hasText(stubsClassifier) ? stubsClassifier : DEFAULT_STUBS_CLASSIFIER; + this.stubsClassifier = StringUtils.hasText(stubsClassifier) ? stubsClassifier + : DEFAULT_STUBS_CLASSIFIER; } public StubsConfiguration(String stubPath) { - String[] parsedPath = parsedStubPathEmptyByDefault(stubPath, STUB_COLON_DELIMITER); + String[] parsedPath = parsedStubPathEmptyByDefault(stubPath, + STUB_COLON_DELIMITER); this.stubsGroupId = parsedPath[0]; this.stubsArtifactId = parsedPath[1]; this.stubsClassifier = parsedPath[2]; } public StubsConfiguration(DependencyPath path) { - String[] parsedPath = parsedDependencyPathEmptyByDefault(path.getPath(), PATH_SLASH_DELIMITER); + String[] parsedPath = parsedDependencyPathEmptyByDefault(path.getPath(), + PATH_SLASH_DELIMITER); this.stubsGroupId = parsedPath[0]; this.stubsArtifactId = parsedPath[1]; this.stubsClassifier = parsedPath[2]; @@ -48,9 +73,10 @@ public class StubsConfiguration { if (splitPath.length >= 2) { stubsGroupId = splitPath[0]; stubsArtifactId = splitPath[1]; - stubsClassifier = splitPath.length == 3 ? splitPath[2] : DEFAULT_STUBS_CLASSIFIER; + stubsClassifier = splitPath.length == 3 ? splitPath[2] + : DEFAULT_STUBS_CLASSIFIER; } - return new String[]{stubsGroupId, stubsArtifactId, stubsClassifier}; + return new String[] { stubsGroupId, stubsArtifactId, stubsClassifier }; } private String[] parsedDependencyPathEmptyByDefault(String path, String delimiter) { @@ -66,18 +92,20 @@ public class StubsConfiguration { stubsArtifactId = lastElement; stubsClassifier = DEFAULT_STUBS_CLASSIFIER; } - return new String[]{stubsGroupId, stubsArtifactId, stubsClassifier}; + return new String[] { stubsGroupId, stubsArtifactId, stubsClassifier }; } private boolean isDefined() { - return StringUtils.hasText(this.stubsGroupId) && StringUtils.hasText(this.stubsArtifactId); + return StringUtils.hasText(this.stubsGroupId) + && StringUtils.hasText(this.stubsArtifactId); } public String toColonSeparatedDependencyNotation() { - if(!isDefined()) { + if (!isDefined()) { return ""; } - return StringUtils.collectionToDelimitedString(Arrays.asList(getStubsGroupId(), getStubsArtifactId(), getStubsClassifier()), STUB_COLON_DELIMITER); + return StringUtils.collectionToDelimitedString(Arrays.asList(getStubsGroupId(), + getStubsArtifactId(), getStubsClassifier()), STUB_COLON_DELIMITER); } public String getStubsGroupId() { @@ -93,9 +121,10 @@ public class StubsConfiguration { } /** - * Marker class to discern between the stubs location and dependency registration path + * Marker class to discern between the stubs location and dependency registration path. */ - static class DependencyPath { + public static class DependencyPath { + private final String path; public DependencyPath(String path) { @@ -105,5 +134,7 @@ public class StubsConfiguration { public String getPath() { return this.path; } + } + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependencies.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependencies.java index d9885d14..5e00fad2 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependencies.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependencies.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -13,15 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.zookeeper.discovery.dependency; -import javax.annotation.PostConstruct; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import javax.annotation.PostConstruct; + import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.zookeeper.discovery.dependency.StubsConfiguration.DependencyPath; @@ -30,7 +32,7 @@ import org.springframework.util.StringUtils; import static org.springframework.cloud.zookeeper.discovery.DependencyPathUtils.sanitize; /** - * Representation of this service's dependencies in Zookeeper + * Representation of this service's dependencies in Zookeeper. * * @author Marcin Grzejszczak * @since 1.0.0 @@ -39,18 +41,18 @@ import static org.springframework.cloud.zookeeper.discovery.DependencyPathUtils. public class ZookeeperDependencies { /** - * Common prefix that will be applied to all Zookeeper dependencies' paths + * Common prefix that will be applied to all Zookeeper dependencies' paths. */ private String prefix = ""; /** - * Mapping of alias to ZookeeperDependency. From Ribbon perspective the alias - * is actually serviceID since Ribbon can't accept nested structures in serviceID + * Mapping of alias to ZookeeperDependency. From Ribbon perspective the alias is + * actually serviceID since Ribbon can't accept nested structures in serviceID. */ private Map dependencies = new LinkedHashMap<>(); /** - * Default health endpoint that will be checked to verify that a dependency is alive + * Default health endpoint that will be checked to verify that a dependency is alive. */ @Value("${spring.cloud.zookeeper.dependency.ribbon.loadbalancer.defaulthealthendpoint:/health}") private String defaultHealthEndpoint; @@ -60,7 +62,8 @@ public class ZookeeperDependencies { if (StringUtils.hasText(this.prefix)) { this.prefix = sanitize(this.prefix); } - for (Map.Entry entry : this.dependencies.entrySet()) { + for (Map.Entry entry : this.dependencies + .entrySet()) { ZookeeperDependency value = entry.getValue(); if (!StringUtils.hasText(value.getPath())) { @@ -79,8 +82,10 @@ public class ZookeeperDependencies { private void setStubDefinition(ZookeeperDependency value) { if (!StringUtils.hasText(value.getStubs())) { - value.setStubsConfiguration(new StubsConfiguration(new DependencyPath(value.getPath()))); - } else { + value.setStubsConfiguration( + new StubsConfiguration(new DependencyPath(value.getPath()))); + } + else { value.setStubsConfiguration(new StubsConfiguration(value.getStubs())); } } @@ -94,7 +99,8 @@ public class ZookeeperDependencies { } public ZookeeperDependency getDependencyForPath(final String path) { - for (Map.Entry zookeeperDependencyEntry : this.dependencies.entrySet()) { + for (Map.Entry zookeeperDependencyEntry : this.dependencies + .entrySet()) { if (zookeeperDependencyEntry.getValue().getPath().equals(path)) { return zookeeperDependencyEntry.getValue(); } @@ -103,7 +109,8 @@ public class ZookeeperDependencies { } public ZookeeperDependency getDependencyForAlias(final String alias) { - for (Map.Entry zookeeperDependencyEntry : this.dependencies.entrySet()) { + for (Map.Entry zookeeperDependencyEntry : this.dependencies + .entrySet()) { if (zookeeperDependencyEntry.getKey().equals(alias)) { return zookeeperDependencyEntry.getValue(); } @@ -120,7 +127,8 @@ public class ZookeeperDependencies { } public String getAliasForPath(final String path) { - for (Map.Entry zookeeperDependencyEntry : this.dependencies.entrySet()) { + for (Map.Entry zookeeperDependencyEntry : this.dependencies + .entrySet()) { if (zookeeperDependencyEntry.getValue().getPath().equals(path)) { return zookeeperDependencyEntry.getKey(); } @@ -130,7 +138,8 @@ public class ZookeeperDependencies { public Collection getDependencyNames() { List names = new ArrayList<>(); - for (Map.Entry zookeeperDependencyEntry : this.dependencies.entrySet()) { + for (Map.Entry zookeeperDependencyEntry : this.dependencies + .entrySet()) { names.add(zookeeperDependencyEntry.getValue().getPath()); } return names; @@ -165,8 +174,10 @@ public class ZookeeperDependencies { final StringBuffer sb = new StringBuffer("ZookeeperDependencies{"); sb.append("prefix='").append(this.prefix).append('\''); sb.append(", dependencies=").append(this.dependencies); - sb.append(", defaultHealthEndpoint='").append(this.defaultHealthEndpoint).append('\''); + sb.append(", defaultHealthEndpoint='").append(this.defaultHealthEndpoint) + .append('\''); sb.append('}'); return sb.toString(); } + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependenciesAutoConfiguration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependenciesAutoConfiguration.java index 026ab00e..38c1230b 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependenciesAutoConfiguration.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependenciesAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.zookeeper.discovery.dependency; import org.springframework.boot.autoconfigure.AutoConfigureAfter; diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependency.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependency.java index 701e5820..342dc797 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependency.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependency.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -34,58 +34,64 @@ import static java.util.Collections.singletonList; public class ZookeeperDependency { private static final String VERSION_PLACEHOLDER_REGEX = "\\$version"; + private static final String CONTENT_TYPE_HEADER = "Content-Type"; /** * Path under which the dependency is registered in Zookeeper. The common prefix - * {@link ZookeeperDependencies#prefix} will be applied to this path + * {@link ZookeeperDependencies#prefix} will be applied to this path. */ private String path; /** - * Type of load balancer that should be used for this particular dependency + * Type of load balancer that should be used for this particular dependency. */ private LoadBalancerType loadBalancerType = LoadBalancerType.ROUND_ROBIN; /** - * Content type template with {@code $version} placeholder which will be filled - * by the {@link ZookeeperDependency#version} variable. + * Content type template with {@code $version} placeholder which will be filled by the + * {@link ZookeeperDependency#version} variable. *

* e.g. {@code 'application/vnd.some-service.$version+json'} */ private String contentTypeTemplate = ""; /** - * Provide the current version number of the dependency. This version will be placed under the - * {@code $version} placeholder in {@link ZookeeperDependency#contentTypeTemplate} + * Provide the current version number of the dependency. This version will be placed + * under the {@code $version} placeholder in + * {@link ZookeeperDependency#contentTypeTemplate}. */ private String version = ""; /** - * You can provide a map of default headers that should be attached when sending a message to the dependency + * You can provide a map of default headers that should be attached when sending a + * message to the dependency. */ private Map> headers = new HashMap<>(); /** - * If set to true - if the dependency is not present on startup then the application will not boot successfully + * If set to true - if the dependency is not present on startup then the application + * will not boot successfully. *

- * {@link org.springframework.cloud.zookeeper.discovery.watcher.presence.DependencyPresenceOnStartupVerifier;} + * {@link org.springframework.cloud.zookeeper.discovery.watcher.presence.DependencyPresenceOnStartupVerifier} * {@link org.springframework.cloud.zookeeper.discovery.watcher.DefaultDependencyWatcher} */ private boolean required; /** - * Colon separated notation of the stubs. E.g. {@code org.springframework:zookeeper-sample:stubs}. If not provided - * the {@code path} will be parsed to try to split it into groupId and artifactId. If not provided the classifier - * will by default equal {@code stubs} + * Colon separated notation of the stubs. E.g. + * {@code org.springframework:zookeeper-sample:stubs}. If not provided the + * {@code path} will be parsed to try to split it into groupId and artifactId. If not + * provided the classifier will by default equal {@code stubs} */ private String stubs; public ZookeeperDependency() { } - public ZookeeperDependency(String path, LoadBalancerType loadBalancerType, String contentTypeTemplate, - String version, Map> headers, boolean required, String stubs) { + public ZookeeperDependency(String path, LoadBalancerType loadBalancerType, + String contentTypeTemplate, String version, + Map> headers, boolean required, String stubs) { this.path = path; this.loadBalancerType = loadBalancerType; this.contentTypeTemplate = contentTypeTemplate; @@ -96,7 +102,7 @@ public class ZookeeperDependency { } /** - * Parsed stubs path + * Parsed stubs path. */ private StubsConfiguration stubsConfiguration; @@ -107,8 +113,10 @@ public class ZookeeperDependency { } /** - * Function that will replace the placeholder {@link ZookeeperDependency#VERSION_PLACEHOLDER_REGEX} from the - * {@link ZookeeperDependency#contentTypeTemplate} with value from {@link ZookeeperDependency#version}. + * Function that will replace the placeholder + * {@link ZookeeperDependency#VERSION_PLACEHOLDER_REGEX} from the + * {@link ZookeeperDependency#contentTypeTemplate} with value from + * {@link ZookeeperDependency#version}. *

*

* e.g. having: @@ -117,17 +125,19 @@ public class ZookeeperDependency { *

*

* the result of the function will be {@code 'application/vnd.some-service.v1+json'} - * * @return content type template with version */ public String getContentTypeWithVersion() { - if (!StringUtils.hasText(this.contentTypeTemplate) || !StringUtils.hasText(this.version)) { + if (!StringUtils.hasText(this.contentTypeTemplate) + || !StringUtils.hasText(this.version)) { return ""; } - return this.contentTypeTemplate.replaceAll(VERSION_PLACEHOLDER_REGEX, this.version); + return this.contentTypeTemplate.replaceAll(VERSION_PLACEHOLDER_REGEX, + this.version); } - public Map> getUpdatedHeaders(Map> headers) { + public Map> getUpdatedHeaders( + Map> headers) { Map> newHeaders = new HashMap<>(headers); if (hasContentTypeTemplate()) { setContentTypeFromTemplate(newHeaders); @@ -142,7 +152,8 @@ public class ZookeeperDependency { Collection contentTypes = headers.get(CONTENT_TYPE_HEADER); if (contentTypes == null || contentTypes.isEmpty()) { headers.put(CONTENT_TYPE_HEADER, singletonList(getContentTypeWithVersion())); - } else { + } + else { contentTypes.add(getContentTypeWithVersion()); } } @@ -152,7 +163,8 @@ public class ZookeeperDependency { Collection value = newHeaders.get(entry.getKey()); if (value == null || value.isEmpty()) { newHeaders.put(entry.getKey(), entry.getValue()); - } else { + } + else { value.addAll(entry.getValue()); } } @@ -235,7 +247,8 @@ public class ZookeeperDependency { final StringBuffer sb = new StringBuffer("ZookeeperDependency{"); sb.append("path='").append(this.path).append('\''); sb.append(", loadBalancerType=").append(this.loadBalancerType); - sb.append(", contentTypeTemplate='").append(this.contentTypeTemplate).append('\''); + sb.append(", contentTypeTemplate='").append(this.contentTypeTemplate) + .append('\''); sb.append(", version='").append(this.version).append('\''); sb.append(", headers=").append(this.headers); sb.append(", required=").append(this.required); @@ -244,4 +257,5 @@ public class ZookeeperDependency { sb.append('}'); return sb.toString(); } + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DefaultDependencyWatcher.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DefaultDependencyWatcher.java index f1ff1885..2bdd7832 100755 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DefaultDependencyWatcher.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DefaultDependencyWatcher.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.zookeeper.discovery.watcher; import java.io.IOException; @@ -22,6 +23,7 @@ import java.util.concurrent.ConcurrentHashMap; import org.apache.curator.x.discovery.ServiceCache; import org.apache.curator.x.discovery.ServiceDiscovery; + import org.springframework.cloud.client.discovery.event.InstanceRegisteredEvent; import org.springframework.cloud.zookeeper.discovery.ZookeeperInstance; import org.springframework.cloud.zookeeper.discovery.dependency.ZookeeperDependencies; @@ -31,28 +33,33 @@ import org.springframework.context.ApplicationListener; import org.springframework.util.ReflectionUtils; /** - * This Dependency Watcher will verify the presence of dependencies upon startup and registers listeners - * to changing of state of dependencies during the application's lifecycle. + * This Dependency Watcher will verify the presence of dependencies upon startup and + * registers listeners to changing of state of dependencies during the application's + * lifecycle. * * @author Marcin Grzejszczak * @author Michal Chmielarz, 4financeIT * @since 1.0.0 - * * @see DependencyPresenceOnStartupVerifier * @see DependencyWatcherListener */ -public class DefaultDependencyWatcher implements DependencyRegistrationHookProvider, ApplicationListener> { +public class DefaultDependencyWatcher implements DependencyRegistrationHookProvider, + ApplicationListener> { private final Map> dependencyRegistry = new ConcurrentHashMap<>(); + private final List listeners; + private ServiceDiscovery serviceDiscovery; + private final DependencyPresenceOnStartupVerifier dependencyPresenceOnStartupVerifier; + private final ZookeeperDependencies zookeeperDependencies; public DefaultDependencyWatcher(ServiceDiscovery serviceDiscovery, - DependencyPresenceOnStartupVerifier dependencyPresenceOnStartupVerifier, - List dependencyWatcherListeners, - ZookeeperDependencies zookeeperDependencies) { + DependencyPresenceOnStartupVerifier dependencyPresenceOnStartupVerifier, + List dependencyWatcherListeners, + ZookeeperDependencies zookeeperDependencies) { this.serviceDiscovery = serviceDiscovery; this.dependencyPresenceOnStartupVerifier = dependencyPresenceOnStartupVerifier; this.listeners = dependencyWatcherListeners; @@ -66,19 +73,22 @@ public class DefaultDependencyWatcher implements DependencyRegistrationHookProvi @Override public void registerDependencyRegistrationHooks() { - for (ZookeeperDependency zookeeperDependency : this.zookeeperDependencies.getDependencyConfigurations()) { + for (ZookeeperDependency zookeeperDependency : this.zookeeperDependencies + .getDependencyConfigurations()) { String dependencyPath = zookeeperDependency.getPath(); - ServiceCache serviceCache = getServiceDiscovery() - .serviceCacheBuilder().name(dependencyPath).build(); + ServiceCache serviceCache = getServiceDiscovery().serviceCacheBuilder() + .name(dependencyPath).build(); try { serviceCache.start(); } catch (Exception e) { ReflectionUtils.rethrowRuntimeException(e); } - this.dependencyPresenceOnStartupVerifier.verifyDependencyPresence(dependencyPath, serviceCache, zookeeperDependency.isRequired()); + this.dependencyPresenceOnStartupVerifier.verifyDependencyPresence( + dependencyPath, serviceCache, zookeeperDependency.isRequired()); this.dependencyRegistry.put(dependencyPath, serviceCache); - serviceCache.addListener(new DependencyStateChangeListenerRegistry(this.listeners, dependencyPath, serviceCache)); + serviceCache.addListener(new DependencyStateChangeListenerRegistry( + this.listeners, dependencyPath, serviceCache)); } } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyRegistrationHookProvider.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyRegistrationHookProvider.java index 66786555..604a06b4 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyRegistrationHookProvider.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyRegistrationHookProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -13,13 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.zookeeper.discovery.watcher; import java.io.IOException; /** - * Implementations of this interface are required to register dependency registration hooks - * on startup and their cleaning upon application context shutdown. + * Implementations of this interface are required to register dependency registration + * hooks on startup and their cleaning upon application context shutdown. * * @author Marcin Grzejszczak * @since 1.0.0 @@ -27,16 +28,14 @@ import java.io.IOException; public interface DependencyRegistrationHookProvider { /** - * Register hooks upon dependencies registration - * - * @throws Exception + * Register hooks upon dependencies registration. + * @throws Exception if registration fails. */ void registerDependencyRegistrationHooks() throws Exception; /** - * Unregister hooks upon dependencies registration - * - * @throws IOException + * Unregister hooks upon dependencies registration. + * @throws IOException if clearing fails. */ void clearDependencyRegistrationHooks() throws IOException; diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyState.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyState.java index 68375679..2cd9bc28 100755 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyState.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyState.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -13,16 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.zookeeper.discovery.watcher; /** - * - * Represents a dependency's Zookeeper connection state + * Represents a dependency's Zookeeper connection state. * * @author Marcin Grzejszczak * @since 1.0.0 */ public enum DependencyState { - CONNECTED, - DISCONNECTED + + /** + * valid states. + */ + CONNECTED, DISCONNECTED + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyStateChangeListenerRegistry.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyStateChangeListenerRegistry.java index da7314af..8fcb4427 100755 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyStateChangeListenerRegistry.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyStateChangeListenerRegistry.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.zookeeper.discovery.watcher; import java.util.List; @@ -25,7 +26,7 @@ import org.apache.curator.x.discovery.ServiceCache; import org.apache.curator.x.discovery.details.ServiceCacheListener; /** - * Informs all the DependencyWatcherListeners that a dependency's state has changed + * Informs all the DependencyWatcherListeners that a dependency's state has changed. * * @author Marcin Grzejszczak * @author Tomasz Nurkiewicz, 4financeIT @@ -33,13 +34,18 @@ import org.apache.curator.x.discovery.details.ServiceCacheListener; */ public class DependencyStateChangeListenerRegistry implements ServiceCacheListener { - private static final Log log = LogFactory.getLog(DependencyStateChangeListenerRegistry.class); + private static final Log log = LogFactory + .getLog(DependencyStateChangeListenerRegistry.class); private final List listeners; + private final String dependencyName; + private final ServiceCache serviceCache; - public DependencyStateChangeListenerRegistry(List listeners, String dependencyName, ServiceCache serviceCache) { + public DependencyStateChangeListenerRegistry( + List listeners, String dependencyName, + ServiceCache serviceCache) { this.listeners = listeners; this.dependencyName = dependencyName; this.serviceCache = serviceCache; @@ -47,13 +53,15 @@ public class DependencyStateChangeListenerRegistry implements ServiceCacheListen @Override public void cacheChanged() { - DependencyState state = this.serviceCache.getInstances().isEmpty() ? DependencyState.DISCONNECTED : DependencyState.CONNECTED; + DependencyState state = this.serviceCache.getInstances().isEmpty() + ? DependencyState.DISCONNECTED : DependencyState.CONNECTED; logCurrentState(state); informListeners(state); } private void logCurrentState(DependencyState dependencyState) { - log.info("Service cache state change for '"+this.dependencyName+"' instances, current service state: " + dependencyState); + log.info("Service cache state change for '" + this.dependencyName + + "' instances, current service state: " + dependencyState); } private void informListeners(DependencyState state) { @@ -66,4 +74,5 @@ public class DependencyStateChangeListenerRegistry implements ServiceCacheListen public void stateChanged(CuratorFramework client, ConnectionState newState) { // TODO do something or ignore for what is worth } + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyWatcherAutoConfiguration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyWatcherAutoConfiguration.java index 7e2f9436..433d25d3 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyWatcherAutoConfiguration.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyWatcherAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -13,12 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.zookeeper.discovery.watcher; import java.util.ArrayList; import java.util.List; import org.apache.curator.x.discovery.ServiceDiscovery; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; @@ -34,12 +36,11 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** - * Provides hooks for observing dependency lifecycle in Zookeeper. - * Needs custom dependencies to be set in order to work. + * Provides hooks for observing dependency lifecycle in Zookeeper. Needs custom + * dependencies to be set in order to work. * * @author Marcin Grzejszczak * @since 1.0.0 - * * @see ZookeeperDependencies */ @Configuration @@ -65,8 +66,8 @@ public class DependencyWatcherAutoConfiguration { DependencyPresenceOnStartupVerifier dependencyPresenceOnStartupVerifier, ZookeeperDependencies zookeeperDependencies) { return new DefaultDependencyWatcher(serviceDiscovery, - dependencyPresenceOnStartupVerifier, - this.dependencyWatcherListeners, + dependencyPresenceOnStartupVerifier, this.dependencyWatcherListeners, zookeeperDependencies); } + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyWatcherListener.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyWatcherListener.java index 86c0bd09..5b1ea54d 100755 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyWatcherListener.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/DependencyWatcherListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -13,24 +13,24 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.zookeeper.discovery.watcher; /** - * Performs logic upon change of state of a dependency {@link DependencyState} - * in the service discovery system. + * Performs logic upon change of state of a dependency {@link DependencyState} in the + * service discovery system. * * @author Marcin Grzejszczak * @since 1.0.0 - * * @see org.springframework.cloud.zookeeper.discovery.dependency.ZookeeperDependencies */ public interface DependencyWatcherListener { /** - * Method executed upon state change of a dependency - * + * Method executed upon state change of a dependency. * @param dependencyName - alias from microservice configuration * @param newState - new state of the dependency */ void stateChanged(String dependencyName, DependencyState newState); + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/DefaultDependencyPresenceOnStartupVerifier.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/DefaultDependencyPresenceOnStartupVerifier.java index 5b825ae2..bde347a0 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/DefaultDependencyPresenceOnStartupVerifier.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/DefaultDependencyPresenceOnStartupVerifier.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -13,19 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.zookeeper.discovery.watcher.presence; /** * By default passes logging dependency checker in order not to shutdown the application - * if dependency is missing + * if dependency is missing. * * @author Marcin Grzejszczak - * @version 1.0.0 - * * @see LogMissingDependencyChecker + * @version 1.0.0 */ -public class DefaultDependencyPresenceOnStartupVerifier extends DependencyPresenceOnStartupVerifier { +public class DefaultDependencyPresenceOnStartupVerifier + extends DependencyPresenceOnStartupVerifier { + public DefaultDependencyPresenceOnStartupVerifier() { super(new LogMissingDependencyChecker()); } + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/DependencyPresenceOnStartupVerifier.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/DependencyPresenceOnStartupVerifier.java index 3138f3e6..40660bbe 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/DependencyPresenceOnStartupVerifier.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/DependencyPresenceOnStartupVerifier.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -13,37 +13,45 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.zookeeper.discovery.watcher.presence; import org.apache.curator.x.discovery.ServiceCache; /** - * Verifier that checks for presence of mandatory dependencies and delegates to an optional - * presence checker verification of presence of optional dependencies. + * Verifier that checks for presence of mandatory dependencies and delegates to an + * optional presence checker verification of presence of optional dependencies. * - * The default implementation of required dependencies will result in shutting down of the application - * if the dependency is missing. + * The default implementation of required dependencies will result in shutting down of the + * application if the dependency is missing. * * @author Marcin Grzejszczak * @author Tomasz Szymanski, 4financeIT - * @version 1.0.0 - * * @see FailOnMissingDependencyChecker + * @version 1.0.0 */ public abstract class DependencyPresenceOnStartupVerifier { + private static final PresenceChecker MANDATORY_DEPENDENCY_CHECKER = new FailOnMissingDependencyChecker(); + private final PresenceChecker optionalDependencyChecker; - public DependencyPresenceOnStartupVerifier(PresenceChecker optionalDependencyChecker) { + public DependencyPresenceOnStartupVerifier( + PresenceChecker optionalDependencyChecker) { this.optionalDependencyChecker = optionalDependencyChecker; } @SuppressWarnings("unchecked") - public void verifyDependencyPresence(String dependencyName, @SuppressWarnings("rawtypes") ServiceCache serviceCache, boolean required) { + public void verifyDependencyPresence(String dependencyName, + @SuppressWarnings("rawtypes") ServiceCache serviceCache, boolean required) { if (required) { - MANDATORY_DEPENDENCY_CHECKER.checkPresence(dependencyName, serviceCache.getInstances()); - } else { - this.optionalDependencyChecker.checkPresence(dependencyName, serviceCache.getInstances()); + MANDATORY_DEPENDENCY_CHECKER.checkPresence(dependencyName, + serviceCache.getInstances()); + } + else { + this.optionalDependencyChecker.checkPresence(dependencyName, + serviceCache.getInstances()); } } + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/FailOnMissingDependencyChecker.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/FailOnMissingDependencyChecker.java index c1abe117..86117f03 100755 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/FailOnMissingDependencyChecker.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/FailOnMissingDependencyChecker.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.zookeeper.discovery.watcher.presence; import java.util.List; @@ -20,15 +21,18 @@ import java.util.List; import org.apache.curator.x.discovery.ServiceInstance; /** - * Will result in throwing an exception if there are no running instances of the dependency + * Will result in throwing an exception if there are no running instances of the + * dependency. * * @author Marcin Grzejszczak * @author Adam Chudzik, 4financeIT * @since 1.0.0 */ public class FailOnMissingDependencyChecker implements PresenceChecker { + @Override - public void checkPresence(String dependencyName, List> serviceInstances) { + public void checkPresence(String dependencyName, + List> serviceInstances) { if (serviceInstances.isEmpty()) { throw new NoInstancesRunningException(dependencyName); } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/LogMissingDependencyChecker.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/LogMissingDependencyChecker.java index 88f61409..e60763a8 100755 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/LogMissingDependencyChecker.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/LogMissingDependencyChecker.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.zookeeper.discovery.watcher.presence; import java.util.List; @@ -22,7 +23,7 @@ import org.apache.commons.logging.LogFactory; import org.apache.curator.x.discovery.ServiceInstance; /** - * Will log the missing microservice dependency + * Will log the missing microservice dependency. * * @author Marcin Grzejszczak * @author Tomasz Dziurko, 4financeIT @@ -33,7 +34,8 @@ public class LogMissingDependencyChecker implements PresenceChecker { private static final Log log = LogFactory.getLog(LogMissingDependencyChecker.class); @Override - public void checkPresence(String dependencyName, List> serviceInstances) { + public void checkPresence(String dependencyName, + List> serviceInstances) { if (serviceInstances.isEmpty()) { log.warn("Microservice dependency with name [" + dependencyName + "] is missing."); diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/NoInstancesRunningException.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/NoInstancesRunningException.java index b7699fe1..d220db00 100755 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/NoInstancesRunningException.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/NoInstancesRunningException.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.zookeeper.discovery.watcher.presence; /** @@ -20,7 +21,10 @@ package org.springframework.cloud.zookeeper.discovery.watcher.presence; * @since 1.0.0 */ public class NoInstancesRunningException extends RuntimeException { + public NoInstancesRunningException(String dependencyName) { - super("Required microservice dependency with name [" + dependencyName + "] is missing"); + super("Required microservice dependency with name [" + dependencyName + + "] is missing"); } + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/PresenceChecker.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/PresenceChecker.java index 184822c2..2c4781ca 100755 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/PresenceChecker.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/PresenceChecker.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.zookeeper.discovery.watcher.presence; import java.util.List; @@ -20,8 +21,8 @@ import java.util.List; import org.apache.curator.x.discovery.ServiceInstance; /** - * The implementation of this interface will be called upon checking if a dependency with a given name - * is present upon startup within the provided service instances. + * The implementation of this interface will be called upon checking if a dependency with + * a given name is present upon startup within the provided service instances. * * @author Marcin Grzejszczak * @since 1.0.0 @@ -29,10 +30,10 @@ import org.apache.curator.x.discovery.ServiceInstance; public interface PresenceChecker { /** - * Checks if a given dependency is present - * - * @param dependencyName - * @param serviceInstances - instances to check the dependency for + * Checks if a given dependency is present. + * @param dependencyName Name of the dependency. + * @param serviceInstances - instances to check the dependency for. */ void checkPresence(String dependencyName, List> serviceInstances); + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ServiceInstanceRegistration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ServiceInstanceRegistration.java index af9c8558..79ca9023 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ServiceInstanceRegistration.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ServiceInstanceRegistration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -16,22 +16,23 @@ package org.springframework.cloud.zookeeper.serviceregistry; -import org.apache.curator.x.discovery.ServiceInstance; -import org.apache.curator.x.discovery.ServiceInstanceBuilder; -import org.apache.curator.x.discovery.ServiceType; -import org.apache.curator.x.discovery.UriSpec; -import org.springframework.cloud.zookeeper.discovery.ZookeeperInstance; - import java.net.URI; import java.util.Collections; import java.util.Map; +import org.apache.curator.x.discovery.ServiceInstance; +import org.apache.curator.x.discovery.ServiceInstanceBuilder; +import org.apache.curator.x.discovery.ServiceType; +import org.apache.curator.x.discovery.UriSpec; + +import org.springframework.cloud.zookeeper.discovery.ZookeeperInstance; + import static org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryProperties.DEFAULT_URI_SPEC; /** - * {@link org.springframework.cloud.client.serviceregistry.Registration} that lazily builds - * a {@link ServiceInstance} so the port can by dynamically set (for instance, when the - * user wants a dynamic port for spring boot. + * {@link org.springframework.cloud.client.serviceregistry.Registration} that lazily + * builds a {@link ServiceInstance} so the port can by dynamically set (for instance, when + * the user wants a dynamic port for spring boot. * * @author Spencer Gibb */ @@ -40,86 +41,23 @@ public class ServiceInstanceRegistration implements ZookeeperRegistration { public static RegistrationBuilder builder() { try { return new RegistrationBuilder(ServiceInstance.builder()); - } catch (Exception e) { + } + catch (Exception e) { throw new RuntimeException("Error creating ServiceInstanceBuilder", e); } } - public static RegistrationBuilder builder(ServiceInstanceBuilder builder) { + public static RegistrationBuilder builder( + ServiceInstanceBuilder builder) { return new RegistrationBuilder(builder); } - public static class RegistrationBuilder { - protected ServiceInstanceBuilder builder; - - public RegistrationBuilder(ServiceInstanceBuilder builder) { - this.builder = builder; - } - - public ServiceInstanceRegistration build() { - return new ServiceInstanceRegistration(this.builder); - } - - public RegistrationBuilder name(String name) { - this.builder.name(name); - return this; - } - - public RegistrationBuilder address(String address) { - this.builder.address(address); - return this; - } - - public RegistrationBuilder id(String id) { - this.builder.id(id); - return this; - } - - public RegistrationBuilder port(int port) { - this.builder.port(port); - return this; - } - - public RegistrationBuilder sslPort(int port) { - this.builder.sslPort(port); - return this; - } - - public RegistrationBuilder payload(ZookeeperInstance payload) { - this.builder.payload(payload); - return this; - } - - public RegistrationBuilder serviceType(ServiceType serviceType) { - this.builder.serviceType(serviceType); - return this; - } - - public RegistrationBuilder registrationTimeUTC(long registrationTimeUTC) { - this.builder.registrationTimeUTC(registrationTimeUTC); - return this; - } - - public RegistrationBuilder uriSpec(UriSpec uriSpec) { - this.builder.uriSpec(uriSpec); - return this; - } - - public RegistrationBuilder uriSpec(String uriSpec) { - this.builder.uriSpec(new UriSpec(uriSpec)); - return this; - } - - public RegistrationBuilder defaultUriSpec() { - this.builder.uriSpec(new UriSpec(DEFAULT_URI_SPEC)); - return this; - } - } - protected ServiceInstance serviceInstance; + protected ServiceInstanceBuilder builder; - public ServiceInstanceRegistration(ServiceInstanceBuilder builder) { + public ServiceInstanceRegistration( + ServiceInstanceBuilder builder) { this.builder = builder; } @@ -185,4 +123,77 @@ public class ServiceInstanceRegistration implements ZookeeperRegistration { } return this.serviceInstance.getPayload().getMetadata(); } + + /** + * A builder for ServiceInstanceRegistration. + */ + public static class RegistrationBuilder { + + protected ServiceInstanceBuilder builder; + + public RegistrationBuilder(ServiceInstanceBuilder builder) { + this.builder = builder; + } + + public ServiceInstanceRegistration build() { + return new ServiceInstanceRegistration(this.builder); + } + + public RegistrationBuilder name(String name) { + this.builder.name(name); + return this; + } + + public RegistrationBuilder address(String address) { + this.builder.address(address); + return this; + } + + public RegistrationBuilder id(String id) { + this.builder.id(id); + return this; + } + + public RegistrationBuilder port(int port) { + this.builder.port(port); + return this; + } + + public RegistrationBuilder sslPort(int port) { + this.builder.sslPort(port); + return this; + } + + public RegistrationBuilder payload(ZookeeperInstance payload) { + this.builder.payload(payload); + return this; + } + + public RegistrationBuilder serviceType(ServiceType serviceType) { + this.builder.serviceType(serviceType); + return this; + } + + public RegistrationBuilder registrationTimeUTC(long registrationTimeUTC) { + this.builder.registrationTimeUTC(registrationTimeUTC); + return this; + } + + public RegistrationBuilder uriSpec(UriSpec uriSpec) { + this.builder.uriSpec(uriSpec); + return this; + } + + public RegistrationBuilder uriSpec(String uriSpec) { + this.builder.uriSpec(new UriSpec(uriSpec)); + return this; + } + + public RegistrationBuilder defaultUriSpec() { + this.builder.uriSpec(new UriSpec(DEFAULT_URI_SPEC)); + return this; + } + + } + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperAutoServiceRegistration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperAutoServiceRegistration.java index 8dd157f5..aaf9d4e2 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperAutoServiceRegistration.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperAutoServiceRegistration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -18,34 +18,36 @@ package org.springframework.cloud.zookeeper.serviceregistry; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.cloud.client.serviceregistry.AbstractAutoServiceRegistration; import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties; import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryProperties; /** - * Zookeeper {@link AbstractAutoServiceRegistration} - * that uses {@link ZookeeperServiceRegistry} to register and de-register instances. + * Zookeeper {@link AbstractAutoServiceRegistration} that uses + * {@link ZookeeperServiceRegistry} to register and de-register instances. * * @author Spencer Gibb * @since 1.0.0 */ -public class ZookeeperAutoServiceRegistration extends AbstractAutoServiceRegistration { +public class ZookeeperAutoServiceRegistration + extends AbstractAutoServiceRegistration { - private static final Log log = LogFactory.getLog(ZookeeperAutoServiceRegistration.class); + private static final Log log = LogFactory + .getLog(ZookeeperAutoServiceRegistration.class); private ZookeeperRegistration registration; + private ZookeeperDiscoveryProperties properties; public ZookeeperAutoServiceRegistration(ZookeeperServiceRegistry registry, - ZookeeperRegistration registration, - ZookeeperDiscoveryProperties properties) { + ZookeeperRegistration registration, ZookeeperDiscoveryProperties properties) { this(registry, registration, properties, null); } public ZookeeperAutoServiceRegistration(ZookeeperServiceRegistry registry, - ZookeeperRegistration registration, - ZookeeperDiscoveryProperties properties, - AutoServiceRegistrationProperties arProperties) { + ZookeeperRegistration registration, ZookeeperDiscoveryProperties properties, + AutoServiceRegistrationProperties arProperties) { super(registry, arProperties); this.registration = registration; this.properties = properties; @@ -93,4 +95,5 @@ public class ZookeeperAutoServiceRegistration extends AbstractAutoServiceRegistr protected Object getConfiguration() { return this.properties; } + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperAutoServiceRegistrationAutoConfiguration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperAutoServiceRegistrationAutoConfiguration.java index 4f5c3976..542f4fa1 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperAutoServiceRegistrationAutoConfiguration.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperAutoServiceRegistrationAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -38,8 +38,9 @@ import org.springframework.util.StringUtils; @ConditionalOnMissingBean(type = "org.springframework.cloud.zookeeper.discovery.ZookeeperLifecycle") @ConditionalOnZookeeperDiscoveryEnabled @ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true) -@AutoConfigureAfter( { ZookeeperServiceRegistryAutoConfiguration.class} ) -@AutoConfigureBefore( {AutoServiceRegistrationAutoConfiguration.class,ZookeeperDiscoveryAutoConfiguration.class} ) +@AutoConfigureAfter({ ZookeeperServiceRegistryAutoConfiguration.class }) +@AutoConfigureBefore({ AutoServiceRegistrationAutoConfiguration.class, + ZookeeperDiscoveryAutoConfiguration.class }) public class ZookeeperAutoServiceRegistrationAutoConfiguration { @Bean @@ -73,7 +74,6 @@ public class ZookeeperAutoServiceRegistrationAutoConfiguration { builder.id(properties.getInstanceId()); } - // TODO add customizer? return builder.build(); diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperRegistration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperRegistration.java index 7db1bca7..34ecb905 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperRegistration.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperRegistration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -17,6 +17,7 @@ package org.springframework.cloud.zookeeper.serviceregistry; import org.apache.curator.x.discovery.ServiceInstance; + import org.springframework.cloud.client.serviceregistry.Registration; import org.springframework.cloud.zookeeper.discovery.ZookeeperInstance; @@ -28,4 +29,5 @@ public interface ZookeeperRegistration extends Registration { ServiceInstance getServiceInstance(); void setPort(int port); + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperServiceRegistry.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperServiceRegistry.java index d59c05d4..e34b0ed1 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperServiceRegistry.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperServiceRegistry.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -22,6 +22,7 @@ import java.io.IOException; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.ServiceInstance; + import org.springframework.beans.factory.SmartInitializingSingleton; import org.springframework.cloud.client.serviceregistry.ServiceRegistry; import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryProperties; @@ -36,8 +37,8 @@ import static org.springframework.util.ReflectionUtils.rethrowRuntimeException; /** * @author Spencer Gibb */ -public class ZookeeperServiceRegistry implements ServiceRegistry, SmartInitializingSingleton, - Closeable { +public class ZookeeperServiceRegistry implements ServiceRegistry, + SmartInitializingSingleton, Closeable { // private AtomicBoolean started = new AtomicBoolean(); @@ -48,24 +49,28 @@ public class ZookeeperServiceRegistry implements ServiceRegistry instanceSerializer; private ServiceDiscovery serviceDiscovery; - public ZookeeperServiceRegistry(ServiceDiscovery serviceDiscovery) { + public ZookeeperServiceRegistry( + ServiceDiscovery serviceDiscovery) { this.serviceDiscovery = serviceDiscovery; } /** - * TODO: add when ZookeeperServiceDiscovery is removed - * One can override this method to provide custom way of registering {@link ServiceDiscovery} + * TODO: add when ZookeeperServiceDiscovery is removed One can override this method to + * provide custom way of registering {@link ServiceDiscovery} + */ + /* + * private void configureServiceDiscovery() { + * this.zookeeperServiceDiscovery.configureServiceDiscovery(this. + * zookeeperServiceDiscovery.getServiceDiscoveryRef(), this.curator, this.properties, + * this.instanceSerializer, this.zookeeperServiceDiscovery.getServiceInstanceRef()); } */ - /*private void configureServiceDiscovery() { - this.zookeeperServiceDiscovery.configureServiceDiscovery(this.zookeeperServiceDiscovery.getServiceDiscoveryRef(), - this.curator, this.properties, this.instanceSerializer, this.zookeeperServiceDiscovery.getServiceInstanceRef()); - }*/ @Override public void register(ZookeeperRegistration registration) { try { getServiceDiscovery().registerService(registration.getServiceInstance()); - } catch (Exception e) { + } + catch (Exception e) { rethrowRuntimeException(e); } } @@ -78,7 +83,8 @@ public class ZookeeperServiceRegistry implements ServiceRegistry serviceInstance = registration.getServiceInstance(); + ServiceInstance serviceInstance = registration + .getServiceInstance(); ZookeeperInstance instance = serviceInstance.getPayload(); instance.getMetadata().put(INSTANCE_STATUS_KEY, status); try { getServiceDiscovery().updateService(serviceInstance); - } catch (Exception e) { + } + catch (Exception e) { ReflectionUtils.rethrowRuntimeException(e); } } @@ -129,7 +139,10 @@ public class ZookeeperServiceRegistry implements ServiceRegistry> getServiceDiscoveryRef() { - return this.zookeeperServiceDiscovery.getServiceDiscoveryRef(); - }*/ + /* + * protected AtomicReference> + * getServiceDiscoveryRef() { return + * this.zookeeperServiceDiscovery.getServiceDiscoveryRef(); } + */ + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperServiceRegistryAutoConfiguration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperServiceRegistryAutoConfiguration.java index e91707c5..d6b6fab7 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperServiceRegistryAutoConfiguration.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperServiceRegistryAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -19,6 +19,7 @@ package org.springframework.cloud.zookeeper.serviceregistry; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.details.InstanceSerializer; import org.apache.curator.x.discovery.details.JsonInstanceSerializer; + import org.springframework.beans.BeansException; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; @@ -40,7 +41,8 @@ import org.springframework.context.annotation.Configuration; @ConditionalOnZookeeperDiscoveryEnabled @ConditionalOnProperty(value = "spring.cloud.service-registry.enabled", matchIfMissing = true) @AutoConfigureBefore(ServiceRegistryAutoConfiguration.class) -public class ZookeeperServiceRegistryAutoConfiguration implements ApplicationContextAware { +public class ZookeeperServiceRegistryAutoConfiguration + implements ApplicationContextAware { private ApplicationContext context; @@ -63,7 +65,9 @@ public class ZookeeperServiceRegistryAutoConfiguration implements ApplicationCon @Bean @ConditionalOnMissingBean - public ZookeeperDiscoveryProperties zookeeperDiscoveryProperties(InetUtils inetUtils) { + public ZookeeperDiscoveryProperties zookeeperDiscoveryProperties( + InetUtils inetUtils) { return new ZookeeperDiscoveryProperties(inetUtils); } + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/support/CuratorServiceDiscoveryAutoConfiguration.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/support/CuratorServiceDiscoveryAutoConfiguration.java index 5b16c135..968ead35 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/support/CuratorServiceDiscoveryAutoConfiguration.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/support/CuratorServiceDiscoveryAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 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. @@ -21,6 +21,7 @@ import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.ServiceDiscoveryBuilder; import org.apache.curator.x.discovery.details.InstanceSerializer; import org.apache.curator.x.discovery.details.JsonInstanceSerializer; + import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.cloud.zookeeper.discovery.ConditionalOnZookeeperDiscoveryEnabled; @@ -58,6 +59,8 @@ public class CuratorServiceDiscoveryAutoConfiguration { @ConditionalOnMissingBean public ServiceDiscovery curatorServiceDiscovery( ServiceDiscoveryCustomizer customizer) { - return customizer.customize(ServiceDiscoveryBuilder.builder(ZookeeperInstance.class)); + return customizer + .customize(ServiceDiscoveryBuilder.builder(ZookeeperInstance.class)); } + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/support/DefaultServiceDiscoveryCustomizer.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/support/DefaultServiceDiscoveryCustomizer.java index fdc768f6..a83573ab 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/support/DefaultServiceDiscoveryCustomizer.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/support/DefaultServiceDiscoveryCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 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. @@ -20,27 +20,32 @@ import org.apache.curator.framework.CuratorFramework; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.ServiceDiscoveryBuilder; import org.apache.curator.x.discovery.details.InstanceSerializer; + import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryProperties; import org.springframework.cloud.zookeeper.discovery.ZookeeperInstance; /** * @author Spencer Gibb */ -public class DefaultServiceDiscoveryCustomizer implements ServiceDiscoveryCustomizer{ +public class DefaultServiceDiscoveryCustomizer implements ServiceDiscoveryCustomizer { + protected CuratorFramework curator; protected ZookeeperDiscoveryProperties properties; protected InstanceSerializer instanceSerializer; - public DefaultServiceDiscoveryCustomizer(CuratorFramework curator, ZookeeperDiscoveryProperties properties, InstanceSerializer instanceSerializer) { + public DefaultServiceDiscoveryCustomizer(CuratorFramework curator, + ZookeeperDiscoveryProperties properties, + InstanceSerializer instanceSerializer) { this.curator = curator; this.properties = properties; this.instanceSerializer = instanceSerializer; } @Override - public ServiceDiscovery customize(ServiceDiscoveryBuilder builder) { + public ServiceDiscovery customize( + ServiceDiscoveryBuilder builder) { // @formatter:off return builder .client(this.curator) @@ -49,4 +54,5 @@ public class DefaultServiceDiscoveryCustomizer implements ServiceDiscoveryCustom .build(); // @formatter:on } + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/support/ServiceDiscoveryCustomizer.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/support/ServiceDiscoveryCustomizer.java index 3829d19c..66fe8057 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/support/ServiceDiscoveryCustomizer.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/support/ServiceDiscoveryCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 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. @@ -18,6 +18,7 @@ package org.springframework.cloud.zookeeper.support; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.ServiceDiscoveryBuilder; + import org.springframework.cloud.zookeeper.discovery.ZookeeperInstance; /** @@ -25,5 +26,7 @@ import org.springframework.cloud.zookeeper.discovery.ZookeeperInstance; */ public interface ServiceDiscoveryCustomizer { - ServiceDiscovery customize(ServiceDiscoveryBuilder builder); + ServiceDiscovery customize( + ServiceDiscoveryBuilder builder); + } diff --git a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/support/StatusConstants.java b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/support/StatusConstants.java index cbf3869d..860930ee 100644 --- a/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/support/StatusConstants.java +++ b/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/support/StatusConstants.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 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. @@ -16,22 +16,31 @@ package org.springframework.cloud.zookeeper.support; +import org.springframework.cloud.zookeeper.discovery.ZookeeperInstance; + /** * @author Spencer Gibb */ -public interface StatusConstants { +public final class StatusConstants { + + private StatusConstants() { + } + /** - * Key to the {@link org.springframework.cloud.zookeeper.discovery.ZookeeperInstance#metadata} map. + * Key to the + * {@link ZookeeperInstance#getMetadata()} + * map. */ - String INSTANCE_STATUS_KEY = "instance_status"; + public static final String INSTANCE_STATUS_KEY = "instance_status"; /** * UP value for {@link StatusConstants#INSTANCE_STATUS_KEY} key. */ - String STATUS_UP = "UP"; + public static final String STATUS_UP = "UP"; /** * OUT_OF_SERVICE value for {@link StatusConstants#INSTANCE_STATUS_KEY} key. */ - String STATUS_OUT_OF_SERVICE = "OUT_OF_SERVICE"; + public static final String STATUS_OUT_OF_SERVICE = "OUT_OF_SERVICE"; + } diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/ZookeeperServerListTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/ZookeeperServerListTests.java index 41eec0d3..c2aee122 100644 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/ZookeeperServerListTests.java +++ b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/ZookeeperServerListTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 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. @@ -24,6 +24,7 @@ import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.ServiceInstance; import org.assertj.core.data.MapEntry; import org.junit.Test; + import org.springframework.cloud.zookeeper.discovery.ZookeeperInstance; import org.springframework.cloud.zookeeper.discovery.ZookeeperServer; import org.springframework.cloud.zookeeper.discovery.ZookeeperServerList; @@ -52,7 +53,8 @@ public class ZookeeperServerListTests { @Test @SuppressWarnings("unchecked") public void testEmptyInstancesReturnsEmptyList() throws Exception { - ServiceDiscovery serviceDiscovery = mock(ServiceDiscovery.class); + ServiceDiscovery serviceDiscovery = mock( + ServiceDiscovery.class); when(serviceDiscovery.queryForInstances(anyString())).thenReturn(null); ZookeeperServerList serverList = new ZookeeperServerList(serviceDiscovery); @@ -66,27 +68,31 @@ public class ZookeeperServerListTests { ArrayList> instances = new ArrayList<>(); instances.add(serviceInstance(1, null)); - ServiceDiscovery serviceDiscovery = mock(ServiceDiscovery.class); - when(serviceDiscovery.queryForInstances(nullable(String.class))).thenReturn(instances); + ServiceDiscovery serviceDiscovery = mock( + ServiceDiscovery.class); + when(serviceDiscovery.queryForInstances(nullable(String.class))) + .thenReturn(instances); ZookeeperServerList serverList = new ZookeeperServerList(serviceDiscovery); List servers = serverList.getInitialListOfServers(); assertThat(servers).hasSize(1); } - private ServiceInstance serviceInstance(int instanceNum, String instanceStatus) { + private ServiceInstance serviceInstance(int instanceNum, + String instanceStatus) { String id = "instance" + instanceNum + "id"; String name = "instance" + instanceNum + "name"; ZookeeperInstance payload = null; if (instanceStatus != null) { - payload = new ZookeeperInstance(id, name, Collections.singletonMap(INSTANCE_STATUS_KEY, instanceStatus)); + payload = new ZookeeperInstance(id, name, + Collections.singletonMap(INSTANCE_STATUS_KEY, instanceStatus)); } String address = "instance" + instanceNum + "addr"; int port = 8080 + instanceNum; - return new ServiceInstance<>(name, id, address, port, null, payload, - 0, null, null); + return new ServiceInstance<>(name, id, address, port, null, payload, 0, null, + null); } @Test @@ -96,8 +102,10 @@ public class ZookeeperServerListTests { instances.add(serviceInstance(1, STATUS_UP)); instances.add(serviceInstance(2, STATUS_OUT_OF_SERVICE)); - ServiceDiscovery serviceDiscovery = mock(ServiceDiscovery.class); - when(serviceDiscovery.queryForInstances(nullable(String.class))).thenReturn(instances); + ServiceDiscovery serviceDiscovery = mock( + ServiceDiscovery.class); + when(serviceDiscovery.queryForInstances(nullable(String.class))) + .thenReturn(instances); ZookeeperServerList serverList = new ZookeeperServerList(serviceDiscovery); List servers = serverList.getInitialListOfServers(); @@ -106,4 +114,5 @@ public class ZookeeperServerListTests { assertThat(servers.get(0).getInstance().getPayload().getMetadata()) .contains(MapEntry.entry(INSTANCE_STATUS_KEY, STATUS_UP)); } + } diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/TestServiceRegistrar.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/TestServiceRegistrar.java index 925f5233..fb434f92 100644 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/TestServiceRegistrar.java +++ b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/TestServiceRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.zookeeper.discovery; import java.io.IOException; @@ -26,7 +27,9 @@ import org.apache.curator.x.discovery.UriSpec; public class TestServiceRegistrar { private final int serverPort; + private final CuratorFramework curatorFramework; + private final ServiceDiscovery serviceDiscovery; public TestServiceRegistrar(int serverPort, CuratorFramework curatorFramework) { @@ -38,33 +41,29 @@ public class TestServiceRegistrar { public void start() { try { this.serviceDiscovery.start(); - } catch (Exception e) { + } + catch (Exception e) { throw new RuntimeException(e); } } public ServiceInstance serviceInstance() { try { - return ServiceInstance.builder().uriSpec(new UriSpec("{scheme}://{address}:{port}/")) - .address("localhost") - .port(this.serverPort) - .name("testInstance") + return ServiceInstance.builder() + .uriSpec(new UriSpec("{scheme}://{address}:{port}/")) + .address("localhost").port(this.serverPort).name("testInstance") .build(); - } catch (Exception e) { + } + catch (Exception e) { throw new RuntimeException(e); } } public ServiceDiscovery serviceDiscovery() { - return ServiceDiscoveryBuilder - .builder(Void.class) - .basePath("/services") - .client(this.curatorFramework) - .thisInstance(serviceInstance()) - .build(); + return ServiceDiscoveryBuilder.builder(Void.class).basePath("/services") + .client(this.curatorFramework).thisInstance(serviceInstance()).build(); } - public void stop() { try { this.serviceDiscovery.close(); @@ -73,4 +72,5 @@ public class TestServiceRegistrar { throw new RuntimeException(e); } } + } diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryAutoRegistrationFalseTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryAutoRegistrationFalseTests.java index accaedc1..bd0339f3 100644 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryAutoRegistrationFalseTests.java +++ b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryAutoRegistrationFalseTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 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. @@ -20,6 +20,7 @@ import java.util.List; 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,18 +45,22 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Spencer Gibb */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = ZookeeperDiscoveryAutoRegistrationFalseTests.Config.class, - properties = { "spring.application.name=testzkautoregfalse", "debug=true" }, - webEnvironment = RANDOM_PORT) +@SpringBootTest(classes = ZookeeperDiscoveryAutoRegistrationFalseTests.Config.class, properties = { + "spring.application.name=testzkautoregfalse", + "debug=true" }, webEnvironment = RANDOM_PORT) @DirtiesContext public class ZookeeperDiscoveryAutoRegistrationFalseTests { - @Autowired DiscoveryClient discoveryClient; - @Value("${spring.application.name}") String springAppName; + @Autowired + DiscoveryClient discoveryClient; - @Test public void discovery_client_is_zookeeper() { - //given: this.discoveryClient - //expect: + @Value("${spring.application.name}") + String springAppName; + + @Test + public void discovery_client_is_zookeeper() { + // given: this.discoveryClient + // expect: then(discoveryClient).isInstanceOf(CompositeDiscoveryClient.class); CompositeDiscoveryClient composite = (CompositeDiscoveryClient) discoveryClient; List discoveryClients = composite.getDiscoveryClients(); @@ -63,10 +68,12 @@ public class ZookeeperDiscoveryAutoRegistrationFalseTests { then(first).isInstanceOf(ZookeeperDiscoveryClient.class); } - @Test public void application_should_not_have_been_registered() { - //given: - List instances = this.discoveryClient.getInstances(springAppName); - //expect: + @Test + public void application_should_not_have_been_registered() { + // given: + List instances = this.discoveryClient + .getInstances(springAppName); + // expect: then(instances).isEmpty(); } @@ -82,8 +89,11 @@ public class ZookeeperDiscoveryAutoRegistrationFalseTests { @Profile("ribbon") class PingController { - @RequestMapping("/ping") String ping() { + @RequestMapping("/ping") + String ping() { return "pong"; } + } + } diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryClientTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryClientTests.java index 04558e95..37bf9fc6 100644 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryClientTests.java +++ b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryClientTests.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.zookeeper.discovery; import java.util.List; @@ -17,9 +33,11 @@ import static org.mockito.Mockito.when; */ public class ZookeeperDiscoveryClientTests { - @Test public void should_return_an_empty_list_of_services_if_service_discovery_is_null() { + @Test + public void should_return_an_empty_list_of_services_if_service_discovery_is_null() { // given: - ServiceDiscovery serviceDiscovery = mock(ServiceDiscovery.class); + ServiceDiscovery serviceDiscovery = mock( + ServiceDiscovery.class); ZookeeperDiscoveryClient zookeeperDiscoveryClient = new ZookeeperDiscoveryClient( serviceDiscovery, null, new ZookeeperDiscoveryProperties()); // when: @@ -31,7 +49,8 @@ public class ZookeeperDiscoveryClientTests { @Test public void getServicesShouldReturnEmptyWhenNoNodeException() throws Exception { // given: - ServiceDiscovery serviceDiscovery = mock(ServiceDiscovery.class); + ServiceDiscovery serviceDiscovery = mock( + ServiceDiscovery.class); when(serviceDiscovery.queryForNames()).thenThrow(new NoNodeException()); ZookeeperDiscoveryClient discoveryClient = new ZookeeperDiscoveryClient( serviceDiscovery, null, new ZookeeperDiscoveryProperties()); @@ -44,8 +63,10 @@ public class ZookeeperDiscoveryClientTests { @Test public void getInstancesshouldReturnEmptyWhenNoNodeException() throws Exception { // given: - ServiceDiscovery serviceDiscovery = mock(ServiceDiscovery.class); - when(serviceDiscovery.queryForInstances("myservice")).thenThrow(new NoNodeException()); + ServiceDiscovery serviceDiscovery = mock( + ServiceDiscovery.class); + when(serviceDiscovery.queryForInstances("myservice")) + .thenThrow(new NoNodeException()); ZookeeperDiscoveryClient discoveryClient = new ZookeeperDiscoveryClient( serviceDiscovery, null, new ZookeeperDiscoveryProperties()); // when: @@ -53,4 +74,5 @@ public class ZookeeperDiscoveryClientTests { // then: then(instances).isEmpty(); } + } diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryDisabledTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryDisabledTests.java index abc87808..bd5d4852 100644 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryDisabledTests.java +++ b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryDisabledTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 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. @@ -20,8 +20,10 @@ import org.apache.curator.framework.CuratorFramework; import org.junit.Ignore; 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; import org.springframework.cloud.zookeeper.discovery.test.CommonTestConfig; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -33,12 +35,13 @@ import org.springframework.test.context.junit4.SpringRunner; */ @RunWith(SpringRunner.class) @SpringBootTest(classes = ZookeeperDiscoveryDisabledTests.SomeApp.class, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - properties = {"spring.cloud.zookeeper.discovery.enabled=false", "debug=true"}) + webEnvironment = WebEnvironment.RANDOM_PORT, properties = { + "spring.cloud.zookeeper.discovery.enabled=false", "debug=true" }) public class ZookeeperDiscoveryDisabledTests { @Test - @Ignore //FIXME 2.0.0 error creating zookeeperHealthIndicator, CuratorFramework not found, but report says it is + @Ignore // FIXME 2.0.0 error creating zookeeperHealthIndicator, CuratorFramework not + // found, but report says it is public void should_start_the_context_with_discovery_disabled() throws Exception { } @@ -46,9 +49,12 @@ public class ZookeeperDiscoveryDisabledTests { @EnableAutoConfiguration @Import(CommonTestConfig.class) static class SomeApp { + @Bean CuratorFramework curator() { return null; } + } + } diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryHealthIndicatorDisabledTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryHealthIndicatorDisabledTests.java index 96a5d077..346cdc2c 100644 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryHealthIndicatorDisabledTests.java +++ b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryHealthIndicatorDisabledTests.java @@ -1,7 +1,24 @@ +/* + * 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.zookeeper.discovery; 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; @@ -17,23 +34,26 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Spencer Gibb */ @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = RANDOM_PORT, - properties = "management.health.zookeeper.enabled=false") +@SpringBootTest(webEnvironment = RANDOM_PORT, properties = "management.health.zookeeper.enabled=false") public class ZookeeperDiscoveryHealthIndicatorDisabledTests { @Autowired(required = false) private ZookeeperDiscoveryHealthIndicator healthIndicator; - // Issue: #101 - ZookeeperDiscoveryHealthIndicator should be able to be disabled with a property - @Test public void healthIndicatorDisabled() { + // Issue: #101 - ZookeeperDiscoveryHealthIndicator should be able to be disabled with + // a property + @Test + public void healthIndicatorDisabled() { // when: // then: then(this.healthIndicator).isNull(); } - + @SpringBootConfiguration @EnableAutoConfiguration @Import(CommonTestConfig.class) - static class Config {} + static class Config { + + } } diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryHealthIndicatorWithNestedStructureTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryHealthIndicatorWithNestedStructureTests.java index bfe3c4c5..394f6d6d 100644 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryHealthIndicatorWithNestedStructureTests.java +++ b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryHealthIndicatorWithNestedStructureTests.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.zookeeper.discovery; import java.lang.invoke.MethodHandles; @@ -10,6 +26,7 @@ import org.apache.commons.logging.LogFactory; import org.apache.curator.framework.CuratorFramework; 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; @@ -37,27 +54,32 @@ import static org.springframework.cloud.zookeeper.discovery.test.TestRibbonClien */ @RunWith(SpringRunner.class) @SpringBootTest(classes = ZookeeperDiscoveryHealthIndicatorWithNestedStructureTests.Config.class, - properties = "management.endpoints.web.exposure.include=*", - webEnvironment = RANDOM_PORT) + properties = "management.endpoints.web.exposure.include=*", webEnvironment = RANDOM_PORT) @ActiveProfiles("nestedstructure") public class ZookeeperDiscoveryHealthIndicatorWithNestedStructureTests { - private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); + private static final Log log = LogFactory + .getLog(MethodHandles.lookup().lookupClass()); - @Autowired TestRibbonClient testRibbonClient; - @Autowired CuratorFramework curatorFramework; + @Autowired + TestRibbonClient testRibbonClient; + + @Autowired + CuratorFramework curatorFramework; // Issue: #54 - ZookeeperDiscoveryHealthIndicator fails on nested structure - @Test public void should_return_a_response_that_app_is_in_a_healthy_state_when_nested_folders_in_zookeeper_are_present() + @Test + public void should_return_a_response_that_app_is_in_a_healthy_state_when_nested_folders_in_zookeeper_are_present() throws Exception { // when: String response = this.testRibbonClient.callService("me", BASE_PATH + "/health"); // then: log.info("Received response [" + response + "]"); then(this.curatorFramework.getChildren().forPath("/services/me")).isNotEmpty(); - then(this.curatorFramework.getChildren().forPath("/services/a/b/c/d/anotherservice")).isNotEmpty(); + then(this.curatorFramework.getChildren() + .forPath("/services/a/b/c/d/anotherservice")).isNotEmpty(); } - + @Configuration @EnableAutoConfiguration @Import(CommonTestConfig.class) @@ -66,19 +88,18 @@ public class ZookeeperDiscoveryHealthIndicatorWithNestedStructureTests { @Autowired ZookeeperServiceRegistry serviceRegistry; + private ZookeeperRegistration registration; @PostConstruct void registerNestedDependency() { try { - this.registration = ServiceInstanceRegistration.builder() - .defaultUriSpec() - .address("anyUrl") - .port(10) - .name("/a/b/c/d/anotherservice") + this.registration = ServiceInstanceRegistration.builder().defaultUriSpec() + .address("anyUrl").port(10).name("/a/b/c/d/anotherservice") .build(); this.serviceRegistry.register(registration); - } catch (Exception e) { + } + catch (Exception e) { throw new RuntimeException(e); } } @@ -88,9 +109,12 @@ public class ZookeeperDiscoveryHealthIndicatorWithNestedStructureTests { this.serviceRegistry.deregister(this.registration); } - @Bean TestRibbonClient testRibbonClient(@LoadBalanced RestTemplate restTemplate, + @Bean + TestRibbonClient testRibbonClient(@LoadBalanced RestTemplate restTemplate, @Value("${spring.application.name}") String springAppName) { return new TestRibbonClient(restTemplate, springAppName); } + } + } diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryPropertiesTest.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryPropertiesTest.java index f44d56a0..bdd2e4ed 100644 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryPropertiesTest.java +++ b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryPropertiesTest.java @@ -1,37 +1,55 @@ +/* + * 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.zookeeper.discovery; +import java.util.Arrays; + import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; + import org.springframework.cloud.commons.util.InetUtils; import org.springframework.cloud.commons.util.InetUtilsProperties; -import java.util.Arrays; - import static org.assertj.core.api.BDDAssertions.then; @RunWith(Parameterized.class) public class ZookeeperDiscoveryPropertiesTest { - private String root; + private String root; - public ZookeeperDiscoveryPropertiesTest(String root) { - this.root = root; - } + public ZookeeperDiscoveryPropertiesTest(String root) { + this.root = root; + } - @Parameterized.Parameters(name = "With root {0}") - public static Iterable rootVariations() { - return Arrays.asList("es", "es/","/es"); - } + @Parameterized.Parameters(name = "With root {0}") + public static Iterable rootVariations() { + return Arrays.asList("es", "es/", "/es"); + } - @Test - public void should_escape_root() { - // given: - ZookeeperDiscoveryProperties zookeeperDiscoveryProperties = new ZookeeperDiscoveryProperties(new InetUtils(new InetUtilsProperties())); - // when: - zookeeperDiscoveryProperties.setRoot(root); - // then: - then(zookeeperDiscoveryProperties.getRoot()).isEqualTo("/es"); - } + @Test + public void should_escape_root() { + // given: + ZookeeperDiscoveryProperties zookeeperDiscoveryProperties = new ZookeeperDiscoveryProperties( + new InetUtils(new InetUtilsProperties())); + // when: + zookeeperDiscoveryProperties.setRoot(root); + // then: + then(zookeeperDiscoveryProperties.getRoot()).isEqualTo("/es"); + } } diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryPropertiesTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryPropertiesTests.java index 212563f1..29de662f 100644 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryPropertiesTests.java +++ b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryPropertiesTests.java @@ -1,7 +1,24 @@ +/* + * 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.zookeeper.discovery; 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; @@ -17,10 +34,10 @@ import static org.assertj.core.api.Assertions.assertThat; * @author wmz7year */ @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(properties = {"pring.application.name=testZookeeperDiscovery", +@SpringBootTest(properties = { "pring.application.name=testZookeeperDiscovery", "spring.cloud.zookeeper.discovery.instance-id=zkpropstestid-123", "spring.cloud.zookeeper.discovery.preferIpAddress=true", - "spring.cloud.zookeeper.discovery.instanceIpAddress=1.1.1.1"}, + "spring.cloud.zookeeper.discovery.instanceIpAddress=1.1.1.1" }, classes = ZookeeperDiscoveryPropertiesTests.Config.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class ZookeeperDiscoveryPropertiesTests { @@ -30,7 +47,8 @@ public class ZookeeperDiscoveryPropertiesTests { @Test public void testPreferIpAddress() { - assertThat(this.discoveryProperties.getInstanceId()).isEqualTo("zkpropstestid-123"); + assertThat(this.discoveryProperties.getInstanceId()) + .isEqualTo("zkpropstestid-123"); assertThat(this.discoveryProperties.getInstanceHost()).isEqualTo("1.1.1.1"); } @@ -40,4 +58,5 @@ public class ZookeeperDiscoveryPropertiesTests { static class Config { } + } diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoverySecurePortTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoverySecurePortTests.java index 26a385b3..682821ef 100644 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoverySecurePortTests.java +++ b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoverySecurePortTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 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. @@ -18,6 +18,7 @@ package org.springframework.cloud.zookeeper.discovery; 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; @@ -42,13 +43,10 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Marcin Grzejszczak */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = ZookeeperDiscoverySecurePortTests.Config.class, - properties = { - "feign.hystrix.enabled=false", - "spring.cloud.zookeeper.discovery.uriSpec={scheme}://{address}:{port}/contextPath", - "spring.cloud.zookeeper.discovery.instance-ssl-port=8443", - }, - webEnvironment = RANDOM_PORT) +@SpringBootTest(classes = ZookeeperDiscoverySecurePortTests.Config.class, properties = { + "feign.hystrix.enabled=false", + "spring.cloud.zookeeper.discovery.uriSpec={scheme}://{address}:{port}/contextPath", + "spring.cloud.zookeeper.discovery.instance-ssl-port=8443" }, webEnvironment = RANDOM_PORT) @ActiveProfiles("ribbon") @DirtiesContext public class ZookeeperDiscoverySecurePortTests { @@ -67,10 +65,12 @@ public class ZookeeperDiscoverySecurePortTests { @Test public void zookeeperServerIntrospectorWorks() { - ServerIntrospector serverIntrospector = this.clientFactory.getInstance(springAppName, ServerIntrospector.class); + ServerIntrospector serverIntrospector = this.clientFactory + .getInstance(springAppName, ServerIntrospector.class); then(serverIntrospector).isInstanceOf(ZookeeperServerIntrospector.class); - ZookeeperServer zookeeperServer = new ZookeeperServer(this.zookeeperRegistration.getServiceInstance()); + ZookeeperServer zookeeperServer = new ZookeeperServer( + this.zookeeperRegistration.getServiceInstance()); then(serverIntrospector.isSecure(zookeeperServer)).isTrue(); } @@ -82,7 +82,8 @@ public class ZookeeperDiscoverySecurePortTests { @Test public void shouldSetServiceInstanceSslPort() { - then(this.zookeeperRegistration.getServiceInstance().getSslPort()).isEqualTo(8443); + then(this.zookeeperRegistration.getServiceInstance().getSslPort()) + .isEqualTo(8443); } @Configuration @@ -90,6 +91,7 @@ public class ZookeeperDiscoverySecurePortTests { @Import(CommonTestConfig.class) @Profile("ribbon") static class Config { + } } diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryTests.java index 9fa0dce1..c157c1c9 100644 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryTests.java +++ b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperDiscoveryTests.java @@ -1,9 +1,28 @@ +/* + * 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.zookeeper.discovery; import java.util.List; +import com.jayway.awaitility.Awaitility; +import com.toomuchcoding.jsonassert.JsonPath; 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; @@ -30,9 +49,6 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; -import com.jayway.awaitility.Awaitility; -import com.toomuchcoding.jsonassert.JsonPath; - import static org.assertj.core.api.BDDAssertions.then; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; import static org.springframework.cloud.zookeeper.discovery.test.TestRibbonClient.BASE_PATH; @@ -42,57 +58,72 @@ import static org.springframework.cloud.zookeeper.discovery.test.TestRibbonClien * @author Tim Ysewyn */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = ZookeeperDiscoveryTests.Config.class, - properties = { - "feign.hystrix.enabled=false", - "spring.cloud.zookeeper.discovery.uri-spec={scheme}://{address}:{port}/contextPath", - "management.endpoints.web.exposure.include=*" - }, - webEnvironment = RANDOM_PORT) +@SpringBootTest(classes = ZookeeperDiscoveryTests.Config.class, properties = { + "feign.hystrix.enabled=false", + "spring.cloud.zookeeper.discovery.uri-spec={scheme}://{address}:{port}/contextPath", + "management.endpoints.web.exposure.include=*" }, webEnvironment = RANDOM_PORT) @ActiveProfiles("ribbon") @DirtiesContext public class ZookeeperDiscoveryTests { - @Autowired TestRibbonClient testRibbonClient; - @Autowired DiscoveryClient discoveryClient; - @Autowired ServiceInstanceRegistration serviceDiscovery; - @Value("${spring.application.name}") String springAppName; - @Autowired IdUsingFeignClient idUsingFeignClient; - @Autowired Registration registration; + @Autowired + TestRibbonClient testRibbonClient; - @Test public void should_find_the_app_by_its_name_via_Ribbon() { - //expect: + @Autowired + DiscoveryClient discoveryClient; + + @Autowired + ServiceInstanceRegistration serviceDiscovery; + + @Value("${spring.application.name}") + String springAppName; + + @Autowired + IdUsingFeignClient idUsingFeignClient; + + @Autowired + Registration registration; + + @Test + public void should_find_the_app_by_its_name_via_Ribbon() { + // expect: then(registeredServiceStatusViaServiceName()).isEqualTo("UP"); } - @Test public void should_find_a_collaborator_via_discovery_client() { - //given: - List instances = this.discoveryClient.getInstances(this.springAppName); + @Test + public void should_find_a_collaborator_via_discovery_client() { + // given: + List instances = this.discoveryClient + .getInstances(this.springAppName); ServiceInstance instance = instances.get(0); - //expect: + // expect: then(registeredServiceStatus(instance)).isEqualTo("UP"); then(instance.getInstanceId()).isEqualTo("ribbon-instance-id-123"); - then(instance.getMetadata().get("testMetadataKey")).isEqualTo("testMetadataValue"); + then(instance.getMetadata().get("testMetadataKey")) + .isEqualTo("testMetadataValue"); then(instance).isInstanceOf(ZookeeperServiceInstance.class); ZookeeperServiceInstance zkInstance = (ZookeeperServiceInstance) instance; then(zkInstance.getServiceInstance().getId()).isEqualTo("ribbon-instance-id-123"); } - @Test public void should_present_application_name_as_id_of_the_service_instance() { - //given: - //expect: + @Test + public void should_present_application_name_as_id_of_the_service_instance() { + // given: + // expect: then(this.springAppName).isEqualTo(this.registration.getServiceId()); } - @Test public void should_service_instance_uri_match_uriSpec() { - //given: - //expect: + @Test + public void should_service_instance_uri_match_uriSpec() { + // given: + // expect: then(this.registration.getUri()).hasPath("/contextPath"); } - @Test public void should_find_an_instance_using_feign_via_service_id() { + @Test + public void should_find_an_instance_using_feign_via_service_id() { final IdUsingFeignClient idUsingFeignClient = this.idUsingFeignClient; - //expect: + // expect: Awaitility.await().until(() -> { then(idUsingFeignClient.hi()).isNotEmpty(); return true; @@ -100,23 +131,29 @@ public class ZookeeperDiscoveryTests { } private String registeredServiceStatusViaServiceName() { - return JsonPath.builder(this.testRibbonClient.thisHealthCheck()).field("status").read(String.class); + return JsonPath.builder(this.testRibbonClient.thisHealthCheck()).field("status") + .read(String.class); } private String registeredServiceStatus(ServiceInstance instance) { - return JsonPath.builder(this.testRibbonClient.callOnUrl(instance.getHost()+":"+instance.getPort(), BASE_PATH + "/health")).field("status").read(String.class); + return JsonPath.builder(this.testRibbonClient.callOnUrl( + instance.getHost() + ":" + instance.getPort(), BASE_PATH + "/health")) + .field("status").read(String.class); } - @Test public void should_properly_find_local_instance() { - //expect: - then(this.serviceDiscovery.getServiceInstance().getAddress()).isEqualTo(this.registration.getHost()); + @Test + public void should_properly_find_local_instance() { + // expect: + then(this.serviceDiscovery.getServiceInstance().getAddress()) + .isEqualTo(this.registration.getHost()); } - - + @FeignClient("ribbonApp") public interface IdUsingFeignClient { + @RequestMapping(method = RequestMethod.GET, value = "/hi") String hi(); + } @Configuration @@ -127,7 +164,8 @@ public class ZookeeperDiscoveryTests { @RestController static class Config { - @Bean TestRibbonClient testRibbonClient(@LoadBalanced RestTemplate restTemplate, + @Bean + TestRibbonClient testRibbonClient(@LoadBalanced RestTemplate restTemplate, @Value("${spring.application.name}") String springAppName) { return new TestRibbonClient(restTemplate, springAppName); } @@ -136,14 +174,18 @@ public class ZookeeperDiscoveryTests { public String hi() { return "hi"; } + } @Controller @Profile("ribbon") class PingController { - @RequestMapping("/ping") String ping() { + @RequestMapping("/ping") + String ping() { return "pong"; } + } + } diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperLifecycleRegistrationDisabledTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperLifecycleRegistrationDisabledTests.java index 55694ab4..0dd50be7 100644 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperLifecycleRegistrationDisabledTests.java +++ b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeperLifecycleRegistrationDisabledTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -20,6 +20,7 @@ import java.util.List; 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,31 +30,34 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit4.SpringRunner; -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; /** * @author Spencer Gibb */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = ZookeeperLifecycleRegistrationDisabledTests.TestPropsConfig.class, - properties = { "spring.application.name=myTestNotRegisteredService", - "spring.cloud.zookeeper.discovery.register=false", "spring.cloud.zookeeper.dependency.enabled=false"}, - webEnvironment = RANDOM_PORT) +@SpringBootTest(classes = ZookeeperLifecycleRegistrationDisabledTests.TestPropsConfig.class, properties = { + "spring.application.name=myTestNotRegisteredService", + "spring.cloud.zookeeper.discovery.register=false", + "spring.cloud.zookeeper.dependency.enabled=false" }, webEnvironment = RANDOM_PORT) public class ZookeeperLifecycleRegistrationDisabledTests { - @Autowired private ZookeeperDiscoveryClient client; @Test public void contextLoads() { - List instances = this.client.getInstances("myTestNotRegisteredService"); - assertTrue("service was registered", instances.isEmpty()); + List instances = this.client + .getInstances("myTestNotRegisteredService"); + assertThat(instances.isEmpty()).as("service was registered").isTrue(); } @Configuration @EnableAutoConfiguration @Import({ CommonTestConfig.class }) - static class TestPropsConfig { } + static class TestPropsConfig { + + } + } diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeprDiscoveryNonWebAppTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeprDiscoveryNonWebAppTests.java index 954321ad..7cde7ac3 100644 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeprDiscoveryNonWebAppTests.java +++ b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/ZookeeprDiscoveryNonWebAppTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 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. @@ -16,10 +16,12 @@ package org.springframework.cloud.zookeeper.discovery; +import com.jayway.awaitility.Awaitility; import org.apache.curator.test.TestingServer; import org.junit.After; import org.junit.Before; import org.junit.Test; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.WebApplicationType; @@ -36,23 +38,24 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; -import com.jayway.awaitility.Awaitility; - import static org.assertj.core.api.BDDAssertions.then; /** * Test for gh-91, using s-c-zookeeper in a non-web app. + * * @author Marcin Grzejszczak */ public class ZookeeprDiscoveryNonWebAppTests { TestingServer server; + String connectionString; @Before public void setup() throws Exception { this.server = new TestingServer(SocketUtils.findAvailableTcpPort()); - this.connectionString = "--spring.cloud.zookeeper.connectString=" + this.server.getConnectString(); + this.connectionString = "--spring.cloud.zookeeper.connectString=" + + this.server.getConnectString(); } @After @@ -64,25 +67,29 @@ public class ZookeeprDiscoveryNonWebAppTests { public void should_work_when_using_web_client_without_the_web_environment() throws Exception { SpringApplication producerApp = new SpringApplicationBuilder(HelloProducer.class) - .web(WebApplicationType.SERVLET) - .build(); - SpringApplication clientApplication = new SpringApplicationBuilder(HelloClient.class) - .web(WebApplicationType.NONE) - .build(); + .web(WebApplicationType.SERVLET).build(); + SpringApplication clientApplication = new SpringApplicationBuilder( + HelloClient.class).web(WebApplicationType.NONE).build(); - try (ConfigurableApplicationContext producerContext = producerApp.run(this.connectionString, "--server.port=0", + try (ConfigurableApplicationContext producerContext = producerApp.run( + this.connectionString, "--server.port=0", "--spring.application.name=hello-world", "--debug")) { - try (final ConfigurableApplicationContext context = clientApplication.run(this.connectionString, + try (ConfigurableApplicationContext context = clientApplication.run( + this.connectionString, "--spring.cloud.zookeeper.discovery.register=false")) { Awaitility.await().until(new Runnable() { - @Override public void run() { + @Override + public void run() { try { HelloClient bean = context.getBean(HelloClient.class); then(bean.discoveryClient.getServices()).isNotEmpty(); - then(bean.discoveryClient.getInstances("hello-world")).isNotEmpty(); - String string = bean.restTemplate.getForObject("http://hello-world/", String.class); + then(bean.discoveryClient.getInstances("hello-world")) + .isNotEmpty(); + String string = bean.restTemplate + .getForObject("http://hello-world/", String.class); then(string).isEqualTo("foo"); - } catch (IllegalStateException e) { + } + catch (IllegalStateException e) { throw new AssertionError(e); } } @@ -91,9 +98,10 @@ public class ZookeeprDiscoveryNonWebAppTests { } } - @EnableAutoConfiguration(exclude = {JmxAutoConfiguration.class}) + @EnableAutoConfiguration(exclude = { JmxAutoConfiguration.class }) @Configuration static class HelloClient { + @LoadBalanced @Bean RestTemplate restTemplate() { @@ -103,10 +111,12 @@ public class ZookeeprDiscoveryNonWebAppTests { @Autowired DiscoveryClient discoveryClient; - @Autowired RestTemplate restTemplate; + @Autowired + RestTemplate restTemplate; + } - @EnableAutoConfiguration(exclude = {JmxAutoConfiguration.class}) + @EnableAutoConfiguration(exclude = { JmxAutoConfiguration.class }) @RestController static class HelloProducer { @@ -116,4 +126,5 @@ public class ZookeeprDiscoveryNonWebAppTests { } } + } diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/configclient/DiscoveryClientConfigServiceAutoConfigurationTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/configclient/DiscoveryClientConfigServiceAutoConfigurationTests.java index fdd20262..572bc83c 100644 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/configclient/DiscoveryClientConfigServiceAutoConfigurationTests.java +++ b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/configclient/DiscoveryClientConfigServiceAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -39,7 +39,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -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.atLeast; import static org.mockito.Mockito.mock; @@ -70,14 +70,14 @@ public class DiscoveryClientConfigServiceAutoConfigurationTests { "spring.cloud.zookeeper.discovery.instance-port:7001", "spring.cloud.zookeeper.discovery.instance-host:foo", "spring.cloud.config.discovery.service-id:configserver"); - assertEquals( 1, this.context - .getBeanNamesForType(ZookeeperConfigServerAutoConfiguration.class).length); - ZookeeperDiscoveryClient client = this.context.getParent().getBean( - ZookeeperDiscoveryClient.class); + assertThat(this.context.getBeanNamesForType( + ZookeeperConfigServerAutoConfiguration.class).length).isEqualTo(1); + ZookeeperDiscoveryClient client = this.context.getParent() + .getBean(ZookeeperDiscoveryClient.class); verify(client, atLeast(2)).getInstances("configserver"); ConfigClientProperties locator = this.context .getBean(ConfigClientProperties.class); - assertEquals("http://foo:7001/", locator.getUri()[0]); + assertThat(locator.getUri()[0]).isEqualTo("http://foo:7001/"); } private void setup(String... env) { @@ -92,7 +92,8 @@ public class DiscoveryClientConfigServiceAutoConfigurationTests { this.context = new AnnotationConfigApplicationContext(); this.context.setParent(parent); this.context.register(PropertyPlaceholderAutoConfiguration.class, - ZookeeperConfigServerAutoConfiguration.class, ZookeeperAutoConfiguration.class, + ZookeeperConfigServerAutoConfiguration.class, + ZookeeperAutoConfiguration.class, ZookeeperDiscoveryClientConfiguration.class); this.context.refresh(); } diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/configclient/ZookeeperConfigServerAutoConfigurationTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/configclient/ZookeeperConfigServerAutoConfigurationTests.java index f8c37237..19c3c6d0 100644 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/configclient/ZookeeperConfigServerAutoConfigurationTests.java +++ b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/configclient/ZookeeperConfigServerAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -28,7 +28,6 @@ import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; /** * @author Dave Syer @@ -48,16 +47,19 @@ public class ZookeeperConfigServerAutoConfigurationTests { public void offByDefault() { this.context = new AnnotationConfigApplicationContext( ZookeeperConfigServerAutoConfiguration.class); - assertEquals(0, - this.context.getBeanNamesForType(ZookeeperDiscoveryProperties.class).length); + assertThat(this.context + .getBeanNamesForType(ZookeeperDiscoveryProperties.class).length) + .isEqualTo(0); } @Test public void onWhenRequested() { setup("spring.cloud.config.server.prefix=/config"); - assertEquals(1, - this.context.getBeanNamesForType(ZookeeperDiscoveryProperties.class).length); - ZookeeperDiscoveryProperties properties = this.context.getBean(ZookeeperDiscoveryProperties.class); + assertThat(this.context + .getBeanNamesForType(ZookeeperDiscoveryProperties.class).length) + .isEqualTo(1); + ZookeeperDiscoveryProperties properties = this.context + .getBean(ZookeeperDiscoveryProperties.class); assertThat(properties.getMetadata()).containsEntry("configPath", "/config"); } @@ -66,8 +68,7 @@ public class ZookeeperConfigServerAutoConfigurationTests { PropertyPlaceholderAutoConfiguration.class, ZookeeperConfigServerAutoConfiguration.class, ConfigServerProperties.class, ZookeeperDiscoveryProperties.class) - .web(WebApplicationType.NONE) - .properties(env).run(); + .web(WebApplicationType.NONE).properties(env).run(); } } diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyConfig.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyConfig.java index 23c02ae8..ec4ce5e2 100644 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyConfig.java +++ b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyConfig.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.zookeeper.discovery.dependency; import java.util.Collection; @@ -24,7 +40,8 @@ import static org.assertj.core.api.BDDAssertions.then; @Configuration @EnableAutoConfiguration @Import(CommonTestConfig.class) -@EnableFeignClients(basePackageClasses = {AliasUsingFeignClient.class, IdUsingFeignClient.class}) +@EnableFeignClients(basePackageClasses = { AliasUsingFeignClient.class, + IdUsingFeignClient.class }) public class DependencyConfig { @Bean @@ -61,17 +78,21 @@ class PortListener implements ApplicationListener { @FeignClient("someAlias") interface AliasUsingFeignClient { + @RequestMapping(method = RequestMethod.GET, value = "/application/beans") String getBeans(); @RequestMapping(method = RequestMethod.GET, value = "/checkHeaders") String checkHeaders(); + } @FeignClient("nameWithoutAlias") interface IdUsingFeignClient { + @RequestMapping(method = RequestMethod.GET, value = "/application/beans") String getBeans(); + } @RestController @@ -83,21 +104,24 @@ class PingController { this.portListener = portListener; } - @RequestMapping("/ping") String ping() { + @RequestMapping("/ping") + String ping() { return "pong"; } - @RequestMapping("/port") Integer port() { + @RequestMapping("/port") + Integer port() { return this.portListener.getPort(); } - @RequestMapping("/checkHeaders") String checkHeaders(@RequestHeader("Content-Type") String contentType, - @RequestHeader("header1") - Collection header1, - @RequestHeader("header2") Collection header2) { + @RequestMapping("/checkHeaders") + String checkHeaders(@RequestHeader("Content-Type") String contentType, + @RequestHeader("header1") Collection header1, + @RequestHeader("header2") Collection header2) { then(contentType).isEqualTo("application/vnd.newsletter.v1+json"); then(header1).containsExactly("value1"); then(header2).containsExactly("value2"); return "ok"; } + } diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/StickyRuleTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/StickyRuleTests.java index 981f4c52..ebffa29e 100644 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/StickyRuleTests.java +++ b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/StickyRuleTests.java @@ -1,13 +1,33 @@ +/* + * 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.zookeeper.discovery.dependency; import java.net.URI; import java.util.List; import java.util.concurrent.Callable; +import com.jayway.awaitility.Awaitility; +import com.netflix.loadbalancer.IPing; +import com.netflix.loadbalancer.NoOpPing; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.test.TestingServer; 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; @@ -25,35 +45,36 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.SocketUtils; import org.springframework.web.client.RestTemplate; -import com.jayway.awaitility.Awaitility; -import com.netflix.loadbalancer.IPing; -import com.netflix.loadbalancer.NoOpPing; - /** * @author Marcin Grzejszczak */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = StickyRuleTests.Config.class, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@SpringBootTest(classes = StickyRuleTests.Config.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("loadbalancerclient") public class StickyRuleTests { - @Autowired LoadBalancerClient loadBalancerClient; - @Autowired DiscoveryClient discoveryClient; - + @Autowired + LoadBalancerClient loadBalancerClient; + + @Autowired + DiscoveryClient discoveryClient; + @Test public void should_use_sticky_load_balancing_strategy_taken_from_Zookeeper_dependencies() { - //given: - System.setProperty("spring.cloud.zookeeper.dependency.ribbon.loadbalancer.checkping", "false"); - //expect: - thereAreTwoRegisteredServices(); - URI uri = getUriForAlias(); - Awaitility.await().until(uriMatchesTwice(uri)); + // given: + System.setProperty( + "spring.cloud.zookeeper.dependency.ribbon.loadbalancer.checkping", + "false"); + // expect: + thereAreTwoRegisteredServices(); + URI uri = getUriForAlias(); + Awaitility.await().until(uriMatchesTwice(uri)); } private Callable uriMatchesTwice(final URI uri) { return new Callable() { - @Override public Boolean call() throws Exception { + @Override + public Boolean call() throws Exception { return uriMatches() && uriMatches(); } @@ -73,38 +94,47 @@ public class StickyRuleTests { return alias != null ? alias.getUri() : null; } - @Configuration @EnableAutoConfiguration @Profile("loadbalancerclient") static class Config { @Bean - @LoadBalanced RestTemplate loadBalancedRestTemplate() { + @LoadBalanced + RestTemplate loadBalancedRestTemplate() { return new RestTemplate(); } - @Bean(destroyMethod = "close") TestingServer testingServer() throws Exception { + @Bean(destroyMethod = "close") + TestingServer testingServer() throws Exception { return new TestingServer(SocketUtils.findAvailableTcpPort()); } - @Bean ZookeeperProperties zookeeperProperties() throws Exception { + @Bean + ZookeeperProperties zookeeperProperties() throws Exception { ZookeeperProperties zookeeperProperties = new ZookeeperProperties(); - zookeeperProperties.setConnectString("localhost:"+ testingServer().getPort()); + zookeeperProperties + .setConnectString("localhost:" + testingServer().getPort()); return zookeeperProperties; } @Bean(initMethod = "start", destroyMethod = "stop") TestServiceRegistrar serviceOne(CuratorFramework curatorFramework) { - return new TestServiceRegistrar(SocketUtils.findAvailableTcpPort(), curatorFramework); + return new TestServiceRegistrar(SocketUtils.findAvailableTcpPort(), + curatorFramework); } - @Bean(initMethod = "start", destroyMethod = "stop") TestServiceRegistrar serviceTwo(CuratorFramework curatorFramework) { - return new TestServiceRegistrar(SocketUtils.findAvailableTcpPort(), curatorFramework); + @Bean(initMethod = "start", destroyMethod = "stop") + TestServiceRegistrar serviceTwo(CuratorFramework curatorFramework) { + return new TestServiceRegistrar(SocketUtils.findAvailableTcpPort(), + curatorFramework); } - @Bean IPing noOpPing() { + @Bean + IPing noOpPing() { return new NoOpPing(); } + } + } diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/StubsConfigurationTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/StubsConfigurationTests.java index 187f0f1c..d8f341c9 100644 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/StubsConfigurationTests.java +++ b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/StubsConfigurationTests.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.zookeeper.discovery.dependency; import org.junit.Test; @@ -11,30 +27,31 @@ public class StubsConfigurationTests { @Test public void should_return_empty_colon_separated_dependency_notation_if_empty_path_has_been_provided() { - //given: + // given: String path = ""; - //when: + // when: StubsConfiguration stubsConfiguration = new StubsConfiguration(path); - //then: + // then: then(stubsConfiguration.toColonSeparatedDependencyNotation()).isEqualTo(""); } + @Test public void should_return_empty_colon_separated_dependency_notation_if_invalid_path_has_been_provided() { - //given: + // given: String path = "pl/"; - //when: + // when: StubsConfiguration stubsConfiguration = new StubsConfiguration(path); - //then: + // then: then(stubsConfiguration.toColonSeparatedDependencyNotation()).isEqualTo(""); } @Test public void should_properly_parse_invalid_colon_separated_path_into_empty_notation() { - //given: + // given: String path = "pl/a"; - //when: + // when: StubsConfiguration stubsConfiguration = new StubsConfiguration(path); - //then: + // then: then(stubsConfiguration.toColonSeparatedDependencyNotation()).isEqualTo(""); then(stubsConfiguration.getStubsGroupId()).isEqualTo(""); then(stubsConfiguration.getStubsArtifactId()).isEqualTo(""); @@ -43,12 +60,14 @@ public class StubsConfigurationTests { @Test public void should_parse_the_path_into_group_artifact_and_classifier() { - //given: + // given: String path = "pl/a"; - //when: - StubsConfiguration stubsConfiguration = new StubsConfiguration(new StubsConfiguration.DependencyPath(path)); - //then: - then(stubsConfiguration.toColonSeparatedDependencyNotation()).isEqualTo("pl:a:stubs"); + // when: + StubsConfiguration stubsConfiguration = new StubsConfiguration( + new StubsConfiguration.DependencyPath(path)); + // then: + then(stubsConfiguration.toColonSeparatedDependencyNotation()) + .isEqualTo("pl:a:stubs"); then(stubsConfiguration.getStubsGroupId()).isEqualTo("pl"); then(stubsConfiguration.getStubsArtifactId()).isEqualTo("a"); then(stubsConfiguration.getStubsClassifier()).isEqualTo("stubs"); @@ -56,13 +75,15 @@ public class StubsConfigurationTests { @Test public void should_properly_set_group_artifact_and_classifier() { - //when: - StubsConfiguration stubsConfiguration = new StubsConfiguration("pl", "a", "superstubs"); - //then: - then(stubsConfiguration.toColonSeparatedDependencyNotation()).isEqualTo("pl:a:superstubs"); + // when: + StubsConfiguration stubsConfiguration = new StubsConfiguration("pl", "a", + "superstubs"); + // then: + then(stubsConfiguration.toColonSeparatedDependencyNotation()) + .isEqualTo("pl:a:superstubs"); then(stubsConfiguration.getStubsGroupId()).isEqualTo("pl"); then(stubsConfiguration.getStubsArtifactId()).isEqualTo("a"); then(stubsConfiguration.getStubsClassifier()).isEqualTo("superstubs"); } - + } diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependenciesTest.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependenciesTest.java index e561515c..09ab77b4 100644 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependenciesTest.java +++ b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependenciesTest.java @@ -1,51 +1,71 @@ -package org.springframework.cloud.zookeeper.discovery.dependency; +/* + * 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. + */ -import org.junit.Test; +package org.springframework.cloud.zookeeper.discovery.dependency; import java.util.LinkedHashMap; import java.util.Map; +import org.junit.Test; + import static org.assertj.core.api.BDDAssertions.then; public class ZookeeperDependenciesTest { - @Test - public void should_properly_sanitize_dependency_path() { - // given: - Map dependencies = new LinkedHashMap<>(); - ZookeeperDependency cat = new ZookeeperDependency(); - cat.setPath("/cats/cat"); - dependencies.put("cat", cat); - ZookeeperDependency dog = new ZookeeperDependency(); - dog.setPath("dogs/dog"); - dependencies.put("dog", dog); - ZookeeperDependencies zookeeperDependencies = new ZookeeperDependencies(); - zookeeperDependencies.setDependencies(dependencies); - // when: - zookeeperDependencies.init(); - // then: - then(zookeeperDependencies.getDependencies().get("cat").getPath()).isEqualTo("/cats/cat"); - then(zookeeperDependencies.getDependencies().get("dog").getPath()).isEqualTo("/dogs/dog"); - } + @Test + public void should_properly_sanitize_dependency_path() { + // given: + Map dependencies = new LinkedHashMap<>(); + ZookeeperDependency cat = new ZookeeperDependency(); + cat.setPath("/cats/cat"); + dependencies.put("cat", cat); + ZookeeperDependency dog = new ZookeeperDependency(); + dog.setPath("dogs/dog"); + dependencies.put("dog", dog); + ZookeeperDependencies zookeeperDependencies = new ZookeeperDependencies(); + zookeeperDependencies.setDependencies(dependencies); + // when: + zookeeperDependencies.init(); + // then: + then(zookeeperDependencies.getDependencies().get("cat").getPath()) + .isEqualTo("/cats/cat"); + then(zookeeperDependencies.getDependencies().get("dog").getPath()) + .isEqualTo("/dogs/dog"); + } - @Test - public void should_properly_sanitize_dependency_path_with_prefix() { - // given: - Map dependencies = new LinkedHashMap<>(); - ZookeeperDependency cat = new ZookeeperDependency(); - cat.setPath("/cats/cat"); - dependencies.put("cat", cat); - ZookeeperDependency dog = new ZookeeperDependency(); - dog.setPath("dogs/dog"); - dependencies.put("dog", dog); - ZookeeperDependencies zookeeperDependencies = new ZookeeperDependencies(); - zookeeperDependencies.setPrefix("animals/"); - zookeeperDependencies.setDependencies(dependencies); - // when: - zookeeperDependencies.init(); - // then: - then(zookeeperDependencies.getDependencies().get("cat").getPath()).isEqualTo("/animals/cats/cat"); - then(zookeeperDependencies.getDependencies().get("dog").getPath()).isEqualTo("/animals/dogs/dog"); - } + @Test + public void should_properly_sanitize_dependency_path_with_prefix() { + // given: + Map dependencies = new LinkedHashMap<>(); + ZookeeperDependency cat = new ZookeeperDependency(); + cat.setPath("/cats/cat"); + dependencies.put("cat", cat); + ZookeeperDependency dog = new ZookeeperDependency(); + dog.setPath("dogs/dog"); + dependencies.put("dog", dog); + ZookeeperDependencies zookeeperDependencies = new ZookeeperDependencies(); + zookeeperDependencies.setPrefix("animals/"); + zookeeperDependencies.setDependencies(dependencies); + // when: + zookeeperDependencies.init(); + // then: + then(zookeeperDependencies.getDependencies().get("cat").getPath()) + .isEqualTo("/animals/cats/cat"); + then(zookeeperDependencies.getDependencies().get("dog").getPath()) + .isEqualTo("/animals/dogs/dog"); + } -} \ No newline at end of file +} diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependenciesTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependenciesTests.java index 62bde7aa..dc78de3a 100644 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependenciesTests.java +++ b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDependenciesTests.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.zookeeper.discovery.dependency; import java.util.Collection; @@ -16,18 +32,14 @@ import static org.assertj.core.api.BDDAssertions.then; public class ZookeeperDependenciesTests { private static final ZookeeperDependency EXPECTED_DEPENDENCY = new ZookeeperDependency( - "path", - LoadBalancerType.RANDOM, - "contentTypeTemplate", - "version", - defaultHeader(), - false, - "" - ); + "path", LoadBalancerType.RANDOM, "contentTypeTemplate", "version", + defaultHeader(), false, ""); + private static final Map DEPENDENCIES = defaultDependencies(); private static Map> defaultHeader() { - return Collections.singletonMap("header", (Collection) Collections.singletonList("value")); + return Collections.singletonMap("header", + (Collection) Collections.singletonList("value")); } private static Map defaultDependencies() { @@ -37,59 +49,72 @@ public class ZookeeperDependenciesTests { } ZookeeperDependencies zookeeperDependencies = new ZookeeperDependencies(); - + @Before public void setup() { this.zookeeperDependencies.setDependencies(DEPENDENCIES); } - @Test public void should_retrieve_dependency_dependency_for_good_path() { + @Test + public void should_retrieve_dependency_dependency_for_good_path() { // expect: - then(this.zookeeperDependencies.getDependencyForPath("path")).isEqualTo(EXPECTED_DEPENDENCY); + then(this.zookeeperDependencies.getDependencyForPath("path")) + .isEqualTo(EXPECTED_DEPENDENCY); } - @Test public void should_retrieve_null_dependency_dependency_for_bad_path() { + @Test + public void should_retrieve_null_dependency_dependency_for_bad_path() { // expect: then(this.zookeeperDependencies.getDependencyForPath("unknownPath")).isNull(); } - @Test public void should_retrieve_dependency_for_good_alias() { + @Test + public void should_retrieve_dependency_for_good_alias() { // expect: - then(this.zookeeperDependencies.getDependencyForAlias("alias")).isEqualTo(EXPECTED_DEPENDENCY); + then(this.zookeeperDependencies.getDependencyForAlias("alias")) + .isEqualTo(EXPECTED_DEPENDENCY); } - @Test public void should_retrieve_null_dependency_for_bad_alias() { + @Test + public void should_retrieve_null_dependency_for_bad_alias() { // expect: then(this.zookeeperDependencies.getDependencyForAlias("unknownAlias")).isNull(); } - @Test public void should_retrieve_alias_for_good_path() { + @Test + public void should_retrieve_alias_for_good_path() { // expect: then(this.zookeeperDependencies.getAliasForPath("path")).isEqualTo("alias"); } - @Test public void should_retrieve_empty_alias_for_bad_path() { + @Test + public void should_retrieve_empty_alias_for_bad_path() { // expect: then(this.zookeeperDependencies.getAliasForPath("unkownPath")).isEmpty(); } - @Test public void should_retrieve_path_for_good_alias() { + @Test + public void should_retrieve_path_for_good_alias() { // expect: then(this.zookeeperDependencies.getPathForAlias("alias")).isEqualTo("path"); } - @Test public void should_retrieve_empty_path_for_bad_alias() { + @Test + public void should_retrieve_empty_path_for_bad_alias() { // expect: then(this.zookeeperDependencies.getPathForAlias("unknownAlias")).isEmpty(); } - @Test public void should_successfully_replace_version_in_content_type_template() { + @Test + public void should_successfully_replace_version_in_content_type_template() { // given: ZookeeperDependency zookeeperDependency = new ZookeeperDependency(); - zookeeperDependency.setContentTypeTemplate("application/vnd.some-service.$version+json"); + zookeeperDependency + .setContentTypeTemplate("application/vnd.some-service.$version+json"); zookeeperDependency.setVersion("v1"); // expect: - then(zookeeperDependency.getContentTypeWithVersion()).isEqualTo("application/vnd.some-service.v1+json"); + then(zookeeperDependency.getContentTypeWithVersion()) + .isEqualTo("application/vnd.some-service.v1+json"); } - + } diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDiscoveryWithDependenciesIntegrationTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDiscoveryWithDependenciesIntegrationTests.java index 9b9dc2c7..fe54373d 100644 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDiscoveryWithDependenciesIntegrationTests.java +++ b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDiscoveryWithDependenciesIntegrationTests.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.zookeeper.discovery.dependency; import java.util.List; @@ -6,6 +22,7 @@ import java.util.concurrent.Callable; 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; @@ -26,135 +43,168 @@ import static org.springframework.cloud.zookeeper.discovery.test.TestRibbonClien * @author Marcin Grzejszczak */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = ZookeeperDiscoveryWithDependenciesIntegrationTests.Config.class, - properties = {"feign.hystrix.enabled=false", "debug=true", "management.endpoints.web.exposure.include=*"}, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@SpringBootTest(classes = ZookeeperDiscoveryWithDependenciesIntegrationTests.Config.class, properties = { + "feign.hystrix.enabled=false", "debug=true", + "management.endpoints.web.exposure.include=*" }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("dependencies") public class ZookeeperDiscoveryWithDependenciesIntegrationTests { - @Autowired TestRibbonClient testRibbonClient; - @Autowired DiscoveryClient discoveryClient; - @Autowired AliasUsingFeignClient aliasUsingFeignClient; - @Autowired IdUsingFeignClient idUsingFeignClient; - @Autowired ZookeeperDependencies zookeeperDependencies; + @Autowired + TestRibbonClient testRibbonClient; - @Test public void should_find_an_instance_via_path_when_alias_is_not_found() { + @Autowired + DiscoveryClient discoveryClient; + + @Autowired + AliasUsingFeignClient aliasUsingFeignClient; + + @Autowired + IdUsingFeignClient idUsingFeignClient; + + @Autowired + ZookeeperDependencies zookeeperDependencies; + + @Test + public void should_find_an_instance_via_path_when_alias_is_not_found() { // given: final DiscoveryClient discoveryClient = this.discoveryClient; // expect: await().until(new Callable() { - @Override public Boolean call() throws Exception { + @Override + public Boolean call() throws Exception { return !discoveryClient.getInstances("nameWithoutAlias").isEmpty(); } }); } - @Test public void should_fill_out_properly_the_stub_section_of_a_dependency() { + @Test + public void should_fill_out_properly_the_stub_section_of_a_dependency() { // given: - StubsConfiguration stubsConfiguration = this.zookeeperDependencies.getDependencies().get("someAlias").getStubsConfiguration(); + StubsConfiguration stubsConfiguration = this.zookeeperDependencies + .getDependencies().get("someAlias").getStubsConfiguration(); // expect: then(stubsConfiguration.getStubsGroupId()).isEqualTo("org.springframework"); then(stubsConfiguration.getStubsArtifactId()).isEqualTo("foo"); then(stubsConfiguration.getStubsClassifier()).isEqualTo("stubs"); } - @Ignore //FIXME 2.0.0 - @Test public void should_find_an_instance_using_feign_via_serviceID_when_alias_is_not_found() { + @Ignore // FIXME 2.0.0 + @Test + public void should_find_an_instance_using_feign_via_serviceID_when_alias_is_not_found() { // given: final IdUsingFeignClient idUsingFeignClient = this.idUsingFeignClient; // expect: await().until(new Callable() { - @Override public Boolean call() throws Exception { + @Override + public Boolean call() throws Exception { then(idUsingFeignClient.getBeans()).isNotEmpty(); return true; } }); } - @Ignore //FIXME 2.0.0 - @Test public void should_find_a_collaborator_via_load_balanced_rest_template_by_using_its_alias_from_dependencies() { + @Ignore // FIXME 2.0.0 + @Test + public void should_find_a_collaborator_via_load_balanced_rest_template_by_using_its_alias_from_dependencies() { // expect: await().until(new Callable() { - @Override public Boolean call() throws Exception { + @Override + public Boolean call() throws Exception { return callingServiceAtBeansEndpointIsNotEmpty(); } }); } - @Ignore //FIXME 2.0.0 - @Test public void should_find_a_collaborator_using_feign_by_using_its_alias_from_dependencies() { + @Ignore // FIXME 2.0.0 + @Test + public void should_find_a_collaborator_using_feign_by_using_its_alias_from_dependencies() { // given: final AliasUsingFeignClient aliasUsingFeignClient = this.aliasUsingFeignClient; // expect: await().until(new Callable() { - @Override public Boolean call() throws Exception { + @Override + public Boolean call() throws Exception { then(aliasUsingFeignClient.getBeans()).isNotEmpty(); return true; } }); } - @Test public void should_have_headers_from_dependencies_attached_to_the_request_via_load_balanced_rest_template() { + @Test + public void should_have_headers_from_dependencies_attached_to_the_request_via_load_balanced_rest_template() { // expect: await().until(new Callable() { - @Override public Boolean call() throws Exception { + @Override + public Boolean call() throws Exception { callingServiceToCheckIfHeadersArePassed(); return true; } }); } - @Ignore //FIXME 2.0.0 - @Test public void should_have_headers_from_dependencies_attached_to_the_request_via_feign() { + @Ignore // FIXME 2.0.0 + @Test + public void should_have_headers_from_dependencies_attached_to_the_request_via_feign() { // given: final AliasUsingFeignClient aliasUsingFeignClient = this.aliasUsingFeignClient; // expect: await().until(new Callable() { - @Override public Boolean call() throws Exception { + @Override + public Boolean call() throws Exception { aliasUsingFeignClient.checkHeaders(); return true; } }); } - @Test public void should_find_a_collaborator_via_discovery_client() { + @Test + public void should_find_a_collaborator_via_discovery_client() { // // given: final DiscoveryClient discoveryClient = this.discoveryClient; List instances = discoveryClient.getInstances("someAlias"); final ServiceInstance instance = instances.get(0); // expect: await().until(new Callable() { - @Override public Boolean call() throws Exception { + @Override + public Boolean call() throws Exception { return callingServiceViaUrlOnBeansEndpointIsNotEmpty(instance); } }); } - @Test public void should_have_path_equal_to_prefixed_alias() { + @Test + public void should_have_path_equal_to_prefixed_alias() { // given: - ZookeeperDependency dependency = this.zookeeperDependencies.getDependencyForAlias("aliasIsPath"); + ZookeeperDependency dependency = this.zookeeperDependencies + .getDependencyForAlias("aliasIsPath"); // expect: then(dependency.getPath()).isEqualTo("/aliasIsPath"); } - @Test public void should_have_prefixed_alias_equal_to_path() { + @Test + public void should_have_prefixed_alias_equal_to_path() { // given: - ZookeeperDependency dependency = this.zookeeperDependencies.getDependencyForPath("/aliasIsPath"); + ZookeeperDependency dependency = this.zookeeperDependencies + .getDependencyForPath("/aliasIsPath"); // expect: then(dependency.getPath()).isEqualTo("/aliasIsPath"); } - @Test public void should_have_path_set_via_string_constructor() { + @Test + public void should_have_path_set_via_string_constructor() { // given: - ZookeeperDependency dependency = this.zookeeperDependencies.getDependencyForAlias("anotherAlias"); + ZookeeperDependency dependency = this.zookeeperDependencies + .getDependencyForAlias("anotherAlias"); // expect: then(dependency.getPath()).isEqualTo("/myPath"); } // #138 - @Test public void should_parse_dependency_with_path() { + @Test + public void should_parse_dependency_with_path() { // given: - StubsConfiguration someServiceStub = this.zookeeperDependencies.getDependencyForAlias("some-service").getStubsConfiguration(); + StubsConfiguration someServiceStub = this.zookeeperDependencies + .getDependencyForAlias("some-service").getStubsConfiguration(); // expect: then(someServiceStub.getStubsGroupId()).isEqualTo("io.company.department"); then(someServiceStub.getStubsArtifactId()).isEqualTo("some-service"); @@ -162,11 +212,16 @@ public class ZookeeperDiscoveryWithDependenciesIntegrationTests { } private boolean callingServiceAtBeansEndpointIsNotEmpty() { - return !this.testRibbonClient.callService("someAlias", BASE_PATH + "/beans").isEmpty(); + return !this.testRibbonClient.callService("someAlias", BASE_PATH + "/beans") + .isEmpty(); } - private boolean callingServiceViaUrlOnBeansEndpointIsNotEmpty(ServiceInstance instance) { - return !this.testRibbonClient.callOnUrl(instance.getHost() + ":" + instance.getPort(), BASE_PATH + "/beans").isEmpty(); + private boolean callingServiceViaUrlOnBeansEndpointIsNotEmpty( + ServiceInstance instance) { + return !this.testRibbonClient + .callOnUrl(instance.getHost() + ":" + instance.getPort(), + BASE_PATH + "/beans") + .isEmpty(); } private void callingServiceToCheckIfHeadersArePassed() { @@ -177,5 +232,8 @@ public class ZookeeperDiscoveryWithDependenciesIntegrationTests { @EnableAutoConfiguration @Import(DependencyConfig.class) @Profile("dependencies") - static class Config { } + static class Config { + + } + } diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDiscoveryWithDyingDependenciesTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDiscoveryWithDyingDependenciesTests.java index 2157a8b6..a681ba31 100644 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDiscoveryWithDyingDependenciesTests.java +++ b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/dependency/ZookeeperDiscoveryWithDyingDependenciesTests.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.zookeeper.discovery.dependency; import java.io.Closeable; @@ -11,6 +27,7 @@ import org.apache.curator.test.TestingServer; import org.assertj.core.api.BDDAssertions; import org.junit.Ignore; import org.junit.Test; + import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.zookeeper.discovery.test.TestRibbonClient; @@ -28,33 +45,36 @@ import static com.jayway.awaitility.Awaitility.await; @Ignore public class ZookeeperDiscoveryWithDyingDependenciesTests { - private static final Log log = LogFactory.getLog(ZookeeperDiscoveryWithDyingDependenciesTests.class); + private static final Log log = LogFactory + .getLog(ZookeeperDiscoveryWithDyingDependenciesTests.class); // Issue: #45 - @Test public void should_refresh_a_dependency_in_Ribbon_when_the_dependency_has_deregistered_and_registered_in_Zookeeper() + @Test + public void should_refresh_a_dependency_in_Ribbon_when_the_dependency_has_deregistered_and_registered_in_Zookeeper() throws Exception { ConfigurableApplicationContext serverContext = null; ConfigurableApplicationContext clientContext = null; TestingServer testingServer = null; try { - //given: + // given: int zookeeperPort = SocketUtils.findAvailableTcpPort(); testingServer = new TestingServer(zookeeperPort); System.setProperty("spring.jmx.enabled", "false"); - System.setProperty("spring.cloud.zookeeper.connectString", "127.0.0.1:"+zookeeperPort); - //and: + System.setProperty("spring.cloud.zookeeper.connectString", + "127.0.0.1:" + zookeeperPort); + // and: serverContext = contextWithProfile("server"); clientContext = contextWithProfile("client"); - //and: + // and: Integer serverPortBeforeDying = callServiceAtPortEndpoint(clientContext); - //and: + // and: serverContext = restartContext(serverContext, "server"); - //expect: - await().atMost(5, TimeUnit.SECONDS).until( - applicationHasStartedOnANewPort(clientContext, serverPortBeforeDying) - ); - } finally { - //cleanup: + // expect: + await().atMost(5, TimeUnit.SECONDS).until(applicationHasStartedOnANewPort( + clientContext, serverPortBeforeDying)); + } + finally { + // cleanup: close(serverContext); close(clientContext); close(testingServer); @@ -65,10 +85,13 @@ public class ZookeeperDiscoveryWithDyingDependenciesTests { final ConfigurableApplicationContext clientContext, final Integer serverPortBeforeDying) { return new Callable() { - @Override public Boolean call() throws Exception { + @Override + public Boolean call() throws Exception { try { - BDDAssertions.then(callServiceAtPortEndpoint(clientContext)).isNotEqualTo(serverPortBeforeDying); - } catch (Exception e) { + BDDAssertions.then(callServiceAtPortEndpoint(clientContext)) + .isNotEqualTo(serverPortBeforeDying); + } + catch (Exception e) { log.error("Exception occurred while trying to call the server", e); return false; } @@ -78,26 +101,32 @@ public class ZookeeperDiscoveryWithDyingDependenciesTests { } private void close(Closeable closeable) throws IOException { - if(closeable != null) { + if (closeable != null) { closeable.close(); } } + private ConfigurableApplicationContext contextWithProfile(String profile) { return new SpringApplicationBuilder(Config.class).profiles(profile).build().run(); } - private ConfigurableApplicationContext restartContext(ConfigurableApplicationContext configurableApplicationContext, String profile) + private ConfigurableApplicationContext restartContext( + ConfigurableApplicationContext configurableApplicationContext, String profile) throws IOException { close(configurableApplicationContext); return contextWithProfile(profile); } private Integer callServiceAtPortEndpoint(ApplicationContext applicationContext) { - return applicationContext.getBean(TestRibbonClient.class).callService("testInstance", "port", Integer.class); + return applicationContext.getBean(TestRibbonClient.class) + .callService("testInstance", "port", Integer.class); } @Configuration @EnableAutoConfiguration @Import(DependencyConfig.class) - static class Config { } + static class Config { + + } + } diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/test/CommonTestConfig.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/test/CommonTestConfig.java index 7c250c94..328369ea 100644 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/test/CommonTestConfig.java +++ b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/test/CommonTestConfig.java @@ -1,6 +1,23 @@ +/* + * 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.zookeeper.discovery.test; import org.apache.curator.test.TestingServer; + import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.zookeeper.ZookeeperProperties; import org.springframework.context.annotation.Bean; @@ -8,21 +25,29 @@ import org.springframework.context.annotation.Configuration; import org.springframework.util.SocketUtils; import org.springframework.web.client.RestTemplate; +/** + * + */ @Configuration public class CommonTestConfig { @Bean - @LoadBalanced RestTemplate loadBalancedRestTemplate() { + @LoadBalanced + RestTemplate loadBalancedRestTemplate() { return new RestTemplate(); } - @Bean(destroyMethod = "close") TestingServer testingServer() throws Exception { + @Bean(destroyMethod = "close") + TestingServer testingServer() throws Exception { return new TestingServer(SocketUtils.findAvailableTcpPort()); } - @Bean ZookeeperProperties zookeeperProperties(TestingServer testingServer) throws Exception { + @Bean + ZookeeperProperties zookeeperProperties(TestingServer testingServer) + throws Exception { ZookeeperProperties zookeeperProperties = new ZookeeperProperties(); zookeeperProperties.setConnectString("localhost:" + testingServer.getPort()); return zookeeperProperties; } + } diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/test/TestRibbonClient.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/test/TestRibbonClient.java index 1fb34806..2239d824 100644 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/test/TestRibbonClient.java +++ b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/test/TestRibbonClient.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.zookeeper.discovery.test; import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties; @@ -23,12 +39,13 @@ public class TestRibbonClient extends TestServiceRestClient { } public String thisHealthCheck() { - return this.restTemplate - .getForObject("http://" + this.thisAppName + BASE_PATH + "/health", String.class); + return this.restTemplate.getForObject( + "http://" + this.thisAppName + BASE_PATH + "/health", String.class); } public Integer thisPort() { - return this.restTemplate - .getForObject("http://" + this.thisAppName + "/port", Integer.class); + return this.restTemplate.getForObject("http://" + this.thisAppName + "/port", + Integer.class); } + } diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/test/TestServiceRestClient.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/test/TestServiceRestClient.java index 6a54be31..3e3dc4f0 100644 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/test/TestServiceRestClient.java +++ b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/test/TestServiceRestClient.java @@ -1,13 +1,31 @@ +/* + * 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.zookeeper.discovery.test; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.web.client.RestTemplate; /** * @author Marcin Grzejszczak */ public class TestServiceRestClient { + private static final Log log = LogFactory.getLog(TestServiceRestClient.class); protected final RestTemplate restTemplate; @@ -17,7 +35,7 @@ public class TestServiceRestClient { } public T callService(String alias, String endpoint, Class clazz) { - String url = "http://" + alias +"/" + endpoint; + String url = "http://" + alias + "/" + endpoint; log.info("Calling [" + url + "]"); return this.restTemplate.getForObject(url, clazz); } @@ -33,4 +51,5 @@ public class TestServiceRestClient { return new RestTemplate().getForObject("http://" + url + endpoint, String.class); } + } diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/watcher/DefaultDependencyWatcherSpringTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/watcher/DefaultDependencyWatcherSpringTests.java index 726f0528..152cad6d 100644 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/watcher/DefaultDependencyWatcherSpringTests.java +++ b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/watcher/DefaultDependencyWatcherSpringTests.java @@ -1,7 +1,24 @@ +/* + * 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.zookeeper.discovery.watcher; import java.util.concurrent.Callable; +import com.jayway.awaitility.Awaitility; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; @@ -10,6 +27,7 @@ import org.apache.curator.x.discovery.ServiceCache; 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; @@ -27,8 +45,6 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.SocketUtils; import org.springframework.web.client.RestTemplate; -import com.jayway.awaitility.Awaitility; - import static org.assertj.core.api.BDDAssertions.then; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; @@ -40,26 +56,36 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen @ActiveProfiles("watcher") public class DefaultDependencyWatcherSpringTests { - @Autowired AssertableDependencyPresenceOnStartupVerifier dependencyPresenceOnStartupVerifier; - @Autowired AssertableDependencyWatcherListener dependencyWatcherListener; - @Autowired ZookeeperRegistration zookeeperRegistration; - @Autowired ZookeeperServiceRegistry registry; + @Autowired + AssertableDependencyPresenceOnStartupVerifier dependencyPresenceOnStartupVerifier; + @Autowired + AssertableDependencyWatcherListener dependencyWatcherListener; - @Test public void should_verify_that_presence_of_a_dependency_has_been_checked() { + @Autowired + ZookeeperRegistration zookeeperRegistration; + + @Autowired + ZookeeperServiceRegistry registry; + + @Test + public void should_verify_that_presence_of_a_dependency_has_been_checked() { then(this.dependencyPresenceOnStartupVerifier.startupPresenceVerified).isTrue(); } - @Ignore //FIXME 2.0.0 - @Test public void should_verify_that_dependency_watcher_listener_is_successfully_registered_and_operational() + @Ignore // FIXME 2.0.0 + @Test + public void should_verify_that_dependency_watcher_listener_is_successfully_registered_and_operational() throws Exception { - //when: + // when: this.registry.deregister(this.zookeeperRegistration); - //then: + // then: Awaitility.await().until(new Callable() { - @Override public Boolean call() throws Exception { - then(DefaultDependencyWatcherSpringTests.this.dependencyWatcherListener.dependencyState).isEqualTo(DependencyState.DISCONNECTED); + @Override + public Boolean call() throws Exception { + then(DefaultDependencyWatcherSpringTests.this.dependencyWatcherListener.dependencyState) + .isEqualTo(DependencyState.DISCONNECTED); return true; } }); @@ -71,7 +97,8 @@ public class DefaultDependencyWatcherSpringTests { static class Config { @Bean - @LoadBalanced RestTemplate loadBalancedRestTemplate() { + @LoadBalanced + RestTemplate loadBalancedRestTemplate() { return new RestTemplate(); } @@ -80,14 +107,16 @@ public class DefaultDependencyWatcherSpringTests { return new PropertySourcesPlaceholderConfigurer(); } - @Bean(destroyMethod = "close") TestingServer testingServer() throws Exception { + @Bean(destroyMethod = "close") + TestingServer testingServer() throws Exception { return new TestingServer(SocketUtils.findAvailableTcpPort()); } @Bean(initMethod = "start", destroyMethod = "close") CuratorFramework curatorFramework() throws Exception { - CuratorFramework curatorFramework = CuratorFrameworkFactory - .newClient(testingServer().getConnectString(), new ExponentialBackoffRetry(20, 20, 500)); + CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient( + testingServer().getConnectString(), + new ExponentialBackoffRetry(20, 20, 500)); return curatorFramework; } @@ -96,13 +125,15 @@ public class DefaultDependencyWatcherSpringTests { return new AssertableDependencyWatcherListener(); } - @Bean DependencyPresenceOnStartupVerifier dependencyPresenceOnStartupVerifier() { + @Bean + DependencyPresenceOnStartupVerifier dependencyPresenceOnStartupVerifier() { return new AssertableDependencyPresenceOnStartupVerifier(); } } - static class AssertableDependencyWatcherListener implements DependencyWatcherListener { + static class AssertableDependencyWatcherListener + implements DependencyWatcherListener { DependencyState dependencyState = DependencyState.CONNECTED; @@ -110,9 +141,11 @@ public class DefaultDependencyWatcherSpringTests { public void stateChanged(String dependencyName, DependencyState newState) { dependencyState = newState; } + } - static class AssertableDependencyPresenceOnStartupVerifier extends DependencyPresenceOnStartupVerifier { + static class AssertableDependencyPresenceOnStartupVerifier + extends DependencyPresenceOnStartupVerifier { boolean startupPresenceVerified = false; @@ -120,9 +153,12 @@ public class DefaultDependencyWatcherSpringTests { super(new LogMissingDependencyChecker()); } - @Override public void verifyDependencyPresence(String dependencyName, + @Override + public void verifyDependencyPresence(String dependencyName, ServiceCache serviceCache, boolean required) { startupPresenceVerified = true; } + } + } diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/DefaultDependencyPresenceOnStartupVerifierTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/DefaultDependencyPresenceOnStartupVerifierTests.java index 729c02d7..b7e2f6ed 100644 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/DefaultDependencyPresenceOnStartupVerifierTests.java +++ b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/DefaultDependencyPresenceOnStartupVerifierTests.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.zookeeper.discovery.watcher.presence; import java.util.Collections; @@ -17,18 +33,21 @@ public class DefaultDependencyPresenceOnStartupVerifierTests { private static final String SERVICE_NAME = "service01"; - @Test public void should_throw_exception_if_obligatory_dependencies_are_missing() { - //given: + @Test + public void should_throw_exception_if_obligatory_dependencies_are_missing() { + // given: DefaultDependencyPresenceOnStartupVerifier dependencyVerifier = new DefaultDependencyPresenceOnStartupVerifier(); ServiceCache serviceCache = mock(ServiceCache.class); given(serviceCache.getInstances()).willReturn(Collections.emptyList()); - //when: + // when: try { dependencyVerifier.verifyDependencyPresence(SERVICE_NAME, serviceCache, true); Assert.fail("Should throw no instances running exception"); - } catch (Exception e) { - //then: + } + catch (Exception e) { + // then: then(e).isInstanceOf(NoInstancesRunningException.class); } } + } diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/DependencyPresenceOnStartupVerifierTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/DependencyPresenceOnStartupVerifierTests.java index 88f1f611..42dfbf0d 100644 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/DependencyPresenceOnStartupVerifierTests.java +++ b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/discovery/watcher/presence/DependencyPresenceOnStartupVerifierTests.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.zookeeper.discovery.watcher.presence; import java.util.Collections; @@ -16,17 +32,20 @@ public class DependencyPresenceOnStartupVerifierTests { private static final String SERVICE_NAME = "service01"; - @Test public void should_check_optional_dependency_using_optional_dependency_checker() { - //given: + @Test + public void should_check_optional_dependency_using_optional_dependency_checker() { + // given: PresenceChecker optionalDependencyChecker = mock(PresenceChecker.class); - DependencyPresenceOnStartupVerifier dependencyVerifier = new DependencyPresenceOnStartupVerifier(optionalDependencyChecker) { + DependencyPresenceOnStartupVerifier dependencyVerifier = new DependencyPresenceOnStartupVerifier( + optionalDependencyChecker) { }; ServiceCache serviceCache = mock(ServiceCache.class); given(serviceCache.getInstances()).willReturn(Collections.emptyList()); - //when: + // when: dependencyVerifier.verifyDependencyPresence(SERVICE_NAME, serviceCache, false); - //then: - then(optionalDependencyChecker).should().checkPresence(SERVICE_NAME, serviceCache.getInstances()); + // then: + then(optionalDependencyChecker).should().checkPresence(SERVICE_NAME, + serviceCache.getInstances()); } - + } diff --git a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperAutoServiceRegistrationTests.java b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperAutoServiceRegistrationTests.java index 70018522..40c36f2e 100644 --- a/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperAutoServiceRegistrationTests.java +++ b/spring-cloud-zookeeper-discovery/src/test/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperAutoServiceRegistrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -22,6 +22,7 @@ import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.ServiceInstance; 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; @@ -39,8 +40,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Spencer Gibb */ @RunWith(SpringRunner.class) -@SpringBootTest(properties = { "spring.application.name=myTestService1-F" }, - webEnvironment = RANDOM_PORT) +@SpringBootTest(properties = { + "spring.application.name=myTestService1-F" }, webEnvironment = RANDOM_PORT) public class ZookeeperAutoServiceRegistrationTests { @Autowired @@ -54,29 +55,40 @@ public class ZookeeperAutoServiceRegistrationTests { @Test public void contextLoads() throws Exception { - Collection> instances = serviceDiscovery.queryForInstances("myTestService1-F"); + Collection> instances = serviceDiscovery + .queryForInstances("myTestService1-F"); assertThat(instances).hasSize(1); ServiceInstance instance = instances.iterator().next(); assertThat(instance).isNotNull(); assertThat(instance.getName()).isEqualTo("myTestService1-F"); - /*Response> response = consul.getAgentServices(); - Map services = response.getValue(); - Service service = services.get(registration.getServiceId()); - assertNotNull("service was null", service); - assertNotEquals("service port is 0", 0, service.getPort().intValue()); - assertFalse("service id contained invalid character: " + service.getId(), service.getId().contains(":")); - assertEquals("service id was wrong", registration.getServiceId(), service.getId()); - assertEquals("service name was wrong", "myTestService1-FF-something", service.getService()); - assertFalse("service address must not be empty", StringUtils.isEmpty(service.getAddress())); - assertEquals("service address must equals hostname from discovery properties", discoveryProperties.getHostname(), service.getAddress());*/ + /* + * Response> response = consul.getAgentServices(); + * Map services = response.getValue(); Service service = + * services.get(registration.getServiceId()); assertNotNull("service was null", + * service); assertNotEquals("service port is 0", 0, + * service.getPort().intValue()); + * assertFalse("service id contained invalid character: " + service.getId(), + * service.getId().contains(":")); assertEquals("service id was wrong", + * registration.getServiceId(), service.getId()); + * assertEquals("service name was wrong", "myTestService1-FF-something", + * service.getService()); assertFalse("service address must not be empty", + * StringUtils.isEmpty(service.getAddress())); + * assertEquals("service address must equals hostname from discovery properties", + * discoveryProperties.getHostname(), service.getAddress()); + */ } @SpringBootConfiguration @EnableAutoConfiguration - @Import({CommonTestConfig.class}) - /*@ImportAutoConfiguration({AutoServiceRegistrationAutoConfiguration.class, ZookeeperAutoServiceRegistration.class, - ZookeeperServiceRegistryAutoConfiguration.class})*/ - protected static class TestConfig { } -} + @Import({ CommonTestConfig.class }) + /* + * @ImportAutoConfiguration({AutoServiceRegistrationAutoConfiguration.class, + * ZookeeperAutoServiceRegistration.class, + * ZookeeperServiceRegistryAutoConfiguration.class}) + */ + protected static class TestConfig { + } + +} diff --git a/spring-cloud-zookeeper-sample/src/main/java/org/springframework/cloud/zookeeper/sample/SampleZookeeperApplication.java b/spring-cloud-zookeeper-sample/src/main/java/org/springframework/cloud/zookeeper/sample/SampleZookeeperApplication.java index 95c0167b..b35c8274 100644 --- a/spring-cloud-zookeeper-sample/src/main/java/org/springframework/cloud/zookeeper/sample/SampleZookeeperApplication.java +++ b/spring-cloud-zookeeper-sample/src/main/java/org/springframework/cloud/zookeeper/sample/SampleZookeeperApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -63,6 +63,9 @@ public class SampleZookeeperApplication { @Autowired(required = false) private Registration registration; + @Autowired + private RestTemplate rest; + @RequestMapping("/") public ServiceInstance lb() { return this.loadBalancer.choose(this.appName); @@ -83,27 +86,26 @@ public class SampleZookeeperApplication { return this.env.getProperty(prop, "Not Found"); } - @FeignClient("testZookeeperApp") - interface AppClient { - @RequestMapping(path = "/hi", method = RequestMethod.GET) - String hi(); - } - - @Autowired - RestTemplate rest; - public String rt() { return this.rest.getForObject("http://" + this.appName + "/hi", String.class); } - public static void main(String[] args) { - SpringApplication.run(SampleZookeeperApplication.class, args); - } - @Bean @LoadBalanced RestTemplate loadBalancedRestTemplate() { return new RestTemplate(); } + public static void main(String[] args) { + SpringApplication.run(SampleZookeeperApplication.class, args); + } + + @FeignClient("testZookeeperApp") + interface AppClient { + + @RequestMapping(path = "/hi", method = RequestMethod.GET) + String hi(); + + } + } diff --git a/spring-cloud-zookeeper-sample/src/test/java/org/springframework/cloud/zookeeper/sample/SampleApplicationTests.java b/spring-cloud-zookeeper-sample/src/test/java/org/springframework/cloud/zookeeper/sample/SampleApplicationTests.java index 5357a01f..f1b33a30 100644 --- a/spring-cloud-zookeeper-sample/src/test/java/org/springframework/cloud/zookeeper/sample/SampleApplicationTests.java +++ b/spring-cloud-zookeeper-sample/src/test/java/org/springframework/cloud/zookeeper/sample/SampleApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-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. @@ -18,6 +18,7 @@ package org.springframework.cloud.zookeeper.sample; import org.apache.curator.test.TestingServer; import org.junit.Test; + import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.context.ConfigurableApplicationContext; @@ -29,21 +30,24 @@ import static org.assertj.core.api.Assertions.assertThat; public class SampleApplicationTests { - @Test public void contextLoads() throws Exception { + @Test + public void contextLoads() throws Exception { int zkPort = SocketUtils.findAvailableTcpPort(); TestingServer server = new TestingServer(zkPort); - int port = SocketUtils.findAvailableTcpPort(zkPort+1); + int port = SocketUtils.findAvailableTcpPort(zkPort + 1); - ConfigurableApplicationContext context = new SpringApplicationBuilder(SampleZookeeperApplication.class).run( - "--server.port="+port, - "--management.endpoints.web.exposure.include=*", - "--spring.cloud.zookeeper.connect-string=localhost:" + zkPort); + ConfigurableApplicationContext context = new SpringApplicationBuilder( + SampleZookeeperApplication.class).run("--server.port=" + port, + "--management.endpoints.web.exposure.include=*", + "--spring.cloud.zookeeper.connect-string=localhost:" + zkPort); - ResponseEntity response = new TestRestTemplate().getForEntity("http://localhost:"+port+"/hi", String.class); + ResponseEntity response = new TestRestTemplate() + .getForEntity("http://localhost:" + port + "/hi", String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); context.close(); server.close(); } + } diff --git a/spring-cloud-zookeeper-sample/src/test/java/org/springframework/cloud/zookeeper/sample/ZookeeperDisabledTests.java b/spring-cloud-zookeeper-sample/src/test/java/org/springframework/cloud/zookeeper/sample/ZookeeperDisabledTests.java index a81c80c3..3cc22f7e 100644 --- a/spring-cloud-zookeeper-sample/src/test/java/org/springframework/cloud/zookeeper/sample/ZookeeperDisabledTests.java +++ b/spring-cloud-zookeeper-sample/src/test/java/org/springframework/cloud/zookeeper/sample/ZookeeperDisabledTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 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. @@ -18,6 +18,7 @@ package org.springframework.cloud.zookeeper.sample; 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.zookeeper.ZookeeperAutoConfiguration; @@ -78,21 +79,35 @@ public class ZookeeperDisabledTests { @Autowired(required = false) private CuratorServiceDiscoveryAutoConfiguration curatorServiceDiscoveryAutoConfiguration; - @Test public void allPartsOfZookeeperDisabled() throws Exception { - assertThat(this.zookeeperAutoConfiguration).as("ZookeeperAutoConfiguration was not disabled").isNull(); - assertThat(this.zookeeperConfigAutoConfiguration).as("ZookeeperConfigAutoConfiguration was not disabled").isNull(); - assertThat(this.ribbonZookeeperAutoConfiguration).as("RibbonZookeeperAutoConfiguration was not disabled").isNull(); - assertThat(this.zookeeperDiscoveryAutoConfiguration).as("ZookeeperDiscoveryAutoConfiguration was not disabled").isNull(); - assertThat(this.dependencyFeignClientAutoConfiguration).as("DependencyFeignClientAutoConfiguration was not disabled").isNull(); - assertThat(this.dependencyRibbonAutoConfiguration).as("DependencyRibbonAutoConfiguration was not disabled").isNull(); - assertThat(this.dependencyRestTemplateAutoConfiguration).as("DependencyRestTemplateAutoConfiguration was not disabled").isNull(); - assertThat(this.zookeeperDependenciesAutoConfiguration).as("ZookeeperDependenciesAutoConfiguration was not disabled").isNull(); - assertThat(this.dependencyWatcherAutoConfiguration).as("DependencyWatcherAutoConfiguration was not disabled").isNull(); - assertThat(this.zookeeperAutoServiceRegistrationAutoConfiguration).as("ZookeeperAutoServiceRegistrationAutoConfiguration was not disabled").isNull(); - assertThat(this.zookeeperServiceRegistryAutoConfiguration).as("ZookeeperServiceRegistryAutoConfiguration was not disabled").isNull(); - assertThat(this.curatorServiceDiscoveryAutoConfiguration).as("CuratorServiceDiscoveryAutoConfiguration was not disabled").isNull(); + assertThat(this.zookeeperAutoConfiguration) + .as("ZookeeperAutoConfiguration was not disabled").isNull(); + assertThat(this.zookeeperConfigAutoConfiguration) + .as("ZookeeperConfigAutoConfiguration was not disabled").isNull(); + assertThat(this.ribbonZookeeperAutoConfiguration) + .as("RibbonZookeeperAutoConfiguration was not disabled").isNull(); + assertThat(this.zookeeperDiscoveryAutoConfiguration) + .as("ZookeeperDiscoveryAutoConfiguration was not disabled").isNull(); + assertThat(this.dependencyFeignClientAutoConfiguration) + .as("DependencyFeignClientAutoConfiguration was not disabled").isNull(); + assertThat(this.dependencyRibbonAutoConfiguration) + .as("DependencyRibbonAutoConfiguration was not disabled").isNull(); + assertThat(this.dependencyRestTemplateAutoConfiguration) + .as("DependencyRestTemplateAutoConfiguration was not disabled").isNull(); + assertThat(this.zookeeperDependenciesAutoConfiguration) + .as("ZookeeperDependenciesAutoConfiguration was not disabled").isNull(); + assertThat(this.dependencyWatcherAutoConfiguration) + .as("DependencyWatcherAutoConfiguration was not disabled").isNull(); + assertThat(this.zookeeperAutoServiceRegistrationAutoConfiguration) + .as("ZookeeperAutoServiceRegistrationAutoConfiguration was not disabled") + .isNull(); + assertThat(this.zookeeperServiceRegistryAutoConfiguration) + .as("ZookeeperServiceRegistryAutoConfiguration was not disabled") + .isNull(); + assertThat(this.curatorServiceDiscoveryAutoConfiguration) + .as("CuratorServiceDiscoveryAutoConfiguration was not disabled").isNull(); } + }