SGF-535 - Allow both SpEL and property placeholder expressions to be used in the locators/servers attributes of the <gfe:pool> XML namespace element.

(cherry picked from commit b7bcabd9b8b1922ddad09af8ad62e9041f3674c7)
Signed-off-by: John Blum <jblum@pivotal.io>
This commit is contained in:
John Blum
2016-09-28 13:25:20 -07:00
parent d7cff53d2d
commit fba37379cd
24 changed files with 1234 additions and 1342 deletions

View File

@@ -19,6 +19,13 @@ package org.springframework.data.gemfire.client;
import java.net.InetSocketAddress;
import java.util.List;
import com.gemstone.gemfire.cache.client.ClientCache;
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.cache.query.QueryService;
import com.gemstone.gemfire.distributed.DistributedSystem;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
@@ -35,17 +42,10 @@ import org.springframework.data.gemfire.util.DistributedSystemUtils;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import com.gemstone.gemfire.cache.client.ClientCache;
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.cache.query.QueryService;
import com.gemstone.gemfire.distributed.DistributedSystem;
/**
* 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.
*
@@ -596,5 +596,4 @@ public class PoolFactoryBean implements FactoryBean<Pool>, InitializingBean, Dis
public void setThreadLocalConnections(boolean threadLocalConnections) {
this.threadLocalConnections = threadLocalConnections;
}
}

View File

@@ -16,11 +16,8 @@
package org.springframework.data.gemfire.config;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.config.BeanDefinition;
@@ -42,21 +39,24 @@ import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;
/**
* Parser for GFE &lt;pool;gt; bean definitions.
*
* Parser for &lt;gfe:pool&gt; 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 {
static final AtomicBoolean INFRASTRUCTURE_REGISTRATION = new AtomicBoolean(false);
static final AtomicBoolean INFRASTRUCTURE_COMPONENTS_REGISTERED = new AtomicBoolean(false);
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 Pattern PROPERTY_PLACEHOLDER_PATTERN = Pattern.compile("\\$\\{.+\\}");
protected static final String DEFAULT_HOST = "localhost";
protected static final String HOST_ATTRIBUTE_NAME = "host";
protected static final String LOCATOR_ELEMENT_NAME = "locator";
@@ -66,8 +66,8 @@ class PoolParser extends AbstractSingleBeanDefinitionParser {
protected static final String SERVERS_ATTRIBUTE_NAME = "servers";
/* (non-Javadoc) */
static void registerSupportingInfrastructureComponents(ParserContext parserContext) {
if (INFRASTRUCTURE_REGISTRATION.compareAndSet(false, true)) {
static void registerInfrastructureComponents(ParserContext parserContext) {
if (INFRASTRUCTURE_COMPONENTS_REGISTERED.compareAndSet(false, true)) {
AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder
.genericBeanDefinition(ClientRegionAndPoolBeanFactoryPostProcessor.class)
.setRole(BeanDefinition.ROLE_INFRASTRUCTURE)
@@ -85,7 +85,7 @@ class PoolParser extends AbstractSingleBeanDefinitionParser {
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
registerSupportingInfrastructureComponents(parserContext);
registerInfrastructureComponents(parserContext);
ParsingUtils.setPropertyValue(element, builder, "free-connection-timeout");
ParsingUtils.setPropertyValue(element, builder, "idle-timeout");
@@ -124,13 +124,13 @@ class PoolParser extends AbstractSingleBeanDefinitionParser {
}
}
locators.addAll(parseLocators(element, getRegistry(parserContext)));
servers.addAll(parseServers(element, getRegistry(parserContext)));
boolean locatorsSet = parseLocators(element, getRegistry(parserContext));
boolean serversSet = parseServers(element, getRegistry(parserContext));
// NOTE if neither Locators nor Servers were specified, then setup a connection to a Server
// running on localhost, listening on the default CacheServer port, 40404
if (childElements.isEmpty() && !hasAttributes(element, LOCATORS_ATTRIBUTE_NAME, SERVERS_ATTRIBUTE_NAME)) {
servers.add(buildConnection(DEFAULT_HOST, String.valueOf(DEFAULT_SERVER_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()) {
@@ -142,43 +142,15 @@ class PoolParser extends AbstractSingleBeanDefinitionParser {
}
}
/* (non-Javadoc) */
boolean hasAttributes(Element element, String... attributeNames) {
for (String attributeName : attributeNames) {
if (element.hasAttribute(attributeName)) {
return true;
}
}
return false;
}
/* (non-Javadoc) */
boolean isPropertyPlaceholder(String value) {
return PROPERTY_PLACEHOLDER_PATTERN.matcher(value).matches();
}
/* (non-Javadoc) */
BeanDefinitionRegistry getRegistry(ParserContext parserContext) {
return parserContext.getRegistry();
}
/* (non-Javadoc) */
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));
@@ -186,6 +158,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);
@@ -197,51 +181,6 @@ class PoolParser extends AbstractSingleBeanDefinitionParser {
: String.valueOf(DEFAULT_LOCATOR_PORT)));
}
/* (non-Javadoc) */
List<BeanDefinition> parseConnections(String hostPortCommaDelimitedList, boolean server) {
List<BeanDefinition> connections = Collections.emptyList();
if (StringUtils.hasText(hostPortCommaDelimitedList)) {
String[] hostsPorts = hostPortCommaDelimitedList.split(",");
connections = new ArrayList<BeanDefinition>(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) */
BeanDefinition parseLocator(Element element) {
return buildConnection(element.getAttribute(HOST_ATTRIBUTE_NAME),
@@ -249,14 +188,12 @@ class PoolParser extends AbstractSingleBeanDefinitionParser {
}
/* (non-Javadoc) */
List<BeanDefinition> parseLocators(Element element, BeanDefinitionRegistry registry) {
List<BeanDefinition> beanDefinitions = Collections.emptyList();
boolean parseLocators(Element element, BeanDefinitionRegistry registry) {
String locatorsAttributeValue = element.getAttribute(LOCATORS_ATTRIBUTE_NAME);
if (isPropertyPlaceholder(locatorsAttributeValue)) {
BeanDefinitionBuilder addLocatorsMethodInvokingBeanBuilder = BeanDefinitionBuilder.genericBeanDefinition(
MethodInvokingBean.class);
if (StringUtils.hasText(locatorsAttributeValue)) {
BeanDefinitionBuilder addLocatorsMethodInvokingBeanBuilder =
BeanDefinitionBuilder.genericBeanDefinition(MethodInvokingBean.class);
addLocatorsMethodInvokingBeanBuilder.addPropertyReference("targetObject", resolveDereferencedId(element));
addLocatorsMethodInvokingBeanBuilder.addPropertyValue("targetMethod", "addLocators");
@@ -267,12 +204,11 @@ class PoolParser extends AbstractSingleBeanDefinitionParser {
addLocatorsMethodInvokingBeanBuilder.getBeanDefinition();
BeanDefinitionReaderUtils.registerWithGeneratedName(addLocatorsMethodInvokingBean, registry);
}
else {
beanDefinitions = parseConnections(locatorsAttributeValue, false);
return true;
}
return beanDefinitions;
return false;
}
/* (non-Javadoc) */
@@ -282,14 +218,12 @@ class PoolParser extends AbstractSingleBeanDefinitionParser {
}
/* (non-Javadoc) */
List<BeanDefinition> parseServers(Element element, BeanDefinitionRegistry registry) {
List<BeanDefinition> beanDefinitions = Collections.emptyList();
boolean parseServers(Element element, BeanDefinitionRegistry registry) {
String serversAttributeValue = element.getAttribute(SERVERS_ATTRIBUTE_NAME);
if (isPropertyPlaceholder(serversAttributeValue)) {
BeanDefinitionBuilder addServersMethodInvokingBeanBuilder = BeanDefinitionBuilder.genericBeanDefinition(
MethodInvokingBean.class);
if (StringUtils.hasText(serversAttributeValue)) {
BeanDefinitionBuilder addServersMethodInvokingBeanBuilder =
BeanDefinitionBuilder.genericBeanDefinition(MethodInvokingBean.class);
addServersMethodInvokingBeanBuilder.addPropertyReference("targetObject", resolveDereferencedId(element));
addServersMethodInvokingBeanBuilder.addPropertyValue("targetMethod", "addServers");
@@ -300,12 +234,11 @@ class PoolParser extends AbstractSingleBeanDefinitionParser {
addServersMethodInvokingBeanBuilder.getBeanDefinition();
BeanDefinitionReaderUtils.registerWithGeneratedName(addServersMethodInvokingBean, registry);
}
else {
beanDefinitions = parseConnections(serversAttributeValue, true);
return true;
}
return beanDefinitions;
return false;
}
/* (non-Javadoc) */
@@ -333,5 +266,4 @@ class PoolParser extends AbstractSingleBeanDefinitionParser {
return id;
}
}

View File

@@ -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<ConnectionEndpo
* @see ConnectionEndpoint#DEFAULT_HOST
*/
public ConnectionEndpoint(String host, int port) {
Assert.isTrue(port >= 0 && port <= 65535, String.format("port number (%1$d) must be between 0 and 65535", port));
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.
*
@@ -208,5 +214,4 @@ public class ConnectionEndpoint implements Cloneable, Comparable<ConnectionEndpo
public String toString() {
return String.format("%1$s[%2$d]", getHost(), getPort());
}
}

View File

@@ -26,7 +26,6 @@ import java.util.List;
import org.springframework.data.gemfire.util.ArrayUtils;
import org.springframework.data.gemfire.util.CollectionUtils;
import org.springframework.data.gemfire.util.SpringUtils;
/**
* The ConnectionEndpointList class is an Iterable collection of ConnectionEndpoint objects.
@@ -34,6 +33,7 @@ import org.springframework.data.gemfire.util.SpringUtils;
* @author John Blum
* @see java.lang.Iterable
* @see java.net.InetSocketAddress
* @see java.util.AbstractList
* @see org.springframework.data.gemfire.support.ConnectionEndpoint
* @since 1.6.3
*/
@@ -97,7 +97,8 @@ public class ConnectionEndpointList extends AbstractList<ConnectionEndpoint> {
* @see org.springframework.data.gemfire.support.ConnectionEndpoint#parse(String, int)
*/
public static ConnectionEndpointList parse(int defaultPort, String... hostsPorts) {
List<ConnectionEndpoint> connectionEndpoints = new ArrayList<ConnectionEndpoint>(hostsPorts.length);
List<ConnectionEndpoint> connectionEndpoints = new ArrayList<ConnectionEndpoint>(
ArrayUtils.length((Object) hostsPorts));
for (String hostPort : ArrayUtils.nullSafeArray(hostsPorts, String.class)) {
connectionEndpoints.add(ConnectionEndpoint.parse(hostPort, defaultPort));
@@ -139,7 +140,7 @@ public class ConnectionEndpointList extends AbstractList<ConnectionEndpoint> {
/* (non-Javadoc) */
@Override
public boolean add(ConnectionEndpoint connectionEndpoint) {
return (add(SpringUtils.toArray(connectionEndpoint)) == this);
return (add(ArrayUtils.asArray(connectionEndpoint)) == this);
}
/**
@@ -334,5 +335,4 @@ public class ConnectionEndpointList extends AbstractList<ConnectionEndpoint> {
public String toString() {
return connectionEndpoints.toString();
}
}

View File

@@ -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 <T> 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> 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 <T> 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> 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 <T> 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> 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.
@@ -119,4 +158,17 @@ public abstract class ArrayUtils {
return newArray;
}
/**
* Sort the array of elements according to the elements natural ordering.
*
* @param <T> {@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 extends Comparable<T>> T[] sort(T[] array) {
Arrays.sort(array);
return array;
}
}

View File

@@ -16,6 +16,7 @@
package org.springframework.data.gemfire.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
@@ -26,12 +27,16 @@ 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.
*
* @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
@@ -97,6 +102,7 @@ public abstract class CollectionUtils extends org.springframework.util.Collectio
* @return the given {@link Collection} if not null or return an empty {@link Collection}
* (implemented with {@link List}).
* @see java.util.Collections#emptyList()
* @see java.util.Collection
*/
public static <T> Collection<T> nullSafeCollection(Collection<T> collection) {
return (collection != null ? collection : Collections.<T>emptyList());
@@ -140,6 +146,7 @@ public abstract class CollectionUtils extends org.springframework.util.Collectio
* @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 <T> List<T> nullSafeList(List<T> list) {
return (list != null ? list : Collections.<T>emptyList());
@@ -154,6 +161,7 @@ public abstract class CollectionUtils extends org.springframework.util.Collectio
* @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 <K, V> Map<K, V> nullSafeMap(Map<K, V> map) {
return (map != null ? map : Collections.<K, V>emptyMap());
@@ -167,8 +175,48 @@ public abstract class CollectionUtils extends org.springframework.util.Collectio
* @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 <T> Set<T> nullSafeSet(Set<T> set) {
return (set != null ? set : Collections.<T>emptySet());
}
/**
* Sors the elements of the given {@link List} by their natural, {@link Comparable} ordering.
*
* @param <T> {@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 <T extends Comparable<T>> List<T> sort(List<T> list) {
Collections.sort(list);
return list;
}
/**
* Returns a sub-list of elements from the given {@link List} based on the provided {@code indices}.
*
* @param <T> 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 <T> List<T> subList(List<T> source, int... indices) {
Assert.notNull(source, "List must not be null");
List<T> result = new ArrayList<T>(indices.length);
for (int index : indices) {
result.add(source.get(index));
}
return result;
}
}

View File

@@ -17,10 +17,6 @@
package org.springframework.data.gemfire.util;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.util.StringUtils;
@@ -31,6 +27,7 @@ import org.springframework.util.StringUtils;
* @since 1.8.0
*/
@SuppressWarnings("unused")
// TODO rename this utiltiy class using a more intuitive, meaningful name
public abstract class SpringUtils {
/* (non-Javadoc) */
@@ -47,22 +44,4 @@ public abstract class SpringUtils {
public static String dereferenceBean(String beanName) {
return String.format("%1$s%2$s", BeanFactory.FACTORY_BEAN_PREFIX, beanName);
}
/* (non-Javadoc) */
public static <T> T[] toArray(T... array) {
return array;
}
/* (non-Javadoc) */
public static <T extends Comparable<T>> T[] sort(T[] array) {
Arrays.sort(array);
return array;
}
/* (non-Javadoc) */
public static <T extends Comparable<T>> List<T> sort(List<T> list) {
Collections.sort(list);
return list;
}
}

View File

@@ -38,11 +38,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;
@@ -58,6 +53,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.

View File

@@ -45,6 +45,14 @@ import java.util.Map;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;
import com.gemstone.gemfire.cache.CacheClosedException;
import com.gemstone.gemfire.cache.GemFireCache;
import com.gemstone.gemfire.cache.client.ClientCache;
import com.gemstone.gemfire.cache.client.ClientCacheFactory;
import com.gemstone.gemfire.cache.client.Pool;
import com.gemstone.gemfire.distributed.DistributedSystem;
import com.gemstone.gemfire.pdx.PdxSerializer;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
@@ -54,16 +62,8 @@ import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.gemfire.GemfireUtils;
import org.springframework.data.gemfire.config.GemfireConstants;
import org.springframework.data.gemfire.support.ConnectionEndpoint;
import org.springframework.data.gemfire.util.ArrayUtils;
import org.springframework.data.gemfire.util.DistributedSystemUtils;
import org.springframework.data.gemfire.util.SpringUtils;
import com.gemstone.gemfire.cache.CacheClosedException;
import com.gemstone.gemfire.cache.GemFireCache;
import com.gemstone.gemfire.cache.client.ClientCache;
import com.gemstone.gemfire.cache.client.ClientCacheFactory;
import com.gemstone.gemfire.cache.client.Pool;
import com.gemstone.gemfire.distributed.DistributedSystem;
import com.gemstone.gemfire.pdx.PdxSerializer;
/**
* The ClientCacheFactoryBeanTest class is a test suite of test cases testing the contract and functionality
@@ -1359,7 +1359,7 @@ public class ClientCacheFactoryBeanTest {
assertThat(clientCacheFactoryBean.getLocators().findOne("skullbox"), is(equalTo(skullbox)));
assertThat(clientCacheFactoryBean.getLocators().findOne("boombox"), is(equalTo(boombox)));
clientCacheFactoryBean.setLocators(SpringUtils.toArray(localhost));
clientCacheFactoryBean.setLocators(ArrayUtils.asArray(localhost));
assertThat(clientCacheFactoryBean.getLocators().size(), is(equalTo(1)));
assertThat(clientCacheFactoryBean.getLocators().findOne("localhost"), is(equalTo(localhost)));
@@ -1394,7 +1394,7 @@ public class ClientCacheFactoryBeanTest {
assertThat(clientCacheFactoryBean.getServers().findOne("skullbox"), is(equalTo(skullbox)));
assertThat(clientCacheFactoryBean.getServers().findOne("boombox"), is(equalTo(boombox)));
clientCacheFactoryBean.setServers(SpringUtils.toArray(localhost));
clientCacheFactoryBean.setServers(ArrayUtils.asArray(localhost));
assertThat(clientCacheFactoryBean.getServers().size(), is(equalTo(1)));
assertThat(clientCacheFactoryBean.getServers().findOne("localhost"), is(equalTo(localhost)));
@@ -1404,5 +1404,4 @@ public class ClientCacheFactoryBeanTest {
assertThat(clientCacheFactoryBean.getServers(), is(notNullValue()));
assertThat(clientCacheFactoryBean.getServers().isEmpty(), is(true));
}
}

View File

@@ -38,20 +38,20 @@ import java.net.InetSocketAddress;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicBoolean;
import com.gemstone.gemfire.cache.client.ClientCache;
import com.gemstone.gemfire.cache.client.Pool;
import com.gemstone.gemfire.cache.client.PoolFactory;
import com.gemstone.gemfire.cache.query.QueryService;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.data.gemfire.TestUtils;
import org.springframework.data.gemfire.support.ConnectionEndpoint;
import org.springframework.data.gemfire.util.SpringUtils;
import org.springframework.data.gemfire.util.ArrayUtils;
import org.springframework.data.util.ReflectionUtils;
import com.gemstone.gemfire.cache.client.ClientCache;
import com.gemstone.gemfire.cache.client.Pool;
import com.gemstone.gemfire.cache.client.PoolFactory;
import com.gemstone.gemfire.cache.query.QueryService;
/**
* The PoolFactoryBeanTest class is a test suite of test cases testing the contract and functionality
* of the PoolFactoryBean class.
@@ -276,7 +276,7 @@ public class PoolFactoryBeanTest {
assertThat(poolFactoryBean.getLocators().findOne("skullbox"), is(equalTo(skullbox)));
assertThat(poolFactoryBean.getLocators().findOne("boombox"), is(equalTo(boombox)));
poolFactoryBean.setLocators(SpringUtils.toArray(localhost));
poolFactoryBean.setLocators(ArrayUtils.asArray(localhost));
assertThat(poolFactoryBean.getLocators().size(), is(equalTo(1)));
assertThat(poolFactoryBean.getLocators().findOne("localhost"), is(equalTo(localhost)));
@@ -311,7 +311,7 @@ public class PoolFactoryBeanTest {
assertThat(poolFactoryBean.getServers().findOne("skullbox"), is(equalTo(skullbox)));
assertThat(poolFactoryBean.getServers().findOne("boombox"), is(equalTo(boombox)));
poolFactoryBean.setServers(SpringUtils.toArray(localhost));
poolFactoryBean.setServers(ArrayUtils.asArray(localhost));
assertThat(poolFactoryBean.getServers().size(), is(equalTo(1)));
assertThat(poolFactoryBean.getServers().findOne("localhost"), is(equalTo(localhost)));
@@ -339,7 +339,7 @@ public class PoolFactoryBeanTest {
poolFactoryBean.setFreeConnectionTimeout(5000);
poolFactoryBean.setIdleTimeout(120000l);
poolFactoryBean.setLoadConditioningInterval(300000);
poolFactoryBean.setLocators(SpringUtils.toArray(newConnectionEndpoint("skullbox", 11235)));
poolFactoryBean.setLocators(ArrayUtils.asArray(newConnectionEndpoint("skullbox", 11235)));
poolFactoryBean.setMaxConnections(500);
poolFactoryBean.setMinConnections(50);
poolFactoryBean.setMultiUserAuthentication(true);
@@ -348,7 +348,7 @@ public class PoolFactoryBeanTest {
poolFactoryBean.setReadTimeout(30000);
poolFactoryBean.setRetryAttempts(1);
poolFactoryBean.setServerGroup("TestGroup");
poolFactoryBean.setServers(SpringUtils.toArray(newConnectionEndpoint("boombox", 12480)));
poolFactoryBean.setServers(ArrayUtils.asArray(newConnectionEndpoint("boombox", 12480)));
poolFactoryBean.setSocketBufferSize(16384);
poolFactoryBean.setStatisticInterval(500);
poolFactoryBean.setSubscriptionAckInterval(200);
@@ -539,5 +539,4 @@ public class PoolFactoryBeanTest {
pool.releaseThreadLocalConnection();
}
}

View File

@@ -16,15 +16,17 @@
package org.springframework.data.gemfire.client;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
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.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;
@@ -37,15 +39,13 @@ 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.data.gemfire.util.SpringUtils;
import org.springframework.data.gemfire.util.CollectionUtils;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.gemstone.gemfire.cache.client.Pool;
import com.gemstone.gemfire.cache.client.PoolFactory;
import org.springframework.util.Assert;
/**
* The PoolUsingLocatorsAndServersPropertyPlaceholdersTest class is a test suite of test cases testing the use of
* The PoolsConfiguredWithLocatorsAndServersExpressionsIntegrationTests class is a test suite of test cases testing the use of
* property placeholder values in the nested &lt;gfe:locator&gt; and &lt;gfe:server&gt; sub-elements
* of the &lt;gfe:pool&gt; element as well as the <code>locators</code> and <code>servers</code> attributes.
*
@@ -61,8 +61,9 @@ import com.gemstone.gemfire.cache.client.PoolFactory;
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class PoolUsingLocatorsAndServersPropertyPlaceholdersTest {
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();
@@ -77,6 +78,11 @@ public class PoolUsingLocatorsAndServersPropertyPlaceholdersTest {
@SuppressWarnings("unused")
private Pool serverPool;
@Autowired
@Qualifier("anotherLocatorPool")
@SuppressWarnings("unused")
private Pool anotherLocatorPool;
@Autowired
@Qualifier("anotherServerPool")
@SuppressWarnings("unused")
@@ -87,48 +93,55 @@ public class PoolUsingLocatorsAndServersPropertyPlaceholdersTest {
}
protected void assertConnectionEndpoints(Iterable<ConnectionEndpoint> connectionEndpoints, String... expected) {
assertThat(connectionEndpoints, is(notNullValue()));
assertThat(connectionEndpoints).isNotNull();
int index = 0;
for (ConnectionEndpoint connectionEndpoint : connectionEndpoints) {
assertThat(connectionEndpoint.toString(), is(equalTo(expected[index++])));
assertThat(connectionEndpoint.toString()).isEqualTo(expected[index++]);
}
assertThat(index, is(equalTo(expected.length)));
assertThat(index).isEqualTo(expected.length);
}
@Test
public void anotherLocatorPoolFactoryConfiguration() {
String[] expected = { "localhost[10335]", "cardboardbox[10334]", "safetydepositbox[10336]", "pobox[10334]" };
assertThat(anotherLocators.size()).isEqualTo(expected.length);
assertConnectionEndpoints(anotherLocators, expected);
}
@Test
public void anotherServerPoolFactoryConfiguration() {
String[] expected = { "boombox[1234]", "jambox[40404]", "toolbox[8181]" };
assertThat(anotherServers.size(), is(equalTo(expected.length)));
assertConnectionEndpoints(SpringUtils.sort(anotherServers), expected);
assertThat(anotherServers.size()).isEqualTo(expected.length);
assertConnectionEndpoints(CollectionUtils.sort(anotherServers), expected);
}
@Test
public void locatorPoolFactoryConfiguration() {
String[] expected = { "backspace[10334]", "jambox[11235]", "mars[30303]", "pluto[20668]", "skullbox[12480]" };
assertThat(locators.size(), is(equalTo(expected.length)));
assertConnectionEndpoints(SpringUtils.sort(locators), expected);
assertThat(locators.size()).isEqualTo(expected.length);
assertConnectionEndpoints(CollectionUtils.sort(locators), expected);
}
@Test
public void serverPoolFactoryConfiguration() {
String[] expected = { "earth[4554]", "jupiter[40404]", "mercury[1234]", "neptune[42424]", "saturn[41414]",
String[] expected = { "earth[4554]", "jupiter[40404]", "mars[5112]", "mercury[1234]", "neptune[42424]", "saturn[41414]",
"uranis[0]", "venus[9876]" };
assertThat(servers.size(), is(equalTo(expected.length)));
assertConnectionEndpoints(SpringUtils.sort(servers), expected);
assertThat(servers.size()).isEqualTo(expected.length);
assertConnectionEndpoints(CollectionUtils.sort(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");
@@ -138,6 +151,12 @@ public class PoolUsingLocatorsAndServersPropertyPlaceholdersTest {
}
}
public static class AnotherLocatorPoolFactoryBean extends TestPoolFactoryBean {
@Override ConnectionEndpointList getLocatorList() {
return anotherLocators;
}
}
public static class AnotherServerPoolFactoryBean extends TestPoolFactoryBean {
@Override ConnectionEndpointList getServerList() {
return anotherServers;
@@ -156,6 +175,29 @@ public class PoolUsingLocatorsAndServersPropertyPlaceholdersTest {
}
}
@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() {
@@ -198,5 +240,4 @@ public class PoolUsingLocatorsAndServersPropertyPlaceholdersTest {
return true;
}
}
}

View File

@@ -16,22 +16,18 @@
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.Pool;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.gemfire.TestUtils;
import org.springframework.data.gemfire.client.PoolAdapter;
import org.springframework.data.gemfire.client.PoolFactoryBean;
import org.springframework.data.gemfire.support.ConnectionEndpoint;
import org.springframework.data.gemfire.support.ConnectionEndpointList;
@@ -40,8 +36,16 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Integration tests for {@link PoolParser} and {@link PoolFactoryBean}.
*
* @author Costin Leau
* @author John Blum
* @see org.junit.Test
* @see org.springframework.data.gemfire.client.PoolAdapter
* @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)
@@ -49,141 +53,150 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
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.get(0), 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("gemfirePool"), is(true));
assertThat(context.containsBean("gemfire-pool"), is(true));
public void gemfirePoolIsConfiguredProperly() throws Exception {
assertThat(applicationContext.containsBean("gemfirePool")).isTrue();
assertThat(applicationContext.containsBean("gemfire-pool")).isTrue();
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 servers = TestUtils.readField("servers", poolFactoryBean);
assertThat(servers, is(notNullValue()));
assertThat(servers.size(), is(equalTo(1)));
assertConnectionEndpoint(servers.iterator().next(), PoolParser.DEFAULT_HOST, PoolParser.DEFAULT_SERVER_PORT);
assertConnectionEndpoint(servers, PoolParser.DEFAULT_HOST, PoolParser.DEFAULT_SERVER_PORT);
ConnectionEndpointList locators = TestUtils.readField("locators", poolFactoryBean);
assertThat(locators, is(notNullValue()));
assertThat(locators.isEmpty(), is(true));
assertNoConnectionEndpoints(locators);
}
@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<ConnectionEndpoint> 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 testServerPool() throws Exception {
assertTrue(context.containsBean("server"));
public void serverPoolIsConfiguredProperly() throws Exception {
assertThat(applicationContext.containsBean("server")).isTrue();
PoolFactoryBean poolFactoryBean = context.getBean("&server", PoolFactoryBean.class);
PoolFactoryBean poolFactoryBean = applicationContext.getBean("&server", PoolFactoryBean.class);
Pool pool = poolFactoryBean.getPool();
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(pool).isInstanceOf(PoolAdapter.class);
assertThat(pool.getFreeConnectionTimeout()).isEqualTo(2000);
assertThat(pool.getIdleTimeout()).isEqualTo(20000L);
assertThat(pool.getLoadConditioningInterval()).isEqualTo(10000);
assertThat(Boolean.TRUE.equals(TestUtils.readField("keepAlive", poolFactoryBean))).isTrue();
assertThat(pool.getMaxConnections()).isEqualTo(100);
assertThat(pool.getMinConnections()).isEqualTo(5);
assertThat(pool.getMultiuserAuthentication()).isTrue();
assertThat(pool.getPingInterval()).isEqualTo(5000L);
assertThat(pool.getPRSingleHopEnabled()).isFalse();
assertThat(pool.getReadTimeout()).isEqualTo(500);
assertThat(pool.getRetryAttempts()).isEqualTo(5);
assertThat(pool.getServerGroup()).isEqualTo("TestGroup");
assertThat(pool.getSocketBufferSize()).isEqualTo(65536);
assertThat(pool.getStatisticInterval()).isEqualTo(250);
assertThat(pool.getSubscriptionAckInterval()).isEqualTo(250);
assertThat(pool.getSubscriptionEnabled()).isTrue();
assertThat(pool.getSubscriptionMessageTrackingTimeout()).isEqualTo(30000);
assertThat(pool.getSubscriptionRedundancy()).isEqualTo(2);
assertThat(pool.getThreadLocalConnections()).isFalse();
ConnectionEndpointList servers = TestUtils.readField("servers", poolFactoryBean);
assertNotNull(servers);
assertEquals(2, servers.size());
assertThat(servers).isNotNull();
assertThat(servers.size()).isEqualTo(2);
Iterator<ConnectionEndpoint> 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<ConnectionEndpoint> locatorIterator = locators.iterator();
assertConnectionEndpoint(locatorIterator.next(), "foobar", 55421);
assertConnectionEndpoint(locatorIterator.next(), "lavatube", 11235);
assertConnectionEndpoint(locatorIterator.next(), "zod", 10334);
assertConnectionEndpoint(locatorIterator.next(), "earth", 54321);
assertConnectionEndpoint(locatorIterator.next(), "venus", 11235);
assertConnectionEndpoint(locatorIterator.next(), "mars", 10334);
assertConnectionEndpoint(locatorIterator.next(), "localhost", 12480);
}
@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<ConnectionEndpoint> serverIterator = servers.iterator();
assertConnectionEndpoint(serverIterator.next(), "scorch", 21480);
assertConnectionEndpoint(serverIterator.next(), "scorn", 51515);
assertConnectionEndpoint(serverIterator.next(), "duke", 21480);
assertConnectionEndpoint(serverIterator.next(), "nukem", 51515);
assertConnectionEndpoint(serverIterator.next(), "skullbox", 9110);
}
}

View File

@@ -1,753 +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.instanceOf;
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.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isA;
import static org.mockito.Matchers.notNull;
import static org.mockito.Mockito.doAnswer;
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.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.config.MethodInvokingBean;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.data.gemfire.client.PoolFactoryBean;
import org.springframework.data.gemfire.support.ConnectionEndpoint;
import org.springframework.data.gemfire.support.ConnectionEndpointList;
import org.springframework.util.StringUtils;
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.junit.runner.RunWith
* @see org.mockito.Mock
* @see org.mockito.Mockito
* @see org.mockito.runners.MockitoJUnitRunner
* @see org.springframework.data.gemfire.client.PoolFactoryBean
* @see org.springframework.data.gemfire.config.PoolParser
* @since 1.7.0
*/
@RunWith(MockitoJUnitRunner.class)
public class PoolParserTest {
@Mock
private BeanDefinitionRegistry mockRegistry;
private PoolParser parser;
@Before
public void setup() {
PoolParser.INFRASTRUCTURE_REGISTRATION.set(true);
parser = new PoolParser() {
@Override BeanDefinitionRegistry getRegistry(final ParserContext parserContext) {
return mockRegistry;
}
};
}
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)));
}
protected void assertPropertyValue(PropertyValues propertyValues, String propertyName, Object propertyValue) {
assertThat(propertyValues.getPropertyValue(propertyName).getValue(), is(equalTo(propertyValue)));
}
protected String generatedBeanName(Class<?> type) {
return generatedBeanName(type.getName());
}
protected String generatedBeanName(String beanClassName) {
return String.format("%1$s%2$s%3$d", beanClassName, BeanDefinitionReaderUtils.GENERATED_BEAN_NAME_SEPARATOR, 0);
}
@Test
@SuppressWarnings("unchecked")
public void getBeanClass() {
assertThat((Class<PoolFactoryBean>) parser.getBeanClass(null), is(equalTo(PoolFactoryBean.class)));
}
@Test
@SuppressWarnings("unchecked")
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.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(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("comet");
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("quasar");
when(mockLocatorElementTwo.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, null, builder);
BeanDefinition poolDefinition = builder.getBeanDefinition();
assertThat(poolDefinition, is(notNullValue()));
PropertyValues poolPropertyValues = poolDefinition.getPropertyValues();
assertPropertyValue(poolPropertyValues, "freeConnectionTimeout", "5000");
assertPropertyValue(poolPropertyValues, "idleTimeout", "120000");
assertPropertyValue(poolPropertyValues, "keepAlive", "true");
assertPropertyValue(poolPropertyValues, "loadConditioningInterval", "300000");
assertPropertyValue(poolPropertyValues, "maxConnections", "500");
assertPropertyValue(poolPropertyValues, "minConnections", "50");
assertPropertyValue(poolPropertyValues, "multiUserAuthentication", "true");
assertPropertyValue(poolPropertyValues, "pingInterval", "15000");
assertPropertyValue(poolPropertyValues, "prSingleHopEnabled", "true");
assertPropertyValue(poolPropertyValues, "readTimeout", "20000");
assertPropertyValue(poolPropertyValues, "retryAttempts", "1");
assertPropertyValue(poolPropertyValues, "serverGroup", "TestGroup");
assertPropertyValue(poolPropertyValues, "socketBufferSize", "16384");
assertPropertyValue(poolPropertyValues, "statisticInterval", "500");
assertPropertyValue(poolPropertyValues, "subscriptionAckInterval", "200");
assertPropertyValue(poolPropertyValues, "subscriptionEnabled", "true");
assertPropertyValue(poolPropertyValues, "subscriptionMessageTrackingTimeout", "30000");
assertPropertyValue(poolPropertyValues, "subscriptionRedundancy", "2");
assertPropertyValue(poolPropertyValues, "threadLocalConnections", "false");
assertThat(poolPropertyValues.contains("locators"), is(true));
assertThat(poolPropertyValues.contains("servers"), is(true));
ManagedList<BeanDefinition> locators = (ManagedList<BeanDefinition>)
poolPropertyValues.getPropertyValue("locators").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<BeanDefinition> servers = (ManagedList<BeanDefinition>) poolDefinition.getPropertyValues()
.getPropertyValue("servers").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)).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, 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(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
@SuppressWarnings("unchecked")
public void doParseWithNoLocatorsOrServersSpecified() {
Element mockPoolElement = mock(Element.class);
NodeList mockNodeList = mock(NodeList.class);
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("");
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, is(notNullValue()));
PropertyValues poolPropertyValues = poolDefinition.getPropertyValues();
assertThat(poolPropertyValues.contains("locators"), is(false));
assertThat(poolPropertyValues.contains("servers"), is(true));
ManagedList<BeanDefinition> servers = (ManagedList<BeanDefinition>)
poolPropertyValues.getPropertyValue("servers").getValue();
assertThat(servers, is(notNullValue()));
assertThat(servers.size(), is(equalTo(1)));
assertBeanDefinition(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)).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);
NodeList mockNodeList = mock(NodeList.class);
when(mockPoolElement.getAttribute(PoolParser.ID_ATTRIBUTE)).thenReturn("TestPool");
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(true);
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 poolDefinition = poolBuilder.getBeanDefinition();
assertThat(poolDefinition, is(notNullValue()));
PropertyValues poolPropertyValues = poolDefinition.getPropertyValues();
assertThat(poolPropertyValues.contains("locators"), is(false));
assertThat(poolPropertyValues.contains("servers"), is(false));
when(mockRegistry.containsBeanDefinition(anyString())).thenReturn(false);
doAnswer(new Answer<Void>() {
@Override public Void answer(final InvocationOnMock invocation) throws Throwable {
String generatedName = invocation.getArgumentAt(0, String.class);
BeanDefinition addServersDefinition = invocation.getArgumentAt(1, BeanDefinition.class);
assertThat(StringUtils.hasText(generatedName), is(true));
assertThat(generatedName, is(equalTo(generatedBeanName(addServersDefinition.getBeanClassName()))));
assertThat(addServersDefinition, is(notNull()));
assertThat(addServersDefinition.getBeanClassName(), is(equalTo(MethodInvokingBean.class.getName())));
PropertyValues addServersPropertyValues = addServersDefinition.getPropertyValues();
assertThat(addServersPropertyValues, is(notNullValue()));
assertPropertyValue(addServersPropertyValues, "targetObject", new RuntimeBeanReference("&TestPool"));
assertPropertyValue(addServersPropertyValues, "targetMethod", "addServers");
Object arguments = addServersPropertyValues.getPropertyValue("arguments").getValue();
assertThat(arguments, is(instanceOf(BeanDefinition.class)));
BeanDefinition argumentsDefinition = (BeanDefinition) arguments;
assertThat(argumentsDefinition.getBeanClassName(), is(equalTo(ConnectionEndpointList.class.getName())));
ConstructorArgumentValues constructorArguments = argumentsDefinition.getConstructorArgumentValues();
assertThat(constructorArguments, is(notNullValue()));
assertThat(constructorArguments.getArgumentCount(), is(equalTo(2)));
assertThat((Integer) constructorArguments.getArgumentValue(0, Integer.class).getValue(),
is(equalTo(PoolParser.DEFAULT_SERVER_PORT)));
assertThat(String.valueOf(constructorArguments.getArgumentValue(1, String.class).getValue()),
is(equalTo("${gemfire.server.hosts-and-ports}")));
return null;
}
}).when(mockRegistry).registerBeanDefinition(eq(generatedBeanName(MethodInvokingBean.class)),
any(BeanDefinition.class));
verify(mockPoolElement, times(1)).getAttribute(eq(PoolParser.ID_ATTRIBUTE));
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));
verify(mockPoolElement, times(1)).getChildNodes();
verify(mockNodeList, times(1)).getLength();
verify(mockNodeList, never()).item(anyInt());
verify(mockRegistry, times(1)).containsBeanDefinition(eq(generatedBeanName(MethodInvokingBean.class)));
verify(mockRegistry, times(1)).registerBeanDefinition(eq(generatedBeanName(MethodInvokingBean.class)),
isA(BeanDefinition.class));
}
@Test
public void hasAttributesReturnsTrueAndShortcircuts() {
Element mockElement = mock(Element.class);
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);
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())));
ConstructorArgumentValues constructorArguments = beanDefinition.getConstructorArgumentValues();
assertThat(constructorArguments, is(notNullValue()));
assertThat(constructorArguments.getArgumentValue(0, Integer.class).getValue().toString(),
is(equalTo(String.valueOf(PoolParser.DEFAULT_LOCATOR_PORT))));
assertThat(constructorArguments.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())));
ConstructorArgumentValues constructorArguments = beanDefinition.getConstructorArgumentValues();
assertThat(constructorArguments, is(notNullValue()));
assertThat(constructorArguments.getArgumentValue(0, Integer.class).getValue().toString(),
is(equalTo(String.valueOf(PoolParser.DEFAULT_SERVER_PORT))));
assertThat(constructorArguments.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<BeanDefinition> 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<BeanDefinition> 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);
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);
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);
when(mockElement.getAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME))).thenReturn(
"jupiter, saturn[1234], [9876] ");
List<BeanDefinition> locators = parser.parseLocators(mockElement, mockRegistry);
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);
when(mockElement.getAttribute(eq(PoolParser.ID_ATTRIBUTE))).thenReturn(null);
when(mockElement.getAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME))).thenReturn(
"${gemfire.locators.hosts-and-ports}");
when(mockRegistry.containsBeanDefinition(anyString())).thenReturn(false);
doAnswer(new Answer<Void>() {
@Override public Void answer(final InvocationOnMock invocation) throws Throwable {
String generatedName = invocation.getArgumentAt(0, String.class);
BeanDefinition addServersDefinition = invocation.getArgumentAt(1, BeanDefinition.class);
assertThat(StringUtils.hasText(generatedName), is(true));
assertThat(generatedName, is(equalTo(generatedBeanName(addServersDefinition.getBeanClassName()))));
assertThat(addServersDefinition, is(notNullValue()));
assertThat(addServersDefinition.getBeanClassName(), is(equalTo(MethodInvokingBean.class.getName())));
PropertyValues addServersPropertyValues = addServersDefinition.getPropertyValues();
assertThat(addServersPropertyValues, is(notNullValue()));
assertPropertyValue(addServersPropertyValues, "targetObject", new RuntimeBeanReference("&gemfirePool"));
assertPropertyValue(addServersPropertyValues, "targetMethod", "addLocators");
Object arguments = addServersPropertyValues.getPropertyValue("arguments").getValue();
assertThat(arguments, is(instanceOf(BeanDefinition.class)));
BeanDefinition argumentsDefinition = (BeanDefinition) arguments;
assertThat(argumentsDefinition.getBeanClassName(), is(equalTo(ConnectionEndpointList.class.getName())));
ConstructorArgumentValues constructorArguments = argumentsDefinition.getConstructorArgumentValues();
assertThat(constructorArguments, is(notNullValue()));
assertThat(constructorArguments.getArgumentCount(), is(equalTo(2)));
assertThat(String.valueOf(constructorArguments.getArgumentValue(0, Integer.class).getValue()),
is(equalTo(String.valueOf(PoolParser.DEFAULT_LOCATOR_PORT))));
assertThat(String.valueOf(constructorArguments.getArgumentValue(1, String.class).getValue()),
is(equalTo("${gemfire.locators.hosts-and-ports}")));
return null;
}
}).when(mockRegistry).registerBeanDefinition(eq(generatedBeanName(MethodInvokingBean.class)),
any(BeanDefinition.class));
List<BeanDefinition> locators = parser.parseLocators(mockElement, mockRegistry);
assertThat(locators, is(notNullValue()));
assertThat(locators.isEmpty(), is(true));
verify(mockElement, times(1)).getAttribute(eq(PoolParser.ID_ATTRIBUTE));
verify(mockElement, times(1)).getAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME));
verify(mockRegistry, times(1)).containsBeanDefinition(eq(generatedBeanName(MethodInvokingBean.class)));
verify(mockRegistry, times(1)).registerBeanDefinition(eq(generatedBeanName(MethodInvokingBean.class)),
isA(BeanDefinition.class));
}
@Test
public void parseServer() {
Element mockElement = mock(Element.class);
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);
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);
when(mockElement.getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME))).thenReturn(" neptune[], venus[9876]");
List<BeanDefinition> servers = parser.parseServers(mockElement, mockRegistry);
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);
when(mockElement.getAttribute(eq(PoolParser.ID_ATTRIBUTE))).thenReturn(null);
when(mockElement.getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME))).thenReturn(
"${gemfire.servers.hosts-and-ports}");
when(mockRegistry.containsBeanDefinition(anyString())).thenReturn(false);
doAnswer(new Answer<Void>() {
@Override public Void answer(final InvocationOnMock invocation) throws Throwable {
String generatedName = invocation.getArgumentAt(0, String.class);
BeanDefinition addServersDefinition = invocation.getArgumentAt(1, BeanDefinition.class);
assertThat(StringUtils.hasText(generatedName), is(true));
assertThat(generatedName, is(equalTo(generatedBeanName(addServersDefinition.getBeanClassName()))));
assertThat(addServersDefinition, is(notNullValue()));
assertThat(addServersDefinition.getBeanClassName(), is(equalTo(MethodInvokingBean.class.getName())));
PropertyValues addServersPropertyValues = addServersDefinition.getPropertyValues();
assertThat(addServersPropertyValues, is(notNullValue()));
assertPropertyValue(addServersPropertyValues, "targetObject", new RuntimeBeanReference("&gemfirePool"));
assertPropertyValue(addServersPropertyValues, "targetMethod", "addServers");
Object arguments = addServersPropertyValues.getPropertyValue("arguments").getValue();
assertThat(arguments, is(instanceOf(BeanDefinition.class)));
BeanDefinition argumentsDefinition = (BeanDefinition) arguments;
assertThat(argumentsDefinition.getBeanClassName(), is(equalTo(ConnectionEndpointList.class.getName())));
ConstructorArgumentValues constructorArguments = argumentsDefinition.getConstructorArgumentValues();
assertThat(constructorArguments, is(notNullValue()));
assertThat(constructorArguments.getArgumentCount(), is(equalTo(2)));
assertThat(String.valueOf(constructorArguments.getArgumentValue(0, Object.class).getValue()),
is(equalTo(String.valueOf(PoolParser.DEFAULT_SERVER_PORT))));
assertThat(String.valueOf(constructorArguments.getArgumentValue(1, String.class).getValue()),
is(equalTo("${gemfire.servers.hosts-and-ports}")));
return null;
}
}).when(mockRegistry).registerBeanDefinition(eq(generatedBeanName(MethodInvokingBean.class)),
any(BeanDefinition.class));
List<BeanDefinition> servers = parser.parseServers(mockElement, mockRegistry);
assertThat(servers, is(notNullValue()));
assertThat(servers.isEmpty(), is(true));
verify(mockElement, times(1)).getAttribute(eq(PoolParser.ID_ATTRIBUTE));
verify(mockElement, times(1)).getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME));
verify(mockRegistry, times(1)).containsBeanDefinition(eq(generatedBeanName(MethodInvokingBean.class)));
verify(mockRegistry, times(1)).registerBeanDefinition(eq(generatedBeanName(MethodInvokingBean.class)),
isA(BeanDefinition.class));
}
}

View File

@@ -0,0 +1,565 @@
/*
* 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.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.doAnswer;
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.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.config.MethodInvokingBean;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.data.gemfire.client.PoolFactoryBean;
import org.springframework.data.gemfire.support.ConnectionEndpoint;
import org.springframework.data.gemfire.support.ConnectionEndpointList;
import org.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;
@Before
public void setup() {
PoolParser.INFRASTRUCTURE_COMPONENTS_REGISTERED.set(true);
parser = new PoolParser() {
@Override BeanDefinitionRegistry getRegistry(ParserContext parserContext) {
return mockRegistry;
}
};
}
protected void assertBeanDefinition(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 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);
}
protected String generateBeanName(Class<?> type) {
return generateBeanName(type.getName());
}
protected String generateBeanName(String beanClassName) {
return String.format("%1$s%2$s%3$d", beanClassName, BeanDefinitionReaderUtils.GENERATED_BEAN_NAME_SEPARATOR, 0);
}
protected Answer<Void> newAnswer(final String beanReference, final String targetMethod,
final String host, final String port) {
return new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
String generatedName = invocation.getArgumentAt(0, String.class);
BeanDefinition methodInvokingBeanDefinition = invocation.getArgumentAt(1, BeanDefinition.class);
assertThat(methodInvokingBeanDefinition).isNotNull();
assertThat(methodInvokingBeanDefinition.getBeanClassName()).isEqualTo(MethodInvokingBean.class.getName());
assertThat(generatedName).isEqualTo(generateBeanName(methodInvokingBeanDefinition.getBeanClassName()));
assertPropertyValue(methodInvokingBeanDefinition, "targetObject", new RuntimeBeanReference(beanReference));
assertPropertyValue(methodInvokingBeanDefinition, "targetMethod", targetMethod);
BeanDefinition argumentsDefinition = getPropertyValue(methodInvokingBeanDefinition, "arguments");
assertThat(argumentsDefinition.getBeanClassName()).isEqualTo(ConnectionEndpointList.class.getName());
ConstructorArgumentValues constructorArguments = argumentsDefinition.getConstructorArgumentValues();
assertThat(constructorArguments.getArgumentCount()).isEqualTo(2);
assertThat(constructorArguments.getArgumentValue(0, Integer.class).getValue()).isEqualTo(port);
assertThat(constructorArguments.getArgumentValue(1, String.class).getValue()).isEqualTo(host);
return null;
}
};
}
@SuppressWarnings("unchecked")
protected <T> 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, "locators");
assertPropertyPresent(poolDefinition, "servers");
ManagedList<BeanDefinition> locators = getPropertyValue(poolDefinition, "locators");
assertThat(locators).isNotNull();
assertThat(locators.size()).isEqualTo(2);
assertBeanDefinition(locators.get(0), "venus", "1025");
assertBeanDefinition(locators.get(1), "mars", String.valueOf(PoolParser.DEFAULT_LOCATOR_PORT));
ManagedList<BeanDefinition> servers = getPropertyValue(poolDefinition, "servers");
assertThat(servers).isNotNull();
assertThat(servers.size()).isEqualTo(1);
assertBeanDefinition(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();
PropertyValues poolPropertyValues = poolDefinition.getPropertyValues();
assertThat(poolPropertyValues.contains("locators")).isFalse();
assertThat(poolPropertyValues.contains("servers")).isTrue();
ManagedList<BeanDefinition> servers = getPropertyValue(poolDefinition, "servers");
assertThat(servers).isNotNull();
assertThat(servers.size()).isEqualTo(1);
assertBeanDefinition(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);
when(mockRegistry.containsBeanDefinition(anyString())).thenReturn(false);
Answer<Void> answer = newAnswer("&TestPool", "addLocators",
"#{T(example.app.config.GemFireProperties).locatorHostsPorts()}",
String.valueOf(PoolParser.DEFAULT_LOCATOR_PORT));
doAnswer(answer).when(mockRegistry).registerBeanDefinition(eq(generateBeanName(MethodInvokingBean.class)),
any(BeanDefinition.class));
BeanDefinitionBuilder poolBuilder = BeanDefinitionBuilder.genericBeanDefinition(
parser.getBeanClass(mockPoolElement));
parser.doParse(mockPoolElement, null, poolBuilder);
BeanDefinition poolDefinition = poolBuilder.getBeanDefinition();
assertThat(poolDefinition).isNotNull();
assertPropertyNotPresent(poolDefinition, "locators");
assertPropertyNotPresent(poolDefinition, "servers");
verify(mockPoolElement, times(1)).getAttribute(eq(PoolParser.ID_ATTRIBUTE));
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());
verify(mockRegistry, times(1)).containsBeanDefinition(eq(generateBeanName(MethodInvokingBean.class)));
verify(mockRegistry, times(1)).registerBeanDefinition(eq(generateBeanName(MethodInvokingBean.class)),
isA(BeanDefinition.class));
}
@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);
when(mockRegistry.containsBeanDefinition(anyString())).thenReturn(false);
Answer<Void> answer = newAnswer("&TestPool", "addServers", "${gemfire.server.hosts-and-ports}",
String.valueOf(PoolParser.DEFAULT_SERVER_PORT));
doAnswer(answer).when(mockRegistry).registerBeanDefinition(eq(generateBeanName(MethodInvokingBean.class)),
any(BeanDefinition.class));
BeanDefinitionBuilder poolBuilder = BeanDefinitionBuilder.genericBeanDefinition(
parser.getBeanClass(mockPoolElement));
parser.doParse(mockPoolElement, null, poolBuilder);
BeanDefinition poolDefinition = poolBuilder.getBeanDefinition();
assertThat(poolDefinition).isNotNull();
assertPropertyNotPresent(poolDefinition, "locators");
assertPropertyNotPresent(poolDefinition, "servers");
verify(mockPoolElement, times(1)).getAttribute(eq(PoolParser.ID_ATTRIBUTE));
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());
verify(mockRegistry, times(1)).containsBeanDefinition(eq(generateBeanName(MethodInvokingBean.class)));
verify(mockRegistry, times(1)).registerBeanDefinition(eq(generateBeanName(MethodInvokingBean.class)),
isA(BeanDefinition.class));
}
@Test
public void buildConnection() {
assertBeanDefinition(parser.buildConnection("earth", "1234", true), "earth", "1234");
assertBeanDefinition(parser.buildConnection("mars", " ", true), "mars",
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("jupiter", "9876", false), "jupiter", "9876");
assertBeanDefinition(parser.buildConnection("saturn", null, false), "saturn",
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 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");
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);
when(mockElement.getAttribute(PoolParser.HOST_ATTRIBUTE_NAME)).thenReturn("");
when(mockElement.getAttribute(PoolParser.PORT_ATTRIBUTE_NAME)).thenReturn(null);
assertBeanDefinition(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] ");
when(mockRegistry.containsBeanDefinition(anyString())).thenReturn(false);
Answer<Void> answer = newAnswer("&TestPool", "addLocators", "jupiter, saturn[1234], [9876] ",
String.valueOf(PoolParser.DEFAULT_LOCATOR_PORT));
doAnswer(answer).when(mockRegistry).registerBeanDefinition(eq(generateBeanName(MethodInvokingBean.class)),
any(BeanDefinition.class));
assertThat(parser.parseLocators(mockElement, mockRegistry)).isTrue();
verify(mockElement, times(1)).getAttribute(eq(PoolParser.ID_ATTRIBUTE));
verify(mockElement, times(1)).getAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME));
verify(mockRegistry, times(1)).containsBeanDefinition(eq(generateBeanName(MethodInvokingBean.class)));
verify(mockRegistry, times(1)).registerBeanDefinition(eq(generateBeanName(MethodInvokingBean.class)),
isA(BeanDefinition.class));
}
@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");
assertBeanDefinition(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("");
assertBeanDefinition(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]");
when(mockRegistry.containsBeanDefinition(anyString())).thenReturn(false);
Answer<Void> answer = newAnswer("&TestPool", "addServers", "mars[], venus[9876]",
String.valueOf(PoolParser.DEFAULT_SERVER_PORT));
doAnswer(answer).when(mockRegistry).registerBeanDefinition(eq(generateBeanName(MethodInvokingBean.class)),
any(BeanDefinition.class));
assertThat(parser.parseServers(mockElement, mockRegistry)).isTrue();
verify(mockElement, times(1)).getAttribute(eq(PoolParser.ID_ATTRIBUTE));
verify(mockElement, times(1)).getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME));
}
}

View File

@@ -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));
}
}

View File

@@ -176,7 +176,8 @@ public class ConnectionEndpointTest {
public void parseWithInvalidDefaultPort() {
exception.expect(IllegalArgumentException.class);
exception.expectCause(is(nullValue(Throwable.class)));
exception.expectMessage("port number (-1248) must be between 0 and 65535");
exception.expectMessage("port number [-1248] must be between 0 and 65535");
ConnectionEndpoint.parse("localhost", -1248);
}
@@ -219,7 +220,8 @@ public class ConnectionEndpointTest {
public void constructConnectionEndpointWithInvalidPort() {
exception.expect(IllegalArgumentException.class);
exception.expectCause(is(nullValue(Throwable.class)));
exception.expectMessage("port number (-1) must be between 0 and 65535");
exception.expectMessage("port number [-1] must be between 0 and 65535");
new ConnectionEndpoint("localhost", -1);
}
@@ -266,5 +268,4 @@ public class ConnectionEndpointTest {
assertThat(socketAddress.getHostName(), is(equalTo(connectionEndpoint.getHost())));
assertThat(socketAddress.getPort(), is(equalTo(connectionEndpoint.getPort())));
}
}

View File

@@ -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> T getFirst(T... array) {
return getFirst(array, null);
}
public static <T> T getFirst(T[] array, T defaultValue) {
return (isEmpty(array) ? defaultValue : array[0]);
}
}

View File

@@ -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 <T> List<T> subList(final List<T> source, final int... indices) {
List<T> result = new ArrayList<T>(indices.length);
for (int index : indices) {
result.add(source.get(index));
}
return result;
}
}

View File

@@ -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 {
}
}
}
}

View File

@@ -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, String.class), is(sameInstance(stringArray)));
Integer[] numberArray = { 1, 2, 3 };
assertThat(ArrayUtils.nullSafeArray(numberArray, Integer.class), is(sameInstance(numberArray)));
Double[] emptyDoubleArray = {};
assertThat(ArrayUtils.nullSafeArray(emptyDoubleArray, Double.class), is(sameInstance(emptyDoubleArray)));
Character[] characterArray = { 'A', 'B', 'C' };
assertThat(ArrayUtils.nullSafeArray(characterArray, Character.class), is(sameInstance(characterArray)));
}
@Test
public void nullSafeArrayWithNullArray() {
Object array = ArrayUtils.nullSafeArray(null, String.class);
assertThat(array, is(instanceOf(String[].class)));
assertThat(((String[]) 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]);
}
}

View File

@@ -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 });
}
}

View File

@@ -16,14 +16,9 @@
package org.springframework.data.gemfire.util;
import static org.hamcrest.Matchers.equalTo;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.sameInstance;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -39,17 +34,19 @@ 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;
/**
* Test suite of test cases testing the contract and functionality of the {@link CollectionUtils} class.
* Unit tests for {@link CollectionUtils}.
*
* @author John Blum
* @see java.util.Collection
* @see java.util.Collections
* @see java.util.List
* @see java.util.Enumeration
* @see java.util.Iterator
* @see java.util.List
* @see java.util.Map
* @see java.util.Set
* @see org.junit.Test
@@ -57,7 +54,10 @@ import org.junit.Test;
* @see org.springframework.data.gemfire.util.CollectionUtils
* @since 1.7.0
*/
public class CollectionUtilsTest {
public class CollectionUtilsUnitTests {
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void asSetContainsAllArrayElements() {
@@ -65,9 +65,9 @@ public class CollectionUtilsTest {
Set<?> set = CollectionUtils.asSet(elements);
assertThat(set, is(notNullValue(Set.class)));
assertThat(set.size(), is(equalTo(elements.length)));
assertThat(set.containsAll(Arrays.asList(elements)), is(true));
assertThat(set).isNotNull();
assertThat(set.size()).isEqualTo(elements.length);
assertThat(set).containsAll(Arrays.asList(elements));
}
@Test
@@ -76,17 +76,17 @@ public class CollectionUtilsTest {
Set<?> set = CollectionUtils.asSet(elements);
assertThat(set, is(notNullValue(Set.class)));
assertThat(set.size(), is(equalTo(2)));
assertThat(set.containsAll(Arrays.asList(elements)), is(true));
assertThat(set).isNotNull();
assertThat(set.size()).isEqualTo(2);
assertThat(set).containsAll(Arrays.asList(elements));
}
@Test(expected = UnsupportedOperationException.class)
public void asSetReturnsUnmodifiableSet() {
Set<Integer> set = CollectionUtils.asSet(1, 2, 3);
assertThat(set, is(notNullValue(Set.class)));
assertThat(set.size(), is(equalTo(3)));
assertThat(set).isNotNull();
assertThat(set.size()).isEqualTo(3);
try {
set.add(4);
@@ -94,7 +94,7 @@ public class CollectionUtilsTest {
set.remove(2);
}
catch (UnsupportedOperationException e) {
assertThat(set.size(), is(equalTo(3)));
assertThat(set.size()).isEqualTo(3);
throw e;
}
}
@@ -110,7 +110,7 @@ public class CollectionUtilsTest {
Iterable<String> iterable = CollectionUtils.iterable(mockEnumeration);
assertThat(iterable, is(notNullValue()));
assertThat(iterable).isNotNull();
List<String> actualList = new ArrayList<String>(3);
@@ -118,7 +118,7 @@ public class CollectionUtilsTest {
actualList.add(element);
}
assertThat(actualList, is(equalTo(Arrays.asList("zero", "one", "two"))));
assertThat(actualList).isEqualTo(Arrays.asList("zero", "one", "two"));
verify(mockEnumeration, times(4)).hasMoreElements();
verify(mockEnumeration, times(3)).nextElement();
@@ -135,7 +135,7 @@ public class CollectionUtilsTest {
Iterable<String> iterable = CollectionUtils.iterable(mockIterator);
assertThat(iterable, is(notNullValue()));
assertThat(iterable).isNotNull();
List<String> actualList = new ArrayList<String>(3);
@@ -143,7 +143,7 @@ public class CollectionUtilsTest {
actualList.add(element);
}
assertThat(actualList, is(equalTo(Arrays.asList("zero", "one", "two"))));
assertThat(actualList).containsAll(Arrays.asList("zero", "one", "two"));
verify(mockIterator, times(4)).hasNext();
verify(mockIterator, times(3)).next();
@@ -153,15 +153,15 @@ public class CollectionUtilsTest {
public void nullSafeCollectionWithNonNullCollection() {
Collection<?> mockCollection = mock(Collection.class);
assertSame(mockCollection, CollectionUtils.nullSafeCollection(mockCollection));
assertThat(CollectionUtils.nullSafeCollection(mockCollection)).isSameAs(mockCollection);
}
@Test
public void nullSafeCollectionWithNullCollection() {
Collection collection = CollectionUtils.nullSafeCollection(null);
assertThat(collection, is(notNullValue(Collection.class)));
assertThat(collection.isEmpty(), is(true));
assertThat(collection).isNotNull();
assertThat(collection.isEmpty()).isTrue();
}
@Test
@@ -169,37 +169,43 @@ public class CollectionUtilsTest {
public void nullSafeIterableWithNonNullIterable() {
Iterable<Object> mockIterable = mock(Iterable.class);
assertThat(CollectionUtils.nullSafeIterable(mockIterable), is(sameInstance(mockIterable)));
assertThat(CollectionUtils.nullSafeIterable(mockIterable)).isSameAs(mockIterable);
}
@Test
public void nullSafeIterableWithNullIterable() {
Iterable<Object> iterable = CollectionUtils.nullSafeIterable(null);
assertThat(iterable, is(not(nullValue(Iterable.class))));
assertThat(iterable.iterator(), is(not(nullValue(Iterator.class))));
assertThat(iterable).isNotNull();
assertThat(iterable.iterator()).isNotNull();
assertThat(iterable.iterator().hasNext()).isFalse();
}
@Test(expected = UnsupportedOperationException.class)
public void nullSafeIterableIterator() {
Iterator<Object> iterator = CollectionUtils.nullSafeIterable(null).iterator();
Iterable<Object> iterable = CollectionUtils.nullSafeIterable(null);
assertThat(iterator, is(not(nullValue())));
assertThat(iterator.hasNext(), is(equalTo(false)));
assertThat(iterable).isNotNull();
Iterator<Object> iterator = iterable.iterator();
assertThat(iterator).isNotNull();
assertThat(iterator.hasNext()).isFalse();
try {
iterator.next();
}
catch (NoSuchElementException ignore) {
assertThat(ignore.getMessage(), is(equalTo("No more elements")));
assertThat(ignore.getCause(), is(nullValue()));
assertThat(ignore.getMessage()).isEqualTo("No more elements");
assertThat(ignore.getCause()).isNull();
try {
iterator.remove();
}
catch (UnsupportedOperationException expected) {
assertThat(expected.getMessage(), is(equalTo("Operation not supported")));
assertThat(expected.getCause(), is(nullValue()));
assertThat(expected.getMessage()).isEqualTo("Operation not supported");
assertThat(expected.getCause()).isNull();
throw expected;
}
}
@@ -209,44 +215,86 @@ public class CollectionUtilsTest {
public void nullSafeListWithNonNullList() {
List<?> mockList = mock(List.class);
assertSame(mockList, CollectionUtils.nullSafeList(mockList));
assertThat(CollectionUtils.nullSafeList(mockList)).isSameAs(mockList);
}
@Test
public void nullSafeListWithNullList() {
List<?> list = CollectionUtils.nullSafeList(null);
assertThat(list, is(notNullValue(List.class)));
assertThat(list.isEmpty(), is(true));
assertThat(list).isNotNull();
assertThat(list.isEmpty()).isTrue();
}
@Test
public void nullSafeMapWithNonNullMap() {
Map<?, ?> mockMap = mock(Map.class);
assertSame(mockMap, CollectionUtils.nullSafeMap(mockMap));
assertThat(CollectionUtils.nullSafeMap(mockMap)).isSameAs(mockMap);
}
@Test
public void nullSafeMapWithNullMap() {
Map<?, ?> map = CollectionUtils.nullSafeMap(null);
assertThat(map, is(notNullValue(Map.class)));
assertThat(map.isEmpty(), is(true));
assertThat(map).isNotNull();
assertThat(map.isEmpty()).isTrue();
}
@Test
public void nullSafeSetWithNonNullSet() {
Set<?> mockSet = mock(Set.class);
assertSame(mockSet, CollectionUtils.nullSafeSet(mockSet));
assertThat(CollectionUtils.nullSafeSet(mockSet)).isSameAs(mockSet);
}
@Test
public void nullSafeSetWithNullSet() {
Set<?> set = CollectionUtils.nullSafeSet(null);
assertThat(set, is(notNullValue(Set.class)));
assertThat(set.isEmpty(), is(true));
assertThat(set).isNotNull();
assertThat(set.isEmpty()).isTrue();
}
@Test
public void sortIsSuccessful() {
List<Integer> list = new ArrayList<Integer>(Arrays.asList(2, 3, 1));
List<Integer> sortedList = CollectionUtils.sort(list);
assertThat(sortedList).isSameAs(list);
assertThat(sortedList).isEqualTo(Arrays.asList(1, 2, 3));
}
@Test
public void subListFromListWithIndexesReturnsSubList() {
List<Integer> list = Arrays.asList(0, 1, 2, 3);
List<Integer> 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<Integer> 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);
}
}

View File

@@ -17,12 +17,18 @@
<prop key="gemfire.cache.client.locators.hosts-and-ports">backspace,jambox[11235],skullbox[12480]</prop>
<prop key="gemfire.cache.client.server.1.host">saturn</prop>
<prop key="gemfire.cache.client.server.1.port">41414</prop>
<prop key="gemfire.cache.client.server.2.host">mars</prop>
<prop key="gemfire.cache.client.server.2.port">5112</prop>
<prop key="gemfire.cache.client.servers.hosts-and-ports">boombox[1234],jambox,toolbox[81$81%]*</prop>
</util:properties>
<context:property-placeholder properties-ref="clientProperties"/>
<bean class="org.springframework.data.gemfire.client.PoolUsingLocatorsAndServersPropertyPlaceholdersTest.TestBeanFactoryPostProcessor"/>
<bean class="org.springframework.data.gemfire.client.PoolsConfiguredWithLocatorsAndServersExpressionsIntegrationTests.TestBeanFactoryPostProcessor"/>
<bean id="spelBean" class="org.springframework.data.gemfire.client.PoolsConfiguredWithLocatorsAndServersExpressionsIntegrationTests.SpELBoundBean">
<constructor-arg index="0" ref="clientProperties"/>
</bean>
<gfe:pool id="locatorPool" locators="${gemfire.cache.client.locators.hosts-and-ports}">
<gfe:locator host="${gemfire.cache.client.locator.1.host}" port="${gemfire.cache.client.locator.1.port}"/>
@@ -30,10 +36,13 @@
</gfe:pool>
<gfe:pool id="serverPool" servers="mercury[1234],venus[9876],earth[4554],jupiter[],uranis[$Ox0+(!)*]">
<gfe:server host="#{spelBean.serverTwoHost()}" port="#{spelBean.serverTwoPort()}"/>
<gfe:server host="${gemfire.cache.client.server.1.host}" port="${gemfire.cache.client.server.1.port}"/>
<gfe:server host="neptune" port="42424"/>
</gfe:pool>
<gfe:pool id="anotherLocatorPool" locators="[10335], cardboardbox[], #{spelBean.locatorsHostsPorts()}"/>
<gfe:pool id="anotherServerPool" servers="${gemfire.cache.client.servers.hosts-and-ports}"/>
</beans>

View File

@@ -25,25 +25,25 @@
<gfe:pool id="simple"/>
<gfe:pool id="locator" locators="skullbox, yorktown[12480]"/>
<gfe:pool id="locator" locators="skullbox, ghostrider[12480]"/>
<gfe:pool id="server" free-connection-timeout="2000" idle-timeout="20000" load-conditioning-interval="10000"
keep-alive="true" max-connections="100" min-connections="5" multi-user-authentication="true"
ping-interval="5000" pr-single-hop-enabled="false" read-timeout="500" retry-attempts="5"
server-group="TestGroup" socket-buffer-size="65536" statistic-interval="5000"
server-group="TestGroup" socket-buffer-size="65536" statistic-interval="250"
subscription-ack-interval="250" subscription-enabled="true" subscription-message-tracking-timeout="30000"
subscription-redundancy="2" thread-local-connections="true">
subscription-redundancy="2" thread-local-connections="false">
<gfe:server host="localhost" port="${gfe.port.4}"/>
<gfe:server host="localhost" port="40405"/>
<gfe:server host="localhost" port="50505"/>
</gfe:pool>
<gfe:pool id="combo-locators" locators="lavatube[11235], zod">
<gfe:locator host="foobar" port="55421"/>
<gfe:pool id="locators" locators="venus[11235], mars, [12480]">
<gfe:locator host="earth" port="54321"/>
</gfe:pool>
<gfe:pool id="combo-servers" servers="skullbox[9110]">
<gfe:server host="scorch" port="21480"/>
<gfe:server host="scorn" port="51515"/>
<gfe:pool id="servers" servers="skullbox[9110]">
<gfe:server host="duke" port="21480"/>
<gfe:server host="nukem" port="51515"/>
</gfe:pool>
</beans>