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 7863d2bf..0801bbeb 100644 --- a/src/main/java/org/springframework/data/gemfire/client/PoolFactoryBean.java +++ b/src/main/java/org/springframework/data/gemfire/client/PoolFactoryBean.java @@ -20,6 +20,11 @@ import java.net.InetSocketAddress; import java.util.Collection; import java.util.Properties; +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 org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.BeanFactory; @@ -34,17 +39,12 @@ import org.springframework.data.gemfire.util.DistributedSystemUtils; import org.springframework.util.Assert; import org.springframework.util.StringUtils; -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; - /** - * FactoryBean for easy declaration and configuration of a GemFire Pool. If a new Pool is created, - * its lifecycle is bound to that of the declaring container. - * - * Note, if the Pool already exists, the existing Pool will be returned as is without any modifications - * and its lifecycle will be unaffected by this factory. + * FactoryBean for easy declaration and configuration of a GemFire {@link Pool}. If a new {@link Pool} is created, + * its lifecycle is bound to that of this declaring factory. + * + * Note, if a {@link Pool} having the configured name already exists, then the existing {@link Pool} will be returned + * as is without any modifications and its lifecycle will be unaffected by this factory. * * @author Costin Leau * @author John Blum @@ -367,5 +367,4 @@ public class PoolFactoryBean implements FactoryBean, InitializingBean, Dis public void setThreadLocalConnections(boolean threadLocalConnections) { this.threadLocalConnections = threadLocalConnections; } - } 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 26b3d5c1..9663b21c 100644 --- a/src/main/java/org/springframework/data/gemfire/config/PoolParser.java +++ b/src/main/java/org/springframework/data/gemfire/config/PoolParser.java @@ -16,39 +16,41 @@ package org.springframework.data.gemfire.config; -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.BeanDefinitionRegistry; import org.springframework.beans.factory.support.ManagedList; import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser; import org.springframework.beans.factory.xml.ParserContext; +import org.springframework.data.gemfire.GemfireUtils; 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.data.gemfire.util.SpringUtils; import org.springframework.util.StringUtils; import org.springframework.util.xml.DomUtils; import org.w3c.dom.Element; /** - * Parser for GFE <pool;gt; bean definitions. - * + * Parser for <gfe:pool> bean definitions. + * * @author Costin Leau * @author David Turanski * @author John Blum + * @see org.springframework.beans.factory.config.BeanDefinition + * @see org.springframework.beans.factory.support.BeanDefinitionBuilder + * @see org.springframework.beans.factory.support.BeanDefinitionRegistry + * @see org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser + * @see org.springframework.data.gemfire.client.PoolFactoryBean */ class PoolParser extends AbstractSingleBeanDefinitionParser { - 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 int DEFAULT_LOCATOR_PORT = GemfireUtils.DEFAULT_LOCATOR_PORT; + protected static final int DEFAULT_SERVER_PORT = GemfireUtils.DEFAULT_CACHE_SERVER_PORT; protected static final String DEFAULT_HOST = "localhost"; protected static final String HOST_ATTRIBUTE_NAME = "host"; @@ -64,7 +66,7 @@ class PoolParser extends AbstractSingleBeanDefinitionParser { } @Override - protected void doParse(Element element, BeanDefinitionBuilder builder) { + protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { ParsingUtils.setPropertyValue(element, builder, "free-connection-timeout"); ParsingUtils.setPropertyValue(element, builder, "idle-timeout"); ParsingUtils.setPropertyValue(element, builder, "load-conditioning-interval"); @@ -102,13 +104,13 @@ class PoolParser extends AbstractSingleBeanDefinitionParser { } } - locators.addAll(parseLocators(element, builder)); - servers.addAll(parseServers(element, builder)); + boolean locatorsSet = parseLocators(element, builder); + boolean serversSet = parseServers(element, builder); - // 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)); + // NOTE: if neither Locators nor Servers were configured, then setup a connection to a Server + // running on localhost, listening on the default CacheServer port 40404 + if (childElements.isEmpty() && !(locatorsSet || serversSet)) { + servers.add(buildConnection(DEFAULT_HOST, String.valueOf(DEFAULT_SERVER_PORT), true)); } if (!locators.isEmpty()) { @@ -120,32 +122,10 @@ class PoolParser extends AbstractSingleBeanDefinitionParser { } } - /* (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 connectionEndpointBuilder = BeanDefinitionBuilder.genericBeanDefinition( - ConnectionEndpoint.class); + BeanDefinitionBuilder connectionEndpointBuilder = + BeanDefinitionBuilder.genericBeanDefinition(ConnectionEndpoint.class); connectionEndpointBuilder.addConstructorArgValue(defaultHost(host)); connectionEndpointBuilder.addConstructorArgValue(defaultPort(port, server)); @@ -153,6 +133,18 @@ class PoolParser extends AbstractSingleBeanDefinitionParser { return connectionEndpointBuilder.getBeanDefinition(); } + /* (non-Javadoc) */ + BeanDefinition buildConnections(String expression, boolean server) { + BeanDefinitionBuilder connectionEndpointListBuilder = + BeanDefinitionBuilder.genericBeanDefinition(ConnectionEndpointList.class); + + connectionEndpointListBuilder.setFactoryMethod("parse"); + connectionEndpointListBuilder.addConstructorArgValue(defaultPort(null, server)); + connectionEndpointListBuilder.addConstructorArgValue(expression); + + return connectionEndpointListBuilder.getBeanDefinition(); + } + /* (non-Javadoc) */ String defaultHost(String host) { return (StringUtils.hasText(host) ? host : DEFAULT_HOST); @@ -164,56 +156,6 @@ class PoolParser extends AbstractSingleBeanDefinitionParser { : String.valueOf(DEFAULT_LOCATOR_PORT))); } - /* (non-Javadoc) */ - List parseConnections(String hostPortCommaDelimitedList, boolean server) { - List connections = Collections.emptyList(); - - if (StringUtils.hasText(hostPortCommaDelimitedList)) { - String[] hostsPorts = hostPortCommaDelimitedList.split(","); - - connections = new ArrayList(hostsPorts.length); - - for (String hostPort : hostsPorts) { - connections.add(parseConnection(hostPort, server)); - } - } - - return connections; - } - - /* (non-Javadoc) */ - BeanDefinition parseConnection(String hostPort, boolean server) { - String host = hostPort.trim(); - String port = defaultPort(null, server); - - int portIndex = host.indexOf('['); - - if (portIndex > -1) { - port = parseDigits(host.substring(portIndex)).trim(); - host = host.substring(0, portIndex).trim(); - } - - return buildConnection(host, port, server); - } - - /* (non-Javadoc) */ - String parseDigits(String value) { - StringBuilder digits = new StringBuilder(); - - for (char character : value.toCharArray()) { - if (Character.isDigit(character)) { - digits.append(character); - } - } - - return digits.toString(); - } - - /* (non-Javadoc) */ - boolean isPropertyPlaceholder(String value) { - return PROPERTY_PLACEHOLDER_PATTERN.matcher(value).matches(); - } - /* (non-Javadoc) */ BeanDefinition parseLocator(Element element) { return buildConnection(element.getAttribute(HOST_ATTRIBUTE_NAME), @@ -221,19 +163,15 @@ class PoolParser extends AbstractSingleBeanDefinitionParser { } /* (non-Javadoc) */ - List parseLocators(Element element, BeanDefinitionBuilder builder) { - List beanDefinitions = Collections.emptyList(); - + boolean parseLocators(Element element, BeanDefinitionBuilder builder) { String locatorsAttributeValue = element.getAttribute(LOCATORS_ATTRIBUTE_NAME); - if (isPropertyPlaceholder(locatorsAttributeValue)) { + if (StringUtils.hasText(locatorsAttributeValue)) { builder.addPropertyValue("locatorEndpointList", buildConnections(locatorsAttributeValue, false)); - } - else { - beanDefinitions = parseConnections(locatorsAttributeValue, false); + return true; } - return beanDefinitions; + return false; } /* (non-Javadoc) */ @@ -243,19 +181,15 @@ class PoolParser extends AbstractSingleBeanDefinitionParser { } /* (non-Javadoc) */ - List parseServers(Element element, BeanDefinitionBuilder builder) { - List beanDefinitions = Collections.emptyList(); - + boolean parseServers(Element element, BeanDefinitionBuilder builder) { String serversAttributeValue = element.getAttribute(SERVERS_ATTRIBUTE_NAME); - if (isPropertyPlaceholder(serversAttributeValue)) { + if (StringUtils.hasText(serversAttributeValue)) { builder.addPropertyValue("serverEndpointList", buildConnections(serversAttributeValue, true)); - } - else { - beanDefinitions = parseConnections(serversAttributeValue, true); + return true; } - return beanDefinitions; + return false; } /* (non-Javadoc) */ @@ -274,5 +208,4 @@ class PoolParser extends AbstractSingleBeanDefinitionParser { return id; } - } diff --git a/src/main/java/org/springframework/data/gemfire/support/ConnectionEndpoint.java b/src/main/java/org/springframework/data/gemfire/support/ConnectionEndpoint.java index 9ea9a8a5..dd2003fc 100644 --- a/src/main/java/org/springframework/data/gemfire/support/ConnectionEndpoint.java +++ b/src/main/java/org/springframework/data/gemfire/support/ConnectionEndpoint.java @@ -18,6 +18,7 @@ package org.springframework.data.gemfire.support; import java.net.InetSocketAddress; +import org.springframework.data.gemfire.util.SpringUtils; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; @@ -126,12 +127,17 @@ public class ConnectionEndpoint implements Cloneable, Comparable= 0 && port <= 65535, String.format("port number (%1$d) must be between 0 and 65535", port)); + Assert.isTrue(isValidPort(port), String.format("port number [%d] must be between 0 and 65535", port)); - this.host = (StringUtils.hasText(host) ? host : DEFAULT_HOST); + this.host = SpringUtils.defaultIfEmpty(host, DEFAULT_HOST); this.port = port; } + /* (non-Javadoc) */ + private boolean isValidPort(int port) { + return (port >= 0 && port <= 65535); + } + /** * Gets the host in this ConnectionEndpoint. * @@ -196,5 +202,4 @@ public class ConnectionEndpoint implements Cloneable, Comparable { * @see org.springframework.data.gemfire.support.ConnectionEndpoint#parse(String, int) */ public static ConnectionEndpointList parse(int defaultPort, String... hostsPorts) { - List connectionEndpoints = new ArrayList(hostsPorts.length); + List connectionEndpoints = new ArrayList( + ArrayUtils.length((Object) hostsPorts)); - for (String hostPort : ArrayUtils.nullSafeArray(hostsPorts)) { + for (String hostPort : ArrayUtils.nullSafeArray(hostsPorts, String.class)) { connectionEndpoints.add(ConnectionEndpoint.parse(hostPort, defaultPort)); } @@ -215,5 +217,4 @@ public class ConnectionEndpointList implements Iterable { 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 7ddc2e4d..703322f5 100644 --- a/src/main/java/org/springframework/data/gemfire/util/ArrayUtils.java +++ b/src/main/java/org/springframework/data/gemfire/util/ArrayUtils.java @@ -1,11 +1,11 @@ /* * Copyright 2002-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. @@ -14,6 +14,7 @@ package org.springframework.data.gemfire.util; import java.lang.reflect.Array; +import java.util.Arrays; /** * The ArrayUtils class is a utility class for working with Object arrays. @@ -24,6 +25,44 @@ import java.lang.reflect.Array; */ public abstract class ArrayUtils { + /** + * Returns the given varargs {@code element} as an array. + * + * @param Class type of the elements. + * @param elements variable list of arguments to return as an array. + * @return an arry for the given varargs {@code elements}. + */ + public static T[] asArray(T... elements) { + return elements; + } + + /** + * Null-safe method to return the first element in the array or {@literal null} + * if the array is {@literal null} or empty. + * + * @param Class type of the array elements. + * @param array the array from which to extract the first element. + * @return the first element in the array or {@literal null} if the array is null or empty. + * @see #getFirst(Object[], Object) + */ + public static T getFirst(T... array) { + return getFirst(array, null); + } + + /** + * Null-safe method to return the first element in the array or the {@code defaultValue} + * if the array is {@literal null} or empty. + * + * @param Class type of the array elements. + * @param array the array from which to extract the first element. + * @param defaultValue value to return if the array is {@literal null} or empty. + * @return the first element in the array or {@code defaultValue} if the array is {@literal null} or empty. + * @see #getFirst(Object[], Object) + */ + public static T getFirst(T[] array, T defaultValue) { + return (isEmpty(array) ? defaultValue : array[0]); + } + /** * Insert an element into the given array at position (index). The element is inserted at the given position * and all elements afterwards are moved to the right. @@ -79,16 +118,18 @@ public abstract class ArrayUtils { } /** - * Null-safe, empty array operation returning the given Object array if not null or an empty Object array + * 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. + * @param Class type of the array elements. + * @param array array of objects on which a null check is performed. + * @param componentType Class type of the array elements. + * @return the given object array if not null, otherwise return an empty object array. + * @see java.lang.reflect.Array#newInstance(Class, int) */ @SuppressWarnings("unchecked") - public static T[] nullSafeArray(T[] array) { - return (array != null ? array : (T[]) new Object[0]); + public static T[] nullSafeArray(T[] array, Class componentType) { + return (array != null ? array : (T[]) Array.newInstance(componentType, 0)); } /** @@ -118,4 +159,16 @@ public abstract class ArrayUtils { return newArray; } + /** + * Sort the array of elements according to the elements natural ordering. + * + * @param {@link Comparable} class type of the array elements. + * @param array array of elements to sort. + * @return the sorted array of elements. + * @see java.util.Arrays#sort(Object[]) + */ + public static > T[] sort(T[] array) { + Arrays.sort(array); + return array; + } } diff --git a/src/main/java/org/springframework/data/gemfire/util/CollectionUtils.java b/src/main/java/org/springframework/data/gemfire/util/CollectionUtils.java index f3f90c37..cb526a6d 100644 --- a/src/main/java/org/springframework/data/gemfire/util/CollectionUtils.java +++ b/src/main/java/org/springframework/data/gemfire/util/CollectionUtils.java @@ -16,11 +16,18 @@ package org.springframework.data.gemfire.util; +import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; +import java.util.HashSet; import java.util.Iterator; +import java.util.List; +import java.util.Map; import java.util.NoSuchElementException; +import java.util.Set; + +import org.springframework.util.Assert; /** * The CollectionUtils class is a utility class for working with Java Collections Framework and classes. @@ -28,12 +35,33 @@ import java.util.NoSuchElementException; * @author John Blum * @see java.util.Collection * @see java.util.Collections +<<<<<<< HEAD +======= + * @see java.util.Enumeration + * @see java.util.Iterator + * @see java.util.List + * @see java.util.Map + * @see java.util.Set +>>>>>>> b7bcabd... SGF-535 - Allow both SpEL and property placeholder expressions to be used in the locators/servers attributes of the XML namespace element. * @see org.springframework.util.CollectionUtils * @since 1.7.0 */ @SuppressWarnings("unused") public abstract class CollectionUtils extends org.springframework.util.CollectionUtils { + /** + * Returns an unmodifiable {@link Set} containing the elements from the given object array. + * + * @param Class type of the elements. + * @param elements array of objects to add to the {@link Set}. + * @return an unmodifiable {@link Set} containing the elements from the given object array. + */ + public static Set asSet(T... elements) { + Set set = new HashSet(elements.length); + Collections.addAll(set, elements); + return Collections.unmodifiableSet(set); + } + /** * Adapts the given Enumeration as an Iterable object for use within a for each loop. * @@ -76,6 +104,7 @@ public abstract class CollectionUtils extends org.springframework.util.Collectio * @param collection the Collection to evaluate for being null. * @return the given Collection if not null, otherwise return an empty Collection (List). * @see java.util.Collections#emptyList() + * @see java.util.Collection */ public static Collection nullSafeCollection(final Collection collection) { return (collection != null ? collection : Collections.emptyList()); @@ -100,15 +129,96 @@ public abstract class CollectionUtils extends org.springframework.util.Collectio } @Override public T next() { - throw new NoSuchElementException("no elements in this Iterator"); + throw new NoSuchElementException("No more elements"); } @Override public void remove() { - throw new UnsupportedOperationException("operation not supported"); + throw new UnsupportedOperationException("Operation not supported"); } }; } }); } + /** + * Null-safe operation returning the given {@link List} if not {@literal null} + * or an empty {@link List} if {@literal null}. + * + * @param Class type of the {@link List} elements. + * @param list {@link List} to evaluate. + * @return the given {@link List} if not null or an empty {@link List}. + * @see java.util.Collections#emptyList() + * @see java.util.List + */ + public static List nullSafeList(List list) { + return (list != null ? list : Collections.emptyList()); + } + + /** + * Null-safe operation returning the given {@link Map} if not {@literal null} + * or an empty {@link Map} if {@literal null}. + * + * @param Class type of the {@link Map Map's} keys. + * @param Class type of the {@link Map Map's} values. + * @param map {@link Map} to evaluate. + * @return the given {@link Map} if not null or an empty {@link Map}. + * @see java.util.Collections#emptyMap() + * @see java.util.Map + */ + public static Map nullSafeMap(Map map) { + return (map != null ? map : Collections.emptyMap()); + } + + /** + * Null-safe operation returning the given {@link Set} if not {@literal null} + * or an empty {@link Set} if {@literal null}. + * + * @param Class type of the {@link Set} elements. + * @param set {@link Set} to evaluate. + * @return the given {@link Set} if not null or an empty {@link Set}. + * @see java.util.Collections#emptySet() + * @see java.util.Set + */ + public static Set nullSafeSet(Set set) { + return (set != null ? set : Collections.emptySet()); + } + + /** + * Sors the elements of the given {@link List} by their natural, {@link Comparable} ordering. + * + * @param {@link Comparable} class type of the collection elements. + * @param list {@link List} of elements to sort. + * @return the {@link List} sorted. + * @see java.util.Collections#sort(List) + * @see java.util.List + */ + public static > List sort(List list) { + Collections.sort(list); + return list; + } + + /** + * Returns a sub-list of elements from the given {@link List} based on the provided {@code indices}. + * + * @param Class type of the elements in the list. + * @param source {@link List} from which the elements of the sub-list is constructed. + * @param indices array of indexes in the {@code source} {@link List} to the elements + * used to construct the sub-list. + * @return a sub-list of elements from the given {@link List} based on the provided {@code indices}. + * @throws IndexOutOfBoundsException if the array of indexes contains an index that is not within + * the bounds of the list. + * @throws NullPointerException if either the list or indexes are null. + * @see java.util.List + */ + public static List subList(List source, int... indices) { + Assert.notNull(source, "List must not be null"); + + List result = new ArrayList(indices.length); + + for (int index : indices) { + result.add(source.get(index)); + } + + return result; + } } diff --git a/src/main/java/org/springframework/data/gemfire/util/SpringUtils.java b/src/main/java/org/springframework/data/gemfire/util/SpringUtils.java new file mode 100644 index 00000000..8a110ce8 --- /dev/null +++ b/src/main/java/org/springframework/data/gemfire/util/SpringUtils.java @@ -0,0 +1,47 @@ +/* + * Copyright 2012 the original author 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.util; + +import org.springframework.beans.factory.BeanFactory; +import org.springframework.util.StringUtils; + +/** + * SpringUtils is a utility class encapsulating common functionality on objects and other class types. + * + * @author John Blum + * @since 1.8.0 + */ +@SuppressWarnings("unused") +// TODO rename this utiltiy class using a more intuitive, meaningful name +public abstract class SpringUtils { + + /* (non-Javadoc) */ + public static String defaultIfEmpty(String value, String defaultValue) { + return (StringUtils.hasText(value) ? value : defaultValue); + } + + /* (non-Javadoc) */ + public static T defaultIfNull(T value, T defaultValue) { + return (value != null ? value : defaultValue); + } + + /* (non-Javadoc) */ + public static String dereferenceBean(String beanName) { + return String.format("%1$s%2$s", BeanFactory.FACTORY_BEAN_PREFIX, beanName); + } +} diff --git a/src/test/java/org/springframework/data/gemfire/RegionFactoryBeanTest.java b/src/test/java/org/springframework/data/gemfire/RegionFactoryBeanTest.java index 4f1e2b11..9c037df9 100644 --- a/src/test/java/org/springframework/data/gemfire/RegionFactoryBeanTest.java +++ b/src/test/java/org/springframework/data/gemfire/RegionFactoryBeanTest.java @@ -34,11 +34,6 @@ import static org.mockito.Mockito.when; import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.After; -import org.junit.Test; -import org.springframework.data.gemfire.support.AbstractRegionFactoryBeanTest; -import org.springframework.data.gemfire.test.support.ArrayUtils; - import com.gemstone.gemfire.cache.Cache; import com.gemstone.gemfire.cache.CustomExpiry; import com.gemstone.gemfire.cache.DataPolicy; @@ -54,6 +49,11 @@ import com.gemstone.gemfire.cache.RegionShortcut; import com.gemstone.gemfire.cache.SubscriptionAttributes; import com.gemstone.gemfire.internal.cache.GemFireCacheImpl; +import org.junit.After; +import org.junit.Test; +import org.springframework.data.gemfire.support.AbstractRegionFactoryBeanTest; +import org.springframework.data.gemfire.util.ArrayUtils; + /** * The RegionFactoryBeanTest class is a test suite of test cases testing the contract and functionality of the * RegionFactoryBean class. diff --git a/src/test/java/org/springframework/data/gemfire/client/ClientCacheFactoryBeanTest.java b/src/test/java/org/springframework/data/gemfire/client/ClientCacheFactoryBeanTest.java index 8455f527..f4337bf2 100644 --- a/src/test/java/org/springframework/data/gemfire/client/ClientCacheFactoryBeanTest.java +++ b/src/test/java/org/springframework/data/gemfire/client/ClientCacheFactoryBeanTest.java @@ -38,12 +38,6 @@ import static org.mockito.Mockito.when; import java.util.Properties; -import org.junit.Test; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.NoSuchBeanDefinitionException; -import org.springframework.context.event.ContextRefreshedEvent; -import org.springframework.data.gemfire.TestUtils; - import com.gemstone.gemfire.cache.CacheClosedException; import com.gemstone.gemfire.cache.GemFireCache; import com.gemstone.gemfire.cache.client.ClientCache; @@ -52,6 +46,12 @@ import com.gemstone.gemfire.cache.client.Pool; import com.gemstone.gemfire.distributed.DistributedSystem; import com.gemstone.gemfire.pdx.PdxSerializer; +import org.junit.Test; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.data.gemfire.TestUtils; + /** * The ClientCacheFactoryBeanTest class is a test suite of test cases testing the contract and functionality * of the SDG ClientCacheFactoryBean class. @@ -570,5 +570,4 @@ public class ClientCacheFactoryBeanTest { public void useClusterConfiguration() { new ClientCacheFactoryBean().setUseClusterConfiguration(true); } - } 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 e6249426..5686f634 100644 --- a/src/test/java/org/springframework/data/gemfire/client/PoolFactoryBeanTest.java +++ b/src/test/java/org/springframework/data/gemfire/client/PoolFactoryBeanTest.java @@ -30,19 +30,18 @@ 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; +import com.gemstone.gemfire.cache.client.Pool; +import com.gemstone.gemfire.cache.client.PoolFactory; + import org.junit.Test; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.data.gemfire.TestUtils; import org.springframework.data.util.ReflectionUtils; -import com.gemstone.gemfire.cache.client.Pool; -import com.gemstone.gemfire.cache.client.PoolFactory; - /** * The PoolFactoryBeanTest class is a test suite of test cases testing the contract and functionality * of the PoolFactoryBean class. @@ -68,6 +67,7 @@ public class PoolFactoryBeanTest { } @Test + @SuppressWarnings("deprecation") public void testAfterPropertiesSet() throws Exception { BeanFactory mockBeanFactory = mock(BeanFactory.class, "MockSpringBeanFactory"); final PoolFactory mockPoolFactory = mock(PoolFactory.class, "MockGemFirePoolFactory"); @@ -139,13 +139,14 @@ public class PoolFactoryBeanTest { verify(mockPoolFactory, times(1)).create(eq("GemFirePool")); } + @SuppressWarnings("deprecation") @Test(expected = IllegalArgumentException.class) public void testAfterPropertiesSetWithNoLocatorsServersSpecified() throws Exception { try { PoolFactoryBean poolFactoryBean = new PoolFactoryBean(); poolFactoryBean.setName("GemFirePool"); - poolFactoryBean.setLocators((Collection) null); + poolFactoryBean.setLocators(null); poolFactoryBean.setServers(Collections.emptyList()); poolFactoryBean.afterPropertiesSet(); } @@ -243,5 +244,4 @@ public class PoolFactoryBeanTest { poolFactoryBean.setPool(null); poolFactoryBean.destroy(); } - } diff --git a/src/test/java/org/springframework/data/gemfire/client/PoolUsingLocatorsAndServersPropertyPlaceholdersTest.java b/src/test/java/org/springframework/data/gemfire/client/PoolUsingLocatorsAndServersPropertyPlaceholdersTest.java deleted file mode 100644 index 4ebdf71c..00000000 --- a/src/test/java/org/springframework/data/gemfire/client/PoolUsingLocatorsAndServersPropertyPlaceholdersTest.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * 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 - protected void resolveDistributedSystem() { - } - } - -} diff --git a/src/test/java/org/springframework/data/gemfire/client/PoolsConfiguredWithLocatorsAndServersExpressionsIntegrationTests.java b/src/test/java/org/springframework/data/gemfire/client/PoolsConfiguredWithLocatorsAndServersExpressionsIntegrationTests.java new file mode 100644 index 00000000..c1f2a97c --- /dev/null +++ b/src/test/java/org/springframework/data/gemfire/client/PoolsConfiguredWithLocatorsAndServersExpressionsIntegrationTests.java @@ -0,0 +1,253 @@ +/* + * 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.assertj.core.api.Assertions.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.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Properties; + +import com.gemstone.gemfire.cache.client.Pool; +import com.gemstone.gemfire.cache.client.PoolFactory; + +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.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +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 org.springframework.util.Assert; + +/** + * The PoolsConfiguredWithLocatorsAndServersExpressionsIntegrationTests class is a test suite of test cases testing the use of + * property placeholder values in the nested <gfe:locator> and <gfe:server> sub-elements + * of the <gfe:pool> element as well as the locators and servers attributes. + * + * @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 + * @see org.springframework.data.gemfire.client.PoolFactoryBean + * @see org.springframework.data.gemfire.config.PoolParser + * @see SGF-433 + * @since 1.6.0 + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration +public class PoolsConfiguredWithLocatorsAndServersExpressionsIntegrationTests { + + private static ConnectionEndpointList anotherLocators = new ConnectionEndpointList(); + private static ConnectionEndpointList anotherServers = new ConnectionEndpointList(); + private static ConnectionEndpointList locators = new ConnectionEndpointList(); + private static ConnectionEndpointList servers = new ConnectionEndpointList(); + + @Autowired + @Qualifier("locatorPool") + @SuppressWarnings("unused") + private Pool locatorPool; + + @Autowired + @Qualifier("serverPool") + @SuppressWarnings("unused") + private Pool serverPool; + + @Autowired + @Qualifier("anotherLocatorPool") + @SuppressWarnings("unused") + private Pool anotherLocatorPool; + + @Autowired + @Qualifier("anotherServerPool") + @SuppressWarnings("unused") + private Pool anotherServerPool; + + protected static ConnectionEndpoint newConnectionEndpoint(String host, int port) { + return new ConnectionEndpoint(host, port); + } + + protected static List toList(Iterable iterable) { + List list = new ArrayList(); + + for (Object element : iterable) { + list.add(String.valueOf(element)); + } + + return list; + } + + protected void assertConnectionEndpoints(Iterable connectionEndpoints, String... expected) { + assertThat(connectionEndpoints).isNotNull(); + + List actual = toList(connectionEndpoints); + + Collections.sort(actual); + + assertThat(actual).isEqualTo(Arrays.asList(expected)); + } + + @Test + public void anotherLocatorPoolFactoryConfiguration() { + String[] expected = { "cardboardbox[10334]", "localhost[10335]", "pobox[10334]", "safetydepositbox[10336]" }; + + assertThat(anotherLocators.size()).isEqualTo(expected.length); + assertConnectionEndpoints(anotherLocators, expected); + } + + @Test + public void anotherServerPoolFactoryConfiguration() { + String[] expected = { "boombox[1234]", "jambox[40404]", "toolbox[8181]" }; + + assertThat(anotherServers.size()).isEqualTo(expected.length); + assertConnectionEndpoints(anotherServers, expected); + } + + @Test + public void locatorPoolFactoryConfiguration() { + String[] expected = { "backspace[10334]", "jambox[11235]", "mars[30303]", "pluto[20668]", "skullbox[12480]" }; + + assertThat(locators.size()).isEqualTo(expected.length); + assertConnectionEndpoints(locators, expected); + } + + @Test + public void serverPoolFactoryConfiguration() { + String[] expected = { "earth[4554]", "jupiter[40404]", "mars[5112]", "mercury[1234]", + "neptune[42424]", "saturn[41414]", "uranis[0]", "venus[9876]" }; + + assertThat(servers.size()).isEqualTo(expected.length); + assertConnectionEndpoints(servers, expected); + } + + public static class TestBeanFactoryPostProcessor implements BeanFactoryPostProcessor { + @Override + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { + BeanDefinition anotherLocatorPoolBeanDefinition = beanFactory.getBeanDefinition("anotherLocatorPool"); + anotherLocatorPoolBeanDefinition.setBeanClassName(AnotherLocatorPoolFactoryBean.class.getName()); + BeanDefinition anotherServerPoolBeanDefinition = beanFactory.getBeanDefinition("anotherServerPool"); + anotherServerPoolBeanDefinition.setBeanClassName(AnotherServerPoolFactoryBean.class.getName()); + BeanDefinition locatorPoolBeanDefinition = beanFactory.getBeanDefinition("locatorPool"); + locatorPoolBeanDefinition.setBeanClassName(LocatorPoolFactoryBean.class.getName()); + BeanDefinition serverPoolBeanDefinition = beanFactory.getBeanDefinition("serverPool"); + serverPoolBeanDefinition.setBeanClassName(ServerPoolFactoryBean.class.getName()); + } + } + + public static class AnotherLocatorPoolFactoryBean extends TestPoolFactoryBean { + @Override ConnectionEndpointList getLocatorList() { + return anotherLocators; + } + } + + public static class AnotherServerPoolFactoryBean extends TestPoolFactoryBean { + @Override ConnectionEndpointList getServerList() { + return anotherServers; + } + } + + public static class LocatorPoolFactoryBean extends TestPoolFactoryBean { + @Override ConnectionEndpointList getLocatorList() { + return locators; + } + } + + public static class ServerPoolFactoryBean extends TestPoolFactoryBean { + @Override ConnectionEndpointList getServerList() { + return servers; + } + } + + @SuppressWarnings("unused") + public static class SpELBoundBean { + + private final Properties clientProperties; + + public SpELBoundBean(Properties clientProperties) { + Assert.notNull(clientProperties, "clientProperties must not be null"); + this.clientProperties = clientProperties; + } + + public String locatorsHostsPorts() { + return "safetydepositbox[10336], pobox"; + } + + public String serverTwoHost() { + return clientProperties.getProperty("gemfire.cache.client.server.2.host"); + } + + public String serverTwoPort() { + return clientProperties.getProperty("gemfire.cache.client.server.2.port"); + } + } + + public static class TestPoolFactoryBean extends PoolFactoryBean { + + ConnectionEndpointList getLocatorList() { + throw new UnsupportedOperationException("Not Implemented"); + } + + ConnectionEndpointList getServerList() { + throw new UnsupportedOperationException("Not Implemented"); + } + + @Override + protected PoolFactory createPoolFactory() { + final PoolFactory mockPoolFactory = mock(PoolFactory.class); + + when(mockPoolFactory.addLocator(anyString(), anyInt())).thenAnswer(new Answer() { + @Override + public PoolFactory answer(InvocationOnMock invocation) throws Throwable { + String host = invocation.getArgumentAt(0, String.class); + int port = invocation.getArgumentAt(1, Integer.class); + getLocatorList().add(newConnectionEndpoint(host, port)); + return mockPoolFactory; + } + }); + + when(mockPoolFactory.addServer(anyString(), anyInt())).thenAnswer(new Answer() { + @Override + public PoolFactory answer(InvocationOnMock invocation) throws Throwable { + String host = invocation.getArgumentAt(0, String.class); + int port = invocation.getArgumentAt(1, Integer.class); + getServerList().add(newConnectionEndpoint(host, port)); + return mockPoolFactory; + } + }); + + return mockPoolFactory; + } + + @Override + protected 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 d5fe1420..2f9da7ee 100644 --- a/src/test/java/org/springframework/data/gemfire/config/PoolNamespaceTest.java +++ b/src/test/java/org/springframework/data/gemfire/config/PoolNamespaceTest.java @@ -16,17 +16,12 @@ 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.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Iterator; +import com.gemstone.gemfire.cache.client.PoolManager; + import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -39,11 +34,16 @@ import org.springframework.data.gemfire.test.GemfireTestApplicationContextInitia import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.gemstone.gemfire.cache.client.PoolManager; - /** + * Integration tests for {@link PoolParser} and {@link PoolFactoryBean}. + * * @author Costin Leau * @author John Blum + * @see org.junit.Test + * @see org.springframework.data.gemfire.client.PoolFactoryBean + * @see org.springframework.data.gemfire.config.PoolParser + * @see org.springframework.data.gemfire.test.GemfireTestApplicationContextInitializer + * @see com.gemstone.gemfire.cache.client.Pool */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations="pool-ns.xml", initializers=GemfireTestApplicationContextInitializer.class) @@ -51,143 +51,150 @@ import com.gemstone.gemfire.cache.client.PoolManager; public class PoolNamespaceTest { @Autowired - private ApplicationContext context; + private ApplicationContext applicationContext; - 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))); + protected void assertConnectionEndpoint(ConnectionEndpointList connectionEndpoints, + String expectedHost, int expectedPort) { + + assertThat(connectionEndpoints).isNotNull(); + assertThat(connectionEndpoints.size()).isEqualTo(1); + assertConnectionEndpoint(connectionEndpoints.iterator().next(), expectedHost, expectedPort); + } + + protected void assertConnectionEndpoint(ConnectionEndpoint connectionEndpoint, + String expectedHost, int expectedPort) { + + assertThat(connectionEndpoint).isNotNull(); + assertThat(connectionEndpoint.getHost()).isEqualTo(expectedHost); + assertThat(connectionEndpoint.getPort()).isEqualTo(expectedPort); + } + + protected void assertNoConnectionEndpoints(ConnectionEndpointList connectionEndpoints) { + assertThat(connectionEndpoints).isNotNull(); + assertThat(connectionEndpoints.isEmpty()).isTrue(); } @Test - public void testBasicClient() throws Exception { - 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")))); + public void gemfirePoolIsConfiguredProperly() throws Exception { + assertThat(applicationContext.containsBean("DEFAULT")).isTrue(); + assertThat(applicationContext.containsBean("gemfirePool")).isTrue(); + assertThat(applicationContext.containsBean("gemfire-pool")).isTrue(); + assertThat(PoolManager.find("DEFAULT")).isEqualTo(applicationContext.getBean("gemfirePool")); - PoolFactoryBean poolFactoryBean = context.getBean("&gemfirePool", PoolFactoryBean.class); + PoolFactoryBean poolFactoryBean = applicationContext.getBean("&gemfirePool", PoolFactoryBean.class); ConnectionEndpointList locators = TestUtils.readField("locators", poolFactoryBean); - assertThat(locators, is(notNullValue())); - assertThat(locators.size(), is(equalTo(1))); - - assertConnectionEndpoint(locators.iterator().next(), "localhost", 40403); + assertConnectionEndpoint(locators, "localhost", 40403); } @Test - public void testSimplePool() throws Exception { - assertThat(context.containsBean("simple"), is(true)); + public void simplePoolIsConfiguredProperly() throws Exception { + assertThat(applicationContext.containsBean("simple")).isTrue(); - PoolFactoryBean poolFactoryBean = context.getBean("&simple", PoolFactoryBean.class); + PoolFactoryBean poolFactoryBean = applicationContext.getBean("&simple", PoolFactoryBean.class); ConnectionEndpointList locators = TestUtils.readField("locators", poolFactoryBean); - assertThat(locators, is(notNullValue())); - assertThat(locators.size(), is(equalTo(1))); - - assertConnectionEndpoint(locators.iterator().next(), PoolParser.DEFAULT_HOST, PoolParser.DEFAULT_LOCATOR_PORT); + assertNoConnectionEndpoints(locators); ConnectionEndpointList servers = TestUtils.readField("servers", poolFactoryBean); - assertThat(servers, is(notNullValue())); - assertThat(servers.isEmpty(), is(true)); + assertConnectionEndpoint(servers, PoolParser.DEFAULT_HOST, PoolParser.DEFAULT_SERVER_PORT); } @Test - public void testLocatorPool() throws Exception { - assertThat(context.containsBean("locator"), is(true)); + public void locatorPoolIsConfiguredProperly() throws Exception { + assertThat(applicationContext.containsBean("locator")).isTrue(); - PoolFactoryBean poolFactoryBean = context.getBean("&locator", PoolFactoryBean.class); + PoolFactoryBean poolFactoryBean = applicationContext.getBean("&locator", PoolFactoryBean.class); ConnectionEndpointList locators = TestUtils.readField("locators", poolFactoryBean); - assertThat(locators, is(notNullValue())); - assertThat(locators.size(), is(equalTo(2))); + assertThat(locators).isNotNull(); + assertThat(locators.size()).isEqualTo(2); Iterator it = locators.iterator(); assertConnectionEndpoint(it.next(), "skullbox", PoolParser.DEFAULT_LOCATOR_PORT); - assertConnectionEndpoint(it.next(), "yorktown", 12480); + assertConnectionEndpoint(it.next(), "ghostrider", 12480); ConnectionEndpointList servers = TestUtils.readField("servers", poolFactoryBean); - assertThat(servers, is(notNullValue())); + assertNoConnectionEndpoints(servers); } @Test - public void testComplexPool() throws Exception { - assertTrue(context.containsBean("complex")); + public void serverPoolIsConfiguredProperly() throws Exception { + assertThat(applicationContext.containsBean("server")).isTrue(); - PoolFactoryBean poolFactoryBean = context.getBean("&complex", PoolFactoryBean.class); + PoolFactoryBean poolFactoryBean = applicationContext.getBean("&server", PoolFactoryBean.class); - assertEquals(2000, TestUtils.readField("freeConnectionTimeout", poolFactoryBean)); - assertEquals(20000l, TestUtils.readField("idleTimeout", poolFactoryBean)); - assertEquals(10000, TestUtils.readField("loadConditioningInterval", 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)); - assertTrue((Boolean) TestUtils.readField("multiUserAuthentication", poolFactoryBean)); - assertEquals(5000l, TestUtils.readField("pingInterval", 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)); - assertEquals(65536, TestUtils.readField("socketBufferSize", poolFactoryBean)); - assertEquals(5000, TestUtils.readField("statisticInterval", poolFactoryBean)); - assertEquals(250, TestUtils.readField("subscriptionAckInterval", poolFactoryBean)); - assertTrue((Boolean) TestUtils.readField("subscriptionEnabled", poolFactoryBean)); - assertEquals(30000, TestUtils.readField("subscriptionMessageTrackingTimeout", poolFactoryBean)); - assertEquals(2, TestUtils.readField("subscriptionRedundancy", poolFactoryBean)); - assertTrue((Boolean) TestUtils.readField("threadLocalConnections", poolFactoryBean)); + assertThat(TestUtils.readField("freeConnectionTimeout", poolFactoryBean)).isEqualTo(2000); + assertThat(TestUtils.readField("idleTimeout", poolFactoryBean)).isEqualTo(20000L); + assertThat(TestUtils.readField("loadConditioningInterval", poolFactoryBean)).isEqualTo(10000); + assertThat(Boolean.TRUE.equals(TestUtils.readField("keepAlive", poolFactoryBean))).isTrue(); + assertThat(TestUtils.readField("maxConnections", poolFactoryBean)).isEqualTo(100); + assertThat(TestUtils.readField("minConnections", poolFactoryBean)).isEqualTo(5); + assertThat((Boolean) TestUtils.readField("multiUserAuthentication", poolFactoryBean)).isTrue(); + assertThat(TestUtils.readField("pingInterval", poolFactoryBean)).isEqualTo(5000L); + assertThat((Boolean) TestUtils.readField("prSingleHopEnabled", poolFactoryBean)).isFalse(); + assertThat(TestUtils.readField("readTimeout", poolFactoryBean)).isEqualTo(500); + assertThat(TestUtils.readField("retryAttempts", poolFactoryBean)).isEqualTo(5); + assertThat(TestUtils.readField("serverGroup", poolFactoryBean)).isEqualTo("TestGroup"); + assertThat(TestUtils.readField("socketBufferSize", poolFactoryBean)).isEqualTo(65536); + assertThat(TestUtils.readField("statisticInterval", poolFactoryBean)).isEqualTo(250); + assertThat(TestUtils.readField("subscriptionAckInterval", poolFactoryBean)).isEqualTo(250); + assertThat((Boolean) TestUtils.readField("subscriptionEnabled", poolFactoryBean)).isTrue(); + assertThat(TestUtils.readField("subscriptionMessageTrackingTimeout", poolFactoryBean)).isEqualTo(30000); + assertThat(TestUtils.readField("subscriptionRedundancy", poolFactoryBean)).isEqualTo(2); + assertThat((Boolean) TestUtils.readField("threadLocalConnections", poolFactoryBean)).isFalse(); ConnectionEndpointList servers = TestUtils.readField("servers", poolFactoryBean); - assertNotNull(servers); - assertEquals(2, servers.size()); + assertThat(servers).isNotNull(); + assertThat(servers.size()).isEqualTo(2); Iterator serversIterator = servers.iterator(); assertConnectionEndpoint(serversIterator.next(), "localhost", 40404); - assertConnectionEndpoint(serversIterator.next(), "localhost", 40405); + assertConnectionEndpoint(serversIterator.next(), "localhost", 50505); } @Test - public void testComboLocatorPool() throws Exception { - assertThat(context.containsBean("combo-locators"), is(true)); + public void locatorsPoolIsConfiguredProperly() throws Exception { + assertThat(applicationContext.containsBean("locators")).isTrue(); - PoolFactoryBean poolFactoryBean = context.getBean("&combo-locators", PoolFactoryBean.class); + PoolFactoryBean poolFactoryBean = applicationContext.getBean("&locators", PoolFactoryBean.class); ConnectionEndpointList locators = TestUtils.readField("locators", poolFactoryBean); - assertThat(locators, is(notNullValue())); - assertThat(locators.size(), is(equalTo(3))); + assertThat(locators).isNotNull(); + assertThat(locators.size()).isEqualTo(4); Iterator locatorIterator = locators.iterator(); - assertConnectionEndpoint(locatorIterator.next(), "foobar", 55421); - assertConnectionEndpoint(locatorIterator.next(), "lavatube", 11235); - assertConnectionEndpoint(locatorIterator.next(), "zod", 10334); + assertConnectionEndpoint(locatorIterator.next(), "venus", 11235); + assertConnectionEndpoint(locatorIterator.next(), "mars", 10334); + assertConnectionEndpoint(locatorIterator.next(), "localhost", 12480); + assertConnectionEndpoint(locatorIterator.next(), "earth", 54321); } @Test - public void testComboServerPool() throws Exception { - assertThat(context.containsBean("combo-servers"), is(true)); + public void serversPoolIsConfiguredProperly() throws Exception { + assertThat(applicationContext.containsBean("servers")).isTrue(); - PoolFactoryBean poolFactoryBean = context.getBean("&combo-servers", PoolFactoryBean.class); + PoolFactoryBean poolFactoryBean = applicationContext.getBean("&servers", PoolFactoryBean.class); ConnectionEndpointList servers = TestUtils.readField("servers", poolFactoryBean); - assertThat(servers, is(notNullValue())); - assertThat(servers.size(), is(equalTo(3))); + assertThat(servers).isNotNull(); + assertThat(servers.size()).isEqualTo(3); Iterator serverIterator = servers.iterator(); - assertConnectionEndpoint(serverIterator.next(), "scorch", 21480); - assertConnectionEndpoint(serverIterator.next(), "scorn", 51515); assertConnectionEndpoint(serverIterator.next(), "skullbox", 9110); + assertConnectionEndpoint(serverIterator.next(), "duke", 21480); + assertConnectionEndpoint(serverIterator.next(), "nukem", 51515); } - } diff --git a/src/test/java/org/springframework/data/gemfire/config/PoolParserTest.java b/src/test/java/org/springframework/data/gemfire/config/PoolParserTest.java deleted file mode 100644 index a901d4ab..00000000 --- a/src/test/java/org/springframework/data/gemfire/config/PoolParserTest.java +++ /dev/null @@ -1,550 +0,0 @@ -/* - * 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.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.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; - -/** - * The PoolParserTest class is a test suite of test cases testing the contract and functionality - * of the PoolParser class. - * - * @author John Blum - * @see org.junit.Test - * @see org.mockito.Mockito - * @see org.springframework.data.gemfire.config.PoolParser - * @since 1.7.0 - */ -public class PoolParserTest { - - private PoolParser parser = new PoolParser(); - - protected void assertBeanDefinition(BeanDefinition beanDefinition, String expectedHost, String expectedPort) { - 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 - @SuppressWarnings("unchecked") - public void getBeanClass() { - assertThat((Class) parser.getBeanClass(null), is(equalTo(PoolFactoryBean.class))); - } - - @Test - @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 defaultHost() { - assertEquals("skullbox", parser.defaultHost("skullbox")); - assertEquals("localhost", parser.defaultHost(null)); - assertEquals("localhost", parser.defaultHost("")); - assertEquals("localhost", parser.defaultHost(" ")); - } - - @Test - 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)); - assertEquals(String.valueOf(PoolParser.DEFAULT_LOCATOR_PORT), parser.defaultPort("", false)); - assertEquals(String.valueOf(PoolParser.DEFAULT_SERVER_PORT), parser.defaultPort(" ", true)); - } - - @Test - public void parseConnection() { - assertBeanDefinition(parser.parseConnection("skullbox[1234]", true), "skullbox", "1234"); - assertBeanDefinition(parser.parseConnection("saturn", true), "saturn", - String.valueOf(PoolParser.DEFAULT_SERVER_PORT)); - assertBeanDefinition(parser.parseConnection("neptune[]", false), "neptune", - String.valueOf(PoolParser.DEFAULT_LOCATOR_PORT)); - assertBeanDefinition(parser.parseConnection("[9876]", true), PoolParser.DEFAULT_HOST, "9876"); - assertBeanDefinition(parser.parseConnection("[]", false), PoolParser.DEFAULT_HOST, - String.valueOf(PoolParser.DEFAULT_LOCATOR_PORT)); - } - - @Test - public void parseSingleConnection() { - List beans = parser.parseConnections("skullbox[1234]", true); - - assertNotNull(beans); - assertFalse(beans.isEmpty()); - assertEquals(1, beans.size()); - assertBeanDefinition(beans.get(0), "skullbox", "1234"); - } - - @Test - public void parseMultipleConnections() { - List beans = parser.parseConnections( - "skullbox[1234],neptune,saturn[ ],jupiter[SlO], [9876],v3nU5[4_567], localhost [1 01 0] ", true); - - assertNotNull(beans); - assertFalse(beans.isEmpty()); - assertEquals(7, beans.size()); - assertBeanDefinition(beans.get(0), "skullbox", "1234"); - assertBeanDefinition(beans.get(1), "neptune", String.valueOf(PoolParser.DEFAULT_SERVER_PORT)); - assertBeanDefinition(beans.get(2), "saturn", String.valueOf(PoolParser.DEFAULT_SERVER_PORT)); - assertBeanDefinition(beans.get(3), "jupiter", String.valueOf(PoolParser.DEFAULT_SERVER_PORT)); - assertBeanDefinition(beans.get(4), "localhost", "9876"); - assertBeanDefinition(beans.get(5), "v3nU5", "4567"); - assertBeanDefinition(beans.get(6), "localhost", "1010"); - } - - @Test - public void parseDigits() { - assertEquals("1234", parser.parseDigits("1234")); - assertEquals("4567", parser.parseDigits(" 4567 ")); - assertEquals("78901", parser.parseDigits("7 89 0 1 ")); - assertEquals("8080", parser.parseDigits("[8080]")); - assertEquals("443", parser.parseDigits(":443")); - assertEquals("", parser.parseDigits("")); - assertEquals("", parser.parseDigits(" ")); - assertEquals("", parser.parseDigits("[]")); - assertEquals("", parser.parseDigits("oneTwoThree")); - } - - @Test - 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 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], [9876] "); - - List locators = parser.parseLocators(mockElement, null); - - 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 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 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]"); - - List servers = parser.parseServers(mockElement, null); - - assertNotNull(servers); - assertFalse(servers.isEmpty()); - assertEquals(2, servers.size()); - assertBeanDefinition(servers.get(0), "neptune", String.valueOf(PoolParser.DEFAULT_SERVER_PORT)); - assertBeanDefinition(servers.get(1), "venus", "9876"); - } - - @Test - public void parseServersWithPropertyPlaceholder() { - Element mockElement = mock(Element.class, "testParseServersWithPropertyPlaceholder.Element"); - - when(mockElement.getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME))).thenReturn( - "${gemfire.servers.hosts-and-ports}"); - - BeanDefinitionBuilder serversBuilder = BeanDefinitionBuilder.genericBeanDefinition( - parser.getBeanClass(mockElement)); - - List servers = parser.parseServers(mockElement, serversBuilder); - - assertThat(servers, is(notNullValue())); - assertThat(servers.isEmpty(), is(true)); - - BeanDefinition serverDefinition = (BeanDefinition) serversBuilder.getBeanDefinition() - .getPropertyValues().getPropertyValue("serverEndpointList").getValue(); - - 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}"))); - - verify(mockElement, times(1)).getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME)); - } - -} diff --git a/src/test/java/org/springframework/data/gemfire/config/PoolParserUnitTests.java b/src/test/java/org/springframework/data/gemfire/config/PoolParserUnitTests.java new file mode 100644 index 00000000..84a01ecd --- /dev/null +++ b/src/test/java/org/springframework/data/gemfire/config/PoolParserUnitTests.java @@ -0,0 +1,509 @@ +/* + * 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.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Matchers.anyInt; +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 org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.ConstructorArgumentValues; +import org.springframework.beans.factory.support.BeanDefinitionBuilder; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +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; + +/** + * Unit tests for {@link PoolParser}. + * + * @author John Blum + * @see org.junit.Test + * @see org.mockito.Mock + * @see org.mockito.Mockito + * @see org.mockito.runners.MockitoJUnitRunner + * @see org.springframework.data.gemfire.config.PoolParser + * @since 1.7.0 + */ +@RunWith(MockitoJUnitRunner.class) +public class PoolParserUnitTests { + + @Mock + private BeanDefinitionRegistry mockRegistry; + + private PoolParser parser = new PoolParser(); + + protected void assertConnectionEndpointBeanDefinition(BeanDefinition beanDefinition, + String expectedHost, String expectedPort) { + + assertThat(beanDefinition).isNotNull(); + assertThat(beanDefinition.getBeanClassName()).isEqualTo(ConnectionEndpoint.class.getName()); + assertThat(beanDefinition.getConstructorArgumentValues().getArgumentCount()).isEqualTo(2); + assertThat(beanDefinition.getConstructorArgumentValues().getArgumentValue(0, String.class).getValue()) + .isEqualTo(expectedHost); + assertThat(beanDefinition.getConstructorArgumentValues().getArgumentValue(1, String.class).getValue()) + .isEqualTo(expectedPort); + } + + protected void assertConnectionEndpointListBeanDefinition(BeanDefinition beanDefinition, + String expectedHost, int expectedPort) { + + assertThat(beanDefinition).isNotNull(); + assertThat(beanDefinition.getBeanClassName()).isEqualTo(ConnectionEndpointList.class.getName()); + assertThat(beanDefinition.getFactoryMethodName()).isEqualTo("parse"); + assertConstructorArgumentValues(beanDefinition, String.valueOf(expectedPort), expectedHost); + } + + protected void assertConstructorArgumentValues(BeanDefinition beanDefinition, Object... values) { + ConstructorArgumentValues constructorArgumentValues = beanDefinition.getConstructorArgumentValues(); + + assertThat(constructorArgumentValues.getArgumentCount()).isEqualTo(values.length); + + int index = 0; + + for (Object value : values) { + assertThat(constructorArgumentValues.getArgumentValue(index++, value.getClass()).getValue()) + .isEqualTo(value); + } + + assertThat(index).isEqualTo(values.length); + } + + protected void assertPropertyNotPresent(BeanDefinition beanDefinition, String propertyName) { + assertThat(beanDefinition.getPropertyValues().contains(propertyName)).isFalse(); + } + + protected void assertPropertyPresent(BeanDefinition beanDefinition, String propertyName) { + assertThat(beanDefinition.getPropertyValues().contains(propertyName)).isTrue(); + } + + protected void assertPropertyValue(BeanDefinition beanDefinition, String propertyName, Object propertyValue) { + assertThat(beanDefinition.getPropertyValues().getPropertyValue(propertyName).getValue()) + .isEqualTo(propertyValue); + } + + @SuppressWarnings("unchecked") + protected T getPropertyValue(BeanDefinition beanDefinition, String propertyName) { + return (T) beanDefinition.getPropertyValues().getPropertyValue(propertyName).getValue(); + } + + @Test + public void getBeanClassIsEqualToPoolFactoryBeanClass() { + assertThat(parser.getBeanClass(null)).isEqualTo(PoolFactoryBean.class); + } + + @Test + public void doParse() { + Element mockPoolElement = mock(Element.class, "testDoParse.MockPoolElement"); + Element mockLocatorElementOne = mock(Element.class, "testDoParse.MockLocatorElementOne"); + Element mockLocatorElementTwo = mock(Element.class, "testDoParse.MockLocatorElementTwo"); + Element mockServerElement = mock(Element.class, "testDoParse.MockServerElement"); + + NodeList mockNodeList = mock(NodeList.class); + + when(mockPoolElement.getAttribute(eq("free-connection-timeout"))).thenReturn("5000"); + when(mockPoolElement.getAttribute(eq("idle-timeout"))).thenReturn("120000"); + when(mockPoolElement.getAttribute(eq("keep-alive"))).thenReturn("true"); + when(mockPoolElement.getAttribute(eq("load-conditioning-interval"))).thenReturn("300000"); + when(mockPoolElement.getAttribute(eq("max-connections"))).thenReturn("500"); + when(mockPoolElement.getAttribute(eq("min-connections"))).thenReturn("50"); + when(mockPoolElement.getAttribute(eq("multi-user-authentication"))).thenReturn("true"); + when(mockPoolElement.getAttribute(eq("ping-interval"))).thenReturn("15000"); + when(mockPoolElement.getAttribute(eq("pr-single-hop-enabled"))).thenReturn("true"); + when(mockPoolElement.getAttribute(eq("read-timeout"))).thenReturn("20000"); + when(mockPoolElement.getAttribute(eq("retry-attempts"))).thenReturn("1"); + when(mockPoolElement.getAttribute(eq("server-group"))).thenReturn("TestGroup"); + when(mockPoolElement.getAttribute(eq("socket-buffer-size"))).thenReturn("16384"); + when(mockPoolElement.getAttribute(eq("statistic-interval"))).thenReturn("500"); + when(mockPoolElement.getAttribute(eq("subscription-ack-interval"))).thenReturn("200"); + when(mockPoolElement.getAttribute(eq("subscription-enabled"))).thenReturn("true"); + when(mockPoolElement.getAttribute(eq("subscription-message-tracking-timeout"))).thenReturn("30000"); + when(mockPoolElement.getAttribute(eq("subscription-redundancy"))).thenReturn("2"); + when(mockPoolElement.getAttribute(eq("thread-local-connections"))).thenReturn("false"); + when(mockPoolElement.getAttribute(PoolParser.LOCATORS_ATTRIBUTE_NAME)).thenReturn(null); + when(mockPoolElement.getAttribute(PoolParser.SERVERS_ATTRIBUTE_NAME)).thenReturn(null); + when(mockPoolElement.getChildNodes()).thenReturn(mockNodeList); + when(mockNodeList.getLength()).thenReturn(3); + when(mockNodeList.item(eq(0))).thenReturn(mockLocatorElementOne); + when(mockNodeList.item(eq(1))).thenReturn(mockServerElement); + when(mockNodeList.item(eq(2))).thenReturn(mockLocatorElementTwo); + when(mockLocatorElementOne.getLocalName()).thenReturn(PoolParser.LOCATOR_ELEMENT_NAME); + when(mockLocatorElementOne.getAttribute(PoolParser.HOST_ATTRIBUTE_NAME)).thenReturn("venus"); + when(mockLocatorElementOne.getAttribute(PoolParser.PORT_ATTRIBUTE_NAME)).thenReturn("1025"); + when(mockLocatorElementTwo.getLocalName()).thenReturn(PoolParser.LOCATOR_ELEMENT_NAME); + when(mockLocatorElementTwo.getAttribute(PoolParser.HOST_ATTRIBUTE_NAME)).thenReturn("mars"); + when(mockLocatorElementTwo.getAttribute(PoolParser.PORT_ATTRIBUTE_NAME)).thenReturn(" "); + when(mockServerElement.getLocalName()).thenReturn(PoolParser.SERVER_ELEMENT_NAME); + when(mockServerElement.getAttribute(PoolParser.HOST_ATTRIBUTE_NAME)).thenReturn("skullbox"); + when(mockServerElement.getAttribute(PoolParser.PORT_ATTRIBUTE_NAME)).thenReturn("65535"); + + BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition( + parser.getBeanClass(mockPoolElement)); + + parser.doParse(mockPoolElement, null, builder); + + BeanDefinition poolDefinition = builder.getBeanDefinition(); + + assertThat(poolDefinition).isNotNull(); + + assertPropertyValue(poolDefinition, "freeConnectionTimeout", "5000"); + assertPropertyValue(poolDefinition, "idleTimeout", "120000"); + assertPropertyValue(poolDefinition, "keepAlive", "true"); + assertPropertyValue(poolDefinition, "loadConditioningInterval", "300000"); + assertPropertyValue(poolDefinition, "maxConnections", "500"); + assertPropertyValue(poolDefinition, "minConnections", "50"); + assertPropertyValue(poolDefinition, "multiUserAuthentication", "true"); + assertPropertyValue(poolDefinition, "pingInterval", "15000"); + assertPropertyValue(poolDefinition, "prSingleHopEnabled", "true"); + assertPropertyValue(poolDefinition, "readTimeout", "20000"); + assertPropertyValue(poolDefinition, "retryAttempts", "1"); + assertPropertyValue(poolDefinition, "serverGroup", "TestGroup"); + assertPropertyValue(poolDefinition, "socketBufferSize", "16384"); + assertPropertyValue(poolDefinition, "statisticInterval", "500"); + assertPropertyValue(poolDefinition, "subscriptionAckInterval", "200"); + assertPropertyValue(poolDefinition, "subscriptionEnabled", "true"); + assertPropertyValue(poolDefinition, "subscriptionMessageTrackingTimeout", "30000"); + assertPropertyValue(poolDefinition, "subscriptionRedundancy", "2"); + assertPropertyValue(poolDefinition, "threadLocalConnections", "false"); + assertPropertyPresent(poolDefinition, "locatorEndpoints"); + assertPropertyPresent(poolDefinition, "serverEndpoints"); + + ManagedList locators = getPropertyValue(poolDefinition, "locatorEndpoints"); + + assertThat(locators).isNotNull(); + assertThat(locators.size()).isEqualTo(2); + assertConnectionEndpointBeanDefinition(locators.get(0), "venus", "1025"); + assertConnectionEndpointBeanDefinition(locators.get(1), "mars", String.valueOf(PoolParser.DEFAULT_LOCATOR_PORT)); + + ManagedList servers = getPropertyValue(poolDefinition, "serverEndpoints"); + + assertThat(servers).isNotNull(); + assertThat(servers.size()).isEqualTo(1); + assertConnectionEndpointBeanDefinition(servers.get(0), "skullbox", "65535"); + + verify(mockPoolElement, times(1)).getAttribute(eq("free-connection-timeout")); + verify(mockPoolElement, times(1)).getAttribute(eq("idle-timeout")); + verify(mockPoolElement, times(1)).getAttribute(eq("keep-alive")); + verify(mockPoolElement, times(1)).getAttribute(eq("load-conditioning-interval")); + verify(mockPoolElement, times(1)).getAttribute(eq("max-connections")); + verify(mockPoolElement, times(1)).getAttribute(eq("min-connections")); + verify(mockPoolElement, times(1)).getAttribute(eq("multi-user-authentication")); + verify(mockPoolElement, times(1)).getAttribute(eq("ping-interval")); + verify(mockPoolElement, times(1)).getAttribute(eq("pr-single-hop-enabled")); + verify(mockPoolElement, times(1)).getAttribute(eq("read-timeout")); + verify(mockPoolElement, times(1)).getAttribute(eq("retry-attempts")); + verify(mockPoolElement, times(1)).getAttribute(eq("server-group")); + verify(mockPoolElement, times(1)).getAttribute(eq("socket-buffer-size")); + verify(mockPoolElement, times(1)).getAttribute(eq("statistic-interval")); + verify(mockPoolElement, times(1)).getAttribute(eq("subscription-ack-interval")); + verify(mockPoolElement, times(1)).getAttribute(eq("subscription-enabled")); + verify(mockPoolElement, times(1)).getAttribute(eq("subscription-message-tracking-timeout")); + verify(mockPoolElement, times(1)).getAttribute(eq("subscription-redundancy")); + verify(mockPoolElement, times(1)).getAttribute(eq("thread-local-connections")); + 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, times(1)).getAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME)); + verify(mockPoolElement, times(1)).getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME)); + verify(mockLocatorElementOne, times(1)).getLocalName(); + verify(mockLocatorElementOne, times(1)).getAttribute(PoolParser.HOST_ATTRIBUTE_NAME); + verify(mockLocatorElementOne, times(1)).getAttribute(PoolParser.PORT_ATTRIBUTE_NAME); + verify(mockLocatorElementTwo, times(1)).getLocalName(); + verify(mockLocatorElementTwo, times(1)).getAttribute(PoolParser.HOST_ATTRIBUTE_NAME); + verify(mockLocatorElementTwo, 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 + public void doParseWithNoLocatorsAndNoServersConfigured() { + Element mockPoolElement = mock(Element.class); + NodeList mockNodeList = mock(NodeList.class); + + when(mockPoolElement.getAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME))).thenReturn(""); + when(mockPoolElement.getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME))).thenReturn(" "); + when(mockPoolElement.getChildNodes()).thenReturn(mockNodeList); + when(mockNodeList.getLength()).thenReturn(0); + + BeanDefinitionBuilder poolBuilder = BeanDefinitionBuilder.genericBeanDefinition( + parser.getBeanClass(mockPoolElement)); + + parser.doParse(mockPoolElement, null, poolBuilder); + + BeanDefinition poolDefinition = poolBuilder.getBeanDefinition(); + + assertThat(poolDefinition).isNotNull(); + assertPropertyNotPresent(poolDefinition, "locatorEndpoints"); + assertPropertyPresent(poolDefinition, "serverEndpoints"); + + ManagedList servers = getPropertyValue(poolDefinition, "serverEndpoints"); + + assertThat(servers).isNotNull(); + assertThat(servers.size()).isEqualTo(1); + + assertConnectionEndpointBeanDefinition(servers.get(0), PoolParser.DEFAULT_HOST, + String.valueOf(PoolParser.DEFAULT_SERVER_PORT)); + + verify(mockPoolElement, times(1)).getChildNodes(); + verify(mockNodeList, times(1)).getLength(); + verify(mockNodeList, never()).item(anyInt()); + verify(mockPoolElement, times(1)).getAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME)); + verify(mockPoolElement, times(1)).getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME)); + } + + @Test + public void doParseWithLocatorsAttributeConfiguredAsSpELExpression() { + Element mockPoolElement = mock(Element.class); + NodeList mockNodeList = mock(NodeList.class); + + when(mockPoolElement.getAttribute(PoolParser.ID_ATTRIBUTE)).thenReturn("TestPool"); + when(mockPoolElement.getAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME))).thenReturn( + "#{T(example.app.config.GemFireProperties).locatorHostsPorts()}"); + when(mockPoolElement.getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME))).thenReturn(""); + when(mockPoolElement.getChildNodes()).thenReturn(mockNodeList); + when(mockNodeList.getLength()).thenReturn(0); + + BeanDefinitionBuilder poolBuilder = BeanDefinitionBuilder.genericBeanDefinition( + parser.getBeanClass(mockPoolElement)); + + parser.doParse(mockPoolElement, null, poolBuilder); + + BeanDefinition poolBean = poolBuilder.getBeanDefinition(); + + assertPropertyNotPresent(poolBean, "locatorEndpoints"); + assertPropertyNotPresent(poolBean, "serverEndpoints"); + assertPropertyPresent(poolBean, "locatorEndpointList"); + assertConnectionEndpointListBeanDefinition(this.getPropertyValue(poolBean, + "locatorEndpointList"), "#{T(example.app.config.GemFireProperties).locatorHostsPorts()}", + PoolParser.DEFAULT_LOCATOR_PORT); + + verify(mockPoolElement, times(1)).getAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME)); + verify(mockPoolElement, times(1)).getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME)); + verify(mockPoolElement, times(1)).getChildNodes(); + verify(mockNodeList, times(1)).getLength(); + verify(mockNodeList, never()).item(anyInt()); + } + + @Test + public void doParseWithServersAttributeConfiguredAsPropertyPlaceholder() { + Element mockPoolElement = mock(Element.class); + NodeList mockNodeList = mock(NodeList.class); + + when(mockPoolElement.getAttribute(PoolParser.ID_ATTRIBUTE)).thenReturn("TestPool"); + when(mockPoolElement.getAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME))).thenReturn(""); + when(mockPoolElement.getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME))).thenReturn( + "${gemfire.server.hosts-and-ports}"); + when(mockPoolElement.getChildNodes()).thenReturn(mockNodeList); + when(mockNodeList.getLength()).thenReturn(0); + + BeanDefinitionBuilder poolBuilder = BeanDefinitionBuilder.genericBeanDefinition( + parser.getBeanClass(mockPoolElement)); + + parser.doParse(mockPoolElement, null, poolBuilder); + + BeanDefinition poolBean = poolBuilder.getBeanDefinition(); + + assertPropertyNotPresent(poolBean, "locatorEndpoints"); + assertPropertyNotPresent(poolBean, "serverEndpoints"); + assertPropertyPresent(poolBean, "serverEndpointList"); + assertConnectionEndpointListBeanDefinition(this.getPropertyValue(poolBean, + "serverEndpointList"), "${gemfire.server.hosts-and-ports}", PoolParser.DEFAULT_SERVER_PORT); + + verify(mockPoolElement, times(1)).getAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME)); + verify(mockPoolElement, times(1)).getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME)); + verify(mockPoolElement, times(1)).getChildNodes(); + verify(mockNodeList, times(1)).getLength(); + verify(mockNodeList, never()).item(anyInt()); + } + + @Test + public void buildConnection() { + assertConnectionEndpointBeanDefinition(parser.buildConnection("earth", "1234", true), "earth", "1234"); + assertConnectionEndpointBeanDefinition(parser.buildConnection("mars", " ", true), + "mars", String.valueOf(PoolParser.DEFAULT_SERVER_PORT)); + assertConnectionEndpointBeanDefinition(parser.buildConnection(" ", "1234", true), + PoolParser.DEFAULT_HOST, "1234"); + assertConnectionEndpointBeanDefinition(parser.buildConnection(" ", "", true), + PoolParser.DEFAULT_HOST, String.valueOf(PoolParser.DEFAULT_SERVER_PORT)); + assertConnectionEndpointBeanDefinition(parser.buildConnection("jupiter", "9876", false), "jupiter", "9876"); + assertConnectionEndpointBeanDefinition(parser.buildConnection("saturn", null, false), + "saturn", String.valueOf(PoolParser.DEFAULT_LOCATOR_PORT)); + assertConnectionEndpointBeanDefinition(parser.buildConnection(null, "9876", false), + PoolParser.DEFAULT_HOST, "9876"); + assertConnectionEndpointBeanDefinition(parser.buildConnection("", " ", false), + PoolParser.DEFAULT_HOST, String.valueOf(PoolParser.DEFAULT_LOCATOR_PORT)); + } + + @Test + public void buildConnectionsUsingLocator() { + BeanDefinition beanDefinition = parser.buildConnections("${locators}", false); + + assertThat(beanDefinition).isNotNull(); + assertThat(beanDefinition.getBeanClassName()).isEqualTo(ConnectionEndpointList.class.getName()); + + ConstructorArgumentValues constructorArguments = beanDefinition.getConstructorArgumentValues(); + + assertThat(constructorArguments).isNotNull(); + assertThat(constructorArguments.getArgumentCount()).isEqualTo(2); + assertThat(constructorArguments.getArgumentValue(0, Integer.class).getValue()) + .isEqualTo(String.valueOf(PoolParser.DEFAULT_LOCATOR_PORT)); + assertThat(constructorArguments.getArgumentValue(1, String.class).getValue()).isEqualTo("${locators}"); + } + + @Test + public void buildConnectionsUsingServer() { + BeanDefinition beanDefinition = parser.buildConnections("#{servers}", true); + + assertThat(beanDefinition).isNotNull(); + assertThat(beanDefinition.getBeanClassName()).isEqualTo(ConnectionEndpointList.class.getName()); + + ConstructorArgumentValues constructorArguments = beanDefinition.getConstructorArgumentValues(); + + assertThat(constructorArguments).isNotNull(); + assertThat(constructorArguments.getArgumentCount()).isEqualTo(2); + assertThat(constructorArguments.getArgumentValue(0, Integer.class).getValue()) + .isEqualTo(String.valueOf(PoolParser.DEFAULT_SERVER_PORT)); + assertThat(constructorArguments.getArgumentValue(1, String.class).getValue()).isEqualTo("#{servers}"); + } + + @Test + public void defaultHost() { + assertThat(parser.defaultHost("skullbox")).isEqualTo("skullbox"); + assertThat(parser.defaultHost(" ")).isEqualTo("localhost"); + assertThat(parser.defaultHost("")).isEqualTo("localhost"); + assertThat(parser.defaultHost(null)).isEqualTo("localhost"); + } + + @Test + public void defaultPort() { + assertThat(parser.defaultPort("1234", true)).isEqualTo("1234"); + assertThat(parser.defaultPort("9876", false)).isEqualTo("9876"); + assertThat(parser.defaultPort(" ", true)).isEqualTo(String.valueOf(PoolParser.DEFAULT_SERVER_PORT)); + assertThat(parser.defaultPort("", false)).isEqualTo(String.valueOf(PoolParser.DEFAULT_LOCATOR_PORT)); + assertThat(parser.defaultPort(null, true)).isEqualTo(String.valueOf(PoolParser.DEFAULT_SERVER_PORT)); + } + + @Test + public void parseLocator() { + Element mockElement = mock(Element.class); + + when(mockElement.getAttribute(eq(PoolParser.HOST_ATTRIBUTE_NAME))).thenReturn("skullbox"); + when(mockElement.getAttribute(eq(PoolParser.PORT_ATTRIBUTE_NAME))).thenReturn("1234"); + + assertConnectionEndpointBeanDefinition(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 parseLocatorWithNoHostPort() { + Element mockElement = mock(Element.class); + + when(mockElement.getAttribute(PoolParser.HOST_ATTRIBUTE_NAME)).thenReturn(""); + when(mockElement.getAttribute(PoolParser.PORT_ATTRIBUTE_NAME)).thenReturn(null); + + assertConnectionEndpointBeanDefinition(parser.parseLocator(mockElement), PoolParser.DEFAULT_HOST, + String.valueOf(PoolParser.DEFAULT_LOCATOR_PORT)); + + 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); + + when(mockElement.getAttribute(eq(PoolParser.ID_ATTRIBUTE))).thenReturn("TestPool"); + when(mockElement.getAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME))).thenReturn( + "jupiter, saturn[1234], [9876] "); + + BeanDefinitionBuilder poolBuilder = BeanDefinitionBuilder.genericBeanDefinition(parser.getBeanClass(mockElement)); + + assertThat(parser.parseLocators(mockElement, poolBuilder)).isTrue(); + + BeanDefinition poolBean = poolBuilder.getBeanDefinition(); + + assertPropertyPresent(poolBean, "locatorEndpointList"); + assertConnectionEndpointListBeanDefinition(this.getPropertyValue(poolBean, + "locatorEndpointList"), "jupiter, saturn[1234], [9876] ", PoolParser.DEFAULT_LOCATOR_PORT); + + verify(mockElement, times(1)).getAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME)); + } + + @Test + public void parseServer() { + Element mockElement = mock(Element.class); + + when(mockElement.getAttribute(eq(PoolParser.HOST_ATTRIBUTE_NAME))).thenReturn("pluto"); + when(mockElement.getAttribute(eq(PoolParser.PORT_ATTRIBUTE_NAME))).thenReturn("9876"); + + assertConnectionEndpointBeanDefinition(parser.parseServer(mockElement), "pluto", "9876"); + + verify(mockElement, times(1)).getAttribute(eq(PoolParser.HOST_ATTRIBUTE_NAME)); + verify(mockElement, times(1)).getAttribute(eq(PoolParser.PORT_ATTRIBUTE_NAME)); + } + + @Test + public void parseServerWithNoHostPort() { + Element mockElement = mock(Element.class); + + when(mockElement.getAttribute(eq(PoolParser.HOST_ATTRIBUTE_NAME))).thenReturn(" "); + when(mockElement.getAttribute(eq(PoolParser.PORT_ATTRIBUTE_NAME))).thenReturn(""); + + assertConnectionEndpointBeanDefinition(parser.parseServer(mockElement), PoolParser.DEFAULT_HOST, + String.valueOf(PoolParser.DEFAULT_SERVER_PORT)); + + 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); + + when(mockElement.getAttribute(eq(PoolParser.ID_ATTRIBUTE))).thenReturn("TestPool"); + when(mockElement.getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME))).thenReturn("mars[], venus[9876]"); + + BeanDefinitionBuilder poolBuilder = BeanDefinitionBuilder.genericBeanDefinition(parser.getBeanClass(mockElement)); + + assertThat(parser.parseServers(mockElement, poolBuilder)).isTrue(); + + BeanDefinition poolBean = poolBuilder.getBeanDefinition(); + + assertPropertyPresent(poolBean, "serverEndpointList"); + assertConnectionEndpointListBeanDefinition(this.getPropertyValue(poolBean, + "serverEndpointList"), "mars[], venus[9876]", PoolParser.DEFAULT_SERVER_PORT); + + verify(mockElement, times(1)).getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME)); + } +} diff --git a/src/test/java/org/springframework/data/gemfire/repository/support/SimpleGemfireRepositoryUnitTest.java b/src/test/java/org/springframework/data/gemfire/repository/support/SimpleGemfireRepositoryUnitTest.java index 52501cf1..50d2b2d1 100644 --- a/src/test/java/org/springframework/data/gemfire/repository/support/SimpleGemfireRepositoryUnitTest.java +++ b/src/test/java/org/springframework/data/gemfire/repository/support/SimpleGemfireRepositoryUnitTest.java @@ -40,21 +40,21 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; +import com.gemstone.gemfire.cache.Cache; +import com.gemstone.gemfire.cache.CacheTransactionManager; +import com.gemstone.gemfire.cache.DataPolicy; +import com.gemstone.gemfire.cache.Region; +import com.gemstone.gemfire.cache.RegionAttributes; + import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.springframework.data.gemfire.GemfireTemplate; import org.springframework.data.gemfire.repository.Wrapper; import org.springframework.data.gemfire.repository.sample.Animal; -import org.springframework.data.gemfire.test.support.CollectionUtils; +import org.springframework.data.gemfire.util.CollectionUtils; import org.springframework.data.repository.core.EntityInformation; -import com.gemstone.gemfire.cache.Cache; -import com.gemstone.gemfire.cache.CacheTransactionManager; -import com.gemstone.gemfire.cache.DataPolicy; -import com.gemstone.gemfire.cache.Region; -import com.gemstone.gemfire.cache.RegionAttributes; - /** * The SimpleGemfireRepositoryUnitTest class is a test suite of test cases testing the contract and functionality * of the SimpleGemfireRepository class. @@ -390,5 +390,4 @@ public class SimpleGemfireRepositoryUnitTest { verify(mockRegion, times(0)).clear(); verify(mockRegion, times(1)).removeAll(eq(keys)); } - } diff --git a/src/test/java/org/springframework/data/gemfire/support/ConnectionEndpointTest.java b/src/test/java/org/springframework/data/gemfire/support/ConnectionEndpointTest.java index 7f57c124..a2ca36b1 100644 --- a/src/test/java/org/springframework/data/gemfire/support/ConnectionEndpointTest.java +++ b/src/test/java/org/springframework/data/gemfire/support/ConnectionEndpointTest.java @@ -45,7 +45,7 @@ import org.junit.rules.ExpectedException; public class ConnectionEndpointTest { @Rule - public ExpectedException expectedException = ExpectedException.none(); + public ExpectedException exception = ExpectedException.none(); @Test public void fromInetSocketAddress() { @@ -150,33 +150,34 @@ public class ConnectionEndpointTest { @Test public void parseWithBlankHost() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectCause(is(nullValue(Throwable.class))); - expectedException.expectMessage("'hostPort' must be specified"); + exception.expect(IllegalArgumentException.class); + exception.expectCause(is(nullValue(Throwable.class))); + exception.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"); + exception.expect(IllegalArgumentException.class); + exception.expectCause(is(nullValue(Throwable.class))); + exception.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"); + exception.expect(IllegalArgumentException.class); + exception.expectCause(is(nullValue(Throwable.class))); + exception.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"); + exception.expect(IllegalArgumentException.class); + exception.expectCause(is(nullValue(Throwable.class))); + exception.expectMessage("port number [-1248] must be between 0 and 65535"); + ConnectionEndpoint.parse("localhost", -1248); } @@ -217,9 +218,10 @@ public class ConnectionEndpointTest { @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"); + exception.expect(IllegalArgumentException.class); + exception.expectCause(is(nullValue(Throwable.class))); + exception.expectMessage("port number [-1] must be between 0 and 65535"); + new ConnectionEndpoint("localhost", -1); } @@ -252,5 +254,4 @@ public class ConnectionEndpointTest { assertThat(connectionEndpointThree.compareTo(connectionEndpointTwo), is(greaterThan(0))); assertThat(connectionEndpointThree.compareTo(connectionEndpointThree), is(equalTo(0))); } - } diff --git a/src/test/java/org/springframework/data/gemfire/test/support/ArrayUtils.java b/src/test/java/org/springframework/data/gemfire/test/support/ArrayUtils.java deleted file mode 100644 index 5d28a671..00000000 --- a/src/test/java/org/springframework/data/gemfire/test/support/ArrayUtils.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * 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.test.support; - -/** - * ArrayUtils is a utility class for working with Java arrays. - * - * @author John Blum - * @see org.springframework.data.gemfire.util.ArrayUtils - * @since 1.6.0 - */ -@SuppressWarnings("unused") -// TODO replace with org.springframework.data.gemfire.util.ArrayUtils -public class ArrayUtils extends org.springframework.data.gemfire.util.ArrayUtils { - - public static T getFirst(T... array) { - return getFirst(array, null); - } - - public static T getFirst(T[] array, T defaultValue) { - return (isEmpty(array) ? defaultValue : array[0]); - } - -} diff --git a/src/test/java/org/springframework/data/gemfire/test/support/CollectionUtils.java b/src/test/java/org/springframework/data/gemfire/test/support/CollectionUtils.java deleted file mode 100644 index dae2b3a2..00000000 --- a/src/test/java/org/springframework/data/gemfire/test/support/CollectionUtils.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * 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.test.support; - -import java.util.ArrayList; -import java.util.List; - -/** - * The CollectionUtils class is a utility class for working with the Java Collections Framework. - * - * @author John Blum - * @see java.util.Collection - * @see java.util.Collections - * @see org.springframework.data.gemfire.util.CollectionUtils - * @since 1.5.0 - */ -@SuppressWarnings("unused") -public abstract class CollectionUtils extends org.springframework.data.gemfire.util.CollectionUtils { - - public static List subList(final List source, final int... indices) { - List result = new ArrayList(indices.length); - for (int index : indices) { - result.add(source.get(index)); - } - return result; - } - -} diff --git a/src/test/java/org/springframework/data/gemfire/test/support/ZipUtils.java b/src/test/java/org/springframework/data/gemfire/test/support/ZipUtils.java index f0d01b67..865ba173 100644 --- a/src/test/java/org/springframework/data/gemfire/test/support/ZipUtils.java +++ b/src/test/java/org/springframework/data/gemfire/test/support/ZipUtils.java @@ -25,6 +25,7 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.springframework.core.io.Resource; +import org.springframework.data.gemfire.util.CollectionUtils; import org.springframework.util.Assert; import org.springframework.util.FileCopyUtils; @@ -66,5 +67,4 @@ public abstract class ZipUtils { } } } - } diff --git a/src/test/java/org/springframework/data/gemfire/util/ArrayUtilsTest.java b/src/test/java/org/springframework/data/gemfire/util/ArrayUtilsTest.java deleted file mode 100644 index 3e43802b..00000000 --- a/src/test/java/org/springframework/data/gemfire/util/ArrayUtilsTest.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * 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.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; - -import org.junit.Test; - -/** - * The ArrayUtilsTest class is a test suite of test cases testing the contract and functionality - * of the ArrayUtils class. - * - * @author John Blum - * @see java.util.Arrays - * @see org.junit.Test - * @see org.springframework.data.gemfire.util.ArrayUtils - * @since 1.7.0 - */ -public class ArrayUtilsTest { - - @Test - public void insertAtBeginning() { - Object[] originalArray = { "testing", "tested" }; - Object[] newArray = ArrayUtils.insert(originalArray, 0, "test"); - - assertNotSame(originalArray, newArray); - assertFalse(Arrays.equals(originalArray, newArray)); - assertEquals("test", newArray[0]); - assertEquals("testing", newArray[1]); - assertEquals("tested", newArray[2]); - } - - @Test - public void insertInMiddle() { - Object[] originalArray = { "test", "tested" }; - Object[] newArray = ArrayUtils.insert(originalArray, 1, "testing"); - - assertNotSame(originalArray, newArray); - assertFalse(Arrays.equals(originalArray, newArray)); - assertEquals("test", newArray[0]); - assertEquals("testing", newArray[1]); - assertEquals("tested", newArray[2]); - } - - @Test - public void insertAtEnd() { - Object[] originalArray = { "test", "testing" }; - Object[] newArray = ArrayUtils.insert(originalArray, 2, "tested"); - - assertNotSame(originalArray, newArray); - assertFalse(Arrays.equals(originalArray, newArray)); - assertEquals("test", newArray[0]); - assertEquals("testing", newArray[1]); - assertEquals("tested", newArray[2]); - } - - @Test - public void isEmpty() { - assertFalse(ArrayUtils.isEmpty("test", "testing", "tested")); - assertFalse(ArrayUtils.isEmpty("test")); - assertFalse(ArrayUtils.isEmpty("")); - assertFalse(ArrayUtils.isEmpty(null, null, null)); - assertTrue(ArrayUtils.isEmpty()); - assertTrue(ArrayUtils.isEmpty((Object[]) null)); - } - - @Test - public void length() { - assertEquals(3, ArrayUtils.length("test", "testing", "tested")); - assertEquals(1, ArrayUtils.length("test")); - assertEquals(1, ArrayUtils.length("")); - assertEquals(3, ArrayUtils.length(null, null, null)); - assertEquals(0, ArrayUtils.length()); - assertEquals(0, ArrayUtils.length((Object[]) null)); - } - - @Test - 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); - - assertNotSame(originalArray, newArray); - assertFalse(Arrays.equals(originalArray, newArray)); - assertEquals("testing", newArray[0]); - assertEquals("tested", newArray[1]); - } - - @Test - public void removeFromMiddle() { - Object[] originalArray = { "test", "testing", "tested" }; - Object[] newArray = ArrayUtils.remove(originalArray, 1); - - assertNotSame(originalArray, newArray); - assertFalse(Arrays.equals(originalArray, newArray)); - assertEquals("test", newArray[0]); - assertEquals("tested", newArray[1]); - } - - @Test - public void removeFromEnd() { - Object[] originalArray = { "test", "testing", "tested" }; - Object[] newArray = ArrayUtils.remove(originalArray, 2); - - assertNotSame(originalArray, newArray); - assertFalse(Arrays.equals(originalArray, newArray)); - assertEquals("test", newArray[0]); - assertEquals("testing", newArray[1]); - } - -} diff --git a/src/test/java/org/springframework/data/gemfire/util/ArrayUtilsUnitTests.java b/src/test/java/org/springframework/data/gemfire/util/ArrayUtilsUnitTests.java new file mode 100644 index 00000000..0d0a8d83 --- /dev/null +++ b/src/test/java/org/springframework/data/gemfire/util/ArrayUtilsUnitTests.java @@ -0,0 +1,197 @@ +/* + * 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.util; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; + +import org.junit.Test; + +/** + * Unit tests for {@link ArrayUtils}. + * + * @author John Blum + * @see org.junit.Test + * @see org.springframework.data.gemfire.util.ArrayUtils + * @since 1.7.0 + */ +public class ArrayUtilsUnitTests { + + @Test + public void asArrayRetursEmptyArray() { + Object[] array = ArrayUtils.asArray(); + + assertThat(array).isNotNull(); + assertThat(array.length).isEqualTo(0); + } + + @Test + public void asArrayReturnsMultiElementArray() { + Object[] array = ArrayUtils.asArray(1, 2, 3); + + assertThat(array).isNotNull(); + assertThat(array.length).isEqualTo(3); + assertThat(array).isEqualTo(new Object[] { 1, 2, 3 }); + } + + @Test + public void asArrayReturnsSingleElementArray() { + Object[] array = ArrayUtils.asArray(1); + + assertThat(array).isNotNull(); + assertThat(array.length).isEqualTo(1); + assertThat(array).isEqualTo(new Object[] { 1 }); + } + + @Test + public void getFirstWithNonNullArray() { + assertThat(ArrayUtils.getFirst(1, 2, 3)).isEqualTo(1); + } + + @Test + public void getFirstWithNullOrEmptyArrayAndNoDefaultReturnsNull() { + assertThat(ArrayUtils.getFirst((Object[]) null)).isNull(); + assertThat(ArrayUtils.getFirst()).isNull(); + } + + @Test + public void getFirstWithNullOrEmptyArrayAndDefaultReturnsDefault() { + assertThat(ArrayUtils.getFirst((Object[]) null, "test")).isEqualTo("test"); + assertThat(ArrayUtils.getFirst(new Object[0], "test")).isEqualTo("test"); + } + + @Test + public void insertAtBeginning() { + Object[] originalArray = { "testing", "tested" }; + Object[] newArray = ArrayUtils.insert(originalArray, 0, "test"); + + assertThat(newArray).isNotSameAs(originalArray); + assertThat(Arrays.equals(originalArray, newArray)).isFalse(); + assertThat(newArray).isEqualTo(new Object[] { "test", "testing", "tested" }); + } + + @Test + public void insertInMiddle() { + Object[] originalArray = { "test", "tested" }; + Object[] newArray = ArrayUtils.insert(originalArray, 1, "testing"); + + assertThat(newArray).isNotSameAs(originalArray); + assertThat(Arrays.equals(originalArray, newArray)).isFalse(); + assertThat(newArray).isEqualTo(new Object[] { "test", "testing", "tested" }); + } + + @Test + public void insertAtEnd() { + Object[] originalArray = { "test", "testing" }; + Object[] newArray = ArrayUtils.insert(originalArray, 2, "tested"); + + assertThat(newArray).isNotSameAs(originalArray); + assertThat(Arrays.equals(originalArray, newArray)).isFalse(); + assertThat(newArray).isEqualTo(new Object[] { "test", "testing", "tested" }); + } + + @Test + public void isEmptyIsFalse() { + assertThat(ArrayUtils.isEmpty("test", "testing", "tested")).isFalse(); + assertThat(ArrayUtils.isEmpty("test")).isFalse(); + assertThat(ArrayUtils.isEmpty("")).isFalse(); + assertThat(ArrayUtils.isEmpty(null, null, null)).isFalse(); + } + + @Test + public void isEmptyIsTrue() { + assertThat(ArrayUtils.isEmpty()).isTrue(); + assertThat(ArrayUtils.isEmpty((Object[]) null)).isTrue(); + } + + @Test + public void length() { + assertThat(ArrayUtils.length("test", "testing", "tested")).isEqualTo(3); + assertThat(ArrayUtils.length("test")).isEqualTo(1); + assertThat(ArrayUtils.length("")).isEqualTo(1); + assertThat(ArrayUtils.length(null, null, null)).isEqualTo(3); + assertThat(ArrayUtils.length()).isEqualTo(0); + assertThat(ArrayUtils.length((Object[]) null)).isEqualTo(0); + } + + @Test + public void nullSafeArrayWithNonNullArray() { + String[] stringArray = { "test", "testing", "tested" }; + + assertThat(ArrayUtils.nullSafeArray(stringArray, String.class)).isSameAs(stringArray); + + Integer[] numberArray = { 1, 2, 3 }; + + assertThat(ArrayUtils.nullSafeArray(numberArray, Integer.class)).isSameAs(numberArray); + + Double[] emptyDoubleArray = {}; + + assertThat(ArrayUtils.nullSafeArray(emptyDoubleArray, Double.class)).isSameAs(emptyDoubleArray); + + Character[] characterArray = { 'A', 'B', 'C' }; + + assertThat(ArrayUtils.nullSafeArray(characterArray, Character.class)).isSameAs(characterArray); + } + + @Test + public void nullSafeArrayWithNullArray() { + Object array = ArrayUtils.nullSafeArray(null, String.class); + + assertThat(array).isInstanceOf(String[].class); + assertThat(((String[]) array).length).isEqualTo(0); + } + + @Test + public void removeFromBeginning() { + Object[] originalArray = { "test", "testing", "tested" }; + Object[] newArray = ArrayUtils.remove(originalArray, 0); + + assertThat(newArray).isNotSameAs(originalArray); + assertThat(Arrays.equals(newArray, originalArray)).isFalse(); + assertThat(newArray).isEqualTo(new Object[] { "testing", "tested" }); + } + + @Test + public void removeFromMiddle() { + Object[] originalArray = { "test", "testing", "tested" }; + Object[] newArray = ArrayUtils.remove(originalArray, 1); + + assertThat(newArray).isNotSameAs(originalArray); + assertThat(Arrays.equals(newArray, originalArray)).isFalse(); + assertThat(newArray).isEqualTo(new Object[] { "test", "tested" }); + } + + @Test + public void removeFromEnd() { + Object[] originalArray = { "test", "testing", "tested" }; + Object[] newArray = ArrayUtils.remove(originalArray, 2); + + assertThat(newArray).isNotSameAs(originalArray); + assertThat(Arrays.equals(newArray, originalArray)).isFalse(); + assertThat(newArray).isEqualTo(new Object[] { "test", "testing" }); + } + + @Test + public void sortIsSuccessful() { + Comparable[] array = new Comparable[] { 2, 3, 1 }; + Comparable[] sortedArray = ArrayUtils.sort(array); + + assertThat(sortedArray).isSameAs(array); + assertThat(sortedArray).isEqualTo(new Comparable[] { 1, 2, 3 }); + } +} diff --git a/src/test/java/org/springframework/data/gemfire/util/CollectionUtilsTest.java b/src/test/java/org/springframework/data/gemfire/util/CollectionUtilsTest.java deleted file mode 100644 index 28f07e51..00000000 --- a/src/test/java/org/springframework/data/gemfire/util/CollectionUtilsTest.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * 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.util; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.CoreMatchers.sameInstance; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; - -import org.junit.Test; - -/** - * The CollectionUtilsTest class is a test suite of test cases testing the contract and functionality - * of the CollectionUtils class. - * - * @author John Blum - * @see java.util.Collection - * @see java.util.Enumeration - * @see java.util.Iterator - * @see org.junit.Test - * @see org.mockito.Mockito - * @see org.springframework.data.gemfire.util.CollectionUtils - * @since 1.7.0 - */ -public class CollectionUtilsTest { - - @Test - @SuppressWarnings("unchecked") - public void iterableEnumeration() { - Enumeration mockEnumeration = mock(Enumeration.class, "MockEnumeration"); - - when(mockEnumeration.hasMoreElements()).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false); - when(mockEnumeration.nextElement()).thenReturn("zero").thenReturn("one").thenReturn("two") - .thenThrow(new NoSuchElementException("Enumeration exhausted")); - - Iterable iterable = CollectionUtils.iterable(mockEnumeration); - - assertThat(iterable, is(notNullValue())); - - List actualList = new ArrayList(3); - - for (String element : iterable) { - actualList.add(element); - } - - assertThat(actualList, is(equalTo(Arrays.asList("zero", "one", "two")))); - - verify(mockEnumeration, times(4)).hasMoreElements(); - verify(mockEnumeration, times(3)).nextElement(); - } - - @Test - @SuppressWarnings("unchecked") - public void iterableIterator() { - Iterator mockIterator = mock(Iterator.class, "MockIterator"); - - when(mockIterator.hasNext()).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false); - when(mockIterator.next()).thenReturn("zero").thenReturn("one").thenReturn("two") - .thenThrow(new NoSuchElementException("Iterator exhausted")); - - Iterable iterable = CollectionUtils.iterable(mockIterator); - - assertThat(iterable, is(notNullValue())); - - List actualList = new ArrayList(3); - - for (String element : iterable) { - actualList.add(element); - } - - assertThat(actualList, is(equalTo(Arrays.asList("zero", "one", "two")))); - - verify(mockIterator, times(4)).hasNext(); - verify(mockIterator, times(3)).next(); - } - - @Test - public void nullSafeCollectionWithNonNullCollection() { - List mockList = mock(List.class); - - assertSame(mockList, CollectionUtils.nullSafeCollection(mockList)); - } - - @Test - public void nullSafeCollectionWithNullCollection() { - Collection collection = CollectionUtils.nullSafeCollection(null); - - assertNotNull(collection); - assertTrue(collection.isEmpty()); - } - - @Test - @SuppressWarnings("unchecked") - public void nullSafeIterableWithNonNullIterable() { - Iterable mockIterable = mock(Iterable.class); - - assertThat(CollectionUtils.nullSafeIterable(mockIterable), is(sameInstance(mockIterable))); - } - - @Test - public void nullSafeIterableWithNullIterable() { - Iterable iterable = CollectionUtils.nullSafeIterable(null); - - assertThat(iterable, is(not(nullValue()))); - assertThat(iterable.iterator(), is(not(nullValue()))); - } - - @Test(expected = UnsupportedOperationException.class) - public void nullSafeIterableIterator() { - Iterator iterator = CollectionUtils.nullSafeIterable(null).iterator(); - - assertThat(iterator, is(not(nullValue()))); - assertThat(iterator.hasNext(), is(equalTo(false))); - - try { - iterator.next(); - } - catch (NoSuchElementException ignore) { - assertThat(ignore.getMessage(), is(equalTo("no elements in this Iterator"))); - assertThat(ignore.getCause(), is(nullValue())); - - try { - iterator.remove(); - } - catch (UnsupportedOperationException expected) { - assertThat(expected.getMessage(), is(equalTo("operation not supported"))); - assertThat(expected.getCause(), is(nullValue())); - throw expected; - } - } - } - -} diff --git a/src/test/java/org/springframework/data/gemfire/util/CollectionUtilsUnitTests.java b/src/test/java/org/springframework/data/gemfire/util/CollectionUtilsUnitTests.java new file mode 100644 index 00000000..3e4ceeab --- /dev/null +++ b/src/test/java/org/springframework/data/gemfire/util/CollectionUtilsUnitTests.java @@ -0,0 +1,310 @@ +/* + * 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.util; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Enumeration; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Set; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +/** +<<<<<<< HEAD:src/test/java/org/springframework/data/gemfire/util/CollectionUtilsTest.java + * The CollectionUtilsTest class is a test suite of test cases testing the contract and functionality + * of the CollectionUtils class. + * + * @author John Blum + * @see java.util.Collection + * @see java.util.Enumeration + * @see java.util.Iterator +======= + * Unit tests for {@link CollectionUtils}. + * + * @author John Blum + * @see java.util.Collection + * @see java.util.Collections + * @see java.util.Enumeration + * @see java.util.Iterator + * @see java.util.List + * @see java.util.Map + * @see java.util.Set +>>>>>>> b7bcabd... SGF-535 - Allow both SpEL and property placeholder expressions to be used in the locators/servers attributes of the XML namespace element.:src/test/java/org/springframework/data/gemfire/util/CollectionUtilsUnitTests.java + * @see org.junit.Test + * @see org.mockito.Mockito + * @see org.springframework.data.gemfire.util.CollectionUtils + * @since 1.7.0 + */ +public class CollectionUtilsUnitTests { + + @Rule + public ExpectedException exception = ExpectedException.none(); + + @Test + public void asSetContainsAllArrayElements() { + Object[] elements = { "a", "b", "c" }; + + Set set = CollectionUtils.asSet(elements); + + assertThat(set).isNotNull(); + assertThat(set.size()).isEqualTo(elements.length); + assertThat(set).containsAll(Arrays.asList(elements)); + } + + @Test + public void asSetContainsUniqueArrayElements() { + Object[] elements = { 1, 2, 1 }; + + Set set = CollectionUtils.asSet(elements); + + assertThat(set).isNotNull(); + assertThat(set.size()).isEqualTo(2); + assertThat(set).containsAll(Arrays.asList(elements)); + } + + @Test(expected = UnsupportedOperationException.class) + public void asSetReturnsUnmodifiableSet() { + Set set = CollectionUtils.asSet(1, 2, 3); + + assertThat(set).isNotNull(); + assertThat(set.size()).isEqualTo(3); + + try { + set.add(4); + set.remove(1); + set.remove(2); + } + catch (UnsupportedOperationException e) { + assertThat(set.size()).isEqualTo(3); + throw e; + } + } + + @Test + @SuppressWarnings("unchecked") + public void iterableEnumeration() { + Enumeration mockEnumeration = mock(Enumeration.class, "MockEnumeration"); + + when(mockEnumeration.hasMoreElements()).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false); + when(mockEnumeration.nextElement()).thenReturn("zero").thenReturn("one").thenReturn("two") + .thenThrow(new NoSuchElementException("Enumeration exhausted")); + + Iterable iterable = CollectionUtils.iterable(mockEnumeration); + + assertThat(iterable).isNotNull(); + + List actualList = new ArrayList(3); + + for (String element : iterable) { + actualList.add(element); + } + + assertThat(actualList).isEqualTo(Arrays.asList("zero", "one", "two")); + + verify(mockEnumeration, times(4)).hasMoreElements(); + verify(mockEnumeration, times(3)).nextElement(); + } + + @Test + @SuppressWarnings("unchecked") + public void iterableIterator() { + Iterator mockIterator = mock(Iterator.class, "MockIterator"); + + when(mockIterator.hasNext()).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false); + when(mockIterator.next()).thenReturn("zero").thenReturn("one").thenReturn("two") + .thenThrow(new NoSuchElementException("Iterator exhausted")); + + Iterable iterable = CollectionUtils.iterable(mockIterator); + + assertThat(iterable).isNotNull(); + + List actualList = new ArrayList(3); + + for (String element : iterable) { + actualList.add(element); + } + + assertThat(actualList).containsAll(Arrays.asList("zero", "one", "two")); + + verify(mockIterator, times(4)).hasNext(); + verify(mockIterator, times(3)).next(); + } + + @Test + public void nullSafeCollectionWithNonNullCollection() { + Collection mockCollection = mock(Collection.class); + + assertThat(CollectionUtils.nullSafeCollection(mockCollection)).isSameAs(mockCollection); + } + + @Test + public void nullSafeCollectionWithNullCollection() { + Collection collection = CollectionUtils.nullSafeCollection(null); + + assertThat(collection).isNotNull(); + assertThat(collection.isEmpty()).isTrue(); + } + + @Test + @SuppressWarnings("unchecked") + public void nullSafeIterableWithNonNullIterable() { + Iterable mockIterable = mock(Iterable.class); + + assertThat(CollectionUtils.nullSafeIterable(mockIterable)).isSameAs(mockIterable); + } + + @Test + public void nullSafeIterableWithNullIterable() { + Iterable iterable = CollectionUtils.nullSafeIterable(null); + + assertThat(iterable).isNotNull(); + assertThat(iterable.iterator()).isNotNull(); + assertThat(iterable.iterator().hasNext()).isFalse(); + } + + @Test(expected = UnsupportedOperationException.class) + public void nullSafeIterableIterator() { + Iterable iterable = CollectionUtils.nullSafeIterable(null); + + assertThat(iterable).isNotNull(); + + Iterator iterator = iterable.iterator(); + + assertThat(iterator).isNotNull(); + assertThat(iterator.hasNext()).isFalse(); + + try { + iterator.next(); + } + catch (NoSuchElementException ignore) { + assertThat(ignore.getMessage()).isEqualTo("No more elements"); + assertThat(ignore.getCause()).isNull(); + + try { + iterator.remove(); + } + catch (UnsupportedOperationException expected) { + assertThat(expected.getMessage()).isEqualTo("Operation not supported"); + assertThat(expected.getCause()).isNull(); + + throw expected; + } + } + } + + @Test + public void nullSafeListWithNonNullList() { + List mockList = mock(List.class); + + assertThat(CollectionUtils.nullSafeList(mockList)).isSameAs(mockList); + } + + @Test + public void nullSafeListWithNullList() { + List list = CollectionUtils.nullSafeList(null); + + assertThat(list).isNotNull(); + assertThat(list.isEmpty()).isTrue(); + } + + @Test + public void nullSafeMapWithNonNullMap() { + Map mockMap = mock(Map.class); + + assertThat(CollectionUtils.nullSafeMap(mockMap)).isSameAs(mockMap); + } + + @Test + public void nullSafeMapWithNullMap() { + Map map = CollectionUtils.nullSafeMap(null); + + assertThat(map).isNotNull(); + assertThat(map.isEmpty()).isTrue(); + } + + @Test + public void nullSafeSetWithNonNullSet() { + Set mockSet = mock(Set.class); + + assertThat(CollectionUtils.nullSafeSet(mockSet)).isSameAs(mockSet); + } + + @Test + public void nullSafeSetWithNullSet() { + Set set = CollectionUtils.nullSafeSet(null); + + assertThat(set).isNotNull(); + assertThat(set.isEmpty()).isTrue(); + } + + @Test + public void sortIsSuccessful() { + List list = new ArrayList(Arrays.asList(2, 3, 1)); + List sortedList = CollectionUtils.sort(list); + + assertThat(sortedList).isSameAs(list); + assertThat(sortedList).isEqualTo(Arrays.asList(1, 2, 3)); + } + + @Test + public void subListFromListWithIndexesReturnsSubList() { + List list = Arrays.asList(0, 1, 2, 3); + List subList = CollectionUtils.subList(list, 1, 3); + + assertThat(subList).isNotNull(); + assertThat(subList).isNotSameAs(list); + assertThat(subList.size()).isEqualTo(2); + assertThat(subList).containsAll(Arrays.asList(1, 3)); + } + + @Test + public void subListFromListWithNoIndexesReturnsEmptyList() { + List subList = CollectionUtils.subList(Arrays.asList(0, 1, 2)); + + assertThat(subList).isNotNull(); + assertThat(subList.isEmpty()).isTrue(); + } + + @Test(expected = IndexOutOfBoundsException.class) + public void subListFromListWithInvalidIndexThrowsIndexOutOfBoundsException() { + CollectionUtils.subList(Arrays.asList(0, 1, 2), 1, 3); + } + + @Test + public void subListWithNullSourceListThrowsIllegalArgumentException() { + exception.expect(IllegalArgumentException.class); + exception.expectCause(is(nullValue(Throwable.class))); + exception.expectMessage("List must not be null"); + + CollectionUtils.subList(null, 1, 2, 3); + } +} diff --git a/src/test/resources/org/springframework/data/gemfire/client/PoolUsingLocatorsAndServersPropertyPlaceholdersTest-context.xml b/src/test/resources/org/springframework/data/gemfire/client/PoolsConfiguredWithLocatorsAndServersExpressionsIntegrationTests-context.xml similarity index 63% rename from src/test/resources/org/springframework/data/gemfire/client/PoolUsingLocatorsAndServersPropertyPlaceholdersTest-context.xml rename to src/test/resources/org/springframework/data/gemfire/client/PoolsConfiguredWithLocatorsAndServersExpressionsIntegrationTests-context.xml index e3880f04..56f136ff 100644 --- a/src/test/resources/org/springframework/data/gemfire/client/PoolUsingLocatorsAndServersPropertyPlaceholdersTest-context.xml +++ b/src/test/resources/org/springframework/data/gemfire/client/PoolsConfiguredWithLocatorsAndServersExpressionsIntegrationTests-context.xml @@ -11,17 +11,24 @@ http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd "> - - - - backspace,jambox[11235],skullbox[12480] + pluto 20668 saturn + backspace,jambox[11235],skullbox[12480] 41414 + mars + 5112 + boombox[1234],jambox,toolbox[81$81%]* - + + + + + + + @@ -29,8 +36,13 @@ + + + + + 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 ca890f21..ff1598fc 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 @@ -27,25 +27,25 @@ - + - + subscription-redundancy="2" thread-local-connections="false"> - + - - + + - - - + + +