diff --git a/spring-data-geode/src/main/java/org/springframework/data/gemfire/GemFireProperties.java b/spring-data-geode/src/main/java/org/springframework/data/gemfire/GemFireProperties.java new file mode 100644 index 00000000..a134fb1a --- /dev/null +++ b/spring-data-geode/src/main/java/org/springframework/data/gemfire/GemFireProperties.java @@ -0,0 +1,241 @@ +/* + * Copyright 2020 the original author 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 + * + * https://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; + +import static org.springframework.data.gemfire.util.RuntimeExceptionFactory.newIllegalArgumentException; + +import java.io.File; +import java.util.Arrays; + +import org.apache.geode.distributed.ConfigurationProperties; + +import org.springframework.core.convert.ConversionService; +import org.springframework.core.convert.support.DefaultConversionService; +import org.springframework.util.Assert; + +/** + * An enumeration of Apache Geode {@literal gemfire.properties}. + * + * @author John Blum + * @see org.apache.geode.distributed.ConfigurationProperties + * @since 2.3.0 + */ +@SuppressWarnings("unused") +public enum GemFireProperties { + + ACK_SEVERE_ALERT_THRESHOLD(ConfigurationProperties.ACK_SEVERE_ALERT_THRESHOLD, Long.class, 0), + ACK_WAIT_THRESHOLD(ConfigurationProperties.ACK_WAIT_THRESHOLD, Long.class, 15), + ARCHIVE_DISK_SPACE_LIMIT(ConfigurationProperties.ARCHIVE_DISK_SPACE_LIMIT, Integer.class, 0), + ARCHIVE_FILE_SIZE_LIMIT(ConfigurationProperties.ARCHIVE_FILE_SIZE_LIMIT, Integer.class, 0), + ASYNC_DISTRIBUTION_TIMEOUT(ConfigurationProperties.ASYNC_DISTRIBUTION_TIMEOUT, Long.class, 0), + ASYNC_MAX_QUEUE_SIZE(ConfigurationProperties.ASYNC_MAX_QUEUE_SIZE, Integer.class, 8), + ASYNC_QUEUE_TIMEOUT(ConfigurationProperties.ASYNC_QUEUE_TIMEOUT, Long.class, 60000), + BIND_ADDRESS(ConfigurationProperties.BIND_ADDRESS, String.class), + CACHE_XML_FILE(ConfigurationProperties.CACHE_XML_FILE, String.class), + CLUSTER_CONFIGURATION_DIR(ConfigurationProperties.CLUSTER_CONFIGURATION_DIR, File.class), + CONFLATE_EVENTS(ConfigurationProperties.CONFLATE_EVENTS, String.class, "server"), + CONSERVE_SOCKETS(ConfigurationProperties.CONSERVE_SOCKETS, Boolean.class, true), + DELTA_PROPAGATION(ConfigurationProperties.DELTA_PROPAGATION, Boolean.class, true), + DEPLOY_WORKING_DIRECTORY(ConfigurationProperties.DEPLOY_WORKING_DIR, File.class, new File(".")), + DISABLE_AUTO_RECONNECT(ConfigurationProperties.DISABLE_AUTO_RECONNECT, Boolean.class, false), + DISABLE_JMX(ConfigurationProperties.DISABLE_JMX, Boolean.class, false), + DISABLE_TCP(ConfigurationProperties.DISABLE_TCP, Boolean.class, false), + DISTRIBUTED_SYSTEM_ID(ConfigurationProperties.DISTRIBUTED_SYSTEM_ID, Integer.class, -1), + DISTRIBUTED_TRANSACTIONS(ConfigurationProperties.DISTRIBUTED_TRANSACTIONS, Boolean.class, false), + DURABLE_CLIENT_ID(ConfigurationProperties.DURABLE_CLIENT_ID, String.class), + DURABLE_CLIENT_TIMEOUT(ConfigurationProperties.DURABLE_CLIENT_TIMEOUT, Long.class, 300L), + ENABLE_CLUSTER_CONFIGURATION(ConfigurationProperties.ENABLE_CLUSTER_CONFIGURATION, Boolean.class, true), + ENABLE_MANAGEMENT_REST_SERVICE(ConfigurationProperties.ENABLE_MANAGEMENT_REST_SERVICE, Boolean.class,true), + ENABLE_NETWORK_PARTITION_DETECTION(ConfigurationProperties.ENABLE_NETWORK_PARTITION_DETECTION, Boolean.class, true), + ENABLE_TIME_STATISTICS(ConfigurationProperties.ENABLE_TIME_STATISTICS, Boolean.class, false), + ENFORCE_UNIQUE_HOST(ConfigurationProperties.ENFORCE_UNIQUE_HOST, Boolean.class, false), + //GEODE_DISALLOW_INTERNAL_MESSAGES_WITHOUT_CREDENTIALS("geode.disallow-internal-messages-without-credentials", Boolean.class, false), + GROUPS(ConfigurationProperties.GROUPS, String.class), + HTTP_SERVICE_BIND_ADDRESS(ConfigurationProperties.HTTP_SERVICE_BIND_ADDRESS, String.class), + HTTP_SERVICE_PORT(ConfigurationProperties.HTTP_SERVICE_PORT, Integer.class, 7070), + JMX_MANAGER(ConfigurationProperties.JMX_MANAGER, Boolean.class, false), + JMX_MANAGER_ACCESS_FILE(ConfigurationProperties.JMX_MANAGER_ACCESS_FILE, File.class), + JMX_MANAGER_BIND_ADDRESS(ConfigurationProperties.JMX_MANAGER_BIND_ADDRESS, String.class), + JMX_MANAGER_HOSTNAME_FOR_CLIENTS(ConfigurationProperties.JMX_MANAGER_HOSTNAME_FOR_CLIENTS, String.class), + JMX_MANAGER_PASSWORD_FILE(ConfigurationProperties.JMX_MANAGER_PASSWORD_FILE, File.class), + JMX_MANAGER_PORT(ConfigurationProperties.JMX_MANAGER_PORT, Integer.class, 1099), + JMX_MANAGER_START(ConfigurationProperties.JMX_MANAGER_START, Boolean.class, false), + JMX_MANAGER_UPDATE_RATE(ConfigurationProperties.JMX_MANAGER_UPDATE_RATE, Long.class, 2000L), + LOAD_CLUSTER_CONFIGURATION_FROM_DIR(ConfigurationProperties.LOAD_CLUSTER_CONFIGURATION_FROM_DIR, Boolean.class, false), + LOCATOR_WAIT_TIME(ConfigurationProperties.LOCATOR_WAIT_TIME, Long.class, 0), + LOCATORS(ConfigurationProperties.LOCATORS, String.class), + LOCK_MEMORY(ConfigurationProperties.LOCK_MEMORY, Boolean.class, false), + LOG_DISK_SPACE_LIMIT(ConfigurationProperties.LOG_DISK_SPACE_LIMIT, Integer.class, 0), + LOG_FILE(ConfigurationProperties.LOG_FILE, String.class), + LOG_FILE_SIZE_LIMIT(ConfigurationProperties.LOG_FILE_SIZE_LIMIT, Integer.class, 0), + LOG_LEVEL(ConfigurationProperties.LOG_LEVEL, String.class, "config"), + MAX_NUM_RECONNECT_TRIES(ConfigurationProperties.MAX_NUM_RECONNECT_TRIES, Integer.class, 3), + MAX_WAIT_TIME_RECONNECT(ConfigurationProperties.MAX_WAIT_TIME_RECONNECT, Long.class, 60000), + MCAST_ADDRESS(ConfigurationProperties.MCAST_ADDRESS, String.class, "239.192.81.1"), + MCAST_FLOW_CONTROL(ConfigurationProperties.MCAST_FLOW_CONTROL, String.class, "1048576,0.25, 5000"), + MCAST_PORT(ConfigurationProperties.MCAST_PORT, Integer.class, 10334), + MCAST_RECV_BUFFER_SIZE(ConfigurationProperties.MCAST_RECV_BUFFER_SIZE, Integer.class, 1048576), + MCAST_SEND_BUFFER_SIZE(ConfigurationProperties.MCAST_SEND_BUFFER_SIZE, Integer.class, 65535), + MCAST_TTL(ConfigurationProperties.MCAST_TTL, Integer.class, 32), + MEMBER_TIMEOUT(ConfigurationProperties.MEMBER_TIMEOUT, Long.class, 5000L), + MEMBERSHIP_PORT_RANGE(ConfigurationProperties.MEMBERSHIP_PORT_RANGE, String.class, "41000-61000"), + MEMCACHED_BIND_ADDRESS(ConfigurationProperties.MEMCACHED_BIND_ADDRESS, String.class), + MEMCACHED_PORT(ConfigurationProperties.MEMCACHED_PORT, Integer.class, 0), + MEMCACHED_PROTOCOL(ConfigurationProperties.MEMCACHED_PROTOCOL, String.class, "ASCII"), + NAME(ConfigurationProperties.NAME, String.class), + OFF_HEAP_MEMORY_SIZE(ConfigurationProperties.OFF_HEAP_MEMORY_SIZE, Integer.class), + REDUNDANCY_ZONE(ConfigurationProperties.REDUNDANCY_ZONE, String.class), + REDIS_BIND_ADDRESS(ConfigurationProperties.REDIS_BIND_ADDRESS, String.class), + REDIS_PASSWORD(ConfigurationProperties.REDIS_PASSWORD, String.class), + REDIS_PORT(ConfigurationProperties.REDIS_PORT, Integer.class, 0), + REMOTE_LOCATORS(ConfigurationProperties.REMOTE_LOCATORS, String.class), + REMOVE_UNRESPONSIVE_CLIENT(ConfigurationProperties.REMOVE_UNRESPONSIVE_CLIENT, Boolean.class, false), + SECURITY_AUTH_TOKEN_ENABLED_COMPONENTS(ConfigurationProperties.SECURITY_AUTH_TOKEN_ENABLED_COMPONENTS, String[].class), + SECURITY_CLIENT_AUTH_INIT(ConfigurationProperties.SECURITY_CLIENT_AUTH_INIT, String.class), + SECURITY_LOG_FILE(ConfigurationProperties.SECURITY_LOG_FILE, File.class), + SECURITY_LOG_LEVEL(ConfigurationProperties.SECURITY_LOG_LEVEL, String.class, "config"), + SECURITY_MANAGER(ConfigurationProperties.SECURITY_MANAGER, String.class), + SECURITY_PEER_AUTH_INIT(ConfigurationProperties.SECURITY_PEER_AUTH_INIT, String.class), + SECURITY_PEER_VERIFY_MEMBER_TIMEOUT(ConfigurationProperties.SECURITY_PEER_VERIFY_MEMBER_TIMEOUT, Long.class, 1000L), + SECURITY_POST_PROCESSOR(ConfigurationProperties.SECURITY_POST_PROCESSOR, String.class), + SECURITY_SHIRO_INIT(ConfigurationProperties.SECURITY_SHIRO_INIT, String.class), + SECURITY_UDP_DHALO(ConfigurationProperties.SECURITY_UDP_DHALGO, String.class), + SERIALIZABLE_OBJECT_FILTER(ConfigurationProperties.SERIALIZABLE_OBJECT_FILTER, String.class, "!*"), + SERVER_BIND_ADDRESS(ConfigurationProperties.SERVER_BIND_ADDRESS, String.class), + SOCKET_BUFFER_SIZE(ConfigurationProperties.SOCKET_BUFFER_SIZE, Integer.class, 32768), + SOCKET_LEASE_TIME(ConfigurationProperties.SOCKET_LEASE_TIME, Long.class, 60000L), + SSL_ENABLED_COMPONENTS(ConfigurationProperties.SSL_ENABLED_COMPONENTS, String.class, "all"), + SSL_ENDPOINT_IDENTIFICATION_ENABLED(ConfigurationProperties.SSL_ENDPOINT_IDENTIFICATION_ENABLED, Boolean.class, false), + SSL_REQUIRE_AUTHENTICATION(ConfigurationProperties.SSL_REQUIRE_AUTHENTICATION, Boolean.class, true), + SSL_CIPHERS(ConfigurationProperties.SSL_CIPHERS, String.class, "any"), + SSL_CLUSTER_ALIAS(ConfigurationProperties.SSL_CLUSTER_ALIAS, String.class), + SSL_DEFAULT_ALIAS(ConfigurationProperties.SSL_DEFAULT_ALIAS, String.class), + SSL_GATEWAY_ALIAS(ConfigurationProperties.SSL_GATEWAY_ALIAS, String.class), + SSL_JMX_ALIAS(ConfigurationProperties.SSL_JMX_ALIAS, String.class), + SSL_LOCATOR_ALIAS(ConfigurationProperties.SSL_LOCATOR_ALIAS, String.class), + SSL_SERVER_ALIAS(ConfigurationProperties.SSL_SERVER_ALIAS, String.class), + SSL_WEB_ALIAS(ConfigurationProperties.SSL_WEB_ALIAS, String.class), + SSL_WEB_SERVICE_REQUIRE_AUTHENTICATION(ConfigurationProperties.SSL_WEB_SERVICE_REQUIRE_AUTHENTICATION, Boolean.class, false), + SSL_KEYSTORE(ConfigurationProperties.SSL_KEYSTORE, String.class), + SSL_KEYSTORE_PASSWORD(ConfigurationProperties.SSL_KEYSTORE_PASSWORD, String.class), + SSL_KEYSTORE_TYPE(ConfigurationProperties.SSL_KEYSTORE_TYPE, String.class, "JKS"), + SSL_PROTOCOLS(ConfigurationProperties.SSL_PROTOCOLS, String.class, "any"), + SSL_TRUSTSTORE(ConfigurationProperties.SSL_TRUSTSTORE, String.class), + SSL_TRUSTSTORE_PASSWORD(ConfigurationProperties.SSL_TRUSTSTORE_PASSWORD, String.class), + SSL_TRUSTSTORE_TYPE(ConfigurationProperties.SSL_TRUSTSTORE_TYPE, String.class, "JKS"), + SSL_USE_DEFAULT_CONTEXT(ConfigurationProperties.SSL_USE_DEFAULT_CONTEXT, Boolean.class, false), + START_DEV_REST_API(ConfigurationProperties.START_DEV_REST_API, Boolean.class, false), + START_LOCATOR(ConfigurationProperties.START_LOCATOR, Boolean.class), + STATISTIC_ARCHIVE_FILE(ConfigurationProperties.STATISTIC_ARCHIVE_FILE, File.class), + STATISTIC_SAMPLE_RATE(ConfigurationProperties.STATISTIC_SAMPLE_RATE, Long.class, 1000), + STATISTIC_SAMPLING_ENABLED(ConfigurationProperties.STATISTIC_SAMPLING_ENABLED, Boolean.class, false), + TCP_PORT(ConfigurationProperties.TCP_PORT, Integer.class, 0), + THREAD_MONITOR_ENABLED(ConfigurationProperties.THREAD_MONITOR_ENABLED, Boolean.class, true), + THREAD_MONITOR_INTERVAL_MS(ConfigurationProperties.THREAD_MONITOR_INTERVAL, Long.class, 0), + THREAD_MONITOR_TIME_LIMIT(ConfigurationProperties.THREAD_MONITOR_TIME_LIMIT, Long.class, 30000), + //TOMBSTONE_GC_THRESHOLD("tombstone-gc-threshold", Integer.class, 100000), + UDP_FRAGMENT_SIZE(ConfigurationProperties.UDP_FRAGMENT_SIZE, Integer.class, 60000), + UDP_RECV_BUFFER_SIZE(ConfigurationProperties.UDP_RECV_BUFFER_SIZE, Integer.class, 1048576), + UPD_SEND_BUFFER_SIZE(ConfigurationProperties.UDP_SEND_BUFFER_SIZE, Integer.class, 65535), + USE_CLUSTER_CONFIGURATION(ConfigurationProperties.USE_CLUSTER_CONFIGURATION, Boolean.class, true), + USER_COMMAND_PACKAGES(ConfigurationProperties.USER_COMMAND_PACKAGES, String.class), + VALIDATE_SERIALIZABLE_OBJECTS(ConfigurationProperties.VALIDATE_SERIALIZABLE_OBJECTS, Boolean.class, false); + + public static GemFireProperties from(String propertyName) { + + return Arrays.stream(values()) + .filter(it -> equals(it, propertyName)) + .findFirst() + .orElseThrow(() -> newIllegalArgumentException("[%s] is not a valid Apache Geode property")); + } + + private static boolean equals(GemFireProperties property, String propertyName) { + return property != null && property.getName().equals(propertyName); + } + + private Class nullSafeType(Object target, Class defaultType) { + return target != null ? target.getClass() : defaultType; + } + + private static final Class DEFAULT_PROPERTY_TYPE = Object.class; + + private static final Object DEFAULT_PROPERTY_VALUE = null; + + public static final String PROPERTY_NAME_PREFIX = "gemfire."; + + private final Class propertyType; + + private final ConversionService conversionService; + + /** NOTE: a {@literal null} value represents an unset value */ + private final Object defaultValue; + + private final String propertyName; + + GemFireProperties(String propertyName, Class propertyType) { + this(propertyName, propertyType, null); + } + + GemFireProperties(String propertyName, Class propertyType, Object defaultValue) { + + Assert.hasText(propertyName, "Property name is required"); + + this.conversionService = DefaultConversionService.getSharedInstance(); + this.defaultValue = defaultValue; + this.propertyName = propertyName; + this.propertyType = propertyType; + } + + public Object getDefaultValue() { + return this.defaultValue != null ? this.defaultValue : DEFAULT_PROPERTY_VALUE; + } + + public String getDefaultValueAsString() { + return String.valueOf(getDefaultValue()); + } + + public T getDefaultValueAsType() { + return getDefaultValueAsType(getType()); + } + + @SuppressWarnings("unchecked") + public T getDefaultValueAsType(Class type) { + + Object defaultValue = getDefaultValue(); + + Class defaultValueType = nullSafeType(defaultValue, getType()); + + if (this.conversionService.canConvert(defaultValueType, type)) { + return (T) this.conversionService.convert(getDefaultValue(), type); + } + + throw newIllegalArgumentException("Cannot convert value [%s] from type [%s] to type [%s]", + defaultValue, defaultValueType, type); + } + + public String getName() { + return this.propertyName; + } + + public Class getType() { + return this.propertyType != null ? this.propertyType : DEFAULT_PROPERTY_TYPE; + } + + @Override + public String toString() { + return getName(); + } +} diff --git a/spring-data-geode/src/main/java/org/springframework/data/gemfire/PeerRegionFactoryBean.java b/spring-data-geode/src/main/java/org/springframework/data/gemfire/PeerRegionFactoryBean.java index 22efd087..6e2195d9 100644 --- a/spring-data-geode/src/main/java/org/springframework/data/gemfire/PeerRegionFactoryBean.java +++ b/spring-data-geode/src/main/java/org/springframework/data/gemfire/PeerRegionFactoryBean.java @@ -48,7 +48,6 @@ import org.apache.geode.cache.Scope; import org.apache.geode.cache.asyncqueue.AsyncEventQueue; import org.apache.geode.cache.wan.GatewaySender; import org.apache.geode.compression.Compressor; -import org.apache.geode.internal.cache.UserSpecifiedRegionAttributes; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; @@ -59,6 +58,7 @@ import org.springframework.data.gemfire.eviction.EvictingRegionFactoryBean; import org.springframework.data.gemfire.expiration.ExpiringRegionFactoryBean; import org.springframework.data.gemfire.util.CollectionUtils; import org.springframework.data.gemfire.util.RegionUtils; +import org.springframework.data.gemfire.util.SpringUtils; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; import org.springframework.util.ReflectionUtils; @@ -365,7 +365,7 @@ public abstract class PeerRegionFactoryBean extends ConfigurableRegionFact * @see org.apache.geode.cache.RegionAttributes#getDataPolicy * @see org.apache.geode.cache.DataPolicy */ - @SuppressWarnings({ "deprecation", "unchecked" }) + @SuppressWarnings({ "deprecation", "rawtypes", "unchecked" }) DataPolicy getDataPolicy(RegionFactory regionFactory, RegionShortcut regionShortcut) { return getFieldValue(regionFactory, "attrsFactory", AttributesFactory.class) @@ -471,6 +471,7 @@ public abstract class PeerRegionFactoryBean extends ConfigurableRegionFact * @see org.apache.geode.cache.RegionAttributes * @see org.apache.geode.cache.RegionFactory */ + @SuppressWarnings("rawtypes") protected void mergePartitionAttributes(RegionFactory regionFactory, RegionAttributes regionAttributes) { @@ -520,15 +521,19 @@ public abstract class PeerRegionFactoryBean extends ConfigurableRegionFact * * This method is not part of the PeerRegionFactoryBean API and is strictly used for testing purposes! * - * NOTE unfortunately, must resort to using a GemFire internal class, ugh! - * * @see org.apache.geode.internal.cache.UserSpecifiedRegionAttributes#hasEvictionAttributes */ + boolean isUserSpecifiedEvictionAttributes(RegionAttributes regionAttributes) { - boolean isUserSpecifiedEvictionAttributes(final RegionAttributes regionAttributes) { + SpringUtils.ValueReturningThrowableOperation hasEvictionAttributes = () -> + Optional.ofNullable(regionAttributes) + .map(Object::getClass) + .map(type -> ReflectionUtils.findMethod(type, "hasEvictionAttributes")) + .map(method -> ReflectionUtils.invokeMethod(method, regionAttributes)) + .map(Boolean.TRUE::equals) + .orElse(false); - return regionAttributes instanceof UserSpecifiedRegionAttributes - && ((UserSpecifiedRegionAttributes) regionAttributes).hasEvictionAttributes(); + return SpringUtils.safeGetValue(hasEvictionAttributes, false); } /* @@ -538,7 +543,7 @@ public abstract class PeerRegionFactoryBean extends ConfigurableRegionFact * * @see org.apache.geode.cache.AttributesFactory#validateAttributes(:RegionAttributes) */ - @SuppressWarnings("deprecation") + @SuppressWarnings({ "deprecation", "rawtypes" }) void validateRegionAttributes(RegionAttributes regionAttributes) { org.apache.geode.cache.AttributesFactory.validateAttributes(regionAttributes); } @@ -631,6 +636,7 @@ public abstract class PeerRegionFactoryBean extends ConfigurableRegionFact } } + @SuppressWarnings("rawtypes") private DataPolicy getDataPolicy(RegionAttributes regionAttributes, DataPolicy defaultDataPolicy) { return Optional.ofNullable(regionAttributes) diff --git a/spring-data-geode/src/main/java/org/springframework/data/gemfire/config/annotation/AutoConfiguredAuthenticationConfiguration.java b/spring-data-geode/src/main/java/org/springframework/data/gemfire/config/annotation/AutoConfiguredAuthenticationConfiguration.java index 6b142c9d..7278ac3a 100644 --- a/spring-data-geode/src/main/java/org/springframework/data/gemfire/config/annotation/AutoConfiguredAuthenticationConfiguration.java +++ b/spring-data-geode/src/main/java/org/springframework/data/gemfire/config/annotation/AutoConfiguredAuthenticationConfiguration.java @@ -22,11 +22,6 @@ import java.net.URI; import java.util.Optional; import java.util.Properties; -import org.apache.geode.management.internal.security.ResourceConstants; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; @@ -45,6 +40,9 @@ import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpResponse; import org.springframework.util.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * The {@link AutoConfiguredAuthenticationConfiguration} class is a Spring {@link Configuration @Configuration} class * that auto-configures Pivotal GemFire / Apache Geode Authentication by providing a implementation @@ -78,7 +76,9 @@ public class AutoConfiguredAuthenticationConfiguration { protected static final String DEFAULT_PASSWORD = DEFAULT_USERNAME; protected static final String HTTP_PROTOCOL = "HTTP"; protected static final String SECURITY_CLIENT_AUTH_INIT = "security-client-auth-init"; + protected static final String SECURITY_PASSWORD = "security-password"; protected static final String SECURITY_PEER_AUTH_INIT = "security-peer-auth-init"; + protected static final String SECURITY_USERNAME = "security-username"; private Logger logger = LoggerFactory.getLogger(getClass()); @@ -113,28 +113,23 @@ public class AutoConfiguredAuthenticationConfiguration { logger.debug("HTTP Request URI [{}]", request.getURI()); - Optional.ofNullable(request.getHeaders()) - .ifPresent(httpHeaders -> { + HttpHeaders httpHeaders = request.getHeaders(); - CollectionUtils.nullSafeSet(httpHeaders.keySet()).forEach(httpHeaderName -> { - logger.debug("HTTP Request Header Name [{}] Value [{}]", - httpHeaderName, httpHeaders.get(httpHeaderName)); - }); - }); + CollectionUtils.nullSafeSet(httpHeaders.keySet()).forEach(httpHeaderName -> + logger.debug("HTTP Request Header Name [{}] Value [{}]", + httpHeaderName, httpHeaders.get(httpHeaderName))); ClientHttpResponse response = execution.execute(request, body); - Optional.ofNullable(response) - .ifPresent(it -> { - - try { - logger.debug("HTTP Response Status Code [{}] Message [{}]", - it.getRawStatusCode(), it.getStatusText()); - } - catch (IOException cause) { - logger.debug("Error occurred getting HTTP Response Status Code and Message", cause); - } - }); + if (this.logger.isDebugEnabled()) { + try { + this.logger.debug("HTTP Response Status Code [{}] Message [{}]", + response.getRawStatusCode(), response.getStatusText()); + } + catch (IOException cause) { + this.logger.debug("Error occurred getting HTTP Response Status Code and Message", cause); + } + } return response; }; @@ -163,8 +158,8 @@ public class AutoConfiguredAuthenticationConfiguration { HttpHeaders requestHeaders = request.getHeaders(); - requestHeaders.add(ResourceConstants.USER_NAME, username); - requestHeaders.add(ResourceConstants.PASSWORD, String.valueOf(password)); + requestHeaders.add(SECURITY_USERNAME, username); + requestHeaders.add(SECURITY_PASSWORD, String.valueOf(password)); } return execution.execute(request, body); diff --git a/spring-data-geode/src/main/java/org/springframework/data/gemfire/config/annotation/EnableHttpService.java b/spring-data-geode/src/main/java/org/springframework/data/gemfire/config/annotation/EnableHttpService.java index 6aa1a333..19e4b69e 100644 --- a/spring-data-geode/src/main/java/org/springframework/data/gemfire/config/annotation/EnableHttpService.java +++ b/spring-data-geode/src/main/java/org/springframework/data/gemfire/config/annotation/EnableHttpService.java @@ -14,7 +14,6 @@ * limitations under the License. * */ - package org.springframework.data.gemfire.config.annotation; import java.lang.annotation.Annotation; diff --git a/spring-data-geode/src/main/java/org/springframework/data/gemfire/config/annotation/EnableManager.java b/spring-data-geode/src/main/java/org/springframework/data/gemfire/config/annotation/EnableManager.java index f010e222..78a62ce9 100644 --- a/spring-data-geode/src/main/java/org/springframework/data/gemfire/config/annotation/EnableManager.java +++ b/spring-data-geode/src/main/java/org/springframework/data/gemfire/config/annotation/EnableManager.java @@ -14,7 +14,6 @@ * limitations under the License. * */ - package org.springframework.data.gemfire.config.annotation; import java.lang.annotation.Annotation; diff --git a/spring-data-geode/src/main/java/org/springframework/data/gemfire/function/PojoFunctionWrapper.java b/spring-data-geode/src/main/java/org/springframework/data/gemfire/function/PojoFunctionWrapper.java index d8a943e5..a2b93350 100644 --- a/spring-data-geode/src/main/java/org/springframework/data/gemfire/function/PojoFunctionWrapper.java +++ b/spring-data-geode/src/main/java/org/springframework/data/gemfire/function/PojoFunctionWrapper.java @@ -25,13 +25,13 @@ import org.apache.geode.cache.execute.ResultSender; import org.apache.geode.management.internal.security.ResourcePermissions; import org.apache.geode.security.ResourcePermission; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.springframework.util.ObjectUtils; import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * Invokes a given {@link Object POJO} {@link Method} as a (remote) GemFire/Geode {@link Function}. * @@ -49,7 +49,7 @@ import org.springframework.util.StringUtils; * @see org.apache.geode.cache.execute.Function * @since 1.2.0 */ -@SuppressWarnings("serial") +@SuppressWarnings({ "rawtypes", "serial"}) public class PojoFunctionWrapper implements Function { private static transient Logger logger = LoggerFactory.getLogger(PojoFunctionWrapper.class); diff --git a/spring-data-geode/src/main/java/org/springframework/data/gemfire/repository/query/StringBasedGemfireRepositoryQuery.java b/spring-data-geode/src/main/java/org/springframework/data/gemfire/repository/query/StringBasedGemfireRepositoryQuery.java index 843e6ac2..552c8e17 100644 --- a/spring-data-geode/src/main/java/org/springframework/data/gemfire/repository/query/StringBasedGemfireRepositoryQuery.java +++ b/spring-data-geode/src/main/java/org/springframework/data/gemfire/repository/query/StringBasedGemfireRepositoryQuery.java @@ -226,7 +226,7 @@ public class StringBasedGemfireRepositoryQuery extends GemfireRepositoryQuery { Collection toCollection(Object source) { if (source instanceof SelectResults) { - return ((SelectResults) source).asList(); + return ((SelectResults) source).asList(); } if (source instanceof Collection) { @@ -240,6 +240,7 @@ public class StringBasedGemfireRepositoryQuery extends GemfireRepositoryQuery { return source.getClass().isArray() ? CollectionUtils.arrayToList(source) : Collections.singletonList(source); } + @SuppressWarnings("rawtypes") enum ProvidedQueryPostProcessors implements QueryPostProcessor { HINT { @@ -283,7 +284,7 @@ public class StringBasedGemfireRepositoryQuery extends GemfireRepositoryQuery { @Override public String postProcess(QueryMethod queryMethod, String query, Object... arguments) { - if (queryMethod instanceof GemfireQueryMethod) { + if (queryMethod instanceof GemfireQueryMethod) { GemfireQueryMethod gemfireQueryMethod = (GemfireQueryMethod) queryMethod; diff --git a/spring-data-geode/src/main/java/org/springframework/data/gemfire/util/DistributedSystemUtils.java b/spring-data-geode/src/main/java/org/springframework/data/gemfire/util/DistributedSystemUtils.java index 85f46b26..9f4e2c78 100644 --- a/spring-data-geode/src/main/java/org/springframework/data/gemfire/util/DistributedSystemUtils.java +++ b/spring-data-geode/src/main/java/org/springframework/data/gemfire/util/DistributedSystemUtils.java @@ -22,11 +22,10 @@ import org.apache.geode.cache.GemFireCache; import org.apache.geode.cache.server.CacheServer; import org.apache.geode.distributed.DistributedSystem; import org.apache.geode.distributed.Locator; -import org.apache.geode.distributed.internal.DistributionConfig; import org.apache.geode.distributed.internal.InternalDistributedSystem; import org.apache.geode.distributed.internal.InternalLocator; -import org.apache.geode.internal.DistributionLocator; +import org.springframework.data.gemfire.GemFireProperties; import org.springframework.util.Assert; import org.springframework.util.StringUtils; @@ -36,7 +35,6 @@ import org.springframework.util.StringUtils; * @author John Blum * @see org.apache.geode.cache.GemFireCache * @see org.apache.geode.distributed.DistributedSystem - * @see org.apache.geode.distributed.internal.DistributionConfig * @see org.apache.geode.distributed.internal.InternalDistributedSystem * @see org.apache.geode.internal.DistributionLocator * @since 1.7.0 @@ -45,12 +43,12 @@ import org.springframework.util.StringUtils; public abstract class DistributedSystemUtils extends SpringUtils { public static final int DEFAULT_CACHE_SERVER_PORT = CacheServer.DEFAULT_PORT; - public static final int DEFAULT_LOCATOR_PORT = DistributionLocator.DEFAULT_LOCATOR_PORT; + public static final int DEFAULT_LOCATOR_PORT = 10334; - public static final String DURABLE_CLIENT_ID_PROPERTY_NAME = DistributionConfig.DURABLE_CLIENT_ID_NAME; - public static final String DURABLE_CLIENT_TIMEOUT_PROPERTY_NAME = DistributionConfig.DURABLE_CLIENT_TIMEOUT_NAME; - public static final String GEMFIRE_PREFIX = DistributionConfig.GEMFIRE_PREFIX; - public static final String NAME_PROPERTY_NAME = DistributionConfig.NAME_NAME; + public static final String DURABLE_CLIENT_ID_PROPERTY_NAME = GemFireProperties.DURABLE_CLIENT_ID.getName(); + public static final String DURABLE_CLIENT_TIMEOUT_PROPERTY_NAME = GemFireProperties.DURABLE_CLIENT_TIMEOUT.getName(); + public static final String GEMFIRE_PREFIX = GemFireProperties.PROPERTY_NAME_PREFIX; + public static final String NAME_PROPERTY_NAME = GemFireProperties.NAME.getName(); public static Properties configureDurableClient(Properties gemfireProperties, String durableClientId, Integer durableClientTimeout) { diff --git a/spring-data-geode/src/main/java/org/springframework/data/gemfire/util/RegionUtils.java b/spring-data-geode/src/main/java/org/springframework/data/gemfire/util/RegionUtils.java index 750de481..e34cb683 100644 --- a/spring-data-geode/src/main/java/org/springframework/data/gemfire/util/RegionUtils.java +++ b/spring-data-geode/src/main/java/org/springframework/data/gemfire/util/RegionUtils.java @@ -113,7 +113,7 @@ public abstract class RegionUtils extends CacheUtils { * @return a boolean indicating whether the target {@link Region} is a {@literal client} {@link Region}. * @see org.apache.geode.cache.Region */ - public static boolean isClient(Region region) { + public static boolean isClient(Region region) { return Optional.ofNullable(region) .map(Region::getAttributes) diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/GemFirePropertiesUnitTests.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/GemFirePropertiesUnitTests.java new file mode 100644 index 00000000..819b3391 --- /dev/null +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/GemFirePropertiesUnitTests.java @@ -0,0 +1,115 @@ +/* + * Copyright 2020 the original author 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 + * + * https://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; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.lang.reflect.Field; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import java.util.stream.Collectors; + +import org.junit.Test; + +import org.apache.geode.distributed.ConfigurationProperties; + +import org.springframework.util.ReflectionUtils; + +/** + * Unit Tests for {@link GemFireProperties}. + * + * @author John Blum + * @see org.junit.Test + * @see org.apache.geode.distributed.ConfigurationProperties + * @see org.springframework.data.gemfire.GemFireProperties + * @since 2.3.0 + */ +public class GemFirePropertiesUnitTests { + + private static final Set deprecatedGemFireProperties = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( + "cluster-ssl-ciphers", // all 'cluster-ssl-*' properties replaced by 'ssl-*' properties + "cluster-ssl-enabled", + "cluster-ssl-keystore", + "cluster-ssl-keystore-password", + "cluster-ssl-keystore-type", + "cluster-ssl-protocols", + "cluster-ssl-require-authentication", + "cluster-ssl-truststore", + "cluster-ssl-truststore-password", + "jmx-manager-http-port", // replaced by 'http-service-port' property + "roles", + "security-client-accessor", // replaced by SecurityManager + "security-client-accessor-pp", // replaced by SecurityManager + "security-client-authenticator", // replaced by SecurityManager + "security-client-dhalgo", // use SSL instead + "security-peer-authenticator" // replaced by SecurityManager + ))); + + private Set resolveActualGemFirePropertyNames() { + + return Arrays.stream(GemFireProperties.values()) + .map(GemFireProperties::getName) + .collect(Collectors.toSet()); + } + + private Set resolveExpectedNonDeprecatedGemFirePropertyNames() { + + List nonDeprecatedPublicFields = Arrays.stream(ConfigurationProperties.class.getFields()) + .filter(field -> !field.isAnnotationPresent(Deprecated.class)) + .filter(field -> !field.getName().endsWith("PREFIX")) + .collect(Collectors.toList()); + + return nonDeprecatedPublicFields.stream() + .map(field -> ReflectionUtils.getField(field, null)) + .map(String::valueOf) + .filter(propertyName -> !deprecatedGemFireProperties.contains(propertyName)) + .collect(Collectors.toSet()); + } + + @Test + public void enumeratedGemFirePropertiesContainAllConfigurationProperties() { + + Set actualGemFireProperties = resolveActualGemFirePropertyNames(); + Set expectedGemFireProperties = resolveExpectedNonDeprecatedGemFirePropertyNames(); + Set missingGemFireProperties = new TreeSet<>(expectedGemFireProperties); + + missingGemFireProperties.removeAll(actualGemFireProperties); + + assertThat(missingGemFireProperties) + .describedAs("Expected properties in [%s] not in [%s] include (%s)", + ConfigurationProperties.class.getName(), GemFireProperties.class.getName(), missingGemFireProperties) + .isEmpty(); + } + + @Test + public void enumeratedGemFirePropertiesMatchConfigurationProperties() { + + Set actualGemFireProperties = resolveActualGemFirePropertyNames(); + Set expectedGemFireProperties = resolveExpectedNonDeprecatedGemFirePropertyNames(); + Set missingGemFireProperties = new TreeSet<>(actualGemFireProperties); + + missingGemFireProperties.removeAll(expectedGemFireProperties); + + assertThat(missingGemFireProperties) + .describedAs("Unexpected properties in [%s] not in [%s] include (%s)", + GemFireProperties.class.getName(), ConfigurationProperties.class.getName(), missingGemFireProperties) + .isEmpty(); + } +} diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/PeerRegionFactoryBeanTest.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/PeerRegionFactoryBeanTest.java index 4f51b1c6..c9185dfc 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/PeerRegionFactoryBeanTest.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/PeerRegionFactoryBeanTest.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.springframework.data.gemfire; import static org.junit.Assert.assertEquals; @@ -23,12 +22,12 @@ import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyBoolean; -import static org.mockito.Matchers.anyFloat; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.eq; -import static org.mockito.Matchers.same; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyFloat; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; @@ -37,6 +36,9 @@ import static org.mockito.Mockito.when; import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.After; +import org.junit.Test; + import org.apache.geode.cache.Cache; import org.apache.geode.cache.CustomExpiry; import org.apache.geode.cache.DataPolicy; @@ -50,16 +52,12 @@ import org.apache.geode.cache.RegionAttributes; import org.apache.geode.cache.RegionFactory; import org.apache.geode.cache.RegionShortcut; import org.apache.geode.cache.SubscriptionAttributes; -import org.apache.geode.internal.cache.GemFireCacheImpl; - -import org.junit.After; -import org.junit.Test; import org.springframework.data.gemfire.test.support.AbstractRegionFactoryBeanTests; import org.springframework.data.gemfire.util.ArrayUtils; /** - * Unit tests for {@link PeerRegionFactoryBean}. + * Unit Tests for {@link PeerRegionFactoryBean}. * * @author David Turanski * @author John Blum @@ -73,23 +71,24 @@ import org.springframework.data.gemfire.util.ArrayUtils; * @see PeerRegionFactoryBean * @see org.springframework.data.gemfire.test.support.AbstractRegionFactoryBeanTests */ -@SuppressWarnings("unchecked") +@SuppressWarnings({ "rawtypes", "unchecked" }) public class PeerRegionFactoryBeanTest extends AbstractRegionFactoryBeanTests { private final PeerRegionFactoryBean factoryBean = new TestRegionFactoryBean(); @After public void tearDown() { - factoryBean.setDataPolicy((DataPolicy) null); + + factoryBean.setDataPolicy(null); factoryBean.setShortcut(null); } - @SuppressWarnings("rawtypes") private RegionFactoryBeanConfig defaultConfig() { + return new RegionFactoryBeanConfig(new TestRegionFactoryBean(), "default") { + @Override - public void configureRegionFactoryBean() { - } + public void configureRegionFactoryBean() { } @Override public void verify() { @@ -99,9 +98,10 @@ public class PeerRegionFactoryBeanTest extends AbstractRegionFactoryBeanTests { }; } - @SuppressWarnings("rawtypes") private RegionFactoryBeanConfig persistentConfig() { + return new RegionFactoryBeanConfig(new TestRegionFactoryBean(), "persistent") { + @Override public void configureRegionFactoryBean() { regionFactoryBean.setPersistent(true); @@ -115,7 +115,6 @@ public class PeerRegionFactoryBeanTest extends AbstractRegionFactoryBeanTests { }; } - @SuppressWarnings({ "deprecation", "rawtypes" }) private RegionFactoryBeanConfig invalidPersistentConfig() { return new RegionFactoryBeanConfig(new TestRegionFactoryBean(), "invalid-persistence") { @@ -883,7 +882,7 @@ public class PeerRegionFactoryBeanTest extends AbstractRegionFactoryBeanTests { RegionFactory mockRegionFactory = createMockRegionFactory(); factoryBean.setAttributes(createMockRegionAttributes(DataPolicy.PRELOADED)); - factoryBean.setDataPolicy((DataPolicy) null); + factoryBean.setDataPolicy(null); factoryBean.resolveDataPolicy(mockRegionFactory, null, (String) null); verify(mockRegionFactory, times(1)).setDataPolicy(eq(DataPolicy.PRELOADED)); @@ -896,7 +895,7 @@ public class PeerRegionFactoryBeanTest extends AbstractRegionFactoryBeanTests { RegionFactory mockRegionFactory = createMockRegionFactory(); factoryBean.setAttributes(createMockRegionAttributes(DataPolicy.PARTITION)); - factoryBean.setDataPolicy((DataPolicy) null); + factoryBean.setDataPolicy(null); factoryBean.setPersistent(false); factoryBean.resolveDataPolicy(mockRegionFactory, false, (String) null); @@ -910,7 +909,7 @@ public class PeerRegionFactoryBeanTest extends AbstractRegionFactoryBeanTests { RegionFactory mockRegionFactory = createMockRegionFactory(); factoryBean.setAttributes(createMockRegionAttributes(DataPolicy.PERSISTENT_PARTITION)); - factoryBean.setDataPolicy((DataPolicy) null); + factoryBean.setDataPolicy(null); factoryBean.setPersistent(true); factoryBean.resolveDataPolicy(mockRegionFactory, true, (String) null); @@ -1084,12 +1083,7 @@ public class PeerRegionFactoryBeanTest extends AbstractRegionFactoryBeanTests { verify(mockRegionFactory).setDataPolicy(eq(DataPolicy.PERSISTENT_REPLICATE)); } - protected static class TestRegionFactory extends RegionFactory { - - protected TestRegionFactory() { - super((GemFireCacheImpl) null); - } - } + protected static class TestRegionFactory extends RegionFactory { } protected static class TestRegionFactoryBean extends PeerRegionFactoryBean { } diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/config/annotation/EnableClusterConfigurationWithSecurityIntegrationTests.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/config/annotation/EnableClusterConfigurationWithSecurityIntegrationTests.java index e8f6b45b..a5c5a3b3 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/config/annotation/EnableClusterConfigurationWithSecurityIntegrationTests.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/config/annotation/EnableClusterConfigurationWithSecurityIntegrationTests.java @@ -37,8 +37,6 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.apache.geode.management.internal.security.ResourceConstants; - import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; @@ -89,6 +87,9 @@ import org.springframework.web.client.RestTemplate; @ContextConfiguration(initializers = EnableClusterConfigurationWithSecurityIntegrationTests.SecurityConfigurationApplicationContextInitializer.class) public class EnableClusterConfigurationWithSecurityIntegrationTests { + private static final String SECURITY_USERNAME = "security-username"; + private static final String SECURITY_PASSWORD = "security-password"; + @Autowired @Qualifier("GemFireSecurityAuthenticator") private Authenticator authenticator; @@ -171,9 +172,9 @@ public class EnableClusterConfigurationWithSecurityIntegrationTests { this.configuration.securityAwareClientHttpRequestInterceptor().intercept(mockHttpRequest, body, mockClientHttpRequestExecution); - assertThat(httpHeaders).containsKeys(ResourceConstants.USER_NAME, ResourceConstants.PASSWORD); - assertThat(httpHeaders.getFirst(ResourceConstants.USER_NAME)).isEqualTo("skeletor"); - assertThat(httpHeaders.getFirst(ResourceConstants.PASSWORD)).isEqualTo("s3cr3t"); + assertThat(httpHeaders).containsKeys(SECURITY_USERNAME, SECURITY_PASSWORD); + assertThat(httpHeaders.getFirst(SECURITY_USERNAME)).isEqualTo("skeletor"); + assertThat(httpHeaders.getFirst(SECURITY_PASSWORD)).isEqualTo("s3cr3t"); verify(mockClientHttpRequestExecution, times(1)).execute(eq(mockHttpRequest), eq(body)); verify(mockHttpRequest, times(1)).getHeaders(); diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/config/annotation/EnableIndexingConfigurationUnitTests.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/config/annotation/EnableIndexingConfigurationUnitTests.java index 337dc231..38613689 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/config/annotation/EnableIndexingConfigurationUnitTests.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/config/annotation/EnableIndexingConfigurationUnitTests.java @@ -14,13 +14,12 @@ * limitations under the License. * */ - package org.springframework.data.gemfire.config.annotation; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -28,11 +27,17 @@ import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; +import org.junit.After; +import org.junit.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + import org.apache.geode.cache.Cache; import org.apache.geode.cache.GemFireCache; import org.apache.geode.cache.Region; @@ -46,13 +51,8 @@ import org.apache.geode.cache.query.Index; import org.apache.geode.cache.query.IndexExistsException; import org.apache.geode.cache.query.IndexNameConflictException; import org.apache.geode.cache.query.QueryService; -import org.apache.geode.internal.concurrent.ConcurrentHashSet; import org.apache.lucene.analysis.Analyzer; -import org.junit.After; -import org.junit.Test; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; @@ -70,7 +70,7 @@ import org.springframework.data.gemfire.config.annotation.test.entities.NonEntit import org.springframework.data.gemfire.config.annotation.test.entities.ReplicateRegionEntity; /** - * Unit tests for the {@link EnableIndexing} and {@link IndexConfiguration} class. + * Unit Tests for the {@link EnableIndexing} and {@link IndexConfiguration} class. * * @author John Blum * @see org.junit.Test @@ -90,10 +90,10 @@ import org.springframework.data.gemfire.config.annotation.test.entities.Replicat * @see org.springframework.data.gemfire.mapping.annotation.LuceneIndexed * @since 1.9.0 */ -@SuppressWarnings("unused") +@SuppressWarnings({ "rawtypes", "unused" }) public class EnableIndexingConfigurationUnitTests { - private static final Set indexes = new ConcurrentHashSet<>(); + private static final Set indexes = Collections.synchronizedSet(new HashSet<>()); private ConfigurableApplicationContext applicationContext; @@ -104,7 +104,7 @@ public class EnableIndexingConfigurationUnitTests { } private static String[] asArray(List list) { - return list.toArray(new String[list.size()]); + return list.toArray(new String[0]); } private static String[] toStringArray(Object[] array) { @@ -236,7 +236,6 @@ public class EnableIndexingConfigurationUnitTests { static class GemFireConfiguration { @Bean - @SuppressWarnings("unchecked") Cache gemfireCache() throws Exception { return mockQueryService(mockRegionFactory(mock(Cache.class, "MockGemFireCache"))); } @@ -271,7 +270,7 @@ public class EnableIndexingConfigurationUnitTests { return mockCache; } - @SuppressWarnings("unchecked") + @SuppressWarnings({ "rawtypes", "unchecked" }) Cache mockRegionFactory(Cache mockCache) { RegionFactory mockRegionFactory = mock(RegionFactory.class); diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/config/annotation/GatewaySenderPropertiesTests.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/config/annotation/GatewaySenderPropertiesTests.java index 0d177c21..50a80589 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/config/annotation/GatewaySenderPropertiesTests.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/config/annotation/GatewaySenderPropertiesTests.java @@ -25,6 +25,9 @@ import java.util.Optional; import java.util.TreeMap; import java.util.stream.Collectors; +import org.junit.After; +import org.junit.Test; + import org.apache.geode.cache.DataPolicy; import org.apache.geode.cache.EntryEvent; import org.apache.geode.cache.GemFireCache; @@ -34,17 +37,10 @@ import org.apache.geode.cache.wan.GatewayEventSubstitutionFilter; import org.apache.geode.cache.wan.GatewayQueueEvent; import org.apache.geode.cache.wan.GatewaySender; import org.apache.geode.cache.wan.GatewayTransportFilter; -import org.apache.geode.distributed.internal.DistributionAdvisor; -import org.apache.geode.internal.cache.EntryEventImpl; -import org.apache.geode.internal.cache.wan.AbstractGatewaySender; - -import org.junit.After; -import org.junit.Test; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertySource; import org.springframework.data.gemfire.PartitionedRegionFactoryBean; @@ -57,15 +53,16 @@ import org.springframework.mock.env.MockPropertySource; * Tests for {@link EnableGatewaySenders} and {@link EnableGatewaySender} to test the configuration of {@link GatewaySender} using properties. * * @author Udo Kohlmeyer - * @see Test - * @see Configuration + * @author John Blum + * @see org.junit.Test * @see org.mockito.Mockito - * @see GatewaySenderConfigurer - * @see GatewaySenderConfiguration + * @see org.springframework.data.gemfire.config.annotation.GatewaySenderConfiguration + * @see org.springframework.data.gemfire.config.annotation.GatewaySenderConfigurer * @see org.apache.geode.cache.server.CacheServer + * @see org.springframework.context.annotation.Configuration + * @see org.springframework.data.gemfire.wan.GatewayReceiverFactoryBean * @see org.springframework.test.context.ContextConfiguration * @see org.springframework.test.context.junit4.SpringRunner - * @see org.springframework.data.gemfire.wan.GatewayReceiverFactoryBean * @since 2.2.0 */ public class GatewaySenderPropertiesTests { @@ -528,6 +525,7 @@ public class GatewaySenderPropertiesTests { }) static class TestConfigurationWithMultipleGatewaySenderAnnotations { } + @SuppressWarnings("unused") @EnableGatewaySender(name = "TestGatewaySender") static class TestConfigurationWithProperties { @@ -545,16 +543,18 @@ public class GatewaySenderPropertiesTests { private static class TestGatewaySenderConfigurer implements GatewaySenderConfigurer { - private final Map beanNames = new TreeMap<>(); + private final Map> beanNames = new TreeMap<>(); @Override public void configure(String beanName, GatewaySenderFactoryBean bean) { - beanNames.put(beanName, bean.getTransportFilters().stream() + + this.beanNames.put(beanName, bean.getTransportFilters().stream() .map(transportFilter -> ((TestGatewayTransportFilter) transportFilter).name) .collect(Collectors.toList())); } } + @SuppressWarnings("rawtypes") private static class TestGatewayEventSubstitutionFilter implements GatewayEventSubstitutionFilter { private String name; @@ -594,6 +594,10 @@ public class GatewaySenderPropertiesTests { @Override public void afterAcknowledgement(GatewayQueueEvent gatewayQueueEvent) { } + @Override + public String toString() { + return this.name; + } } private static class TestGatewayTransportFilter implements GatewayTransportFilter { @@ -620,29 +624,15 @@ public class GatewaySenderPropertiesTests { } @Override + @SuppressWarnings("all") public boolean equals(Object obj) { return this.name.equals(((TestGatewayTransportFilter) obj).name); } } - private static class TestGatewaySender extends AbstractGatewaySender implements GatewaySender { - - @Override - public void start() { } - - @Override - public void stop() { } - - @Override - public void setModifiedEventId(EntryEventImpl entryEvent) { } - - @Override - public void fillInProfile(DistributionAdvisor.Profile profile) { } - - } - @PeerCacheApplication @EnableGemFireMockObjects + @SuppressWarnings({ "rawtypes", "unused" }) static class BaseGatewaySenderTestConfiguration { @Bean("Region1") @@ -681,10 +671,12 @@ public class GatewaySenderPropertiesTests { } public PartitionedRegionFactoryBean createRegion(String name, GemFireCache gemFireCache) { - final PartitionedRegionFactoryBean regionFactoryBean = new PartitionedRegionFactoryBean(); + + PartitionedRegionFactoryBean regionFactoryBean = new PartitionedRegionFactoryBean(); regionFactoryBean.setCache(gemFireCache); regionFactoryBean.setDataPolicy(DataPolicy.PARTITION); regionFactoryBean.setName(name); + return regionFactoryBean; } } diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/config/annotation/LoggingConfigurationIntegrationTests.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/config/annotation/LoggingConfigurationIntegrationTests.java index a9217837..311c3f53 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/config/annotation/LoggingConfigurationIntegrationTests.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/config/annotation/LoggingConfigurationIntegrationTests.java @@ -24,16 +24,16 @@ import java.util.Optional; import java.util.Properties; import java.util.concurrent.atomic.AtomicReference; -import org.apache.geode.cache.GemFireCache; -import org.apache.geode.distributed.internal.DistributionConfig; - import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.apache.geode.cache.GemFireCache; + import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.core.env.PropertiesPropertySource; +import org.springframework.data.gemfire.GemFireProperties; import org.springframework.data.gemfire.util.ArrayUtils; import org.springframework.data.gemfire.util.PropertiesBuilder; import org.springframework.util.StringUtils; @@ -45,14 +45,13 @@ import org.springframework.util.StringUtils; * @see java.util.Properties * @see org.junit.Test * @see org.apache.geode.cache.GemFireCache - * @see org.apache.geode.distributed.internal.DistributionConfig * @see org.springframework.context.ConfigurableApplicationContext * @see org.springframework.context.annotation.AnnotationConfigApplicationContext * @see org.springframework.core.env.PropertiesPropertySource * @see org.springframework.data.gemfire.config.annotation.ClientCacheApplication * @see org.springframework.data.gemfire.config.annotation.EnableLogging * @see org.springframework.data.gemfire.util.PropertiesBuilder - * @since 1.0.0 + * @since 1.9.0 */ public class LoggingConfigurationIntegrationTests { @@ -89,8 +88,8 @@ public class LoggingConfigurationIntegrationTests { Properties distributedSystemProperties = gemfireCache.getDistributedSystem().getProperties(); assertThat(distributedSystemProperties).isNotNull(); - assertThat(distributedSystemProperties.getProperty(DistributionConfig.LOG_LEVEL_NAME)).isEqualTo(logLevel); - assertThat(distributedSystemProperties.getProperty(DistributionConfig.LOG_FILE_NAME)).isEqualTo(logFile); + assertThat(distributedSystemProperties.getProperty(GemFireProperties.LOG_LEVEL.getName())).isEqualTo(logLevel); + assertThat(distributedSystemProperties.getProperty(GemFireProperties.LOG_FILE.getName())).isEqualTo(logFile); } private void deleteLogFiles() { @@ -111,10 +110,9 @@ public class LoggingConfigurationIntegrationTests { applicationContext.registerShutdownHook(); Optional.ofNullable(this.propertiesReference.get()) - .ifPresent(properties -> { - applicationContext.getEnvironment().getPropertySources() - .addFirst(new PropertiesPropertySource("Test Properties", properties)); - }); + .ifPresent(properties -> applicationContext.getEnvironment() + .getPropertySources() + .addFirst(new PropertiesPropertySource("Test Properties", properties))); applicationContext.refresh(); diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/config/annotation/PeerCacheApplicationWithAddedCacheServerIntegrationTests.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/config/annotation/PeerCacheApplicationWithAddedCacheServerIntegrationTests.java index d163beff..d3075ea1 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/config/annotation/PeerCacheApplicationWithAddedCacheServerIntegrationTests.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/config/annotation/PeerCacheApplicationWithAddedCacheServerIntegrationTests.java @@ -19,18 +19,18 @@ import static org.assertj.core.api.Assertions.assertThat; import java.util.List; -import org.apache.geode.cache.Cache; -import org.apache.geode.cache.server.CacheServer; -import org.apache.geode.distributed.internal.DistributionConfig; - import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; +import org.apache.geode.cache.Cache; +import org.apache.geode.cache.server.CacheServer; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.data.gemfire.GemFireProperties; import org.springframework.data.gemfire.process.ProcessWrapper; import org.springframework.data.gemfire.test.support.ClientServerIntegrationTestsSupport; import org.springframework.test.context.ContextConfiguration; @@ -44,7 +44,6 @@ import org.springframework.test.context.junit4.SpringRunner; * @see org.junit.Test * @see org.apache.geode.cache.Cache * @see org.apache.geode.cache.server.CacheServer - * @see org.apache.geode.distributed.internal.DistributionConfig * @see org.springframework.test.context.junit4.SpringRunner * @since 2.2.0 */ @@ -68,7 +67,8 @@ public class PeerCacheApplicationWithAddedCacheServerIntegrationTests extends Cl gemfireLocator = run(TestLocatorConfiguration.class, "-Dspring.data.gemfire.locator.port=" + locatorPort, - String.format("-Dgemfire.%s=%s", DistributionConfig.ENABLE_CLUSTER_CONFIGURATION_NAME, false)); + String.format("-D%1$s%2$s=%3$s", GemFireProperties.PROPERTY_NAME_PREFIX, + GemFireProperties.ENABLE_CLUSTER_CONFIGURATION.getName(), false)); waitForServerToStart("localhost", locatorPort); @@ -98,9 +98,9 @@ public class PeerCacheApplicationWithAddedCacheServerIntegrationTests extends Cl assertThat(this.cache.getName()).isEqualTo("PeerCacheApplicationWithAddedCacheServerIntegrationTests"); assertThat(this.cache.getDistributedSystem()).isNotNull(); assertThat(this.cache.getDistributedSystem().getProperties()).isNotNull(); - assertThat(this.cache.getDistributedSystem().getProperties().getProperty(DistributionConfig.LOCATORS_NAME)) + assertThat(this.cache.getDistributedSystem().getProperties().getProperty(GemFireProperties.LOCATORS.getName())) .isEqualTo(String.format("localhost[%d]", locatorPort)); - assertThat(this.cache.getDistributedSystem().getProperties().getProperty(DistributionConfig.NAME_NAME)) + assertThat(this.cache.getDistributedSystem().getProperties().getProperty(GemFireProperties.NAME.getName())) .isEqualTo("PeerCacheApplicationWithAddedCacheServerIntegrationTests"); } diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/fork/GemFireBasedServerProcess.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/fork/GemFireBasedServerProcess.java index 2196ec94..4317057b 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/fork/GemFireBasedServerProcess.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/fork/GemFireBasedServerProcess.java @@ -13,14 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.springframework.data.gemfire.fork; import java.io.File; import org.apache.geode.distributed.ServerLauncher; -import org.apache.geode.distributed.internal.DistributionConfig; +import org.springframework.data.gemfire.GemFireProperties; import org.springframework.data.gemfire.process.support.ProcessUtils; import org.springframework.data.gemfire.test.support.FileSystemUtils; @@ -68,14 +67,12 @@ public class GemFireBasedServerProcess { .setCommand(ServerLauncher.Command.START) .setDisableDefaultServer(true) .setRedirectOutput(false) - .set(DistributionConfig.HTTP_SERVICE_PORT_NAME, + .set(GemFireProperties.HTTP_SERVICE_PORT.getName(), getProperty("spring.data.gemfire.http-service-port", GEMFIRE_HTTP_SERVICE_PORT)) - .set(DistributionConfig.JMX_MANAGER_NAME, Boolean.TRUE.toString()) - .set(DistributionConfig.JMX_MANAGER_START_NAME, Boolean.FALSE.toString()) - .set(DistributionConfig.LOG_LEVEL_NAME, - getProperty("spring.data.gemfire.log-level", GEMFIRE_LOG_LEVEL)) - .set(DistributionConfig.USE_CLUSTER_CONFIGURATION_NAME, - getProperty("spring.data.gemfire.use-cluster-configuration", GEMFIRE_USE_CLUSTER_CONFIGURATION)) + .set(GemFireProperties.JMX_MANAGER.getName(), Boolean.TRUE.toString()) + .set(GemFireProperties.JMX_MANAGER_START.getName(), Boolean.FALSE.toString()) + .set(GemFireProperties.LOG_LEVEL.getName(), getProperty("spring.data.gemfire.log-level", GEMFIRE_LOG_LEVEL)) + .set(GemFireProperties.USE_CLUSTER_CONFIGURATION.getName(), getProperty("spring.data.gemfire.use-cluster-configuration", GEMFIRE_USE_CLUSTER_CONFIGURATION)) .build(); } diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/fork/LocatorProcess.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/fork/LocatorProcess.java index 5fc12f82..db1da90d 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/fork/LocatorProcess.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/fork/LocatorProcess.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.springframework.data.gemfire.fork; import java.io.File; @@ -23,9 +22,9 @@ import java.util.concurrent.TimeUnit; import org.apache.geode.distributed.Locator; import org.apache.geode.distributed.LocatorLauncher; -import org.apache.geode.distributed.internal.DistributionConfig; import org.apache.geode.distributed.internal.InternalLocator; +import org.springframework.data.gemfire.GemFireProperties; import org.springframework.data.gemfire.GemfireUtils; import org.springframework.data.gemfire.process.support.ProcessUtils; import org.springframework.data.gemfire.test.support.FileSystemUtils; @@ -81,17 +80,17 @@ public class LocatorProcess { Properties distributedSystemProperties = new Properties(); - distributedSystemProperties.setProperty(DistributionConfig.ENABLE_CLUSTER_CONFIGURATION_NAME, + distributedSystemProperties.setProperty(GemFireProperties.ENABLE_CLUSTER_CONFIGURATION.getName(), String.valueOf(Boolean.getBoolean("spring.data.gemfire.enable-cluster-configuration"))); - distributedSystemProperties.setProperty(DistributionConfig.HTTP_SERVICE_PORT_NAME, + distributedSystemProperties.setProperty(GemFireProperties.HTTP_SERVICE_PORT.getName(), System.getProperty("spring.data.gemfire.http-service-port", HTTP_SERVICE_PORT)); - distributedSystemProperties.setProperty(DistributionConfig.JMX_MANAGER_NAME, + distributedSystemProperties.setProperty(GemFireProperties.JMX_MANAGER.getName(), System.getProperty("spring.data.gemfire.jmx-manager", Boolean.TRUE.toString())); - distributedSystemProperties.setProperty(DistributionConfig.JMX_MANAGER_START_NAME, + distributedSystemProperties.setProperty(GemFireProperties.JMX_MANAGER_START.getName(), System.getProperty("spring.data.gemfire.jmx-manager-start", Boolean.FALSE.toString())); - distributedSystemProperties.setProperty(DistributionConfig.LOAD_CLUSTER_CONFIG_FROM_DIR_NAME, + distributedSystemProperties.setProperty(GemFireProperties.LOAD_CLUSTER_CONFIGURATION_FROM_DIR.getName(), String.valueOf(loadClusterConfigurationFromDirectory)); - distributedSystemProperties.setProperty(DistributionConfig.LOG_LEVEL_NAME, + distributedSystemProperties.setProperty(GemFireProperties.LOG_LEVEL.getName(), System.getProperty("spring.data.gemfire.log-level", GEMFIRE_LOG_LEVEL)); return InternalLocator.startLocator(locatorPort, null, null, null, @@ -116,15 +115,15 @@ public class LocatorProcess { .setHostnameForClients(getProperty("spring.data.gemfire.hostname-for-clients", HOSTNAME_FOR_CLIENTS)) .setPort(getInteger("spring.data.gemfire.locator.port", DEFAULT_LOCATOR_PORT)) .setRedirectOutput(false) - .set(DistributionConfig.ENABLE_CLUSTER_CONFIGURATION_NAME, + .set(GemFireProperties.ENABLE_CLUSTER_CONFIGURATION.getName(), String.valueOf(getBoolean("spring.data.gemfire.enable-cluster-configuration"))) - .set(DistributionConfig.HTTP_SERVICE_PORT_NAME, + .set(GemFireProperties.HTTP_SERVICE_PORT.getName(), getProperty("spring.data.gemfire.http-service-port", HTTP_SERVICE_PORT)) - .set(DistributionConfig.JMX_MANAGER_NAME, Boolean.TRUE.toString()) - .set(DistributionConfig.JMX_MANAGER_START_NAME, Boolean.FALSE.toString()) - .set(DistributionConfig.LOAD_CLUSTER_CONFIG_FROM_DIR_NAME, + .set(GemFireProperties.JMX_MANAGER.getName(), Boolean.TRUE.toString()) + .set(GemFireProperties.JMX_MANAGER_START.getName(), Boolean.FALSE.toString()) + .set(GemFireProperties.LOAD_CLUSTER_CONFIGURATION_FROM_DIR.getName(), String.valueOf(getBoolean("spring.data.gemfire.load-cluster-configuration"))) - .set(DistributionConfig.LOG_LEVEL_NAME, + .set(GemFireProperties.LOG_LEVEL.getName(), getProperty("spring.data.gemfire.log-level", GEMFIRE_LOG_LEVEL)) .build(); } @@ -153,7 +152,7 @@ public class LocatorProcess { })); } - private static void waitForLocatorStart(final long milliseconds) { + private static void waitForLocatorStart(long milliseconds) { InternalLocator locator = InternalLocator.getLocator(); @@ -166,9 +165,9 @@ public class LocatorProcess { } } - private static boolean isClusterConfigurationEnabled(final InternalLocator locator) { + private static boolean isClusterConfigurationEnabled(Locator locator) { - return locator != null && Boolean.valueOf(locator.getDistributedSystem().getProperties() - .getProperty(DistributionConfig.ENABLE_CLUSTER_CONFIGURATION_NAME)); + return locator != null && Boolean.parseBoolean(locator.getDistributedSystem().getProperties() + .getProperty("enable-cluster-configuration")); } } diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/function/PdxFunctionArgumentResolverTest.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/function/PdxFunctionArgumentResolverTest.java index 4b6c567d..af511015 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/function/PdxFunctionArgumentResolverTest.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/function/PdxFunctionArgumentResolverTest.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.springframework.data.gemfire.function; import static org.junit.Assert.assertEquals; @@ -21,11 +20,16 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import static org.springframework.data.gemfire.util.RuntimeExceptionFactory.newRuntimeException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + import org.apache.geode.cache.Cache; import org.apache.geode.cache.CacheFactory; import org.apache.geode.cache.execute.FunctionContext; @@ -38,10 +42,6 @@ import org.apache.geode.pdx.PdxWriter; import org.apache.geode.pdx.internal.PdxInstanceEnum; import org.apache.geode.pdx.internal.PdxInstanceFactoryImpl; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; @@ -60,7 +60,7 @@ import org.springframework.util.ObjectUtils; * @see org.apache.geode.pdx.internal.PdxInstanceEnum * @since 1.5.2 */ -@SuppressWarnings("unused") +@SuppressWarnings("rawtypes") public class PdxFunctionArgumentResolverTest { private static Cache gemfireCache; @@ -84,24 +84,26 @@ public class PdxFunctionArgumentResolverTest { gemfireCache = null; } - protected Method getMethod(final Class type, final String methodName, final Class... parameterTypes) { + protected Method getMethod(Class type, String methodName, Class... parameterTypes) { + try { return type.getDeclaredMethod(methodName, parameterTypes); } - catch (NoSuchMethodException e) { - throw new RuntimeException(String.format( - "Failed to get method (%1$s) with signature (%2$s) on Class type (%3$s)!", methodName, - getMethodSignature(methodName, parameterTypes), type.getClass().getName())); + catch (NoSuchMethodException cause) { + throw newRuntimeException("Failed to get method [%1$s] with signature [%2$s] on Class type [%3$s]!", + methodName, getMethodSignature(methodName, parameterTypes), type.getName()); } } protected Object getMethodSignature(final String methodName, final Class... parameterTypes) { + StringBuilder methodSignature = new StringBuilder(methodName); + int count = 0; methodSignature.append("("); - for (Class parameterType : parameterTypes) { + for (Class parameterType : parameterTypes) { methodSignature.append(count++ > 0 ? ", :" : ":").append(parameterType.getSimpleName()); } @@ -111,6 +113,7 @@ public class PdxFunctionArgumentResolverTest { } protected void assertArguments(final Object[] expectedArguments, final Object[] actualArguments) { + assertNotNull(actualArguments); assertNotSame(expectedArguments, actualArguments); assertEquals(expectedArguments.length, actualArguments.length); @@ -125,14 +128,18 @@ public class PdxFunctionArgumentResolverTest { } protected PdxInstance toPdxInstance(final Person person) { + PdxInstanceFactory pdxInstanceFactory = gemfireCache.createPdxInstanceFactory(person.getClass().getName()); + pdxInstanceFactory.writeString("firstName", person.getFirstName()); pdxInstanceFactory.writeString("lastName", person.getLastName()); pdxInstanceFactory.writeObject("gender", person.getGender()); + return pdxInstanceFactory.create(); } protected PdxInstance toPdxInstance(final Map objectData) { + PdxInstanceFactory pdxInstanceFactory = gemfireCache.createPdxInstanceFactory(objectData.get("@type").toString()); for (Map.Entry entry : objectData.entrySet()) { @@ -144,13 +151,15 @@ public class PdxFunctionArgumentResolverTest { return pdxInstanceFactory.create(); } - protected PdxInstance toPdxInstance(final Enum enumeratedType) { + protected PdxInstance toPdxInstance(Enum enumeratedType) { + return PdxInstanceFactoryImpl.createPdxEnum(enumeratedType.getClass().getName(), enumeratedType.name(), enumeratedType.ordinal(), (GemFireCacheImpl) gemfireCache); } @Test public void testResolveSimpleFunctionArguments() { + functionArgumentResolver = new PdxFunctionArgumentResolver() { @Override public Method getFunctionAnnotatedMethod() { return getMethod(FunctionExecutions.class, "simpleMethod", Boolean.class, Character.class, @@ -243,7 +252,7 @@ public class PdxFunctionArgumentResolverTest { } }; - Map addressData = new HashMap(5); + Map addressData = new HashMap<>(5); addressData.put("@type", "org.example.Address"); addressData.put("street", "100 Main St."); @@ -262,7 +271,8 @@ public class PdxFunctionArgumentResolverTest { assertArguments(expectedArguments, actualArguments); } - public static interface FunctionExecutions { + @SuppressWarnings("unused") + public interface FunctionExecutions { void simpleMethod(Boolean value1, Character value2, Integer value3, Double value4, String value5); @@ -273,9 +283,10 @@ public class PdxFunctionArgumentResolverTest { void unnecessaryDeserializationMethod(Boolean value1, Object person, String value2, PdxInstanceEnum gender); void unresolvableMethod(String value, Object pdxInstance); + } - public static enum Gender { + public enum Gender { FEMALE, MALE } @@ -309,7 +320,8 @@ public class PdxFunctionArgumentResolverTest { } @Override - public boolean equals(final Object obj) { + public boolean equals(Object obj) { + if (obj == this) { return true; } @@ -344,6 +356,7 @@ public class PdxFunctionArgumentResolverTest { @Override public boolean toData(final Object obj, final PdxWriter out) { + if (obj instanceof Person) { Person person = (Person) obj; out.writeString("firstName", person.getFirstName()); @@ -357,6 +370,7 @@ public class PdxFunctionArgumentResolverTest { @Override public Object fromData(final Class type, final PdxReader in) { + if (Person.class.isAssignableFrom(type)) { return new Person(in.readString("firstName"), in.readString("lastName"), (Gender) in.readObject("gender")); @@ -365,5 +379,4 @@ public class PdxFunctionArgumentResolverTest { return null; } } - } diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/repository/query/StringBasedGemfireRepositoryQueryTest.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/repository/query/StringBasedGemfireRepositoryQueryTest.java index 94ee0ad0..e3b43c01 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/repository/query/StringBasedGemfireRepositoryQueryTest.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/repository/query/StringBasedGemfireRepositoryQueryTest.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.springframework.data.gemfire.repository.query; import static org.hamcrest.CoreMatchers.equalTo; @@ -37,14 +36,12 @@ import java.util.Collection; import java.util.Collections; import java.util.List; -import org.apache.geode.cache.query.SelectResults; -import org.apache.geode.cache.query.internal.ResultsBag; - import org.junit.Test; +import org.apache.geode.cache.query.SelectResults; + /** - * The SpringBasedGemfireRepositoryQueryTest class is a test suite of test cases testing the contract and functionality - * of the StringBasedGemfireRepositoryQuery class. + * Unit Tests for {@link StringBasedGemfireRepositoryQuery} * * @author John Blum * @see org.mockito.Mockito @@ -57,29 +54,16 @@ public class StringBasedGemfireRepositoryQueryTest { private final StringBasedGemfireRepositoryQuery repositoryQuery = new StringBasedGemfireRepositoryQuery(); @Test + @SuppressWarnings("unchecked") public void testToCollectionWithSelectResults() { - SelectResults mockSelectResults = mock(SelectResults.class, "testToCollectionWithSelectResults.SelectResults"); + SelectResults mockSelectResults = mock(SelectResults.class); List expectedList = Arrays.asList("one", "two", "three"); when(mockSelectResults.asList()).thenReturn(expectedList); - Collection actualList = repositoryQuery.toCollection(mockSelectResults); - - assertSame(expectedList, actualList); - } - - @Test - public void testToCollectionWithResultsBag() { - - ResultsBag mockResultsBag = mock(ResultsBag.class, "testToCollectionWithResultsBag.ResultsBag"); - - List expectedList = Arrays.asList("a", "b", "c"); - - when(mockResultsBag.asList()).thenReturn(expectedList); - - Collection actualList = repositoryQuery.toCollection(mockResultsBag); + Collection actualList = this.repositoryQuery.toCollection(mockSelectResults); assertSame(expectedList, actualList); } @@ -89,7 +73,7 @@ public class StringBasedGemfireRepositoryQueryTest { List expectedList = Arrays.asList("x", "y", "z"); - Collection actualList = repositoryQuery.toCollection(expectedList); + Collection actualList = this.repositoryQuery.toCollection(expectedList); assertSame(expectedList, actualList); } @@ -116,7 +100,7 @@ public class StringBasedGemfireRepositoryQueryTest { assertTrue(list instanceof List); assertFalse(list.isEmpty()); assertEquals(1, list.size()); - assertEquals("test", ((List) list).get(0)); + assertEquals("test", ((List) list).get(0)); } @Test diff --git a/spring-data-geode/src/test/java/org/springframework/data/gemfire/test/mock/GemFireMockObjectsSupport.java b/spring-data-geode/src/test/java/org/springframework/data/gemfire/test/mock/GemFireMockObjectsSupport.java index 48e38965..3e19c8ec 100644 --- a/spring-data-geode/src/test/java/org/springframework/data/gemfire/test/mock/GemFireMockObjectsSupport.java +++ b/spring-data-geode/src/test/java/org/springframework/data/gemfire/test/mock/GemFireMockObjectsSupport.java @@ -127,7 +127,6 @@ import org.apache.geode.cache.wan.GatewayTransportFilter; import org.apache.geode.compression.Compressor; import org.apache.geode.distributed.DistributedMember; import org.apache.geode.distributed.DistributedSystem; -import org.apache.geode.internal.concurrent.ConcurrentHashSet; import org.apache.geode.pdx.PdxSerializer; import org.apache.lucene.analysis.Analyzer; @@ -1587,8 +1586,8 @@ public abstract class GemFireMockObjectsSupport extends MockObjectsSupport { QueryService mockQueryService = mock(QueryService.class); - Set cqQueries = new ConcurrentHashSet<>(); - Set indexes = new ConcurrentHashSet<>(); + Set cqQueries = Collections.synchronizedSet(new HashSet<>()); + Set indexes = Collections.synchronizedSet(new HashSet<>()); try { when(mockQueryService.getCqs()).thenAnswer(invocation -> cqQueries.toArray(new CqQuery[cqQueries.size()]));