diff --git a/src/asciidoc/introduction/new-features.adoc b/src/asciidoc/introduction/new-features.adoc index a7c097e1..81bfd0a8 100644 --- a/src/asciidoc/introduction/new-features.adoc +++ b/src/asciidoc/introduction/new-features.adoc @@ -107,7 +107,7 @@ as required by GemFire. * Spring JavaConfig support added to `SpringContextBootstrappingInitializer`. * Support for custom `ClassLoaders` in `SpringContextBootstrappingInitializer` to load Spring-defined bean classes. * Support for `LazyWiringDeclarableSupport` re-initialization and complete replacement for `WiringDeclarableSupport`. -* Adds `locators` and `servers` attributes to the `` element allowing variable Locator/Server +* Adds `locators` and `servers` attributes to the `` element allowing variable Locator/Server endpoint lists configured with Spring's property placeholders. * Enables the use of `` element with non-Spring configured GemFire Servers. * Multi-Index definition and creation support. diff --git a/src/main/java/org/springframework/data/gemfire/client/PoolFactoryBean.java b/src/main/java/org/springframework/data/gemfire/client/PoolFactoryBean.java index 2d3db542..0871c9e0 100644 --- a/src/main/java/org/springframework/data/gemfire/client/PoolFactoryBean.java +++ b/src/main/java/org/springframework/data/gemfire/client/PoolFactoryBean.java @@ -28,7 +28,9 @@ import org.springframework.beans.factory.BeanNameAware; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; -import org.springframework.data.gemfire.util.CollectionUtils; +import org.springframework.data.gemfire.support.ConnectionEndpoint; +import org.springframework.data.gemfire.support.ConnectionEndpointList; +import org.springframework.data.gemfire.util.DistributedSystemUtils; import org.springframework.util.Assert; import org.springframework.util.StringUtils; @@ -36,7 +38,6 @@ import com.gemstone.gemfire.cache.client.Pool; import com.gemstone.gemfire.cache.client.PoolFactory; import com.gemstone.gemfire.cache.client.PoolManager; import com.gemstone.gemfire.distributed.DistributedSystem; -import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem; /** * FactoryBean for easy declaration and configuration of a GemFire Pool. If a new Pool is created, @@ -47,13 +48,26 @@ import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem; * * @author Costin Leau * @author John Blum + * @see java.net.InetSocketAddress + * @see org.springframework.beans.factory.BeanFactory + * @see org.springframework.beans.factory.BeanFactoryAware + * @see org.springframework.beans.factory.BeanNameAware + * @see org.springframework.beans.factory.DisposableBean + * @see org.springframework.beans.factory.FactoryBean + * @see org.springframework.beans.factory.InitializingBean + * @see org.springframework.data.gemfire.support.ConnectionEndpoint + * @see org.springframework.data.gemfire.support.ConnectionEndpointList * @see com.gemstone.gemfire.cache.client.Pool * @see com.gemstone.gemfire.cache.client.PoolFactory * @see com.gemstone.gemfire.cache.client.PoolManager + * @see com.gemstone.gemfire.distributed.DistributedSystem */ @SuppressWarnings("unused") -public class PoolFactoryBean implements FactoryBean, InitializingBean, DisposableBean, BeanNameAware, - BeanFactoryAware { +public class PoolFactoryBean implements FactoryBean, InitializingBean, DisposableBean, + BeanNameAware, BeanFactoryAware { + + protected static final int DEFAULT_LOCATOR_PORT = DistributedSystemUtils.DEFAULT_LOCATOR_PORT; + protected static final int DEFAULT_SERVER_PORT = DistributedSystemUtils.DEFAULT_CACHE_SERVER_PORT; private static final Log log = LogFactory.getLog(PoolFactoryBean.class); @@ -62,8 +76,8 @@ public class PoolFactoryBean implements FactoryBean, InitializingBean, Dis private BeanFactory beanFactory; - private Collection locators; - private Collection servers; + private ConnectionEndpointList locators = new ConnectionEndpointList(); + private ConnectionEndpointList servers = new ConnectionEndpointList(); private Pool pool; @@ -128,7 +142,7 @@ public class PoolFactoryBean implements FactoryBean, InitializingBean, Dis log.debug(String.format("No Pool with name '%1$s' was found. Creating a new Pool...", name)); } - if (CollectionUtils.isEmpty(locators) && CollectionUtils.isEmpty(servers)) { + if (locators.isEmpty() && servers.isEmpty()) { throw new IllegalArgumentException("at least one GemFire Locator or Server is required"); } @@ -155,12 +169,12 @@ public class PoolFactoryBean implements FactoryBean, InitializingBean, Dis poolFactory.setSubscriptionRedundancy(subscriptionRedundancy); poolFactory.setThreadLocalConnections(threadLocalConnections); - for (InetSocketAddress connection : CollectionUtils.nullSafeCollection(locators)) { - poolFactory.addLocator(connection.getHostName(), connection.getPort()); + for (ConnectionEndpoint locator : locators) { + poolFactory.addLocator(locator.getHost(), locator.getPort()); } - for (InetSocketAddress connection : CollectionUtils.nullSafeCollection(servers)) { - poolFactory.addServer(connection.getHostName(), connection.getPort()); + for (ConnectionEndpoint server : servers) { + poolFactory.addServer(server.getHost(), server.getPort()); } // eagerly initialize the GemFire DistributedSystem (if needed) @@ -177,7 +191,7 @@ public class PoolFactoryBean implements FactoryBean, InitializingBean, Dis /* (non-Javadoc) */ void resolveDistributedSystem() { - if (InternalDistributedSystem.getAnyInstance() == null) { + if (DistributedSystemUtils.getDistributedSystem() == null) { doDistributedSystemConnect(resolveGemfireProperties()); } } @@ -257,8 +271,17 @@ public class PoolFactoryBean implements FactoryBean, InitializingBean, Dis this.keepAlive = keepAlive; } - public void setLocators(Collection locators) { - this.locators = locators; + @Deprecated + public void setLocators(Iterable locators) { + setLocatorEndpoints(ConnectionEndpointList.from(locators)); + } + + public void setLocatorEndpoints(Iterable endpoints) { + this.locators.add(endpoints); + } + + public void setLocatorEndpointList(ConnectionEndpointList endpointList) { + setLocatorEndpoints(endpointList); } public void setLoadConditioningInterval(int loadConditioningInterval) { @@ -297,8 +320,17 @@ public class PoolFactoryBean implements FactoryBean, InitializingBean, Dis this.serverGroup = serverGroup; } + @Deprecated public void setServers(Collection servers) { - this.servers = servers; + setServerEndpoints(ConnectionEndpointList.from(servers)); + } + + public void setServerEndpoints(Iterable endpoints) { + this.servers.add(endpoints); + } + + public void setServerEndpointList(ConnectionEndpointList endpointList) { + setServerEndpoints(endpointList); } public void setSocketBufferSize(int socketBufferSize) { diff --git a/src/main/java/org/springframework/data/gemfire/config/PoolParser.java b/src/main/java/org/springframework/data/gemfire/config/PoolParser.java index 90acd783..26b3d5c1 100644 --- a/src/main/java/org/springframework/data/gemfire/config/PoolParser.java +++ b/src/main/java/org/springframework/data/gemfire/config/PoolParser.java @@ -16,24 +16,26 @@ package org.springframework.data.gemfire.config; -import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.Collections; import java.util.List; +import java.util.regex.Pattern; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.ManagedList; -import org.springframework.beans.factory.xml.AbstractSimpleBeanDefinitionParser; +import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.data.gemfire.client.PoolFactoryBean; +import org.springframework.data.gemfire.support.ConnectionEndpoint; +import org.springframework.data.gemfire.support.ConnectionEndpointList; +import org.springframework.data.gemfire.util.DistributedSystemUtils; import org.springframework.util.StringUtils; import org.springframework.util.xml.DomUtils; import org.w3c.dom.Element; -import com.gemstone.gemfire.cache.server.CacheServer; -import com.gemstone.gemfire.internal.DistributionLocator; - /** * Parser for GFE <pool;gt; bean definitions. * @@ -41,10 +43,12 @@ import com.gemstone.gemfire.internal.DistributionLocator; * @author David Turanski * @author John Blum */ -class PoolParser extends AbstractSimpleBeanDefinitionParser { +class PoolParser extends AbstractSingleBeanDefinitionParser { - protected static final int DEFAULT_LOCATOR_PORT = DistributionLocator.DEFAULT_LOCATOR_PORT; - protected static final int DEFAULT_SERVER_PORT = CacheServer.DEFAULT_PORT; + protected static final int DEFAULT_LOCATOR_PORT = DistributedSystemUtils.DEFAULT_LOCATOR_PORT; + protected static final int DEFAULT_SERVER_PORT = DistributedSystemUtils.DEFAULT_CACHE_SERVER_PORT; + + protected static final Pattern PROPERTY_PLACEHOLDER_PATTERN = Pattern.compile("\\$\\{.+\\}"); protected static final String DEFAULT_HOST = "localhost"; protected static final String HOST_ATTRIBUTE_NAME = "host"; @@ -58,53 +62,95 @@ class PoolParser extends AbstractSimpleBeanDefinitionParser { protected Class getBeanClass(Element element) { return PoolFactoryBean.class; } - + @Override - protected void postProcess(BeanDefinitionBuilder builder, Element element) { - List subElements = DomUtils.getChildElements(element); + protected void doParse(Element element, BeanDefinitionBuilder builder) { + ParsingUtils.setPropertyValue(element, builder, "free-connection-timeout"); + ParsingUtils.setPropertyValue(element, builder, "idle-timeout"); + ParsingUtils.setPropertyValue(element, builder, "load-conditioning-interval"); + ParsingUtils.setPropertyValue(element, builder, "keep-alive"); + ParsingUtils.setPropertyValue(element, builder, "max-connections"); + ParsingUtils.setPropertyValue(element, builder, "min-connections"); + ParsingUtils.setPropertyValue(element, builder, "multi-user-authentication"); + ParsingUtils.setPropertyValue(element, builder, "ping-interval"); + ParsingUtils.setPropertyValue(element, builder, "pr-single-hop-enabled"); + ParsingUtils.setPropertyValue(element, builder, "read-timeout"); + ParsingUtils.setPropertyValue(element, builder, "retry-attempts"); + ParsingUtils.setPropertyValue(element, builder, "server-group"); + ParsingUtils.setPropertyValue(element, builder, "socket-buffer-size"); + ParsingUtils.setPropertyValue(element, builder, "statistic-interval"); + ParsingUtils.setPropertyValue(element, builder, "subscription-ack-interval"); + ParsingUtils.setPropertyValue(element, builder, "subscription-enabled"); + ParsingUtils.setPropertyValue(element, builder, "subscription-message-tracking-timeout"); + ParsingUtils.setPropertyValue(element, builder, "subscription-redundancy"); + ParsingUtils.setPropertyValue(element, builder, "thread-local-connections"); - ManagedList locators = new ManagedList(subElements.size()); - ManagedList servers = new ManagedList(subElements.size()); + List childElements = DomUtils.getChildElements(element); - // parse nested locator/server elements - for (Element subElement : subElements) { - String name = subElement.getLocalName(); + ManagedList locators = new ManagedList(childElements.size()); + ManagedList servers = new ManagedList(childElements.size()); - if (LOCATOR_ELEMENT_NAME.equals(name)) { - locators.add(parseLocator(subElement)); + for (Element childElement : childElements) { + String childElementName = childElement.getLocalName(); + + if (LOCATOR_ELEMENT_NAME.equals(childElementName)) { + locators.add(parseLocator(childElement)); } - if (SERVER_ELEMENT_NAME.equals(name)) { - servers.add(parseServer(subElement)); + + if (SERVER_ELEMENT_NAME.equals(childElementName)) { + servers.add(parseServer(childElement)); } } - locators.addAll(parseLocators(element)); - servers.addAll(parseServers(element)); + locators.addAll(parseLocators(element, builder)); + servers.addAll(parseServers(element, builder)); - // NOTE if neither Locators or Servers were specified, then setup a default connection to a Locator - // running on localhost listening on the default Locator port (10334) for convenience - if (locators.isEmpty() && servers.isEmpty()) { + // NOTE if neither Locators nor Servers were specified, then setup a default connection to a Locator + // listening on the default Locator port (10334), running on localhost + if (childElements.isEmpty() && !hasAttributes(element, LOCATORS_ATTRIBUTE_NAME, SERVERS_ATTRIBUTE_NAME)) { locators.add(buildConnection(DEFAULT_HOST, String.valueOf(DEFAULT_LOCATOR_PORT), false)); } if (!locators.isEmpty()) { - builder.addPropertyValue("locators", locators); + builder.addPropertyValue("locatorEndpoints", locators); } if (!servers.isEmpty()) { - builder.addPropertyValue("servers", servers); + builder.addPropertyValue("serverEndpoints", servers); } } + /* (non-Javadoc) */ + boolean hasAttributes(Element element, String... attributeNames) { + for (String attributeName : attributeNames) { + if (element.hasAttribute(attributeName)) { + return true; + } + } + + return false; + } + + BeanDefinition buildConnections(String propertyPlaceholder, boolean server) { + BeanDefinitionBuilder connectionEndpointListBuilder = BeanDefinitionBuilder.genericBeanDefinition( + ConnectionEndpointList.class); + + connectionEndpointListBuilder.setFactoryMethod("parse"); + connectionEndpointListBuilder.addConstructorArgValue(defaultPort(null, server)); + connectionEndpointListBuilder.addConstructorArgValue(propertyPlaceholder); + + return connectionEndpointListBuilder.getBeanDefinition(); + } + /* (non-Javadoc) */ BeanDefinition buildConnection(String host, String port, boolean server) { - BeanDefinitionBuilder inetSocketAddressBuilder = BeanDefinitionBuilder.genericBeanDefinition( - InetSocketAddress.class); + BeanDefinitionBuilder connectionEndpointBuilder = BeanDefinitionBuilder.genericBeanDefinition( + ConnectionEndpoint.class); - inetSocketAddressBuilder.addConstructorArgValue(defaultHost(host)); - inetSocketAddressBuilder.addConstructorArgValue(defaultPort(port, server)); + connectionEndpointBuilder.addConstructorArgValue(defaultHost(host)); + connectionEndpointBuilder.addConstructorArgValue(defaultPort(port, server)); - return inetSocketAddressBuilder.getBeanDefinition(); + return connectionEndpointBuilder.getBeanDefinition(); } /* (non-Javadoc) */ @@ -119,13 +165,15 @@ class PoolParser extends AbstractSimpleBeanDefinitionParser { } /* (non-Javadoc) */ - ManagedList parseConnections(String hostPortCommaDelimitedList, boolean server) { - ManagedList connections = new ManagedList(); + List parseConnections(String hostPortCommaDelimitedList, boolean server) { + List connections = Collections.emptyList(); if (StringUtils.hasText(hostPortCommaDelimitedList)) { - String[] hostPorts = hostPortCommaDelimitedList.split(","); + String[] hostsPorts = hostPortCommaDelimitedList.split(","); - for (String hostPort : hostPorts) { + connections = new ArrayList(hostsPorts.length); + + for (String hostPort : hostsPorts) { connections.add(parseConnection(hostPort, server)); } } @@ -135,17 +183,14 @@ class PoolParser extends AbstractSimpleBeanDefinitionParser { /* (non-Javadoc) */ BeanDefinition parseConnection(String hostPort, boolean server) { + String host = hostPort.trim(); String port = defaultPort(null, server); - String host; - int portIndex = hostPort.indexOf('['); + int portIndex = host.indexOf('['); if (portIndex > -1) { - host = hostPort.substring(0, portIndex).trim(); - port = parseDigits(hostPort.substring(portIndex)).trim(); - } - else { - host = hostPort.trim(); + port = parseDigits(host.substring(portIndex)).trim(); + host = host.substring(0, portIndex).trim(); } return buildConnection(host, port, server); @@ -155,9 +200,9 @@ class PoolParser extends AbstractSimpleBeanDefinitionParser { String parseDigits(String value) { StringBuilder digits = new StringBuilder(); - for (char chr : value.toCharArray()) { - if (Character.isDigit(chr)) { - digits.append(chr); + for (char character : value.toCharArray()) { + if (Character.isDigit(character)) { + digits.append(character); } } @@ -165,21 +210,52 @@ class PoolParser extends AbstractSimpleBeanDefinitionParser { } /* (non-Javadoc) */ - BeanDefinition parseLocator(Element element) { - return buildConnection(element.getAttribute(HOST_ATTRIBUTE_NAME), element.getAttribute(PORT_ATTRIBUTE_NAME), false); + boolean isPropertyPlaceholder(String value) { + return PROPERTY_PLACEHOLDER_PATTERN.matcher(value).matches(); } - ManagedList parseLocators(Element element) { - return parseConnections(element.getAttribute(LOCATORS_ATTRIBUTE_NAME), false); + /* (non-Javadoc) */ + BeanDefinition parseLocator(Element element) { + return buildConnection(element.getAttribute(HOST_ATTRIBUTE_NAME), + element.getAttribute(PORT_ATTRIBUTE_NAME), false); + } + + /* (non-Javadoc) */ + List parseLocators(Element element, BeanDefinitionBuilder builder) { + List beanDefinitions = Collections.emptyList(); + + String locatorsAttributeValue = element.getAttribute(LOCATORS_ATTRIBUTE_NAME); + + if (isPropertyPlaceholder(locatorsAttributeValue)) { + builder.addPropertyValue("locatorEndpointList", buildConnections(locatorsAttributeValue, false)); + } + else { + beanDefinitions = parseConnections(locatorsAttributeValue, false); + } + + return beanDefinitions; } /* (non-Javadoc) */ BeanDefinition parseServer(Element element) { - return buildConnection(element.getAttribute(HOST_ATTRIBUTE_NAME), element.getAttribute(PORT_ATTRIBUTE_NAME), false); + return buildConnection(element.getAttribute(HOST_ATTRIBUTE_NAME), + element.getAttribute(PORT_ATTRIBUTE_NAME), true); } - ManagedList parseServers(Element element) { - return parseConnections(element.getAttribute(SERVERS_ATTRIBUTE_NAME), true); + /* (non-Javadoc) */ + List parseServers(Element element, BeanDefinitionBuilder builder) { + List beanDefinitions = Collections.emptyList(); + + String serversAttributeValue = element.getAttribute(SERVERS_ATTRIBUTE_NAME); + + if (isPropertyPlaceholder(serversAttributeValue)) { + builder.addPropertyValue("serverEndpointList", buildConnections(serversAttributeValue, true)); + } + else { + beanDefinitions = parseConnections(serversAttributeValue, true); + } + + return beanDefinitions; } /* (non-Javadoc) */ diff --git a/src/main/java/org/springframework/data/gemfire/support/ConnectionEndpoint.java b/src/main/java/org/springframework/data/gemfire/support/ConnectionEndpoint.java new file mode 100644 index 00000000..9ea9a8a5 --- /dev/null +++ b/src/main/java/org/springframework/data/gemfire/support/ConnectionEndpoint.java @@ -0,0 +1,200 @@ +/* + * Copyright 2010-2013 the original author 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.data.gemfire.support; + +import java.net.InetSocketAddress; + +import org.springframework.util.Assert; +import org.springframework.util.ObjectUtils; +import org.springframework.util.StringUtils; + +/** + * The ConnectionEndpoint class models a GemFire connection endpoint in the format of hostname[portnumber], + * where hostname is the network name or IP address of the host. + * + * @author John Blum + * @see java.lang.Cloneable + * @see java.lang.Comparable + * @since 1.6.3 + */ +@SuppressWarnings("unused") +public class ConnectionEndpoint implements Cloneable, Comparable { + + protected static final int DEFAULT_PORT = 0; // ephemeral port + + protected static final String DEFAULT_HOST = "localhost"; + + private final int port; + private final String host; + + /** + * Converts the InetSocketAddress into a ConnectionEndpoint. + * + * @param socketAddress the InetSocketAddress used to construct and initialize the ConnectionEndpoint. + * @return a ConnectionEndpoint representing the InetSocketAddress. + * @see java.net.InetSocketAddress + */ + public static ConnectionEndpoint from(InetSocketAddress socketAddress) { + return new ConnectionEndpoint(socketAddress.getHostString(), socketAddress.getPort()); + } + + /** + * Parses the host and port String value into a valid ConnectionEndpoint. + * + * @param hostPort a String value containing the host and port formatted as 'host[port]'. + * @return a valid ConnectionEndpoint initialized with the host and port, or with DEFAULT_PORT + * if port was unspecified. + * @see #parse(String, int) + * @see #DEFAULT_PORT + */ + public static ConnectionEndpoint parse(String hostPort) { + return parse(hostPort, DEFAULT_PORT); + } + + /** + * Parses the host and port value into a valid ConnectionEndpoint. + * + * @param hostPort a String value containing the host and port formatted as 'host[port]'. + * @param defaultPort an Integer value indicating the default port to use if the port is unspecified + * in the host and port String value. + * @return a valid ConnectionEndpoint initialized with the host and port, or with the default port + * if port was unspecified. + * @see #ConnectionEndpoint(String, int) + */ + public static ConnectionEndpoint parse(String hostPort, int defaultPort) { + Assert.hasText(hostPort, "'hostPort' must be specified"); + + String host = StringUtils.trimAllWhitespace(hostPort); + + int port = defaultPort; + int portIndex = hostPort.indexOf("["); + + if (portIndex > -1) { + port = parsePort(parseDigits(host.substring(portIndex)), defaultPort); + host = host.substring(0, portIndex).trim(); + } + + return new ConnectionEndpoint(host, port); + } + + /* (non-Javadoc) */ + static String parseDigits(String value) { + StringBuilder digits = new StringBuilder(); + + if (StringUtils.hasText(value)) { + for (char character : value.toCharArray()) { + if (Character.isDigit(character)) { + digits.append(character); + } + } + } + + return digits.toString(); + } + + /* (non-Javadoc) */ + static int parsePort(String port, int defaultPort) { + try { + return Integer.parseInt(port); + } + catch (NumberFormatException ignore) { + return defaultPort; + } + } + + /** + * Constructs a ConnectionEndpoint initialized with the specific host and port. + * + * @param host the hostname or IP address of the ConnectionEndpoint. If the host is unspecified, + * then ConnectionEndpoint.DEFAULT_HOST will be used. + * @param port the (service) port number in this ConnectionEndpoint. + * @throws IllegalArgumentException if the port number is less than 0. + * @see ConnectionEndpoint#DEFAULT_HOST + */ + public ConnectionEndpoint(String host, int port) { + Assert.isTrue(port >= 0 && port <= 65535, String.format("port number (%1$d) must be between 0 and 65535", port)); + + this.host = (StringUtils.hasText(host) ? host : DEFAULT_HOST); + this.port = port; + } + + /** + * Gets the host in this ConnectionEndpoint. + * + * @return a String value indicating the hostname or IP address in this ConnectionEndpoint. + */ + public String getHost() { + return host; + } + + /** + * Gets the port number in this ConnectionEndpoint. + * + * @return an Integer value indicating the (service) port number in this ConnectionEndpoint. + */ + public int getPort() { + return port; + } + + /* (non-Javadoc) */ + @Override + @SuppressWarnings("all") + protected Object clone() throws CloneNotSupportedException { + return new ConnectionEndpoint(this.getHost(), this.getPort()); + } + + /* (non-Javadoc) */ + @Override + @SuppressWarnings("all") + public int compareTo(ConnectionEndpoint connectionEndpoint) { + int compareValue = getHost().compareTo(connectionEndpoint.getHost()); + return (compareValue != 0 ? compareValue : getPort() - connectionEndpoint.getPort()); + } + + /* (non-Javadoc) */ + @Override + public boolean equals(final Object obj) { + if (obj == this) { + return true; + } + + if (!(obj instanceof ConnectionEndpoint)) { + return false; + } + + ConnectionEndpoint that = (ConnectionEndpoint) obj; + + return ObjectUtils.nullSafeEquals(this.getHost(), that.getHost()) + && ObjectUtils.nullSafeEquals(this.getPort(), that.getPort()); + } + + /* (non-Javadoc) */ + @Override + public int hashCode() { + int hashValue = 17; + hashValue = 37 * hashValue + ObjectUtils.nullSafeHashCode(getHost()); + hashValue = 37 * hashValue + ObjectUtils.nullSafeHashCode(getPort()); + return hashValue; + } + + /* (non-Javadoc) */ + @Override + public String toString() { + return String.format("%1$s[%2$d]", getHost(), getPort()); + } + +} diff --git a/src/main/java/org/springframework/data/gemfire/support/ConnectionEndpointList.java b/src/main/java/org/springframework/data/gemfire/support/ConnectionEndpointList.java new file mode 100644 index 00000000..9c8f036a --- /dev/null +++ b/src/main/java/org/springframework/data/gemfire/support/ConnectionEndpointList.java @@ -0,0 +1,219 @@ +/* + * Copyright 2010-2013 the original author 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.data.gemfire.support; + +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + +import org.springframework.data.gemfire.util.ArrayUtils; +import org.springframework.data.gemfire.util.CollectionUtils; + +/** + * The ConnectionEndpointList class is an Iterable collection of ConnectionEndpoint objects. + * + * @author John Blum + * @see java.lang.Iterable + * @see java.net.InetSocketAddress + * @see org.springframework.data.gemfire.support.ConnectionEndpoint + * @since 1.6.3 + */ +@SuppressWarnings("unused") +public class ConnectionEndpointList implements Iterable { + + private final List connectionEndpoints; + + /** + * Converts the array of InetSocketAddresses into an instance of ConnectionEndpointList. + * + * @param socketAddresses the array of InetSocketAddresses used to initialize an instance of ConnectionEndpointList. + * @return a ConnectionEndpointList representing the array of InetSocketAddresses. + * @see java.net.InetSocketAddress + * @see #from(Iterable) + */ + public static ConnectionEndpointList from(InetSocketAddress... socketAddresses) { + return from(Arrays.asList(socketAddresses)); + } + + /** + * Converts the Iterable collection of InetSocketAddresses into an instance of ConnectionEndpointList. + * + * @param socketAddresses in Iterable collection of InetSocketAddresses used to initialize an instance + * of ConnectionEndpointList. + * @return a ConnectionEndpointList representing the array of InetSocketAddresses. + * @see java.net.InetSocketAddress + */ + public static ConnectionEndpointList from(Iterable socketAddresses) { + List connectionEndpoints = new ArrayList(); + + for (InetSocketAddress socketAddress : CollectionUtils.nullSafeIterable(socketAddresses)) { + connectionEndpoints.add(ConnectionEndpoint.from(socketAddress)); + } + + return new ConnectionEndpointList(connectionEndpoints); + } + + /** + * Parses the array of hosts and ports in the format 'host[port]' to convert into an instance + * of ConnectionEndpointList. + * + * @param defaultPort the default port number to use if port is not specified in a host and port value. + * @param hostsPorts the array of hosts and ports to parse. + * @return a ConnectionEndpointList representing the hosts and ports in the array. + * @see org.springframework.data.gemfire.support.ConnectionEndpoint#parse(String, int) + */ + public static ConnectionEndpointList parse(int defaultPort, String... hostsPorts) { + List connectionEndpoints = new ArrayList(hostsPorts.length); + + for (String hostPort : ArrayUtils.nullSafeArray(hostsPorts)) { + connectionEndpoints.add(ConnectionEndpoint.parse(hostPort, defaultPort)); + } + + return new ConnectionEndpointList(connectionEndpoints); + } + + /** + * Constructs an empty, uninitialized instance of the ConnectionEndpointList collection. + */ + public ConnectionEndpointList() { + this(Collections.emptyList()); + } + + /** + * Constructs an instance of ConnectionEndpointList initialized with the the array of ConnectionEndpoints. + * + * @param connectionEndpoints is an array containing ConnectionEndpoints to add to this collection. + * @see org.springframework.data.gemfire.support.ConnectionEndpoint + * @see #ConnectionEndpointList(Iterable) + */ + public ConnectionEndpointList(ConnectionEndpoint... connectionEndpoints) { + this(Arrays.asList(connectionEndpoints)); + } + + /** + * Constructs an instance of ConnectionEndpointList initialized with the Iterable collection of ConnectionEndpoints. + * + * @param connectionEndpoints the Iterable object containing ConnectionEndpoints to add to this collection. + * @see org.springframework.data.gemfire.support.ConnectionEndpoint + * @see java.lang.Iterable + */ + public ConnectionEndpointList(Iterable connectionEndpoints) { + this.connectionEndpoints = new ArrayList(); + add(connectionEndpoints); + } + + /** + * Adds the array of ConnectionEndpoints to this list. + * + * @param connectionEndpoints the array of ConnectionEndpoints to add to this list. + * @return this ConnectionEndpointList to support the Builder pattern style of chaining. + * @see org.springframework.data.gemfire.support.ConnectionEndpoint + * @see #add(Iterable) + */ + public final ConnectionEndpointList add(ConnectionEndpoint... connectionEndpoints) { + Collections.addAll(this.connectionEndpoints, connectionEndpoints); + return this; + } + + /** + * Adds the Iterable collection of ConnectionEndpoints to this list. + * + * @param connectionEndpoints the Iterable collection of ConnectionEndpoints to add to this list. + * @return this ConnectionEndpointList to support the Builder pattern style of chaining. + * @see org.springframework.data.gemfire.support.ConnectionEndpoint + * @see #add(ConnectionEndpoint...) + */ + public final ConnectionEndpointList add(Iterable connectionEndpoints) { + for (ConnectionEndpoint connectionEndpoint : CollectionUtils.nullSafeIterable(connectionEndpoints)) { + this.connectionEndpoints.add(connectionEndpoint); + } + + return this; + } + + /** + * Finds all ConnectionEndpoints in this list with the specified hostname. + * + * @param host a String indicating the hostname to use in the match. + * @return a ConnectionEndpointList (sub-List) containing all the ConnectionEndpoints matching the given hostname. + * @see #findBy(int) + */ + public ConnectionEndpointList findBy(String host) { + List connectionEndpoints = new ArrayList(size()); + + for (ConnectionEndpoint connectionEndpoint : this) { + if (connectionEndpoint.getHost().equals(host)) { + connectionEndpoints.add(connectionEndpoint); + } + } + + return new ConnectionEndpointList(connectionEndpoints); + } + + /** + * Finds all ConnectionEndpoints in this list with the specified port number. + * + * @param port an Integer value indicating the port number to use in the match. + * @return a ConnectionEndpointList (sub-List) containing all the ConnectionEndpoints matching the given port number. + * @see #findBy(String) + */ + public ConnectionEndpointList findBy(int port) { + List connectionEndpoints = new ArrayList(size()); + + for (ConnectionEndpoint connectionEndpoint : this) { + if (connectionEndpoint.getPort() == port) { + connectionEndpoints.add(connectionEndpoint); + } + } + + return new ConnectionEndpointList(connectionEndpoints); + } + + /** + * Determines whether this collection contains any ConnectionEndpoints. + * + * @return a boolean value indicating whether this collection contains any ConnectionEndpoints. + */ + public boolean isEmpty() { + return connectionEndpoints.isEmpty(); + } + + /* (non-Javadoc) */ + @Override + public Iterator iterator() { + return Collections.unmodifiableList(connectionEndpoints).iterator(); + } + + /** + * Determines the number of ConnectionEndpoints contained in this collection. + * + * @return an integer value indicating the number of ConnectionEndpoints contained in this collection. + */ + public int size() { + return connectionEndpoints.size(); + } + + /* (non-Javadoc) */ + @Override + public String toString() { + return connectionEndpoints.toString(); + } + +} diff --git a/src/main/java/org/springframework/data/gemfire/util/ArrayUtils.java b/src/main/java/org/springframework/data/gemfire/util/ArrayUtils.java index efb5b31f..7ddc2e4d 100644 --- a/src/main/java/org/springframework/data/gemfire/util/ArrayUtils.java +++ b/src/main/java/org/springframework/data/gemfire/util/ArrayUtils.java @@ -78,6 +78,19 @@ public abstract class ArrayUtils { return (array != null ? array.length : 0); } + /** + * Null-safe, empty array operation returning the given Object array if not null or an empty Object array + * if the array argument is null. + * + * @param the element Class type of the array. + * @param array the Object array on which a null check is performed. + * @return the given Object array if not null, otherwise return an empty Object array. + */ + @SuppressWarnings("unchecked") + public static T[] nullSafeArray(T[] array) { + return (array != null ? array : (T[]) new Object[0]); + } + /** * Remove an element from the given array at position (index). The element is removed at the specified position * and all remaining elements are shifted to the left. diff --git a/src/main/java/org/springframework/data/gemfire/util/DistributedSystemUtils.java b/src/main/java/org/springframework/data/gemfire/util/DistributedSystemUtils.java index 57985a79..c73309fb 100644 --- a/src/main/java/org/springframework/data/gemfire/util/DistributedSystemUtils.java +++ b/src/main/java/org/springframework/data/gemfire/util/DistributedSystemUtils.java @@ -16,8 +16,10 @@ package org.springframework.data.gemfire.util; +import com.gemstone.gemfire.cache.server.CacheServer; import com.gemstone.gemfire.distributed.DistributedSystem; import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem; +import com.gemstone.gemfire.internal.DistributionLocator; /** * DistributedSystemUtils is an abstract utility class for working with the GemFire DistributedSystem. @@ -28,6 +30,9 @@ import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem; */ public abstract class DistributedSystemUtils { + public static final int DEFAULT_CACHE_SERVER_PORT = CacheServer.DEFAULT_PORT; + public static final int DEFAULT_LOCATOR_PORT = DistributionLocator.DEFAULT_LOCATOR_PORT; + @SuppressWarnings("unchecked") public static T getDistributedSystem() { return (T) InternalDistributedSystem.getAnyInstance(); diff --git a/src/test/java/org/springframework/data/gemfire/client/ClientCacheSecurityTest.java b/src/test/java/org/springframework/data/gemfire/client/ClientCacheSecurityTest.java index 5eb4ba0a..60e4d61b 100644 --- a/src/test/java/org/springframework/data/gemfire/client/ClientCacheSecurityTest.java +++ b/src/test/java/org/springframework/data/gemfire/client/ClientCacheSecurityTest.java @@ -31,7 +31,6 @@ import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Value; import org.springframework.data.gemfire.fork.ServerProcess; import org.springframework.data.gemfire.process.ProcessExecutor; import org.springframework.data.gemfire.process.ProcessWrapper; @@ -57,6 +56,7 @@ import com.gemstone.gemfire.cache.Region; */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration +@SuppressWarnings("all") public class ClientCacheSecurityTest { private static ProcessWrapper serverProcess; diff --git a/src/test/java/org/springframework/data/gemfire/client/ClientCacheVariableLocatorsTest.java b/src/test/java/org/springframework/data/gemfire/client/ClientCacheVariableLocatorsTest.java new file mode 100644 index 00000000..96917bc0 --- /dev/null +++ b/src/test/java/org/springframework/data/gemfire/client/ClientCacheVariableLocatorsTest.java @@ -0,0 +1,135 @@ +/* + * Copyright 2010-2013 the original author 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.data.gemfire.client; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import javax.annotation.Resource; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.data.gemfire.fork.ServerProcess; +import org.springframework.data.gemfire.process.ProcessExecutor; +import org.springframework.data.gemfire.process.ProcessWrapper; +import org.springframework.data.gemfire.test.support.FileSystemUtils; +import org.springframework.data.gemfire.test.support.ThreadUtils; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.util.Assert; + +import com.gemstone.gemfire.cache.CacheLoader; +import com.gemstone.gemfire.cache.CacheLoaderException; +import com.gemstone.gemfire.cache.LoaderHelper; +import com.gemstone.gemfire.cache.Region; + +/** + * The ClientCacheVariableLocatorsTest class is a test suite of test cases testing the use of variable "locators" + * attribute on <gfe:pool/< in Spring (Data GemFire) configuration meta-data when connecting a client/server. + * + * @author John Blum + * @see org.junit.Test + * @see org.junit.runner.RunWith + * @see org.springframework.test.context.ContextConfiguration + * @see org.springframework.test.context.junit4.SpringJUnit4ClassRunner + * @since 1.6.3 + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration +@SuppressWarnings("all") +public class ClientCacheVariableLocatorsTest { + + private static ProcessWrapper serverProcess; + + @Resource(name = "Example") + private Region example; + + @BeforeClass + public static void setup() throws IOException { + String serverName = ClientCacheVariableServersTest.class.getSimpleName().concat("Server"); + + File serverWorkingDirectory = new File(FileSystemUtils.WORKING_DIRECTORY, serverName.toLowerCase()); + + Assert.isTrue(serverWorkingDirectory.isDirectory() || serverWorkingDirectory.mkdirs()); + + List arguments = new ArrayList(); + + arguments.add(String.format("-Dgemfire.name=%1$s", serverName)); + arguments.add("/".concat(ClientCacheVariableLocatorsTest.class.getName().replace(".", "/") + .concat("-server-context.xml"))); + + serverProcess = ProcessExecutor.launch(serverWorkingDirectory, ServerProcess.class, + arguments.toArray(new String[arguments.size()])); + + waitForServerToStart(TimeUnit.SECONDS.toMillis(20)); + + System.out.printf("Spring-based, GemFire Cache Server process for %1$s should be running...%n", + ClientCacheVariableLocatorsTest.class.getSimpleName()); + } + + private static void waitForServerToStart(final long milliseconds) { + ThreadUtils.timedWait(milliseconds, TimeUnit.MILLISECONDS.toMillis(500), new ThreadUtils.WaitCondition() { + private File serverPidControlFile = new File(serverProcess.getWorkingDirectory(), + ServerProcess.getServerProcessControlFilename()); + + @Override public boolean waiting() { + return !serverPidControlFile.isFile(); + } + }); + } + + @AfterClass + public static void tearDown() { + serverProcess.shutdown(); + + if (Boolean.valueOf(System.getProperty("spring.gemfire.fork.clean", Boolean.TRUE.toString()))) { + org.springframework.util.FileSystemUtils.deleteRecursively(serverProcess.getWorkingDirectory()); + } + } + + @Test + public void clientServerConnectionSuccessful() { + assertThat(example.get("one"), is(equalTo(1))); + assertThat(example.get("two"), is(equalTo(2))); + assertThat(example.get("three"), is(equalTo(3))); + } + + public static class CacheMissCounterCacheLoader implements CacheLoader { + + private static final AtomicInteger cacheMissCounter = new AtomicInteger(0); + + @Override + public Integer load(final LoaderHelper helper) throws CacheLoaderException { + return cacheMissCounter.incrementAndGet(); + } + + @Override + public void close() { + cacheMissCounter.set(0); + } + } + +} diff --git a/src/test/java/org/springframework/data/gemfire/client/ClientCacheVariableServersTest.java b/src/test/java/org/springframework/data/gemfire/client/ClientCacheVariableServersTest.java new file mode 100644 index 00000000..f1b5e65d --- /dev/null +++ b/src/test/java/org/springframework/data/gemfire/client/ClientCacheVariableServersTest.java @@ -0,0 +1,135 @@ +/* + * Copyright 2010-2013 the original author 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.data.gemfire.client; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import javax.annotation.Resource; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.data.gemfire.fork.ServerProcess; +import org.springframework.data.gemfire.process.ProcessExecutor; +import org.springframework.data.gemfire.process.ProcessWrapper; +import org.springframework.data.gemfire.test.support.FileSystemUtils; +import org.springframework.data.gemfire.test.support.ThreadUtils; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.util.Assert; + +import com.gemstone.gemfire.cache.CacheLoader; +import com.gemstone.gemfire.cache.CacheLoaderException; +import com.gemstone.gemfire.cache.LoaderHelper; +import com.gemstone.gemfire.cache.Region; + +/** + * The ClientCacheVariableServersTest class is a test suite of test cases testing the use of variable "servers" + * attribute on <gfe:pool/< in Spring (Data GemFire) configuration meta-data when connecting a client/server. + * + * @author John Blum + * @see org.junit.Test + * @see org.junit.runner.RunWith + * @see org.springframework.test.context.ContextConfiguration + * @see org.springframework.test.context.junit4.SpringJUnit4ClassRunner + * @since 1.6.3 + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration +@SuppressWarnings("all") +public class ClientCacheVariableServersTest { + + private static ProcessWrapper serverProcess; + + @Resource(name = "Example") + private Region example; + + @BeforeClass + public static void setup() throws IOException { + String serverName = ClientCacheVariableServersTest.class.getSimpleName().concat("Server"); + + File serverWorkingDirectory = new File(FileSystemUtils.WORKING_DIRECTORY, serverName.toLowerCase()); + + Assert.isTrue(serverWorkingDirectory.isDirectory() || serverWorkingDirectory.mkdirs()); + + List arguments = new ArrayList(); + + arguments.add(String.format("-Dgemfire.name=%1$s", serverName)); + arguments.add("/".concat(ClientCacheVariableServersTest.class.getName().replace(".", "/") + .concat("-server-context.xml"))); + + serverProcess = ProcessExecutor.launch(serverWorkingDirectory, ServerProcess.class, + arguments.toArray(new String[arguments.size()])); + + waitForServerToStart(TimeUnit.SECONDS.toMillis(20)); + + System.out.printf("Spring-based, GemFire Cache Server process for %1$s should be running...%n", + ClientCacheVariableServersTest.class.getSimpleName()); + } + + private static void waitForServerToStart(final long milliseconds) { + ThreadUtils.timedWait(milliseconds, TimeUnit.MILLISECONDS.toMillis(500), new ThreadUtils.WaitCondition() { + private File serverPidControlFile = new File(serverProcess.getWorkingDirectory(), + ServerProcess.getServerProcessControlFilename()); + + @Override public boolean waiting() { + return !serverPidControlFile.isFile(); + } + }); + } + + @AfterClass + public static void tearDown() { + serverProcess.shutdown(); + + if (Boolean.valueOf(System.getProperty("spring.gemfire.fork.clean", Boolean.TRUE.toString()))) { + org.springframework.util.FileSystemUtils.deleteRecursively(serverProcess.getWorkingDirectory()); + } + } + + @Test + public void clientServerConnectionSuccessful() { + assertThat(example.get("one"), is(equalTo(1))); + assertThat(example.get("two"), is(equalTo(2))); + assertThat(example.get("three"), is(equalTo(3))); + } + + public static class CacheMissCounterCacheLoader implements CacheLoader { + + private static final AtomicInteger cacheMissCounter = new AtomicInteger(0); + + @Override + public Integer load(final LoaderHelper helper) throws CacheLoaderException { + return cacheMissCounter.incrementAndGet(); + } + + @Override + public void close() { + cacheMissCounter.set(0); + } + } + +} diff --git a/src/test/java/org/springframework/data/gemfire/client/PoolFactoryBeanTest.java b/src/test/java/org/springframework/data/gemfire/client/PoolFactoryBeanTest.java index 9768023b..e6249426 100644 --- a/src/test/java/org/springframework/data/gemfire/client/PoolFactoryBeanTest.java +++ b/src/test/java/org/springframework/data/gemfire/client/PoolFactoryBeanTest.java @@ -30,6 +30,7 @@ import static org.mockito.Mockito.when; import java.net.InetAddress; import java.net.InetSocketAddress; +import java.util.Collection; import java.util.Collections; import java.util.Properties; @@ -144,7 +145,7 @@ public class PoolFactoryBeanTest { PoolFactoryBean poolFactoryBean = new PoolFactoryBean(); poolFactoryBean.setName("GemFirePool"); - poolFactoryBean.setLocators(null); + poolFactoryBean.setLocators((Collection) null); poolFactoryBean.setServers(Collections.emptyList()); poolFactoryBean.afterPropertiesSet(); } diff --git a/src/test/java/org/springframework/data/gemfire/client/PoolUsingLocatorsAndServersPropertyPlaceholdersTest.java b/src/test/java/org/springframework/data/gemfire/client/PoolUsingLocatorsAndServersPropertyPlaceholdersTest.java new file mode 100644 index 00000000..54e54372 --- /dev/null +++ b/src/test/java/org/springframework/data/gemfire/client/PoolUsingLocatorsAndServersPropertyPlaceholdersTest.java @@ -0,0 +1,162 @@ +/* + * Copyright 2010-2013 the original author 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.data.gemfire.client; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.mockito.Matchers.anyInt; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanFactoryPostProcessor; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.data.gemfire.support.ConnectionEndpoint; +import org.springframework.data.gemfire.support.ConnectionEndpointList; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.gemstone.gemfire.cache.client.PoolFactory; + +/** + * The PoolUsingLocatorsAndServersPropertyPlaceholdersTest class... + * + * @author John Blum + * @since 1.0.0 + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration +public class PoolUsingLocatorsAndServersPropertyPlaceholdersTest { + + private static ConnectionEndpointList locatorConnectionEndpoints = new ConnectionEndpointList(); + private static ConnectionEndpointList serverConnectionEndpoints = new ConnectionEndpointList(); + + private static PoolFactory mockPoolFactory; + + protected static ConnectionEndpoint newConnectionEndpoint(String host, int port) { + return new ConnectionEndpoint(host, port); + } + + @BeforeClass + public static void setup() { + mockPoolFactory = mock(PoolFactory.class, "MockPoolFactory"); + + when(mockPoolFactory.addLocator(anyString(), anyInt())).thenAnswer(new Answer() { + @Override + public PoolFactory answer(final InvocationOnMock invocation) throws Throwable { + String host = invocation.getArgumentAt(0, String.class); + int port = invocation.getArgumentAt(1, Integer.class); + locatorConnectionEndpoints.add(newConnectionEndpoint(host, port)); + return mockPoolFactory; + } + }); + + when(mockPoolFactory.addServer(anyString(), anyInt())).thenAnswer(new Answer() { + @Override + public PoolFactory answer(final InvocationOnMock invocation) throws Throwable { + String host = invocation.getArgumentAt(0, String.class); + int port = invocation.getArgumentAt(1, Integer.class); + serverConnectionEndpoints.add(newConnectionEndpoint(host, port)); + return mockPoolFactory; + } + }); + } + + protected ConnectionEndpointList sort(ConnectionEndpointList list) { + List connectionEndpoints = new ArrayList(list.size()); + + for (ConnectionEndpoint connectionEndpoint : list) { + connectionEndpoints.add(connectionEndpoint); + } + + Collections.sort(connectionEndpoints); + + return new ConnectionEndpointList(connectionEndpoints); + } + + protected void assertConnectionEndpoints(ConnectionEndpointList connectionEndpoints, String... expected) { + assertThat(connectionEndpoints.isEmpty(), is(false)); + assertThat(connectionEndpoints.size(), is(equalTo(expected.length))); + + int index = 0; + + for (ConnectionEndpoint connectionEndpoint : connectionEndpoints) { + assertThat(connectionEndpoint.toString(), is(equalTo(expected[index++]))); + } + } + + @Test + public void locatorPoolFactoryConfiguration() { + String[] expected = { "backspace[10334]", "jambox[11235]", "mars[30303]", "pluto[20668]", "skullbox[12480]" }; + +// System.out.printf("locatorPool is... %1$s%n", locatorConnectionEndpoints); + + assertThat(locatorConnectionEndpoints.isEmpty(), is(false)); + assertThat(locatorConnectionEndpoints.size(), is(equalTo(expected.length))); + + assertConnectionEndpoints(sort(locatorConnectionEndpoints), expected); + } + + @Test + public void serverPoolFactoryConfiguration() { + String[] expected = { "earth[4554]", "jupiter[40404]", "mercury[1234]", "neptune[42424]", "saturn[41414]", + "uranis[0]", "venus[9876]" }; + +// System.out.printf("serverPool is... %1$s%n", serverConnectionEndpoints); + + assertThat(serverConnectionEndpoints.isEmpty(), is(false)); + assertThat(serverConnectionEndpoints.size(), is(equalTo(expected.length))); + + assertConnectionEndpoints(sort(serverConnectionEndpoints), expected); + } + + public static class TestBeanFactoryPostProcessor implements BeanFactoryPostProcessor { + + @Override + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { + BeanDefinition locatorsPoolBeanDefinition = beanFactory.getBeanDefinition("locatorPool"); + locatorsPoolBeanDefinition.setBeanClassName(TestPoolFactoryBean.class.getName()); + BeanDefinition serversPoolBeanDefinition = beanFactory.getBeanDefinition("serverPool"); + serversPoolBeanDefinition.setBeanClassName(TestPoolFactoryBean.class.getName()); + } + } + + public static class TestPoolFactoryBean extends PoolFactoryBean { + + @Override + protected PoolFactory createPoolFactory() { + return mockPoolFactory; + } + + @Override + void resolveDistributedSystem() { + } + } + +} diff --git a/src/test/java/org/springframework/data/gemfire/config/PoolNamespaceTest.java b/src/test/java/org/springframework/data/gemfire/config/PoolNamespaceTest.java index eebfab21..d5fe1420 100644 --- a/src/test/java/org/springframework/data/gemfire/config/PoolNamespaceTest.java +++ b/src/test/java/org/springframework/data/gemfire/config/PoolNamespaceTest.java @@ -16,14 +16,15 @@ package org.springframework.data.gemfire.config; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; -import java.net.InetSocketAddress; -import java.util.Collection; import java.util.Iterator; import org.junit.Test; @@ -32,6 +33,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.data.gemfire.TestUtils; import org.springframework.data.gemfire.client.PoolFactoryBean; +import org.springframework.data.gemfire.support.ConnectionEndpoint; +import org.springframework.data.gemfire.support.ConnectionEndpointList; import org.springframework.data.gemfire.test.GemfireTestApplicationContextInitializer; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -50,63 +53,67 @@ public class PoolNamespaceTest { @Autowired private ApplicationContext context; - protected void assertSocketAddress(InetSocketAddress socketAddress, String expectedHost, int expectedPort) { - assertNotNull(socketAddress); - assertEquals(expectedHost, socketAddress.getHostName()); - assertEquals(expectedPort, socketAddress.getPort()); + protected void assertConnectionEndpoint(ConnectionEndpoint connectionEndpoint, String expectedHost, int expectedPort) { + assertThat(connectionEndpoint, is(notNullValue())); + assertThat(connectionEndpoint.getHost(), is(equalTo(expectedHost))); + assertThat(connectionEndpoint.getPort(), is(equalTo(expectedPort))); } @Test public void testBasicClient() throws Exception { - assertTrue(context.containsBean("DEFAULT")); - assertTrue(context.containsBean("gemfirePool")); - assertTrue(context.containsBean("gemfire-pool")); - assertEquals(context.getBean("gemfirePool"), PoolManager.find("DEFAULT")); + assertThat(context.containsBean("DEFAULT"), is(true)); + assertThat(context.containsBean("gemfirePool"), is(true)); + assertThat(context.containsBean("gemfire-pool"), is(true)); + assertThat(PoolManager.find("DEFAULT"), is(equalTo(context.getBean("gemfirePool")))); PoolFactoryBean poolFactoryBean = context.getBean("&gemfirePool", PoolFactoryBean.class); - Collection locators = TestUtils.readField("locators", poolFactoryBean); - assertNotNull(locators); - assertEquals(1, locators.size()); + ConnectionEndpointList locators = TestUtils.readField("locators", poolFactoryBean); - assertSocketAddress(locators.iterator().next(), "localhost", 40403); + assertThat(locators, is(notNullValue())); + assertThat(locators.size(), is(equalTo(1))); + + assertConnectionEndpoint(locators.iterator().next(), "localhost", 40403); } @Test public void testSimplePool() throws Exception { - assertTrue(context.containsBean("simple")); + assertThat(context.containsBean("simple"), is(true)); PoolFactoryBean poolFactoryBean = context.getBean("&simple", PoolFactoryBean.class); - Collection locators = TestUtils.readField("locators", poolFactoryBean); - assertNotNull(locators); - assertEquals(1, locators.size()); + ConnectionEndpointList locators = TestUtils.readField("locators", poolFactoryBean); - assertSocketAddress(locators.iterator().next(), PoolParser.DEFAULT_HOST, PoolParser.DEFAULT_LOCATOR_PORT); + assertThat(locators, is(notNullValue())); + assertThat(locators.size(), is(equalTo(1))); - Collection servers = TestUtils.readField("servers", poolFactoryBean); + assertConnectionEndpoint(locators.iterator().next(), PoolParser.DEFAULT_HOST, PoolParser.DEFAULT_LOCATOR_PORT); - assertNull(servers); + ConnectionEndpointList servers = TestUtils.readField("servers", poolFactoryBean); + + assertThat(servers, is(notNullValue())); + assertThat(servers.isEmpty(), is(true)); } @Test public void testLocatorPool() throws Exception { - assertTrue(context.containsBean("locator")); + assertThat(context.containsBean("locator"), is(true)); PoolFactoryBean poolFactoryBean = context.getBean("&locator", PoolFactoryBean.class); - Collection locators = TestUtils.readField("locators", poolFactoryBean); - assertNotNull(locators); - assertEquals(2, locators.size()); + ConnectionEndpointList locators = TestUtils.readField("locators", poolFactoryBean); - Iterator it = locators.iterator(); + assertThat(locators, is(notNullValue())); + assertThat(locators.size(), is(equalTo(2))); - assertSocketAddress(it.next(), "skullbox", PoolParser.DEFAULT_LOCATOR_PORT); - assertSocketAddress(it.next(), "yorktown", 12480); + Iterator it = locators.iterator(); - Collection servers = TestUtils.readField("servers", poolFactoryBean); + assertConnectionEndpoint(it.next(), "skullbox", PoolParser.DEFAULT_LOCATOR_PORT); + assertConnectionEndpoint(it.next(), "yorktown", 12480); - assertNull(servers); + ConnectionEndpointList servers = TestUtils.readField("servers", poolFactoryBean); + + assertThat(servers, is(notNullValue())); } @Test @@ -118,13 +125,13 @@ public class PoolNamespaceTest { assertEquals(2000, TestUtils.readField("freeConnectionTimeout", poolFactoryBean)); assertEquals(20000l, TestUtils.readField("idleTimeout", poolFactoryBean)); assertEquals(10000, TestUtils.readField("loadConditioningInterval", poolFactoryBean)); - assertEquals(false, TestUtils.readField("keepAlive", poolFactoryBean)); + assertEquals(true, TestUtils.readField("keepAlive", poolFactoryBean)); assertEquals(100, TestUtils.readField("maxConnections", poolFactoryBean)); assertEquals(5, TestUtils.readField("minConnections", poolFactoryBean)); assertEquals(5, TestUtils.readField("minConnections", poolFactoryBean)); - assertFalse((Boolean) TestUtils.readField("multiUserAuthentication", poolFactoryBean)); + assertTrue((Boolean) TestUtils.readField("multiUserAuthentication", poolFactoryBean)); assertEquals(5000l, TestUtils.readField("pingInterval", poolFactoryBean)); - assertTrue((Boolean) TestUtils.readField("prSingleHopEnabled", poolFactoryBean)); + assertFalse((Boolean) TestUtils.readField("prSingleHopEnabled", poolFactoryBean)); assertEquals(500, TestUtils.readField("readTimeout", poolFactoryBean)); assertEquals(5, TestUtils.readField("retryAttempts", poolFactoryBean)); assertEquals("TestGroup", TestUtils.readField("serverGroup", poolFactoryBean)); @@ -136,51 +143,51 @@ public class PoolNamespaceTest { assertEquals(2, TestUtils.readField("subscriptionRedundancy", poolFactoryBean)); assertTrue((Boolean) TestUtils.readField("threadLocalConnections", poolFactoryBean)); - Collection servers = TestUtils.readField("servers", poolFactoryBean); + ConnectionEndpointList servers = TestUtils.readField("servers", poolFactoryBean); assertNotNull(servers); assertEquals(2, servers.size()); - Iterator serversIterator = servers.iterator(); + Iterator serversIterator = servers.iterator(); - assertSocketAddress(serversIterator.next(), "localhost", 40404); - assertSocketAddress(serversIterator.next(), "localhost", 40405); + assertConnectionEndpoint(serversIterator.next(), "localhost", 40404); + assertConnectionEndpoint(serversIterator.next(), "localhost", 40405); } @Test public void testComboLocatorPool() throws Exception { - assertTrue(context.containsBean("combo-locators")); + assertThat(context.containsBean("combo-locators"), is(true)); PoolFactoryBean poolFactoryBean = context.getBean("&combo-locators", PoolFactoryBean.class); - Collection locators = TestUtils.readField("locators", poolFactoryBean); - assertNotNull(locators); - assertEquals(3, locators.size()); + ConnectionEndpointList locators = TestUtils.readField("locators", poolFactoryBean); - Iterator locatorIterator = locators.iterator(); + assertThat(locators, is(notNullValue())); + assertThat(locators.size(), is(equalTo(3))); - assertSocketAddress(locatorIterator.next(), "foobar", 55421); - assertSocketAddress(locatorIterator.next(), "lavatube", 11235); - assertSocketAddress(locatorIterator.next(), "zod", 10334); + Iterator locatorIterator = locators.iterator(); + + assertConnectionEndpoint(locatorIterator.next(), "foobar", 55421); + assertConnectionEndpoint(locatorIterator.next(), "lavatube", 11235); + assertConnectionEndpoint(locatorIterator.next(), "zod", 10334); } @Test public void testComboServerPool() throws Exception { - assertTrue(context.containsBean("combo-servers")); + assertThat(context.containsBean("combo-servers"), is(true)); PoolFactoryBean poolFactoryBean = context.getBean("&combo-servers", PoolFactoryBean.class); - Collection locators = TestUtils.readField("servers", poolFactoryBean); - Collection servers = TestUtils.readField("servers", poolFactoryBean); + ConnectionEndpointList servers = TestUtils.readField("servers", poolFactoryBean); - assertNotNull(servers); - assertEquals(3, servers.size()); + assertThat(servers, is(notNullValue())); + assertThat(servers.size(), is(equalTo(3))); - Iterator serverIterator = locators.iterator(); + Iterator serverIterator = servers.iterator(); - assertSocketAddress(serverIterator.next(), "scorch", 21480); - assertSocketAddress(serverIterator.next(), "scorn", 51515); - assertSocketAddress(serverIterator.next(), "skullbox", 9110); + assertConnectionEndpoint(serverIterator.next(), "scorch", 21480); + assertConnectionEndpoint(serverIterator.next(), "scorn", 51515); + assertConnectionEndpoint(serverIterator.next(), "skullbox", 9110); } } diff --git a/src/test/java/org/springframework/data/gemfire/config/PoolParserTest.java b/src/test/java/org/springframework/data/gemfire/config/PoolParserTest.java index 8f2bfa76..a901d4ab 100644 --- a/src/test/java/org/springframework/data/gemfire/config/PoolParserTest.java +++ b/src/test/java/org/springframework/data/gemfire/config/PoolParserTest.java @@ -16,19 +16,32 @@ package org.springframework.data.gemfire.config; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertThat; +import static org.mockito.Matchers.anyInt; +import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.util.List; + import org.junit.Test; +import org.springframework.beans.PropertyValues; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.ManagedList; import org.springframework.data.gemfire.client.PoolFactoryBean; +import org.springframework.data.gemfire.support.ConnectionEndpoint; +import org.springframework.data.gemfire.support.ConnectionEndpointList; import org.w3c.dom.Element; import org.w3c.dom.NodeList; @@ -47,35 +60,267 @@ public class PoolParserTest { private PoolParser parser = new PoolParser(); protected void assertBeanDefinition(BeanDefinition beanDefinition, String expectedHost, String expectedPort) { - assertNotNull(beanDefinition); - assertEquals(2, beanDefinition.getConstructorArgumentValues().getArgumentCount()); - assertEquals(expectedHost, beanDefinition.getConstructorArgumentValues() - .getArgumentValue(0, String.class).getValue()); - assertEquals(expectedPort, beanDefinition.getConstructorArgumentValues() - .getArgumentValue(1, String.class).getValue()); + assertThat(beanDefinition, is(notNullValue())); + assertThat(beanDefinition.getBeanClassName(), is(equalTo(ConnectionEndpoint.class.getName()))); + assertThat(beanDefinition.getConstructorArgumentValues().getArgumentCount(), is(equalTo(2))); + assertThat(beanDefinition.getConstructorArgumentValues().getArgumentValue(0, String.class).getValue().toString(), + is(equalTo(expectedHost))); + assertThat(beanDefinition.getConstructorArgumentValues().getArgumentValue(1, String.class).getValue().toString(), + is(equalTo(expectedPort))); } @Test - public void testGetBeanClass() { - assertEquals(PoolFactoryBean.class, parser.getBeanClass(null)); + @SuppressWarnings("unchecked") + public void getBeanClass() { + assertThat((Class) parser.getBeanClass(null), is(equalTo(PoolFactoryBean.class))); } @Test - public void testBuildConnection() { + @SuppressWarnings("unchecked") + public void doParse() { + Element mockPoolElement = mock(Element.class, "testDoParse.MockPoolElement"); + Element mockLocatorOneElement = mock(Element.class, "testDoParse.MockLocatorOneElement"); + Element mockLocatorTwoElement = mock(Element.class, "testDoParse.MockLocatorTwoElement"); + Element mockServerElement = mock(Element.class, "testDoParse.MockServerElement"); + + NodeList mockNodeList = mock(NodeList.class, "testDoParse.MockNodeList"); + + when(mockPoolElement.hasAttribute(PoolParser.LOCATORS_ATTRIBUTE_NAME)).thenReturn(true); + when(mockPoolElement.getAttribute(PoolParser.LOCATORS_ATTRIBUTE_NAME)).thenReturn("nebula[1234]"); + when(mockPoolElement.hasAttribute(PoolParser.SERVERS_ATTRIBUTE_NAME)).thenReturn(true); + when(mockPoolElement.getAttribute(PoolParser.SERVERS_ATTRIBUTE_NAME)).thenReturn("skullbox[9876], backspace"); + when(mockPoolElement.getChildNodes()).thenReturn(mockNodeList); + when(mockNodeList.getLength()).thenReturn(3); + when(mockNodeList.item(eq(0))).thenReturn(mockLocatorOneElement); + when(mockNodeList.item(eq(1))).thenReturn(mockServerElement); + when(mockNodeList.item(eq(2))).thenReturn(mockLocatorTwoElement); + when(mockLocatorOneElement.getLocalName()).thenReturn(PoolParser.LOCATOR_ELEMENT_NAME); + when(mockLocatorOneElement.getAttribute(PoolParser.HOST_ATTRIBUTE_NAME)).thenReturn("comet"); + when(mockLocatorOneElement.getAttribute(PoolParser.PORT_ATTRIBUTE_NAME)).thenReturn("1025"); + when(mockLocatorTwoElement.getLocalName()).thenReturn(PoolParser.LOCATOR_ELEMENT_NAME); + when(mockLocatorTwoElement.getAttribute(PoolParser.HOST_ATTRIBUTE_NAME)).thenReturn("quasar"); + when(mockLocatorTwoElement.getAttribute(PoolParser.PORT_ATTRIBUTE_NAME)).thenReturn(" "); + when(mockServerElement.getLocalName()).thenReturn(PoolParser.SERVER_ELEMENT_NAME); + when(mockServerElement.getAttribute(PoolParser.HOST_ATTRIBUTE_NAME)).thenReturn("rightshift"); + when(mockServerElement.getAttribute(PoolParser.PORT_ATTRIBUTE_NAME)).thenReturn("4556"); + + BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition( + parser.getBeanClass(mockPoolElement)); + + parser.doParse(mockPoolElement, builder); + + BeanDefinition poolDefinition = builder.getBeanDefinition(); + + PropertyValues poolPropertyValues = poolDefinition.getPropertyValues(); + + assertThat(poolDefinition, is(notNullValue())); + assertThat(poolPropertyValues.contains("locatorEndpoints"), is(true)); + assertThat(poolPropertyValues.contains("locatorEndpointList"), is(false)); + assertThat(poolPropertyValues.contains("serverEndpoints"), is(true)); + assertThat(poolPropertyValues.contains("serverEndpointList"), is(false)); + + ManagedList locators = (ManagedList) + poolPropertyValues.getPropertyValue("locatorEndpoints").getValue(); + + assertThat(locators, is(notNullValue())); + assertThat(locators.size(), is(equalTo(3))); + assertBeanDefinition(locators.get(0), "comet", "1025"); + assertBeanDefinition(locators.get(1), "quasar", String.valueOf(PoolParser.DEFAULT_LOCATOR_PORT)); + assertBeanDefinition(locators.get(2), "nebula", "1234"); + + ManagedList servers = (ManagedList) poolDefinition.getPropertyValues() + .getPropertyValue("serverEndpoints").getValue(); + + assertThat(servers, is(notNullValue())); + assertThat(servers.size(), is(equalTo(3))); + assertBeanDefinition(servers.get(0), "rightshift", "4556"); + assertBeanDefinition(servers.get(1), "skullbox", "9876"); + assertBeanDefinition(servers.get(2), "backspace", String.valueOf(PoolParser.DEFAULT_SERVER_PORT)); + + verify(mockPoolElement, times(1)).getChildNodes(); + verify(mockNodeList, times(4)).getLength(); + verify(mockNodeList, times(1)).item(eq(0)); + verify(mockNodeList, times(1)).item(eq(1)); + verify(mockNodeList, times(1)).item(eq(2)); + verify(mockPoolElement, never()).hasAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME)); + verify(mockPoolElement, times(1)).getAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME)); + verify(mockPoolElement, never()).hasAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME)); + verify(mockPoolElement, times(1)).getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME)); + verify(mockLocatorOneElement, times(1)).getLocalName(); + verify(mockLocatorOneElement, times(1)).getAttribute(PoolParser.HOST_ATTRIBUTE_NAME); + verify(mockLocatorOneElement, times(1)).getAttribute(PoolParser.PORT_ATTRIBUTE_NAME); + verify(mockLocatorTwoElement, times(1)).getLocalName(); + verify(mockLocatorTwoElement, times(1)).getAttribute(PoolParser.HOST_ATTRIBUTE_NAME); + verify(mockLocatorTwoElement, times(1)).getAttribute(PoolParser.PORT_ATTRIBUTE_NAME); + verify(mockServerElement, times(1)).getLocalName(); + verify(mockServerElement, times(1)).getAttribute(PoolParser.HOST_ATTRIBUTE_NAME); + verify(mockServerElement, times(1)).getAttribute(PoolParser.PORT_ATTRIBUTE_NAME); + } + + @Test + @SuppressWarnings("unchecked") + public void doParseWithNoLocatorsOrServersSpecified() { + Element mockPoolElement = mock(Element.class, "testDoParseWithNoLocatorsOrServersSpecified.MockPoolElement"); + + NodeList mockNodeList = mock(NodeList.class, "testDoParseWithNoLocatorsOrServersSpecified.MockNodeList"); + + when(mockNodeList.getLength()).thenReturn(0); + when(mockPoolElement.getChildNodes()).thenReturn(mockNodeList); + when(mockPoolElement.hasAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME))).thenReturn(false); + when(mockPoolElement.getAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME))).thenReturn(""); + when(mockPoolElement.hasAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME))).thenReturn(false); + when(mockPoolElement.getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME))).thenReturn(""); + + BeanDefinitionBuilder poolBuilder = BeanDefinitionBuilder.genericBeanDefinition( + parser.getBeanClass(mockPoolElement)); + + parser.doParse(mockPoolElement, poolBuilder); + + BeanDefinition poolDefinition = poolBuilder.getBeanDefinition(); + + PropertyValues poolPropertyValues = poolDefinition.getPropertyValues(); + + assertThat(poolDefinition, is(notNullValue())); + assertThat(poolPropertyValues.contains("locatorEndpoints"), is(true)); + assertThat(poolPropertyValues.contains("locatorEndpointList"), is(false)); + assertThat(poolPropertyValues.contains("serverEndpoints"), is(false)); + assertThat(poolPropertyValues.contains("serverEndpointList"), is(false)); + + ManagedList locators = (ManagedList) + poolPropertyValues.getPropertyValue("locatorEndpoints").getValue(); + + assertThat(locators, is(notNullValue())); + assertThat(locators.size(), is(equalTo(1))); + assertBeanDefinition(locators.get(0), PoolParser.DEFAULT_HOST, String.valueOf(PoolParser.DEFAULT_LOCATOR_PORT)); + + verify(mockPoolElement, times(1)).getChildNodes(); + verify(mockNodeList, times(1)).getLength(); + verify(mockNodeList, never()).item(anyInt()); + verify(mockPoolElement, times(1)).hasAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME)); + verify(mockPoolElement, times(1)).getAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME)); + verify(mockPoolElement, times(1)).hasAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME)); + verify(mockPoolElement, times(1)).getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME)); + } + + @Test + public void doParseWithServersAttributeValueSpecifiedAsAPropertyPlaceholder() { + Element mockPoolElement = mock(Element.class, "testDoParseWithServersAttributeValueSpecifiedAsAPropertyPlaceholder.MockPoolElement"); + + NodeList mockNodeList = mock(NodeList.class, "testDoParseWithServersAttributeValueSpecifiedAsAPropertyPlaceholder.MockNodeList"); + + when(mockNodeList.getLength()).thenReturn(0); + when(mockPoolElement.getChildNodes()).thenReturn(mockNodeList); + when(mockPoolElement.hasAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME))).thenReturn(false); + when(mockPoolElement.hasAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME))).thenReturn(true); + when(mockPoolElement.getAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME))).thenReturn(""); + when(mockPoolElement.getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME))).thenReturn("${gemfire.server.hosts-and-ports}"); + + BeanDefinitionBuilder poolBuilder = BeanDefinitionBuilder.genericBeanDefinition( + parser.getBeanClass(mockPoolElement)); + + parser.doParse(mockPoolElement, poolBuilder); + + BeanDefinition poolDefinition = poolBuilder.getBeanDefinition(); + + PropertyValues poolPropertyValues = poolDefinition.getPropertyValues(); + + assertThat(poolDefinition, is(notNullValue())); + assertThat(poolPropertyValues.contains("locatorEndpoints"), is(false)); + assertThat(poolPropertyValues.contains("locatorEndpointList"), is(false)); + assertThat(poolPropertyValues.contains("serverEndpoints"), is(false)); + assertThat(poolPropertyValues.contains("serverEndpointList"), is(true)); + + BeanDefinition servers = (BeanDefinition) poolPropertyValues.getPropertyValue("serverEndpointList").getValue(); + + assertThat(servers, is(notNullValue())); + assertThat(servers.getBeanClassName(), is(equalTo(ConnectionEndpointList.class.getName()))); + assertThat(servers.getFactoryMethodName(), is(equalTo("parse"))); + assertThat(servers.getConstructorArgumentValues().getArgumentValue(0, String.class).getValue().toString(), + is(equalTo(String.valueOf(PoolParser.DEFAULT_SERVER_PORT)))); + assertThat(servers.getConstructorArgumentValues().getArgumentValue(1, String.class).getValue().toString(), + is(equalTo("${gemfire.server.hosts-and-ports}"))); + + verify(mockPoolElement, times(1)).getChildNodes(); + verify(mockNodeList, times(1)).getLength(); + verify(mockNodeList, never()).item(anyInt()); + verify(mockPoolElement, times(1)).hasAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME)); + verify(mockPoolElement, times(1)).getAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME)); + verify(mockPoolElement, times(1)).hasAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME)); + verify(mockPoolElement, times(1)).getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME)); + } + + @Test + public void hasAttributesReturnsTrueAndShortcircuts() { + Element mockElement = mock(Element.class, "testHasAttributesIsTrue.MockElement"); + + when(mockElement.hasAttribute("attributeOne")).thenReturn(true); + when(mockElement.hasAttribute("attributeTwo")).thenReturn(true); + + assertThat(parser.hasAttributes(mockElement, "attributeThree", "attributeTwo", "attributeOne"), is(true)); + + verify(mockElement, times(1)).hasAttribute(eq("attributeThree")); + verify(mockElement, times(1)).hasAttribute(eq("attributeTwo")); + verify(mockElement, never()).hasAttribute(eq("attributeOne")); + } + + @Test + public void hasAttributesReturnsFalse() { + Element mockElement = mock(Element.class, "testHasAttributesIsTrue.MockElement"); + + when(mockElement.hasAttribute(anyString())).thenReturn(false); + + assertThat(parser.hasAttributes(mockElement, "one", "two", "three", "four"), is(false)); + + verify(mockElement, times(1)).hasAttribute(eq("one")); + verify(mockElement, times(1)).hasAttribute(eq("two")); + verify(mockElement, times(1)).hasAttribute(eq("three")); + verify(mockElement, times(1)).hasAttribute(eq("four")); + } + + @Test + public void buildConnectionsUsingLocator() { + BeanDefinition beanDefinition = parser.buildConnections("${test}", false); + + assertThat(beanDefinition, is(notNullValue())); + assertThat(beanDefinition.getBeanClassName(), is(equalTo(ConnectionEndpointList.class.getName()))); + assertThat( + beanDefinition.getConstructorArgumentValues().getArgumentValue(0, Integer.class).getValue().toString(), + is(equalTo(String.valueOf(PoolParser.DEFAULT_LOCATOR_PORT)))); + assertThat( + beanDefinition.getConstructorArgumentValues().getArgumentValue(1, String.class).getValue().toString(), + is(equalTo("${test}"))); + } + + @Test + public void buildConnectionsUsingServer() { + BeanDefinition beanDefinition = parser.buildConnections("${test}", true); + + assertThat(beanDefinition, is(notNullValue())); + assertThat(beanDefinition.getBeanClassName(), is(equalTo(ConnectionEndpointList.class.getName()))); + assertThat(beanDefinition.getConstructorArgumentValues().getArgumentValue(0, Integer.class).getValue().toString(), + is(equalTo(String.valueOf(PoolParser.DEFAULT_SERVER_PORT)))); + assertThat(beanDefinition.getConstructorArgumentValues().getArgumentValue(1, String.class).getValue().toString(), + is(equalTo("${test}"))); + } + + @Test + public void buildConnection() { assertBeanDefinition(parser.buildConnection("skullbox", "1234", true), "skullbox", "1234"); assertBeanDefinition(parser.buildConnection("saturn", " ", true), "saturn", String.valueOf(PoolParser.DEFAULT_SERVER_PORT)); + assertBeanDefinition(parser.buildConnection(" ", "1234", true), PoolParser.DEFAULT_HOST, "1234"); assertBeanDefinition(parser.buildConnection(" ", "", true), PoolParser.DEFAULT_HOST, String.valueOf(PoolParser.DEFAULT_SERVER_PORT)); assertBeanDefinition(parser.buildConnection("neptune", "9876", false), "neptune", "9876"); assertBeanDefinition(parser.buildConnection("jupiter", null, false), "jupiter", String.valueOf(PoolParser.DEFAULT_LOCATOR_PORT)); + assertBeanDefinition(parser.buildConnection(null, "9876", false), PoolParser.DEFAULT_HOST, "9876"); assertBeanDefinition(parser.buildConnection("", " ", false), PoolParser.DEFAULT_HOST, String.valueOf(PoolParser.DEFAULT_LOCATOR_PORT)); } @Test - public void testDefaultHost() { + public void defaultHost() { assertEquals("skullbox", parser.defaultHost("skullbox")); assertEquals("localhost", parser.defaultHost(null)); assertEquals("localhost", parser.defaultHost("")); @@ -83,7 +328,7 @@ public class PoolParserTest { } @Test - public void testDefaultPort() { + public void defaultPort() { assertEquals("1234", parser.defaultPort("1234", true)); assertEquals("9876", parser.defaultPort("9876", false)); assertEquals(String.valueOf(PoolParser.DEFAULT_SERVER_PORT), parser.defaultPort(null, true)); @@ -92,7 +337,7 @@ public class PoolParserTest { } @Test - public void testParseConnection() { + public void parseConnection() { assertBeanDefinition(parser.parseConnection("skullbox[1234]", true), "skullbox", "1234"); assertBeanDefinition(parser.parseConnection("saturn", true), "saturn", String.valueOf(PoolParser.DEFAULT_SERVER_PORT)); @@ -104,8 +349,8 @@ public class PoolParserTest { } @Test - public void testParseSingleConnection() { - ManagedList beans = parser.parseConnections("skullbox[1234]", true); + public void parseSingleConnection() { + List beans = parser.parseConnections("skullbox[1234]", true); assertNotNull(beans); assertFalse(beans.isEmpty()); @@ -114,8 +359,8 @@ public class PoolParserTest { } @Test - public void testParseMultipleConnections() { - ManagedList beans = parser.parseConnections( + public void parseMultipleConnections() { + List beans = parser.parseConnections( "skullbox[1234],neptune,saturn[ ],jupiter[SlO], [9876],v3nU5[4_567], localhost [1 01 0] ", true); assertNotNull(beans); @@ -131,7 +376,7 @@ public class PoolParserTest { } @Test - public void testParseDigits() { + public void parseDigits() { assertEquals("1234", parser.parseDigits("1234")); assertEquals("4567", parser.parseDigits(" 4567 ")); assertEquals("78901", parser.parseDigits("7 89 0 1 ")); @@ -144,47 +389,127 @@ public class PoolParserTest { } @Test - public void testParseLocator() { + public void isPropertyPlaceholder() { + assertThat(parser.isPropertyPlaceholder("${some.property}"), is(true)); + assertThat(parser.isPropertyPlaceholder("${test}"), is(true)); + assertThat(parser.isPropertyPlaceholder("${p}"), is(true)); + assertThat(parser.isPropertyPlaceholder("$PROPERTY"), is(false)); + assertThat(parser.isPropertyPlaceholder("%PROPERTY%"), is(false)); + assertThat(parser.isPropertyPlaceholder("$"), is(false)); + assertThat(parser.isPropertyPlaceholder("${"), is(false)); + assertThat(parser.isPropertyPlaceholder("$}"), is(false)); + assertThat(parser.isPropertyPlaceholder("{}"), is(false)); + assertThat(parser.isPropertyPlaceholder("${}"), is(false)); + assertThat(parser.isPropertyPlaceholder(" "), is(false)); + assertThat(parser.isPropertyPlaceholder(""), is(false)); + } + + @Test + public void parseLocator() { Element mockElement = mock(Element.class, "testParseLocator.Element"); when(mockElement.getAttribute(eq(PoolParser.HOST_ATTRIBUTE_NAME))).thenReturn("skullbox"); when(mockElement.getAttribute(eq(PoolParser.PORT_ATTRIBUTE_NAME))).thenReturn("1234"); assertBeanDefinition(parser.parseLocator(mockElement), "skullbox", "1234"); + + verify(mockElement, times(1)).getAttribute(eq(PoolParser.HOST_ATTRIBUTE_NAME)); + verify(mockElement, times(1)).getAttribute(eq(PoolParser.PORT_ATTRIBUTE_NAME)); } @Test - public void testParseLocators() { + public void parseLocatorWithNoHostPort() { + Element mockElement = mock(Element.class, "testParseLocatorWithNoHostPort.Element"); + + when(mockElement.getAttribute(PoolParser.HOST_ATTRIBUTE_NAME)).thenReturn(""); + when(mockElement.getAttribute(PoolParser.PORT_ATTRIBUTE_NAME)).thenReturn(null); + + assertBeanDefinition(parser.parseLocator(mockElement), "localhost", "10334"); + + verify(mockElement, times(1)).getAttribute(eq(PoolParser.HOST_ATTRIBUTE_NAME)); + verify(mockElement, times(1)).getAttribute(eq(PoolParser.PORT_ATTRIBUTE_NAME)); + } + + @Test + public void parseLocators() { Element mockElement = mock(Element.class, "testParseLocators.Element"); - when(mockElement.getAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME))).thenReturn("jupiter, saturn[1234]"); + when(mockElement.getAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME))).thenReturn( + "jupiter, saturn[1234], [9876] "); - ManagedList locators = parser.parseLocators(mockElement); + List locators = parser.parseLocators(mockElement, null); - assertNotNull(locators); - assertFalse(locators.isEmpty()); - assertEquals(2, locators.size()); + assertThat(locators, is(notNullValue())); + assertThat(locators.size(), is(equalTo(3))); assertBeanDefinition(locators.get(0), "jupiter", String.valueOf(PoolParser.DEFAULT_LOCATOR_PORT)); assertBeanDefinition(locators.get(1), "saturn", "1234"); + assertBeanDefinition(locators.get(2), "localhost", "9876"); + + verify(mockElement, times(1)).getAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME)); } @Test - public void testParseServer() { + public void parseLocatorsWithPropertyPlaceholder() { + Element mockElement = mock(Element.class, "testParseLocatorsWithPropertyPlaceholder.Element"); + + when(mockElement.getAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME))).thenReturn( + "${gemfire.locators.hosts-and-ports}"); + + BeanDefinitionBuilder locatorsBuilder = BeanDefinitionBuilder.genericBeanDefinition( + parser.getBeanClass(mockElement)); + + List locators = parser.parseLocators(mockElement, locatorsBuilder); + + assertThat(locators, is(notNullValue())); + assertThat(locators.isEmpty(), is(true)); + + BeanDefinition locatorDefinition = (BeanDefinition) locatorsBuilder.getBeanDefinition() + .getPropertyValues().getPropertyValue("locatorEndpointList").getValue(); + + assertThat(locatorDefinition, is(notNullValue())); + assertThat(locatorDefinition.getBeanClassName(), is(equalTo(ConnectionEndpointList.class.getName()))); + assertThat(locatorDefinition.getFactoryMethodName(), is(equalTo("parse"))); + assertThat(locatorDefinition.getConstructorArgumentValues().getArgumentValue(0, String.class).getValue().toString(), + is(equalTo(String.valueOf(PoolParser.DEFAULT_LOCATOR_PORT)))); + assertThat(locatorDefinition.getConstructorArgumentValues().getArgumentValue(1, String.class).getValue().toString(), + is(equalTo("${gemfire.locators.hosts-and-ports}"))); + + verify(mockElement, times(1)).getAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME)); + } + + @Test + public void parseServer() { Element mockElement = mock(Element.class, "testParseServer.Element"); when(mockElement.getAttribute(eq(PoolParser.HOST_ATTRIBUTE_NAME))).thenReturn("plato"); when(mockElement.getAttribute(eq(PoolParser.PORT_ATTRIBUTE_NAME))).thenReturn("9876"); assertBeanDefinition(parser.parseServer(mockElement), "plato", "9876"); + + verify(mockElement, times(1)).getAttribute(eq(PoolParser.HOST_ATTRIBUTE_NAME)); + verify(mockElement, times(1)).getAttribute(eq(PoolParser.PORT_ATTRIBUTE_NAME)); } @Test - public void testParseServers() { + public void parseServerWithNoHostPort() { + Element mockElement = mock(Element.class, "testParseServerWithNoHostPort.Element"); + + when(mockElement.getAttribute(eq(PoolParser.HOST_ATTRIBUTE_NAME))).thenReturn(" "); + when(mockElement.getAttribute(eq(PoolParser.PORT_ATTRIBUTE_NAME))).thenReturn(""); + + assertBeanDefinition(parser.parseServer(mockElement), "localhost", "40404"); + + verify(mockElement, times(1)).getAttribute(eq(PoolParser.HOST_ATTRIBUTE_NAME)); + verify(mockElement, times(1)).getAttribute(eq(PoolParser.PORT_ATTRIBUTE_NAME)); + } + + @Test + public void parseServers() { Element mockElement = mock(Element.class, "testParseServers.Element"); when(mockElement.getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME))).thenReturn(" neptune[], venus[9876]"); - ManagedList servers = parser.parseServers(mockElement); + List servers = parser.parseServers(mockElement, null); assertNotNull(servers); assertFalse(servers.isEmpty()); @@ -194,91 +519,32 @@ public class PoolParserTest { } @Test - @SuppressWarnings("unchecked") - public void testPostProcess() { - Element mockPoolElement = mock(Element.class, "testPostProcess.MockPoolElement"); - Element mockLocatorOneElement = mock(Element.class, "testPostProcess.MockLocatorOneElement"); - Element mockLocatorTwoElement = mock(Element.class, "testPostProcess.MockLocatorTwoElement"); - Element mockServerElement = mock(Element.class, "testPostProcess.MockServerElement"); + public void parseServersWithPropertyPlaceholder() { + Element mockElement = mock(Element.class, "testParseServersWithPropertyPlaceholder.Element"); - NodeList mockNodeList = mock(NodeList.class, "testPostProcess.MockNodeList"); + when(mockElement.getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME))).thenReturn( + "${gemfire.servers.hosts-and-ports}"); - when(mockPoolElement.getAttribute(PoolParser.LOCATORS_ATTRIBUTE_NAME)).thenReturn("nebula[1122]"); - when(mockPoolElement.getAttribute(PoolParser.SERVERS_ATTRIBUTE_NAME)).thenReturn("skullbox[4848], backspace"); - when(mockPoolElement.getChildNodes()).thenReturn(mockNodeList); - when(mockNodeList.getLength()).thenReturn(3); - when(mockNodeList.item(eq(0))).thenReturn(mockLocatorOneElement); - when(mockNodeList.item(eq(1))).thenReturn(mockServerElement); - when(mockNodeList.item(eq(2))).thenReturn(mockLocatorTwoElement); - when(mockLocatorOneElement.getLocalName()).thenReturn(PoolParser.LOCATOR_ELEMENT_NAME); - when(mockLocatorOneElement.getAttribute(PoolParser.HOST_ATTRIBUTE_NAME)).thenReturn("comet"); - when(mockLocatorOneElement.getAttribute(PoolParser.PORT_ATTRIBUTE_NAME)).thenReturn("1034"); - when(mockLocatorTwoElement.getLocalName()).thenReturn(PoolParser.LOCATOR_ELEMENT_NAME); - when(mockLocatorTwoElement.getAttribute(PoolParser.HOST_ATTRIBUTE_NAME)).thenReturn("quasar"); - when(mockLocatorTwoElement.getAttribute(PoolParser.PORT_ATTRIBUTE_NAME)).thenReturn(" "); - when(mockServerElement.getLocalName()).thenReturn(PoolParser.SERVER_ELEMENT_NAME); - when(mockServerElement.getAttribute(PoolParser.HOST_ATTRIBUTE_NAME)).thenReturn("rightshift"); - when(mockServerElement.getAttribute(PoolParser.PORT_ATTRIBUTE_NAME)).thenReturn("4554"); + BeanDefinitionBuilder serversBuilder = BeanDefinitionBuilder.genericBeanDefinition( + parser.getBeanClass(mockElement)); - BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition( - parser.getBeanClass(mockPoolElement)); + List servers = parser.parseServers(mockElement, serversBuilder); - parser.postProcess(builder, mockPoolElement); + assertThat(servers, is(notNullValue())); + assertThat(servers.isEmpty(), is(true)); - BeanDefinition poolDefinition = builder.getRawBeanDefinition(); + BeanDefinition serverDefinition = (BeanDefinition) serversBuilder.getBeanDefinition() + .getPropertyValues().getPropertyValue("serverEndpointList").getValue(); - assertNotNull(poolDefinition); - assertTrue(poolDefinition.getPropertyValues().contains("locators")); - assertTrue(poolDefinition.getPropertyValues().contains("servers")); + assertThat(serverDefinition, is(notNullValue())); + assertThat(serverDefinition.getBeanClassName(), is(equalTo(ConnectionEndpointList.class.getName()))); + assertThat(serverDefinition.getFactoryMethodName(), is(equalTo("parse"))); + assertThat(serverDefinition.getConstructorArgumentValues().getArgumentValue(0, String.class).getValue().toString(), + is(equalTo(String.valueOf(PoolParser.DEFAULT_SERVER_PORT)))); + assertThat(serverDefinition.getConstructorArgumentValues().getArgumentValue(1, String.class).getValue().toString(), + is(equalTo("${gemfire.servers.hosts-and-ports}"))); - ManagedList locators = (ManagedList) poolDefinition.getPropertyValues() - .getPropertyValue("locators").getValue(); - - assertNotNull(locators); - assertFalse(locators.isEmpty()); - assertEquals(3, locators.size()); - assertBeanDefinition(locators.get(0), "comet", "1034"); - assertBeanDefinition(locators.get(1), "quasar", String.valueOf(PoolParser.DEFAULT_LOCATOR_PORT)); - assertBeanDefinition(locators.get(2), "nebula", "1122"); - - ManagedList servers = (ManagedList) poolDefinition.getPropertyValues() - .getPropertyValue("servers").getValue(); - - assertNotNull(servers); - assertFalse(servers.isEmpty()); - assertEquals(3, servers.size()); - assertBeanDefinition(servers.get(0), "rightshift", "4554"); - assertBeanDefinition(servers.get(1), "skullbox", "4848"); - assertBeanDefinition(servers.get(2), "backspace", String.valueOf(PoolParser.DEFAULT_SERVER_PORT)); - } - - @Test - @SuppressWarnings("unchecked") - public void testPostProcessWithNoLocatorsOrServersSpecified() { - BeanDefinitionBuilder poolBuilder = BeanDefinitionBuilder.genericBeanDefinition(); - Element mockPoolElement = mock(Element.class, "testPostProcessWithNoLocatorsOrServersSpecified.MockPoolElement"); - NodeList mockNodeList = mock(NodeList.class, "testPostProcessWithNoLocatorsOrServersSpecified.MockNodeList"); - - when(mockNodeList.getLength()).thenReturn(0); - when(mockPoolElement.getChildNodes()).thenReturn(mockNodeList); - when(mockPoolElement.getAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME))).thenReturn(""); - when(mockPoolElement.getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME))).thenReturn(""); - - parser.postProcess(poolBuilder, mockPoolElement); - - BeanDefinition poolDefinition = poolBuilder.getBeanDefinition(); - - assertNotNull(poolDefinition); - assertTrue(poolDefinition.getPropertyValues().contains("locators")); - assertFalse(poolDefinition.getPropertyValues().contains("servers")); - - ManagedList locators = (ManagedList) poolDefinition.getPropertyValues() - .getPropertyValue("locators").getValue(); - - assertNotNull(locators); - assertFalse(locators.isEmpty()); - assertEquals(1, locators.size()); - assertBeanDefinition(locators.get(0), "localhost", String.valueOf(PoolParser.DEFAULT_LOCATOR_PORT)); + verify(mockElement, times(1)).getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME)); } } diff --git a/src/test/java/org/springframework/data/gemfire/support/ConnectionEndpointListTest.java b/src/test/java/org/springframework/data/gemfire/support/ConnectionEndpointListTest.java new file mode 100644 index 00000000..6eb44ea1 --- /dev/null +++ b/src/test/java/org/springframework/data/gemfire/support/ConnectionEndpointListTest.java @@ -0,0 +1,263 @@ +/* + * Copyright 2010-2013 the original author 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.data.gemfire.support; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.CoreMatchers.sameInstance; +import static org.junit.Assert.assertThat; + +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +/** + * The ConnectionEndpointListTest class is a test suite of test cases testing the contract and functionality + * of the ConnectionEndpointList class. + * + * @author John Blum + * @see org.junit.Rule + * @see org.junit.Test + * @see org.springframework.data.gemfire.support.ConnectionEndpointList + * @since 1.6.3 + */ +public class ConnectionEndpointListTest { + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + protected ConnectionEndpoint newConnectionEndpoint(String host, int port) { + return new ConnectionEndpoint(host, port); + } + + @Test + public void constructNewEmptyConnectionEndpointList() { + ConnectionEndpointList connectionEndpoints = new ConnectionEndpointList(); + + assertThat(connectionEndpoints.isEmpty(), is(true)); + assertThat(connectionEndpoints.size(), is(equalTo(0))); + } + + @Test + public void constructNewInitializedConnectionEndpointList() { + ConnectionEndpoint[] connectionEndpoints = { + newConnectionEndpoint("jambox", 1234), + newConnectionEndpoint("skullbox", 9876) + }; + + ConnectionEndpointList connectionEndpointList = new ConnectionEndpointList(connectionEndpoints); + + assertThat(connectionEndpointList.isEmpty(), is(false)); + assertThat(connectionEndpointList.size(), is(equalTo(connectionEndpoints.length))); + + int index = 0; + + for (ConnectionEndpoint connectionEndpoint : connectionEndpointList) { + assertThat(connectionEndpoint, is(equalTo(connectionEndpoints[index++]))); + } + } + + @Test + public void fromInetSocketAddresses() { + InetSocketAddress[] inetSocketAddresses = { + new InetSocketAddress("localhost", 1234), + new InetSocketAddress("localhost", 9876) + }; + + ConnectionEndpointList connectionEndpoints = ConnectionEndpointList.from(inetSocketAddresses); + + assertThat(connectionEndpoints, is(notNullValue())); + assertThat(connectionEndpoints.isEmpty(), is(false)); + assertThat(connectionEndpoints.size(), is(equalTo(2))); + + int index = 0; + + for (ConnectionEndpoint connectionEndpoint : connectionEndpoints) { + assertThat(connectionEndpoint.getHost(), is(equalTo(inetSocketAddresses[index].getHostString()))); + assertThat(connectionEndpoint.getPort(), is(equalTo(inetSocketAddresses[index++].getPort()))); + } + } + + @Test + @SuppressWarnings("unchecked") + public void fromIterableInetSocketAddressesIsNullSafe() { + ConnectionEndpointList connectionEndpoints = ConnectionEndpointList.from((Iterable) null); + + assertThat(connectionEndpoints, is(notNullValue())); + assertThat(connectionEndpoints.isEmpty(), is(true)); + assertThat(connectionEndpoints.size(), is(equalTo(0))); + } + + @Test + public void parse() { + ConnectionEndpointList connectionEndpoints = ConnectionEndpointList + .parse(24842, "mercury[11235]", "venus", "[12480]", + "[]", "jupiter[]", "saturn[1, 2-Hundred and 34.zero5]", "neptune[four]"); + + String[] expectedHostPorts = { "mercury[11235]", "venus[24842]", "localhost[12480]", "localhost[24842]", + "jupiter[24842]", "saturn[12345]", "neptune[24842]" }; + + assertThat(connectionEndpoints, is(notNullValue())); + + int index = 0; + + for (ConnectionEndpoint connectionEndpoint : connectionEndpoints) { + assertThat(connectionEndpoint.toString(), is(equalTo(expectedHostPorts[index++]))); + } + } + + @Test + public void parseWithEmptyHostsPortsArgument() { + ConnectionEndpointList connectionEndpoints = ConnectionEndpointList.parse(1234); + + assertThat(connectionEndpoints, is(notNullValue())); + assertThat(connectionEndpoints.isEmpty(), is(true)); + assertThat(connectionEndpoints.size(), is(equalTo(0))); + } + + @Test + @SuppressWarnings("unchecked") + public void addAdditionalConnectionEndpoints() { + ConnectionEndpointList connectionEndpointList = new ConnectionEndpointList(); + + assertThat(connectionEndpointList.isEmpty(), is(true)); + + ConnectionEndpoint[] connectionEndpointsArray = { newConnectionEndpoint("Mercury", 1111) }; + + Iterable connectionEndpointsIterable = Arrays.asList( + newConnectionEndpoint("Venus", 2222), + newConnectionEndpoint("Earth", 3333), + newConnectionEndpoint("Mars", 4444), + newConnectionEndpoint("Jupiter", 5555), + newConnectionEndpoint("Saturn", 6666), + newConnectionEndpoint("Uranis", 7777), + newConnectionEndpoint("Neptune", 8888), + newConnectionEndpoint("Pluto", 9999) + ); + + assertThat(connectionEndpointList.add(connectionEndpointsArray).add(connectionEndpointsIterable), + is(sameInstance(connectionEndpointList))); + + List expected = new ArrayList(9); + + expected.add(connectionEndpointsArray[0]); + expected.addAll((List) connectionEndpointsIterable); + + int index = 0; + + for (ConnectionEndpoint connectionEndpoint : connectionEndpointList) { + assertThat(connectionEndpoint, is(equalTo(expected.get(index++)))); + } + } + + @Test + public void findByHostName() { + ConnectionEndpointList connectionEndpoints = new ConnectionEndpointList( + newConnectionEndpoint("Earth", 10334), + newConnectionEndpoint("Earth", 40404), + newConnectionEndpoint("Mars", 10334), + newConnectionEndpoint("Jupiter", 1234), + newConnectionEndpoint("Saturn", 9876), + newConnectionEndpoint("Neptune", 12345) + ); + + assertThat(connectionEndpoints.isEmpty(), is(false)); + assertThat(connectionEndpoints.size(), is(equalTo(6))); + + ConnectionEndpointList actual = connectionEndpoints.findBy("Earth"); + + assertThat(actual, is(notNullValue())); + assertThat(actual.isEmpty(), is(false)); + assertThat(actual.size(), is(equalTo(2))); + + String[] expected = { "Earth[10334]", "Earth[40404]" }; + int index = 0; + + for (ConnectionEndpoint connectionEndpoint : actual) { + assertThat(connectionEndpoint.toString(), is(equalTo(expected[index++]))); + } + + actual = connectionEndpoints.findBy("Saturn"); + + assertThat(actual, is(notNullValue())); + assertThat(actual.isEmpty(), is(false)); + assertThat(actual.size(), is(equalTo(1))); + assertThat(actual.iterator().next().toString(), is(equalTo("Saturn[9876]"))); + + actual = connectionEndpoints.findBy("Pluto"); + + assertThat(actual, is(notNullValue())); + assertThat(actual.isEmpty(), is(true)); + assertThat(actual.size(), is(equalTo(0))); + } + + @Test + public void findByPortNumber() { + ConnectionEndpointList connectionEndpoints = new ConnectionEndpointList( + newConnectionEndpoint("Earth", 10334), + newConnectionEndpoint("Earth", 40404), + newConnectionEndpoint("Mars", 10334), + newConnectionEndpoint("Jupiter", 1234), + newConnectionEndpoint("Saturn", 9876), + newConnectionEndpoint("Neptune", 12345) + ); + + assertThat(connectionEndpoints.isEmpty(), is(false)); + assertThat(connectionEndpoints.size(), is(equalTo(6))); + + ConnectionEndpointList actual = connectionEndpoints.findBy(10334); + + assertThat(actual, is(notNullValue())); + assertThat(actual.isEmpty(), is(false)); + assertThat(actual.size(), is(equalTo(2))); + + String[] expected = { "Earth[10334]", "Mars[10334]" }; + int index = 0; + + for (ConnectionEndpoint connectionEndpoint : actual) { + assertThat(connectionEndpoint.toString(), is(equalTo(expected[index++]))); + } + + actual = connectionEndpoints.findBy(1234); + + assertThat(actual, is(notNullValue())); + assertThat(actual.isEmpty(), is(false)); + assertThat(actual.size(), is(equalTo(1))); + assertThat(actual.iterator().next().toString(), is(equalTo("Jupiter[1234]"))); + + actual = connectionEndpoints.findBy(80); + + assertThat(actual, is(notNullValue())); + assertThat(actual.isEmpty(), is(true)); + assertThat(actual.size(), is(equalTo(0))); + } + + @Test + public void toStringRepresentation() { + ConnectionEndpointList connectionEndpoints = ConnectionEndpointList.parse(10334, + "skullbox[12480]", "saturn[ 1 12 3 5]", "neptune"); + + assertThat(connectionEndpoints.toString(), is(equalTo("[skullbox[12480], saturn[11235], neptune[10334]]"))); + } + +} diff --git a/src/test/java/org/springframework/data/gemfire/support/ConnectionEndpointTest.java b/src/test/java/org/springframework/data/gemfire/support/ConnectionEndpointTest.java new file mode 100644 index 00000000..7f57c124 --- /dev/null +++ b/src/test/java/org/springframework/data/gemfire/support/ConnectionEndpointTest.java @@ -0,0 +1,256 @@ +/* + * Copyright 2010-2013 the original author 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.data.gemfire.support; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.number.OrderingComparison.greaterThan; +import static org.hamcrest.number.OrderingComparison.lessThan; +import static org.junit.Assert.assertThat; + +import java.net.InetSocketAddress; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +/** + * The ConnectionEndpointTest class is a test suite of test cases testing the contract and functionality + * of the ConnectionEndpoint class representing GemFire Socket connection endpoints to GemFire services + * (such as Locators, etc). + * + * @author John Blum + * @see org.junit.Rule + * @see org.junit.Test + * @see org.junit.rules.ExpectedException + * @see org.springframework.data.gemfire.support.ConnectionEndpoint + * @since 1.6.3 + */ +public class ConnectionEndpointTest { + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Test + public void fromInetSocketAddress() { + InetSocketAddress socketAddress = new InetSocketAddress("localhost", 1234); + + ConnectionEndpoint connectionEndpoint = ConnectionEndpoint.from(socketAddress); + + assertThat(connectionEndpoint, is(notNullValue())); + assertThat(connectionEndpoint.getHost(), is(equalTo(socketAddress.getHostString()))); + assertThat(connectionEndpoint.getPort(), is(equalTo(socketAddress.getPort()))); + } + + @Test + public void parseUsingDefaultHostAndDefaultPort() { + ConnectionEndpoint connectionEndpoint = ConnectionEndpoint.parse("[]"); + + assertThat(connectionEndpoint, is(notNullValue())); + assertThat(connectionEndpoint.getHost(), is(equalTo(ConnectionEndpoint.DEFAULT_HOST))); + assertThat(connectionEndpoint.getPort(), is(equalTo(ConnectionEndpoint.DEFAULT_PORT))); + + connectionEndpoint = ConnectionEndpoint.parse("[]", 1234); + + assertThat(connectionEndpoint, is(notNullValue())); + assertThat(connectionEndpoint.getHost(), is(equalTo(ConnectionEndpoint.DEFAULT_HOST))); + assertThat(connectionEndpoint.getPort(), is(equalTo(1234))); + } + + @Test + public void parseWithHostPort() { + ConnectionEndpoint connectionEndpoint = ConnectionEndpoint.parse("skullbox[12345]", 80); + + assertThat(connectionEndpoint, is(notNullValue())); + assertThat(connectionEndpoint.getHost(), is(equalTo("skullbox"))); + assertThat(connectionEndpoint.getPort(), is(equalTo(12345))); + + connectionEndpoint = ConnectionEndpoint.parse("localhost[0]", 8080); + + assertThat(connectionEndpoint, is(notNullValue())); + assertThat(connectionEndpoint.getHost(), is(equalTo("localhost"))); + assertThat(connectionEndpoint.getPort(), is(equalTo(0))); + + connectionEndpoint = ConnectionEndpoint.parse("jambox[1O1O1]", 443); + + assertThat(connectionEndpoint, is(notNullValue())); + assertThat(connectionEndpoint.getHost(), is(equalTo("jambox"))); + assertThat(connectionEndpoint.getPort(), is(equalTo(111))); + } + + @Test + public void parseWithHostUsingDefaultPort() { + ConnectionEndpoint connectionEndpoint = ConnectionEndpoint.parse("mercury[oneTwoThreeFourFive]", 80); + + assertThat(connectionEndpoint, is(notNullValue())); + assertThat(connectionEndpoint.getHost(), is(equalTo("mercury"))); + assertThat(connectionEndpoint.getPort(), is(equalTo(80))); + + connectionEndpoint = ConnectionEndpoint.parse("venus[OxCAFEBABE]", 443); + + assertThat(connectionEndpoint, is(notNullValue())); + assertThat(connectionEndpoint.getHost(), is(equalTo("venus"))); + assertThat(connectionEndpoint.getPort(), is(equalTo(443))); + + connectionEndpoint = ConnectionEndpoint.parse("jupiter[#(^$)*!]", 21); + + assertThat(connectionEndpoint, is(notNullValue())); + assertThat(connectionEndpoint.getHost(), is(equalTo("jupiter"))); + assertThat(connectionEndpoint.getPort(), is(equalTo(21))); + + connectionEndpoint = ConnectionEndpoint.parse("saturn[]", 22); + + assertThat(connectionEndpoint, is(notNullValue())); + assertThat(connectionEndpoint.getHost(), is(equalTo("saturn"))); + assertThat(connectionEndpoint.getPort(), is(equalTo(22))); + + connectionEndpoint = ConnectionEndpoint.parse("uranis[", 23); + + assertThat(connectionEndpoint, is(notNullValue())); + assertThat(connectionEndpoint.getHost(), is(equalTo("uranis"))); + assertThat(connectionEndpoint.getPort(), is(equalTo(23))); + + connectionEndpoint = ConnectionEndpoint.parse("neptune", 25); + + assertThat(connectionEndpoint, is(notNullValue())); + assertThat(connectionEndpoint.getHost(), is(equalTo("neptune"))); + assertThat(connectionEndpoint.getPort(), is(equalTo(25))); + + connectionEndpoint = ConnectionEndpoint.parse("pluto"); + + assertThat(connectionEndpoint, is(notNullValue())); + assertThat(connectionEndpoint.getHost(), is(equalTo("pluto"))); + assertThat(connectionEndpoint.getPort(), is(equalTo(ConnectionEndpoint.DEFAULT_PORT))); + } + + @Test + public void parseWithPortUsingDefaultHost() { + ConnectionEndpoint connectionEndpoint = ConnectionEndpoint.parse("[12345]", 80); + + assertThat(connectionEndpoint, is(notNullValue())); + assertThat(connectionEndpoint.getHost(), is(equalTo(ConnectionEndpoint.DEFAULT_HOST))); + assertThat(connectionEndpoint.getPort(), is(equalTo(12345))); + } + + @Test + public void parseWithBlankHost() { + expectedException.expect(IllegalArgumentException.class); + expectedException.expectCause(is(nullValue(Throwable.class))); + expectedException.expectMessage("'hostPort' must be specified"); + ConnectionEndpoint.parse(" ", 12345); + } + + @Test + public void parseWithEmptyHost() { + expectedException.expect(IllegalArgumentException.class); + expectedException.expectCause(is(nullValue(Throwable.class))); + expectedException.expectMessage("'hostPort' must be specified"); + ConnectionEndpoint.parse("", 12345); + } + + @Test + public void parseWithNullHost() { + expectedException.expect(IllegalArgumentException.class); + expectedException.expectCause(is(nullValue(Throwable.class))); + expectedException.expectMessage("'hostPort' must be specified"); + ConnectionEndpoint.parse(null, 12345); + } + + @Test + public void parseWithInvalidDefaultPort() { + expectedException.expect(IllegalArgumentException.class); + expectedException.expectCause(is(nullValue(Throwable.class))); + expectedException.expectMessage("port number (-1248) must be between 0 and 65535"); + ConnectionEndpoint.parse("localhost", -1248); + } + + @Test + public void parseDigits() { + assertThat(ConnectionEndpoint.parseDigits("123456789"), is(equalTo("123456789"))); + assertThat(ConnectionEndpoint.parseDigits("3.14159"), is(equalTo("314159"))); + assertThat(ConnectionEndpoint.parseDigits("-21.5"), is(equalTo("215"))); + assertThat(ConnectionEndpoint.parseDigits("$156.78^#99!"), is(equalTo("1567899"))); + assertThat(ConnectionEndpoint.parseDigits("oneTwoThree"), is(equalTo(""))); + assertThat(ConnectionEndpoint.parseDigits(" "), is(equalTo(""))); + assertThat(ConnectionEndpoint.parseDigits(""), is(equalTo(""))); + assertThat(ConnectionEndpoint.parseDigits(null), is(equalTo(""))); + } + + @Test + public void parsePort() { + assertThat(ConnectionEndpoint.parsePort("12345", 80), is(equalTo(12345))); + assertThat(ConnectionEndpoint.parsePort("zero", 80), is(equalTo(80))); + } + + @Test + public void constructConnectionEndpoint() { + ConnectionEndpoint connectionEndpoint = new ConnectionEndpoint("skullbox", 12345); + + assertThat(connectionEndpoint.getHost(), is(equalTo("skullbox"))); + assertThat(connectionEndpoint.getPort(), is(equalTo(12345))); + assertThat(connectionEndpoint.toString(), is(equalTo("skullbox[12345]"))); + } + + @Test + public void constructConnectionEndpointWithDefaultHost() { + ConnectionEndpoint connectionEndpoint = new ConnectionEndpoint(" ", 12345); + + assertThat(connectionEndpoint.getHost(), is(equalTo(ConnectionEndpoint.DEFAULT_HOST))); + assertThat(connectionEndpoint.getPort(), is(equalTo(12345))); + } + + @Test + public void constructConnectionEndpointWithInvalidPort() { + expectedException.expect(IllegalArgumentException.class); + expectedException.expectCause(is(nullValue(Throwable.class))); + expectedException.expectMessage("port number (-1) must be between 0 and 65535"); + new ConnectionEndpoint("localhost", -1); + } + + @Test + public void cloneConnectionEndpoint() throws CloneNotSupportedException { + ConnectionEndpoint originalConnectionEndpoint = new ConnectionEndpoint("skullbox", 12345); + + assertThat(originalConnectionEndpoint.getHost(), is(equalTo("skullbox"))); + assertThat(originalConnectionEndpoint.getPort(), is(equalTo(12345))); + + ConnectionEndpoint clonedConnectionEndpoint = (ConnectionEndpoint) originalConnectionEndpoint.clone(); + + assertThat(clonedConnectionEndpoint, is(notNullValue())); + assertThat(clonedConnectionEndpoint, is(equalTo(originalConnectionEndpoint))); + } + + @Test + public void compareConnectionEndpoints() { + ConnectionEndpoint connectionEndpointOne = new ConnectionEndpoint("localhost", 10334); + ConnectionEndpoint connectionEndpointTwo = new ConnectionEndpoint("localhost", 40404); + ConnectionEndpoint connectionEndpointThree = new ConnectionEndpoint("skullbox", 11235); + + assertThat(connectionEndpointOne.compareTo(connectionEndpointOne), is(equalTo(0))); + assertThat(connectionEndpointOne.compareTo(connectionEndpointTwo), is(lessThan(0))); + assertThat(connectionEndpointOne.compareTo(connectionEndpointThree), is(lessThan(0))); + assertThat(connectionEndpointTwo.compareTo(connectionEndpointOne), is(greaterThan(0))); + assertThat(connectionEndpointTwo.compareTo(connectionEndpointTwo), is(equalTo(0))); + assertThat(connectionEndpointTwo.compareTo(connectionEndpointThree), is(lessThan(0))); + assertThat(connectionEndpointThree.compareTo(connectionEndpointOne), is(greaterThan(0))); + assertThat(connectionEndpointThree.compareTo(connectionEndpointTwo), is(greaterThan(0))); + assertThat(connectionEndpointThree.compareTo(connectionEndpointThree), is(equalTo(0))); + } + +} diff --git a/src/test/java/org/springframework/data/gemfire/util/ArrayUtilsTest.java b/src/test/java/org/springframework/data/gemfire/util/ArrayUtilsTest.java index 155760d8..3e43802b 100644 --- a/src/test/java/org/springframework/data/gemfire/util/ArrayUtilsTest.java +++ b/src/test/java/org/springframework/data/gemfire/util/ArrayUtilsTest.java @@ -16,9 +16,14 @@ package org.springframework.data.gemfire.util; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.sameInstance; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.util.Arrays; @@ -38,7 +43,7 @@ import org.junit.Test; public class ArrayUtilsTest { @Test - public void testInsertBeginning() { + public void insertAtBeginning() { Object[] originalArray = { "testing", "tested" }; Object[] newArray = ArrayUtils.insert(originalArray, 0, "test"); @@ -50,7 +55,7 @@ public class ArrayUtilsTest { } @Test - public void testInsertMiddle() { + public void insertInMiddle() { Object[] originalArray = { "test", "tested" }; Object[] newArray = ArrayUtils.insert(originalArray, 1, "testing"); @@ -62,7 +67,7 @@ public class ArrayUtilsTest { } @Test - public void testInsertEnd() { + public void insertAtEnd() { Object[] originalArray = { "test", "testing" }; Object[] newArray = ArrayUtils.insert(originalArray, 2, "tested"); @@ -74,7 +79,7 @@ public class ArrayUtilsTest { } @Test - public void testIsEmpty() { + public void isEmpty() { assertFalse(ArrayUtils.isEmpty("test", "testing", "tested")); assertFalse(ArrayUtils.isEmpty("test")); assertFalse(ArrayUtils.isEmpty("")); @@ -84,7 +89,7 @@ public class ArrayUtilsTest { } @Test - public void testLength() { + public void length() { assertEquals(3, ArrayUtils.length("test", "testing", "tested")); assertEquals(1, ArrayUtils.length("test")); assertEquals(1, ArrayUtils.length("")); @@ -94,7 +99,34 @@ public class ArrayUtilsTest { } @Test - public void testRemoveBeginning() { + public void nullSafeArrayWithNonNullArray() { + String[] stringArray = { "test", "testing", "tested" }; + + assertThat(ArrayUtils.nullSafeArray(stringArray), is(sameInstance(stringArray))); + + Double[] emptyDoubleArray = {}; + + assertThat(ArrayUtils.nullSafeArray(emptyDoubleArray), is(sameInstance(emptyDoubleArray))); + + Integer[] numberArray = { 1, 2, 3 }; + + assertThat(ArrayUtils.nullSafeArray(numberArray), is(sameInstance(numberArray))); + + Character[] characterArray = { 'A', 'B', 'C' }; + + assertThat(ArrayUtils.nullSafeArray(characterArray), is(sameInstance(characterArray))); + } + + @Test + public void nullSafeArrayWithNullArray() { + Object array = ArrayUtils.nullSafeArray(null); + + assertThat(array, is(instanceOf(Object[].class))); + assertThat(((Object[]) array).length, is(equalTo(0))); + } + + @Test + public void removeFromBeginning() { Object[] originalArray = { "test", "testing", "tested" }; Object[] newArray = ArrayUtils.remove(originalArray, 0); @@ -105,7 +137,7 @@ public class ArrayUtilsTest { } @Test - public void testRemoveMiddle() { + public void removeFromMiddle() { Object[] originalArray = { "test", "testing", "tested" }; Object[] newArray = ArrayUtils.remove(originalArray, 1); @@ -116,7 +148,7 @@ public class ArrayUtilsTest { } @Test - public void testRemoveEnd() { + public void removeFromEnd() { Object[] originalArray = { "test", "testing", "tested" }; Object[] newArray = ArrayUtils.remove(originalArray, 2); diff --git a/src/test/resources/org/springframework/data/gemfire/client/ClientCacheVariableLocatorsTest-context.xml b/src/test/resources/org/springframework/data/gemfire/client/ClientCacheVariableLocatorsTest-context.xml new file mode 100644 index 00000000..fe6d9d55 --- /dev/null +++ b/src/test/resources/org/springframework/data/gemfire/client/ClientCacheVariableLocatorsTest-context.xml @@ -0,0 +1,30 @@ + + + + + localhost[11235] + + + + + + config + + + + + + + + + diff --git a/src/test/resources/org/springframework/data/gemfire/client/ClientCacheVariableLocatorsTest-server-context.xml b/src/test/resources/org/springframework/data/gemfire/client/ClientCacheVariableLocatorsTest-server-context.xml new file mode 100644 index 00000000..8c7b83b3 --- /dev/null +++ b/src/test/resources/org/springframework/data/gemfire/client/ClientCacheVariableLocatorsTest-server-context.xml @@ -0,0 +1,40 @@ + + + + + localhost + 23579 + + + + + + ClientCacheVariableLocatorsTestServer + 0 + warning + localhost[11235] + localhost[11235] + + + + + + + + + + + + + diff --git a/src/test/resources/org/springframework/data/gemfire/client/ClientCacheVariableServersTest-context.xml b/src/test/resources/org/springframework/data/gemfire/client/ClientCacheVariableServersTest-context.xml new file mode 100644 index 00000000..3e4fa273 --- /dev/null +++ b/src/test/resources/org/springframework/data/gemfire/client/ClientCacheVariableServersTest-context.xml @@ -0,0 +1,34 @@ + + + + + localhost[23579],localhost[23654] + localhost + 24448 + + + + + + warning + + + + + + + + + + + diff --git a/src/test/resources/org/springframework/data/gemfire/client/ClientCacheVariableServersTest-server-context.xml b/src/test/resources/org/springframework/data/gemfire/client/ClientCacheVariableServersTest-server-context.xml new file mode 100644 index 00000000..878761f1 --- /dev/null +++ b/src/test/resources/org/springframework/data/gemfire/client/ClientCacheVariableServersTest-server-context.xml @@ -0,0 +1,48 @@ + + + + + localhost + 22357 + localhost + 23654 + localhost + 24448 + + + + + + ClientCacheVariableServersTestServer + 0 + warning + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/org/springframework/data/gemfire/client/PoolUsingLocatorsAndServersPropertyPlaceholdersTest-context.xml b/src/test/resources/org/springframework/data/gemfire/client/PoolUsingLocatorsAndServersPropertyPlaceholdersTest-context.xml new file mode 100644 index 00000000..e3880f04 --- /dev/null +++ b/src/test/resources/org/springframework/data/gemfire/client/PoolUsingLocatorsAndServersPropertyPlaceholdersTest-context.xml @@ -0,0 +1,36 @@ + + + + + + + backspace,jambox[11235],skullbox[12480] + pluto + 20668 + saturn + 41414 + + + + + + + + + + + + + + + diff --git a/src/test/resources/org/springframework/data/gemfire/config/pool-ns.xml b/src/test/resources/org/springframework/data/gemfire/config/pool-ns.xml index 0ee293c5..ca890f21 100644 --- a/src/test/resources/org/springframework/data/gemfire/config/pool-ns.xml +++ b/src/test/resources/org/springframework/data/gemfire/config/pool-ns.xml @@ -30,8 +30,8 @@