From 65d320b3c8a185b5db4b7742ccf787f932cd885a Mon Sep 17 00:00:00 2001 From: Mark Paluch Date: Thu, 27 Jul 2017 15:34:32 +0200 Subject: [PATCH] DATAREDIS-668 - Polishing. Align JavaDoc for consistent wording. Remove superfluous final keyword from variables in DefaultSetOperations. Replace anonymous inner classes with lambdas/method references, where possible. Remove superfluous final keywords used for local variable. Add override JavaDocs and missing Override annoations. Use diamond syntax where possible. Formatting, license headers. Reduce visibility of Default Operations implementations to package-scope. Original pull request: #259. --- src/main/asciidoc/new-features.adoc | 1 + .../config/RedisListenerContainerParser.java | 16 +- .../connection/AbstractRedisConnection.java | 9 +- .../connection/ClusterCommandExecutor.java | 32 +- .../redis/connection/ClusterTopology.java | 26 +- .../data/redis/connection/DataType.java | 10 +- .../connection/DefaultSortParameters.java | 16 +- .../DefaultStringRedisConnection.java | 135 ++-- .../connection/ReactiveNumberCommands.java | 14 +- .../redis/connection/ReactiveSetCommands.java | 24 +- .../redis/connection/RedisClusterNode.java | 24 +- .../redis/connection/RedisGeoCommands.java | 44 +- .../redis/connection/RedisSetCommands.java | 4 +- .../connection/StringRedisConnection.java | 10 +- .../redis/connection/convert/Converters.java | 54 +- .../connection/convert/ListConverter.java | 24 +- .../connection/convert/MapConverter.java | 13 +- .../connection/convert/SetConverter.java | 13 +- .../StringToRedisClientInfoConverter.java | 10 +- .../convert/TransactionResultConverter.java | 13 +- .../connection/jedis/JedisConverters.java | 65 +- .../connection/lettuce/LettuceConnection.java | 6 +- .../lettuce/LettuceSetCommands.java | 6 +- .../connection/util/AbstractSubscription.java | 24 +- .../redis/connection/util/ByteArraySet.java | 6 +- .../redis/connection/util/DecodeUtils.java | 18 +- .../data/redis/core/AbstractOperations.java | 40 +- .../redis/core/DefaultBoundGeoOperations.java | 12 +- .../core/DefaultBoundHashOperations.java | 85 +- .../redis/core/DefaultBoundKeyOperations.java | 43 +- .../core/DefaultBoundListOperations.java | 111 ++- .../redis/core/DefaultBoundSetOperations.java | 129 +++- .../core/DefaultBoundValueOperations.java | 78 +- .../core/DefaultBoundZSetOperations.java | 129 +++- .../redis/core/DefaultClusterOperations.java | 145 +--- .../data/redis/core/DefaultGeoOperations.java | 166 ++-- .../redis/core/DefaultHashOperations.java | 240 +++--- .../core/DefaultHyperLogLogOperations.java | 49 +- .../redis/core/DefaultListOperations.java | 284 ++++--- .../core/DefaultReactiveGeoOperations.java | 4 +- .../core/DefaultReactiveHashOperations.java | 7 +- .../DefaultReactiveHyperLogLogOperations.java | 8 +- .../core/DefaultReactiveListOperations.java | 4 +- .../core/DefaultReactiveSetOperations.java | 4 +- .../core/DefaultReactiveValueOperations.java | 4 +- .../core/DefaultReactiveZSetOperations.java | 4 +- .../data/redis/core/DefaultSetOperations.java | 118 +-- .../redis/core/DefaultValueOperations.java | 249 +++--- .../redis/core/DefaultZSetOperations.java | 484 ++++++------ .../data/redis/core/PartialUpdate.java | 12 +- .../redis/core/ReactiveSetOperations.java | 6 +- .../data/redis/core/RedisCommand.java | 14 +- .../data/redis/core/RedisKeyValueAdapter.java | 2 +- .../redis/core/RedisKeyValueTemplate.java | 2 +- .../data/redis/core/RedisTemplate.java | 724 +++++++++++------- .../data/redis/core/ScanIteration.java | 10 +- .../data/redis/core/SetOperations.java | 4 +- .../redis/core/convert/BinaryConverters.java | 6 +- .../data/redis/core/convert/Bucket.java | 33 +- .../core/convert/CompositeIndexResolver.java | 10 +- .../redis/core/convert/Jsr310Converters.java | 4 +- .../core/convert/KeyspaceConfiguration.java | 2 +- .../core/convert/MappingRedisConverter.java | 376 +++++---- .../redis/core/convert/PathIndexResolver.java | 7 +- .../data/redis/core/convert/RedisData.java | 4 +- .../redis/core/convert/SpelIndexResolver.java | 4 +- .../redis/core/index/IndexConfiguration.java | 8 +- .../core/index/RedisIndexDefinition.java | 12 +- .../core/mapping/RedisMappingContext.java | 27 +- .../core/mapping/RedisPersistentProperty.java | 8 +- .../core/query/DefaultSortCriterion.java | 16 +- .../data/redis/core/query/QueryUtils.java | 12 +- .../redis/core/query/SortQueryBuilder.java | 12 +- .../core/script/DefaultScriptExecutor.java | 27 +- .../data/redis/hash/BeanUtilsHashMapper.java | 12 +- .../hash/DecoratingStringHashMapper.java | 12 +- .../data/redis/hash/Jackson2HashMapper.java | 12 +- .../RedisMessageListenerContainer.java | 88 +-- .../adapter/MessageListenerAdapter.java | 65 +- .../data/redis/repository/cdi/CdiBean.java | 6 +- .../cdi/RedisRepositoryExtension.java | 16 +- .../repository/query/RedisOperationChain.java | 8 +- .../repository/query/RedisQueryCreator.java | 2 +- .../DefaultRedisSerializationContext.java | 2 +- .../serializer/RedisSerializationContext.java | 2 +- .../redis/serializer/SerializationUtils.java | 18 +- .../support/atomic/RedisAtomicDouble.java | 6 +- .../support/atomic/RedisAtomicInteger.java | 6 +- .../redis/support/atomic/RedisAtomicLong.java | 6 +- .../support/collections/CollectionUtils.java | 10 +- .../support/collections/DefaultRedisMap.java | 16 +- .../support/collections/DefaultRedisSet.java | 26 +- .../support/collections/DefaultRedisZSet.java | 35 +- .../support/collections/RedisProperties.java | 20 +- .../redis/support/collections/RedisZSet.java | 30 +- .../data/redis/util/ByteUtils.java | 4 +- .../data/redis/ConnectionFactoryTracker.java | 2 +- .../redis/cache/LegacyRedisCacheTests.java | 66 +- .../data/redis/config/StubErrorHandler.java | 10 +- .../AbstractConnectionIntegrationTests.java | 65 +- ...actConnectionPipelineIntegrationTests.java | 4 +- ...ConnectionTransactionIntegrationTests.java | 2 +- .../ClusterCommandExecutorUnitTests.java | 36 +- .../DefaultStringRedisConnectionTests.java | 38 +- .../RedisClusterConfigurationUnitTests.java | 3 +- .../RedisSentinelConfigurationUnitTests.java | 3 +- .../jedis/JedisClusterConnectionTests.java | 22 +- .../JedisClusterConnectionUnitTests.java | 12 +- .../JedisConnectionIntegrationTests.java | 30 +- .../jedis/JedisConnectionUnitTestSuite.java | 26 +- .../jedis/JedisConvertersUnitTests.java | 2 +- .../redis/connection/jedis/ScanTests.java | 27 +- .../LettuceClusterConnectionTests.java | 26 +- .../LettuceConnectionFactoryTests.java | 6 +- .../LettuceConnectionIntegrationTests.java | 53 +- ...uceConnectionPipelineIntegrationTests.java | 37 +- .../lettuce/LettuceConvertersUnitTests.java | 2 +- .../LettuceReactiveZSetCommandsTests.java | 8 +- .../lettuce/TestEventLoopGroupProvider.java | 4 +- .../core/AbstractOperationsTestParams.java | 2 +- .../DefaultClusterOperationsUnitTests.java | 15 +- .../redis/core/DefaultGeoOperationsTests.java | 11 +- .../core/DefaultHashOperationsTests.java | 13 +- .../DefaultHyperLogLogOperationsTests.java | 9 +- .../core/DefaultListOperationsTests.java | 11 +- ...activeValueOperationsIntegrationTests.java | 6 +- ...eactiveZSetOperationsIntegrationTests.java | 6 +- .../redis/core/DefaultSetOperationsTests.java | 22 +- .../core/DefaultTypedTupleUnitTests.java | 8 +- .../core/DefaultValueOperationsTests.java | 34 +- .../core/DefaultZSetOperationsTests.java | 59 +- .../data/redis/core/IndexWriterUnitTests.java | 12 +- .../core/MultithreadedRedisTemplateTests.java | 10 +- .../redis/core/RedisClusterTemplateTests.java | 30 +- .../redis/core/RedisKeyValueAdapterTests.java | 47 +- .../core/RedisKeyValueAdapterUnitTests.java | 6 +- .../core/RedisKeyValueTemplateTests.java | 507 +++++------- .../data/redis/core/RedisTemplateTests.java | 151 ++-- .../redis/core/RedisTemplateUnitTests.java | 4 +- .../data/redis/core/ScanCursorUnitTests.java | 27 +- .../data/redis/core/SessionTest.java | 20 +- .../core/convert/ConversionTestEntities.java | 4 +- .../MappingRedisConverterUnitTests.java | 141 ++-- .../convert/PathIndexResolverUnitTests.java | 20 +- .../convert/SpelIndexResolverUnitTests.java | 18 +- .../BasicRedisPersistentEntityUnitTests.java | 4 +- ...onfigAwareTimeToLiveAccessorUnitTests.java | 10 +- .../AbstractDefaultScriptExecutorTests.java | 41 +- .../core/script/DefaultRedisScriptTests.java | 13 +- .../DefaultScriptExecutorUnitTests.java | 4 +- .../listener/PubSubResubscribeTests.java | 20 +- .../data/redis/listener/PubSubTestParams.java | 14 +- .../data/redis/listener/PubSubTests.java | 16 +- .../RedisMessageListenerContainerTests.java | 12 +- .../listener/SubscriptionConnectionTests.java | 4 +- .../mapping/BeanUtilsHashMapperTest.java | 10 +- .../mapping/Jackson2HashMapperTests.java | 2 +- .../mapping/Jackson2HashMapperUnitTests.java | 16 +- ...edisRepositoryClusterIntegrationTests.java | 2 +- .../RedisRepositoryIntegrationTests.java | 2 +- .../cdi/RedisCdiDependenciesProducer.java | 4 +- .../Jackson2JsonRedisSerializerTests.java | 2 +- .../SimpleRedisSerializerTests.java | 8 +- .../redis/support/BoundKeyOperationsTest.java | 18 +- .../atomic/RedisAtomicDoubleTests.java | 8 +- .../atomic/RedisAtomicIntegerTests.java | 30 +- .../support/atomic/RedisAtomicLongTests.java | 12 +- .../AbstractRedisCollectionTests.java | 38 +- .../AbstractRedisCollectionUnitTests.java | 2 +- .../collections/AbstractRedisListTests.java | 16 +- .../collections/AbstractRedisMapTests.java | 28 +- .../collections/AbstractRedisSetTests.java | 18 +- .../collections/AbstractRedisZSetTest.java | 12 +- .../collections/CollectionTestParams.java | 22 +- .../RedisCollectionFactoryBeanTests.java | 22 +- .../support/collections/RedisMapTests.java | 16 +- .../collections/RedisPropertiesTests.java | 14 +- .../data/redis/test/util/IsBucketMatcher.java | 20 +- .../data/redis/test/util/MockitoUtils.java | 6 +- .../redis/test/util/RedisSentinelRule.java | 18 +- 180 files changed, 3592 insertions(+), 3327 deletions(-) diff --git a/src/main/asciidoc/new-features.adoc b/src/main/asciidoc/new-features.adoc index b7827da4f..2a62d6f05 100644 --- a/src/main/asciidoc/new-features.adoc +++ b/src/main/asciidoc/new-features.adoc @@ -12,6 +12,7 @@ New and noteworthy in the latest releases. * Reactive connection support using https://github.com/lettuce-io/lettuce-core[lettuce-io/lettuce-core]. * Introduce Redis feature-specific interfaces for `RedisConnection`. * Revised `RedisCache` implementation. +* Add `SPOP` with count command for Redis 3.2. [[new-in-1.8.0]] diff --git a/src/main/java/org/springframework/data/redis/config/RedisListenerContainerParser.java b/src/main/java/org/springframework/data/redis/config/RedisListenerContainerParser.java index 2c66ca935..0f70998e5 100644 --- a/src/main/java/org/springframework/data/redis/config/RedisListenerContainerParser.java +++ b/src/main/java/org/springframework/data/redis/config/RedisListenerContainerParser.java @@ -1,12 +1,12 @@ /* - * Copyright 2011-2013 the original author or authors. - * + * Copyright 2011-2017 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. @@ -38,7 +38,7 @@ import org.w3c.dom.NamedNodeMap; /** * Parser for the Redis <listener-container> element. - * + * * @author Costin Leau */ class RedisListenerContainerParser extends AbstractSimpleBeanDefinitionParser { @@ -73,7 +73,7 @@ class RedisListenerContainerParser extends AbstractSimpleBeanDefinitionParser { List listDefs = DomUtils.getChildElementsByTagName(element, "listener"); if (!listDefs.isEmpty()) { - ManagedMap> listeners = new ManagedMap>( + ManagedMap> listeners = new ManagedMap<>( listDefs.size()); for (Element listElement : listDefs) { Object[] listenerDefinition = parseListener(listElement); @@ -92,7 +92,7 @@ class RedisListenerContainerParser extends AbstractSimpleBeanDefinitionParser { /** * Parses a listener definition. Returns the listener bean reference definition (as the array first entry) and its * associated topics (also as bean definitions). - * + * * @param element * @return */ @@ -113,7 +113,7 @@ class RedisListenerContainerParser extends AbstractSimpleBeanDefinitionParser { } // assemble topics - Collection topics = new ArrayList(); + Collection topics = new ArrayList<>(); // get topic String xTopics = element.getAttribute("topic"); diff --git a/src/main/java/org/springframework/data/redis/connection/AbstractRedisConnection.java b/src/main/java/org/springframework/data/redis/connection/AbstractRedisConnection.java index 9ce3a20b9..d8ea1ade3 100644 --- a/src/main/java/org/springframework/data/redis/connection/AbstractRedisConnection.java +++ b/src/main/java/org/springframework/data/redis/connection/AbstractRedisConnection.java @@ -1,5 +1,5 @@ /* - * Copyright 2014 the original author or authors. + * Copyright 2014-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,12 +25,13 @@ import org.springframework.data.redis.RedisSystemException; /** * @author Christoph Strobl + * @author Mark Paluch * @since 1.4 */ public abstract class AbstractRedisConnection implements DefaultedRedisConnection { private RedisSentinelConfiguration sentinelConfiguration; - private ConcurrentHashMap connectionCache = new ConcurrentHashMap(); + private ConcurrentHashMap connectionCache = new ConcurrentHashMap<>(); /* * (non-Javadoc) @@ -73,7 +74,7 @@ public abstract class AbstractRedisConnection implements DefaultedRedisConnectio /** * Check if node is active by sending ping. - * + * * @param node * @return */ @@ -83,7 +84,7 @@ public abstract class AbstractRedisConnection implements DefaultedRedisConnectio /** * Get {@link RedisSentinelCommands} connected to given node. - * + * * @param sentinel * @return */ diff --git a/src/main/java/org/springframework/data/redis/connection/ClusterCommandExecutor.java b/src/main/java/org/springframework/data/redis/connection/ClusterCommandExecutor.java index 38e80a94f..8fcb49c34 100644 --- a/src/main/java/org/springframework/data/redis/connection/ClusterCommandExecutor.java +++ b/src/main/java/org/springframework/data/redis/connection/ClusterCommandExecutor.java @@ -99,7 +99,7 @@ public class ClusterCommandExecutor implements DisposableBean { public NodeResult executeCommandOnArbitraryNode(ClusterCommandCallback cmd) { Assert.notNull(cmd, "ClusterCommandCallback must not be null!"); - List nodes = new ArrayList(getClusterTopology().getActiveNodes()); + List nodes = new ArrayList<>(getClusterTopology().getActiveNodes()); return executeCommandOnSingleNode(cmd, nodes.get(new Random().nextInt(nodes.size()))); } @@ -133,7 +133,7 @@ public class ClusterCommandExecutor implements DisposableBean { Assert.notNull(client, "Could not acquire resource for node. Is your cluster info up to date?"); try { - return new NodeResult(node, cmd.doInCluster(client)); + return new NodeResult<>(node, cmd.doInCluster(client)); } catch (RuntimeException ex) { RuntimeException translatedException = convertToDataAccessExeption(ex); @@ -188,7 +188,7 @@ public class ClusterCommandExecutor implements DisposableBean { Assert.notNull(callback, "Callback must not be null!"); Assert.notNull(nodes, "Nodes must not be null!"); - List resolvedRedisClusterNodes = new ArrayList(); + List resolvedRedisClusterNodes = new ArrayList<>(); ClusterTopology topology = topologyProvider.getTopology(); for (final RedisClusterNode node : nodes) { @@ -199,7 +199,7 @@ public class ClusterCommandExecutor implements DisposableBean { } } - Map>> futures = new LinkedHashMap>>(); + Map>> futures = new LinkedHashMap<>(); for (final RedisClusterNode node : resolvedRedisClusterNodes) { futures.put(new NodeExecution(node), executor.submit(() -> executeCommandOnSingleNode(callback, node))); @@ -212,10 +212,10 @@ public class ClusterCommandExecutor implements DisposableBean { boolean done = false; - MulitNodeResult result = new MulitNodeResult(); - Map exceptions = new HashMap(); + MulitNodeResult result = new MulitNodeResult<>(); + Map exceptions = new HashMap<>(); - Set saveGuard = new HashSet(); + Set saveGuard = new HashSet<>(); while (!done) { done = true; @@ -255,7 +255,7 @@ public class ClusterCommandExecutor implements DisposableBean { } if (!exceptions.isEmpty()) { - throw new ClusterCommandExecutionFailureException(new ArrayList(exceptions.values())); + throw new ClusterCommandExecutionFailureException(new ArrayList<>(exceptions.values())); } return result; } @@ -270,7 +270,7 @@ public class ClusterCommandExecutor implements DisposableBean { public MulitNodeResult executeMuliKeyCommand(final MultiKeyClusterCommandCallback cmd, Iterable keys) { - Map> nodeKeyMap = new HashMap>(); + Map> nodeKeyMap = new HashMap<>(); for (byte[] key : keys) { for (RedisClusterNode node : getClusterTopology().getKeyServingNodes(key)) { @@ -278,14 +278,14 @@ public class ClusterCommandExecutor implements DisposableBean { if (nodeKeyMap.containsKey(node)) { nodeKeyMap.get(node).add(key); } else { - Set keySet = new LinkedHashSet(); + Set keySet = new LinkedHashSet<>(); keySet.add(key); nodeKeyMap.put(node, keySet); } } } - Map>> futures = new LinkedHashMap>>(); + Map>> futures = new LinkedHashMap<>(); for (final Entry> entry : nodeKeyMap.entrySet()) { @@ -311,7 +311,7 @@ public class ClusterCommandExecutor implements DisposableBean { Assert.notNull(client, "Could not acquire resource for node. Is your cluster info up to date?"); try { - return new NodeResult(node, cmd.doInCluster(client, key), key); + return new NodeResult<>(node, cmd.doInCluster(client, key), key); } catch (RuntimeException ex) { RuntimeException translatedException = convertToDataAccessExeption(ex); @@ -518,7 +518,7 @@ public class ClusterCommandExecutor implements DisposableBean { */ public static class MulitNodeResult { - List> nodeResults = new ArrayList>(); + List> nodeResults = new ArrayList<>(); private void add(NodeResult result) { nodeResults.add(result); @@ -549,7 +549,7 @@ public class ClusterCommandExecutor implements DisposableBean { */ public List resultsAsListSortBy(byte[]... keys) { - ArrayList> clone = new ArrayList>(nodeResults); + ArrayList> clone = new ArrayList<>(nodeResults); Collections.sort(clone, new ResultByReferenceKeyPositionComperator(keys)); return toList(clone); @@ -580,7 +580,7 @@ public class ClusterCommandExecutor implements DisposableBean { private List toList(Collection> source) { - ArrayList result = new ArrayList(); + ArrayList result = new ArrayList<>(); for (NodeResult nodeResult : source) { result.add(nodeResult.getValue()); } @@ -597,7 +597,7 @@ public class ClusterCommandExecutor implements DisposableBean { List reference; public ResultByReferenceKeyPositionComperator(byte[]... keys) { - reference = new ArrayList(new ByteArraySet(Arrays.asList(keys))); + reference = new ArrayList<>(new ByteArraySet(Arrays.asList(keys))); } @Override diff --git a/src/main/java/org/springframework/data/redis/connection/ClusterTopology.java b/src/main/java/org/springframework/data/redis/connection/ClusterTopology.java index b9d2a632f..92cf61c93 100644 --- a/src/main/java/org/springframework/data/redis/connection/ClusterTopology.java +++ b/src/main/java/org/springframework/data/redis/connection/ClusterTopology.java @@ -25,7 +25,7 @@ import org.springframework.util.StringUtils; /** * {@link ClusterTopology} holds snapshot like information about {@link RedisClusterNode}s. - * + * * @author Christoph Strobl * @author Mark Paluch * @since 1.7 @@ -36,7 +36,7 @@ public class ClusterTopology { /** * Creates new instance of {@link ClusterTopology}. - * + * * @param nodes can be {@literal null}. */ public ClusterTopology(Set nodes) { @@ -45,7 +45,7 @@ public class ClusterTopology { /** * Get all {@link RedisClusterNode}s. - * + * * @return never {@literal null}. */ public Set getNodes() { @@ -55,12 +55,12 @@ public class ClusterTopology { /** * Get all nodes (master and slave) in cluster where {@code link-state} is {@literal connected} and {@code flags} does * not contain {@literal fail} or {@literal fail?}. - * + * * @return never {@literal null}. */ public Set getActiveNodes() { - Set activeNodes = new LinkedHashSet(nodes.size()); + Set activeNodes = new LinkedHashSet<>(nodes.size()); for (RedisClusterNode node : nodes) { if (node.isConnected() && !node.isMarkedAsFail()) { activeNodes.add(node); @@ -72,12 +72,12 @@ public class ClusterTopology { /** * Get all master nodes in cluster where {@code link-state} is {@literal connected} and {@code flags} does not contain * {@literal fail} or {@literal fail?}. - * + * * @return never {@literal null}. */ public Set getActiveMasterNodes() { - Set activeMasterNodes = new LinkedHashSet(nodes.size()); + Set activeMasterNodes = new LinkedHashSet<>(nodes.size()); for (RedisClusterNode node : nodes) { if (node.isMaster() && node.isConnected() && !node.isMarkedAsFail()) { activeMasterNodes.add(node); @@ -88,12 +88,12 @@ public class ClusterTopology { /** * Get all master nodes in cluster. - * + * * @return never {@literal null}. */ public Set getMasterNodes() { - Set masterNodes = new LinkedHashSet(nodes.size()); + Set masterNodes = new LinkedHashSet<>(nodes.size()); for (RedisClusterNode node : nodes) { if (node.isMaster()) { masterNodes.add(node); @@ -104,13 +104,13 @@ public class ClusterTopology { /** * Get the {@link RedisClusterNode}s (master and slave) serving s specific slot. - * + * * @param slot * @return never {@literal null}. */ public Set getSlotServingNodes(int slot) { - Set slotServingNodes = new LinkedHashSet(nodes.size()); + Set slotServingNodes = new LinkedHashSet<>(nodes.size()); for (RedisClusterNode node : nodes) { if (node.servesSlot(slot)) { slotServingNodes.add(node); @@ -121,7 +121,7 @@ public class ClusterTopology { /** * Get the {@link RedisClusterNode} that is the current master serving the given key. - * + * * @param key must not be {@literal null}. * @return * @throws ClusterStateFailureException @@ -142,7 +142,7 @@ public class ClusterTopology { /** * Get the {@link RedisClusterNode} matching given {@literal host} and {@literal port}. - * + * * @param host must not be {@literal null}. * @param port * @return diff --git a/src/main/java/org/springframework/data/redis/connection/DataType.java b/src/main/java/org/springframework/data/redis/connection/DataType.java index 6dbc2c880..8c0cc644a 100644 --- a/src/main/java/org/springframework/data/redis/connection/DataType.java +++ b/src/main/java/org/springframework/data/redis/connection/DataType.java @@ -1,5 +1,5 @@ /* - * Copyright 2011-2013 the original author or authors. + * Copyright 2011-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,14 +22,14 @@ import java.util.concurrent.ConcurrentHashMap; /** * Enumeration of the Redis data types. - * + * * @author Costin Leau */ public enum DataType { NONE("none"), STRING("string"), LIST("list"), SET("set"), ZSET("zset"), HASH("hash"); - private static final Map codeLookup = new ConcurrentHashMap(6); + private static final Map codeLookup = new ConcurrentHashMap<>(6); static { for (DataType type : EnumSet.allOf(DataType.class)) @@ -45,7 +45,7 @@ public enum DataType { /** * Returns the code associated with the current enum. - * + * * @return code of this enum */ public String code() { @@ -54,7 +54,7 @@ public enum DataType { /** * Utility method for converting an enum code to an actual enum. - * + * * @param code enum code * @return actual enum corresponding to the given code */ diff --git a/src/main/java/org/springframework/data/redis/connection/DefaultSortParameters.java b/src/main/java/org/springframework/data/redis/connection/DefaultSortParameters.java index d4303e05c..cb15cf9e7 100644 --- a/src/main/java/org/springframework/data/redis/connection/DefaultSortParameters.java +++ b/src/main/java/org/springframework/data/redis/connection/DefaultSortParameters.java @@ -1,12 +1,12 @@ /* - * Copyright 2011-2013 the original author or authors. - * + * Copyright 2011-2017 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 byPattern 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. @@ -20,14 +20,14 @@ import java.util.List; /** * Default implementation for {@link SortParameters}. - * + * * @author Costin Leau */ public class DefaultSortParameters implements SortParameters { private byte[] byPattern; private Range limit; - private final List getPattern = new ArrayList(4); + private final List getPattern = new ArrayList<>(4); private Order order; private Boolean alphabetic; @@ -40,7 +40,7 @@ public class DefaultSortParameters implements SortParameters { /** * Constructs a new DefaultSortParameters instance. - * + * * @param limit * @param order * @param alphabetic @@ -51,7 +51,7 @@ public class DefaultSortParameters implements SortParameters { /** * Constructs a new DefaultSortParameters instance. - * + * * @param byPattern * @param limit * @param getPattern diff --git a/src/main/java/org/springframework/data/redis/connection/DefaultStringRedisConnection.java b/src/main/java/org/springframework/data/redis/connection/DefaultStringRedisConnection.java index 3285ee2f9..93abfec78 100644 --- a/src/main/java/org/springframework/data/redis/connection/DefaultStringRedisConnection.java +++ b/src/main/java/org/springframework/data/redis/connection/DefaultStringRedisConnection.java @@ -79,7 +79,7 @@ public class DefaultStringRedisConnection implements StringRedisConnection, Deco @SuppressWarnings("rawtypes") private Queue pipelineConverters = new LinkedList<>(); @SuppressWarnings("rawtypes") private Queue txConverters = new LinkedList<>(); private boolean deserializePipelineAndTxResults = false; - private IdentityConverter identityConverter = new IdentityConverter(); + private IdentityConverter identityConverter = new IdentityConverter<>(); private class DeserializingConverter implements Converter { public String convert(byte[] source) { @@ -284,7 +284,7 @@ public class DefaultStringRedisConnection implements StringRedisConnection, Deco try { List results = delegate.exec(); if (isPipelined()) { - pipelineConverters.add(new TransactionResultConverter(new LinkedList(txConverters))); + pipelineConverters.add(new TransactionResultConverter(new LinkedList<>(txConverters))); return results; } return convertResults(results, txConverters); @@ -3200,54 +3200,6 @@ public class DefaultStringRedisConnection implements StringRedisConnection, Deco return this.delegate.hScan(key, options); } - /** - * Specifies if pipelined and tx results should be deserialized to Strings. If false, results of - * {@link #closePipeline()} and {@link #exec()} will be of the type returned by the underlying connection - * - * @param deserializePipelineAndTxResults Whether or not to deserialize pipeline and tx results - */ - public void setDeserializePipelineAndTxResults(boolean deserializePipelineAndTxResults) { - this.deserializePipelineAndTxResults = deserializePipelineAndTxResults; - } - - private T convertAndReturn(Object value, Converter converter) { - - if (isFutureConversion()) { - addResultConverter(converter); - } - - return ObjectUtils.nullSafeEquals(converter, identityConverter) ? (T) value : (T) converter.convert(value); - } - - private void addResultConverter(Converter converter) { - if (isQueueing()) { - txConverters.add(converter); - } else { - pipelineConverters.add(converter); - } - } - - private boolean isFutureConversion() { - return isPipelined() || isQueueing(); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - private List convertResults(List results, Queue converters) { - if (!deserializePipelineAndTxResults || results == null) { - return results; - } - if (results.size() != converters.size()) { - // Some of the commands were done directly on the delegate, don't attempt to convert - log.warn("Delegate returned an unexpected number of results. Abandoning type conversion."); - return results; - } - List convertedResults = new ArrayList(); - for (Object result : results) { - convertedResults.add(converters.remove().convert(result)); - } - return convertedResults; - } - /* * (non-Javadoc) * @see org.springframework.data.redis.connection.RedisServerCommands#setClientName(java.lang.String) @@ -3290,29 +3242,23 @@ public class DefaultStringRedisConnection implements StringRedisConnection, Deco @Override public Cursor> hScan(String key, ScanOptions options) { - return new ConvertingCursor, Map.Entry>( + return new ConvertingCursor<>( this.delegate.hScan(this.serialize(key), options), - new Converter, Map.Entry>() { + source -> new Entry() { @Override - public Entry convert(final Entry source) { - return new Map.Entry() { + public String getKey() { + return bytesToString.convert(source.getKey()); + } - @Override - public String getKey() { - return bytesToString.convert(source.getKey()); - } + @Override + public String getValue() { + return bytesToString.convert(source.getValue()); + } - @Override - public String getValue() { - return bytesToString.convert(source.getValue()); - } - - @Override - public String setValue(String value) { - throw new UnsupportedOperationException("Cannot set value for entry in cursor"); - } - }; + @Override + public String setValue(String value) { + throw new UnsupportedOperationException("Cannot set value for entry in cursor"); } }); } @@ -3323,7 +3269,7 @@ public class DefaultStringRedisConnection implements StringRedisConnection, Deco */ @Override public Cursor sScan(String key, ScanOptions options) { - return new ConvertingCursor(this.delegate.sScan(this.serialize(key), options), bytesToString); + return new ConvertingCursor<>(this.delegate.sScan(this.serialize(key), options), bytesToString); } /* @@ -3332,7 +3278,7 @@ public class DefaultStringRedisConnection implements StringRedisConnection, Deco */ @Override public Cursor zScan(String key, ScanOptions options) { - return new ConvertingCursor(delegate.zScan(this.serialize(key), options), + return new ConvertingCursor<>(delegate.zScan(this.serialize(key), options), new TupleConverter()); } @@ -3507,6 +3453,55 @@ public class DefaultStringRedisConnection implements StringRedisConnection, Deco delegate.migrate(key, target, dbIndex, option, timeout); } + /** + * Specifies if pipelined and tx results should be deserialized to Strings. If false, results of + * {@link #closePipeline()} and {@link #exec()} will be of the type returned by the underlying connection + * + * @param deserializePipelineAndTxResults Whether or not to deserialize pipeline and tx results + */ + public void setDeserializePipelineAndTxResults(boolean deserializePipelineAndTxResults) { + this.deserializePipelineAndTxResults = deserializePipelineAndTxResults; + } + + @SuppressWarnings("unchecked") + private T convertAndReturn(Object value, Converter converter) { + + if (isFutureConversion()) { + addResultConverter(converter); + } + + return ObjectUtils.nullSafeEquals(converter, identityConverter) ? (T) value : (T) converter.convert(value); + } + + private void addResultConverter(Converter converter) { + if (isQueueing()) { + txConverters.add(converter); + } else { + pipelineConverters.add(converter); + } + } + + private boolean isFutureConversion() { + return isPipelined() || isQueueing(); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private List convertResults(List results, Queue converters) { + if (!deserializePipelineAndTxResults || results == null) { + return results; + } + if (results.size() != converters.size()) { + // Some of the commands were done directly on the delegate, don't attempt to convert + log.warn("Delegate returned an unexpected number of results. Abandoning type conversion."); + return results; + } + List convertedResults = new ArrayList<>(results.size()); + for (Object result : results) { + convertedResults.add(converters.remove().convert(result)); + } + return convertedResults; + } + /* * (non-Javadoc) * @see org.springframework.data.redis.connection.DecoratedRedisConnection#getDelegate() diff --git a/src/main/java/org/springframework/data/redis/connection/ReactiveNumberCommands.java b/src/main/java/org/springframework/data/redis/connection/ReactiveNumberCommands.java index 687f0bc4b..17f2579f4 100644 --- a/src/main/java/org/springframework/data/redis/connection/ReactiveNumberCommands.java +++ b/src/main/java/org/springframework/data/redis/connection/ReactiveNumberCommands.java @@ -82,7 +82,7 @@ public interface ReactiveNumberCommands { Assert.notNull(key, "Key must not be null!"); - return new IncrByCommand(key, null); + return new IncrByCommand<>(key, null); } /** @@ -96,7 +96,7 @@ public interface ReactiveNumberCommands { Assert.notNull(value, "Value must not be null!"); - return new IncrByCommand(getKey(), value); + return new IncrByCommand<>(getKey(), value); } /** @@ -158,7 +158,7 @@ public interface ReactiveNumberCommands { Assert.notNull(key, "Key must not be null!"); - return new DecrByCommand(key, null); + return new DecrByCommand<>(key, null); } /** @@ -172,7 +172,7 @@ public interface ReactiveNumberCommands { Assert.notNull(value, "Value must not be null!"); - return new DecrByCommand(getKey(), value); + return new DecrByCommand<>(getKey(), value); } /** @@ -259,7 +259,7 @@ public interface ReactiveNumberCommands { Assert.notNull(field, "Field must not be null!"); - return new HIncrByCommand(null, field, null); + return new HIncrByCommand<>(null, field, null); } /** @@ -273,7 +273,7 @@ public interface ReactiveNumberCommands { Assert.notNull(value, "Value must not be null!"); - return new HIncrByCommand(getKey(), field, value); + return new HIncrByCommand<>(getKey(), field, value); } /** @@ -286,7 +286,7 @@ public interface ReactiveNumberCommands { Assert.notNull(key, "Key must not be null!"); - return new HIncrByCommand(key, field, value); + return new HIncrByCommand<>(key, field, value); } /** diff --git a/src/main/java/org/springframework/data/redis/connection/ReactiveSetCommands.java b/src/main/java/org/springframework/data/redis/connection/ReactiveSetCommands.java index 366527d93..2b83fd3c3 100644 --- a/src/main/java/org/springframework/data/redis/connection/ReactiveSetCommands.java +++ b/src/main/java/org/springframework/data/redis/connection/ReactiveSetCommands.java @@ -267,15 +267,34 @@ public interface ReactiveSetCommands { this.count = count; } + /** + * Creates a new {@link SPopCommand} for a single member. + * + * @return a new {@link SPopCommand} for a single member. + */ public static SPopCommand one() { return new SPopCommand(null, 1L); } + /** + * Creates a new {@link SPopCommand} for {@code count} members. + * + * @return a new {@link SPopCommand} for {@code count} members. + */ public static SPopCommand members(long count) { return new SPopCommand(null, count); } + /** + * Applies the {@literal key}. Constructs a new command instance with all previously configured properties. + * + * @param key must not be {@literal null}. + * @return a new {@link SRemCommand} with {@literal key} applied. + */ public SPopCommand from(ByteBuffer key) { + + Assert.notNull(key, "Key must not be null!"); + return new SPopCommand(key, count); } @@ -299,9 +318,10 @@ public interface ReactiveSetCommands { } /** - * Remove and return a random member from set at {@literal key}. + * Remove and return {@code count} random members from set at {@code key}. * * @param key must not be {@literal null}. + * @param count number of random members to pop from the set. * @return * @see Redis Documentation: SPOP */ @@ -742,7 +762,7 @@ public interface ReactiveSetCommands { /** * {@code SUNIONSTORE} command parameters. - * + * * @author Christoph Strobl * @see Redis Documentation: SUNIONSTORE */ diff --git a/src/main/java/org/springframework/data/redis/connection/RedisClusterNode.java b/src/main/java/org/springframework/data/redis/connection/RedisClusterNode.java index 1d62ac6b1..f66abb30c 100644 --- a/src/main/java/org/springframework/data/redis/connection/RedisClusterNode.java +++ b/src/main/java/org/springframework/data/redis/connection/RedisClusterNode.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,7 @@ import org.springframework.util.CollectionUtils; /** * Representation of a Redis server within the cluster. - * + * * @author Christoph Strobl * @author Mark Paluch * @since 1.7 @@ -42,7 +42,7 @@ public class RedisClusterNode extends RedisNode { /** * Creates new {@link RedisClusterNode} with empty {@link SlotRange}. - * + * * @param host must not be {@literal null}. * @param port */ @@ -64,7 +64,7 @@ public class RedisClusterNode extends RedisNode { /** * Creates new {@link RedisClusterNode} with given {@link SlotRange}. - * + * * @param host must not be {@literal null}. * @param port * @param slotRange can be {@literal null}. @@ -88,7 +88,7 @@ public class RedisClusterNode extends RedisNode { /** * Get the served {@link SlotRange}. - * + * * @return never {@literal null}. */ public SlotRange getSlotRange() { @@ -146,7 +146,7 @@ public class RedisClusterNode extends RedisNode { /** * Get {@link RedisClusterNodeBuilder} for creating new {@link RedisClusterNode}. - * + * * @return never {@literal null}. */ public static RedisClusterNodeBuilder newRedisClusterNode() { @@ -170,7 +170,7 @@ public class RedisClusterNode extends RedisNode { Assert.notNull(lowerBound, "LowerBound must not be null!"); Assert.notNull(upperBound, "UpperBound must not be null!"); - this.range = new LinkedHashSet(); + this.range = new LinkedHashSet<>(); for (int i = lowerBound; i <= upperBound; i++) { this.range.add(i); } @@ -178,7 +178,7 @@ public class RedisClusterNode extends RedisNode { public SlotRange(Collection range) { this.range = CollectionUtils.isEmpty(range) ? Collections. emptySet() - : new LinkedHashSet(range); + : new LinkedHashSet<>(range); } @Override @@ -245,7 +245,7 @@ public class RedisClusterNode extends RedisNode { /** * Builder for creating new {@link RedisClusterNode}. - * + * * @author Christoph Strobl * @since 1.7 */ @@ -310,7 +310,7 @@ public class RedisClusterNode extends RedisNode { /** * Set flags for node. - * + * * @param flags * @return */ @@ -322,7 +322,7 @@ public class RedisClusterNode extends RedisNode { /** * Set {@link SlotRange}. - * + * * @param range * @return */ @@ -334,7 +334,7 @@ public class RedisClusterNode extends RedisNode { /** * Set {@link LinkState}. - * + * * @param linkState * @return */ diff --git a/src/main/java/org/springframework/data/redis/connection/RedisGeoCommands.java b/src/main/java/org/springframework/data/redis/connection/RedisGeoCommands.java index 830ed1c85..99e7de7bd 100644 --- a/src/main/java/org/springframework/data/redis/connection/RedisGeoCommands.java +++ b/src/main/java/org/springframework/data/redis/connection/RedisGeoCommands.java @@ -43,7 +43,7 @@ public interface RedisGeoCommands { /** * Add {@link Point} with given member {@literal name} to {@literal key}. - * + * * @param key must not be {@literal null}. * @param point must not be {@literal null}. * @param member must not be {@literal null}. @@ -54,7 +54,7 @@ public interface RedisGeoCommands { /** * Add {@link GeoLocation} to {@literal key}. - * + * * @param key must not be {@literal null}. * @param location must not be {@literal null}. * @return Number of elements added. @@ -70,7 +70,7 @@ public interface RedisGeoCommands { /** * Add {@link Map} of member / {@link Point} pairs to {@literal key}. - * + * * @param key must not be {@literal null}. * @param memberCoordinateMap must not be {@literal null}. * @return Number of elements added. @@ -80,7 +80,7 @@ public interface RedisGeoCommands { /** * Add {@link GeoLocation}s to {@literal key} - * + * * @param key must not be {@literal null}. * @param locations must not be {@literal null}. * @return Number of elements added. @@ -90,7 +90,7 @@ public interface RedisGeoCommands { /** * Get the {@link Distance} between {@literal member1} and {@literal member2}. - * + * * @param key must not be {@literal null}. * @param member1 must not be {@literal null}. * @param member2 must not be {@literal null}. @@ -101,7 +101,7 @@ public interface RedisGeoCommands { /** * Get the {@link Distance} between {@literal member1} and {@literal member2} in the given {@link Metric}. - * + * * @param key must not be {@literal null}. * @param member1 must not be {@literal null}. * @param member2 must not be {@literal null}. @@ -113,7 +113,7 @@ public interface RedisGeoCommands { /** * Get Geohash representation of the position for one or more {@literal member}s. - * + * * @param key must not be {@literal null}. * @param members must not be {@literal null}. * @return never {@literal null}. @@ -123,7 +123,7 @@ public interface RedisGeoCommands { /** * Get the {@link Point} representation of positions for one or more {@literal member}s. - * + * * @param key must not be {@literal null}. * @param members must not be {@literal null}. * @return never {@literal null}. @@ -133,7 +133,7 @@ public interface RedisGeoCommands { /** * Get the {@literal member}s within the boundaries of a given {@link Circle}. - * + * * @param key must not be {@literal null}. * @param within must not be {@literal null}. * @return never {@literal null}. @@ -143,7 +143,7 @@ public interface RedisGeoCommands { /** * Get the {@literal member}s within the boundaries of a given {@link Circle} applying {@link GeoRadiusCommandArgs}. - * + * * @param key must not be {@literal null}. * @param within must not be {@literal null}. * @param args must not be {@literal null}. @@ -155,7 +155,7 @@ public interface RedisGeoCommands { /** * Get the {@literal member}s within the circle defined by the {@literal members} coordinates and given * {@literal radius}. - * + * * @param key must not be {@literal null}. * @param member must not be {@literal null}. * @param radius @@ -169,7 +169,7 @@ public interface RedisGeoCommands { /** * Get the {@literal member}s within the circle defined by the {@literal members} coordinates and given * {@link Distance}. - * + * * @param key must not be {@literal null}. * @param member must not be {@literal null}. * @param radius must not be {@literal null}. @@ -181,7 +181,7 @@ public interface RedisGeoCommands { /** * Get the {@literal member}s within the circle defined by the {@literal members} coordinates, given {@link Distance} * and {@link GeoRadiusCommandArgs}. - * + * * @param key must not be {@literal null}. * @param member must not be {@literal null}. * @param radius must not be {@literal null}. @@ -204,14 +204,14 @@ public interface RedisGeoCommands { /** * Additional arguments (like count/sort/...) to be used with {@link RedisGeoCommands}. - * + * * @author Ninad Divadkar * @author Christoph Strobl * @since 1.8 */ class GeoRadiusCommandArgs implements Cloneable { - Set flags = new LinkedHashSet(2, 1); + Set flags = new LinkedHashSet<>(2, 1); Long limit; Direction sortDirection; @@ -219,7 +219,7 @@ public interface RedisGeoCommands { /** * Create new {@link GeoRadiusCommandArgs}. - * + * * @return never {@literal null}. */ public static GeoRadiusCommandArgs newGeoRadiusArgs() { @@ -250,7 +250,7 @@ public interface RedisGeoCommands { /** * Sort returned items from the nearest to the furthest, relative to the center. - * + * * @return never {@literal null}. */ public GeoRadiusCommandArgs sortAscending() { @@ -261,7 +261,7 @@ public interface RedisGeoCommands { /** * Sort returned items from the furthest to the nearest, relative to the center. - * + * * @return never {@literal null}. */ public GeoRadiusCommandArgs sortDescending() { @@ -272,7 +272,7 @@ public interface RedisGeoCommands { /** * Limit the results to the first N matching items. - * + * * @param count * @return never {@literal null}. */ @@ -333,7 +333,7 @@ public interface RedisGeoCommands { /** * {@link GeoLocation} representing a {@link Point} associated with a {@literal name}. - * + * * @author Christoph Strobl * @param * @since 1.8 @@ -361,7 +361,7 @@ public interface RedisGeoCommands { /** * Creates a new {@link DistanceUnit} using the given muliplier. - * + * * @param multiplier the earth radius at equator. */ private DistanceUnit(double multiplier, String abbreviation) { @@ -378,7 +378,7 @@ public interface RedisGeoCommands { return multiplier; } - /* + /* * (non-Javadoc) * @see org.springframework.data.geo.Metric#getAbbreviation() */ diff --git a/src/main/java/org/springframework/data/redis/connection/RedisSetCommands.java b/src/main/java/org/springframework/data/redis/connection/RedisSetCommands.java index d08791271..461946d1f 100644 --- a/src/main/java/org/springframework/data/redis/connection/RedisSetCommands.java +++ b/src/main/java/org/springframework/data/redis/connection/RedisSetCommands.java @@ -23,7 +23,7 @@ import org.springframework.data.redis.core.ScanOptions; /** * Set-specific commands supported by Redis. - * + * * @author Costin Leau * @author Christoph Strobl * @author Mark Paluch @@ -63,7 +63,7 @@ public interface RedisSetCommands { * Remove and return {@code count} random members from set at {@code key}. * * @param key must not be {@literal null}. - * @param count the number of random members to pop from the set. + * @param count number of random members to pop from the set. * @return empty {@link List} if set does not exist. Never {@literal null}. * @see Redis Documentation: SPOP * @since 2.0 diff --git a/src/main/java/org/springframework/data/redis/connection/StringRedisConnection.java b/src/main/java/org/springframework/data/redis/connection/StringRedisConnection.java index 78f11b3c8..7f9f10a31 100644 --- a/src/main/java/org/springframework/data/redis/connection/StringRedisConnection.java +++ b/src/main/java/org/springframework/data/redis/connection/StringRedisConnection.java @@ -1,12 +1,12 @@ /* * Copyright 2011-2017 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. @@ -37,7 +37,7 @@ import org.springframework.data.redis.serializer.RedisSerializer; /** * Convenience extension of {@link RedisConnection} that accepts and returns {@link String}s instead of byte arrays. * Uses a {@link RedisSerializer} underneath to perform the conversion. - * + * * @author Costin Leau * @author Christoph Strobl * @author Thomas Darimont @@ -53,7 +53,7 @@ public interface StringRedisConnection extends RedisConnection { /** * String-friendly ZSet tuple. */ - public interface StringTuple extends Tuple { + interface StringTuple extends Tuple { String getValueAsString(); } diff --git a/src/main/java/org/springframework/data/redis/connection/convert/Converters.java b/src/main/java/org/springframework/data/redis/connection/convert/Converters.java index 4d4c0dc26..5845603a7 100644 --- a/src/main/java/org/springframework/data/redis/connection/convert/Converters.java +++ b/src/main/java/org/springframework/data/redis/connection/convert/Converters.java @@ -17,7 +17,16 @@ package org.springframework.data.redis.connection.convert; import lombok.RequiredArgsConstructor; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; import java.util.concurrent.TimeUnit; import org.springframework.core.convert.converter.Converter; @@ -66,7 +75,7 @@ abstract public class Converters { static { - flagLookupMap = new LinkedHashMap(Flag.values().length, 1); + flagLookupMap = new LinkedHashMap<>(Flag.values().length, 1); for (Flag flag : Flag.values()) { flagLookupMap.put(flag.getRaw(), flag); } @@ -113,7 +122,7 @@ abstract public class Converters { String raw = args[FLAGS_INDEX]; - Set flags = new LinkedHashSet(8, 1); + Set flags = new LinkedHashSet<>(8, 1); if (StringUtils.hasText(raw)) { for (String flag : raw.split(",")) { flags.add(flagLookupMap.get(flag)); @@ -134,7 +143,7 @@ abstract public class Converters { private SlotRange parseSlotRange(String[] args) { - Set slots = new LinkedHashSet(); + Set slots = new LinkedHashSet<>(); for (int i = SLOTS_INDEX; i < args.length; i++) { @@ -241,7 +250,7 @@ abstract public class Converters { return Collections.emptySet(); } - Set nodes = new LinkedHashSet(lines.size()); + Set nodes = new LinkedHashSet<>(lines.size()); for (String line : lines) { nodes.add(toClusterNode(line)); @@ -268,7 +277,7 @@ abstract public class Converters { } public static List toObjects(Set tuples) { - List tupleArgs = new ArrayList(tuples.size() * 2); + List tupleArgs = new ArrayList<>(tuples.size() * 2); for (Tuple tuple : tuples) { tupleArgs.add(tuple.getScore()); tupleArgs.add(tuple.getValue()); @@ -316,13 +325,7 @@ abstract public class Converters { */ public static Converter secondsToTimeUnit(final TimeUnit timeUnit) { - return new Converter() { - - @Override - public Long convert(Long seconds) { - return secondsToTimeUnit(seconds, timeUnit); - } - }; + return seconds -> secondsToTimeUnit(seconds, timeUnit); } /** @@ -353,13 +356,7 @@ abstract public class Converters { */ public static Converter millisecondsToTimeUnit(final TimeUnit timeUnit) { - return new Converter() { - - @Override - public Long convert(Long seconds) { - return millisecondsToTimeUnit(seconds, timeUnit); - } - }; + return seconds -> millisecondsToTimeUnit(seconds, timeUnit); } /** @@ -371,7 +368,7 @@ abstract public class Converters { */ public static Converter>, GeoResults>> deserializingGeoResultsConverter( RedisSerializer serializer) { - return new DeserializingGeoResultsConverter(serializer); + return new DeserializingGeoResultsConverter<>(serializer); } /** @@ -414,8 +411,9 @@ abstract public class Converters { * @return the converter. * @since 2.0 */ - public static Converter, Properties> mapToPropertiesConverter() { - return MAP_TO_PROPERTIES; + @SuppressWarnings("unchecked") + public static Converter, Properties> mapToPropertiesConverter() { + return (Converter) MAP_TO_PROPERTIES; } /** @@ -462,18 +460,18 @@ abstract public class Converters { public GeoResults> convert(GeoResults> source) { if (source == null) { - return new GeoResults>(Collections.>> emptyList()); + return new GeoResults<>(Collections.>> emptyList()); } - List>> values = new ArrayList>>(source.getContent().size()); + List>> values = new ArrayList<>(source.getContent().size()); for (GeoResult> value : source.getContent()) { - values.add(new GeoResult>( - new GeoLocation(serializer.deserialize(value.getContent().getName()), value.getContent().getPoint()), + values.add(new GeoResult<>( + new GeoLocation<>(serializer.deserialize(value.getContent().getName()), value.getContent().getPoint()), value.getDistance())); } - return new GeoResults>(values, source.getAverageDistance().getMetric()); + return new GeoResults<>(values, source.getAverageDistance().getMetric()); } } } diff --git a/src/main/java/org/springframework/data/redis/connection/convert/ListConverter.java b/src/main/java/org/springframework/data/redis/connection/convert/ListConverter.java index 6ed35c122..569075250 100644 --- a/src/main/java/org/springframework/data/redis/connection/convert/ListConverter.java +++ b/src/main/java/org/springframework/data/redis/connection/convert/ListConverter.java @@ -1,3 +1,18 @@ +/* + * Copyright 2017 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.redis.connection.convert; import java.util.ArrayList; @@ -7,8 +22,9 @@ import org.springframework.core.convert.converter.Converter; /** * Converts a List of values of one type to a List of values of another type - * + * * @author Jennifer Hickey + * @author Mark Paluch * @param The type of elements in the List to convert * @param The type of elements in the converted List */ @@ -24,14 +40,16 @@ public class ListConverter implements Converter, List> { } public List convert(List source) { + if (source == null) { return null; } - List results = new ArrayList(); + + List results = new ArrayList<>(); for (S result : source) { results.add(itemConverter.convert(result)); } + return results; } - } diff --git a/src/main/java/org/springframework/data/redis/connection/convert/MapConverter.java b/src/main/java/org/springframework/data/redis/connection/convert/MapConverter.java index 50b48372c..5f1163e3a 100644 --- a/src/main/java/org/springframework/data/redis/connection/convert/MapConverter.java +++ b/src/main/java/org/springframework/data/redis/connection/convert/MapConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2013 the original author or authors. + * Copyright 2013-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +23,7 @@ import org.springframework.core.convert.converter.Converter; /** * Converts a Map of values of one key/value type to a Map of values of another type - * + * * @author Jennifer Hickey * @param The type of keys and values in the Map to convert * @param The type of keys and values in the converted Map @@ -40,18 +40,23 @@ public class MapConverter implements Converter, Map> { } public Map convert(Map source) { + if (source == null) { return null; } + Map results; + if (source instanceof LinkedHashMap) { - results = new LinkedHashMap(); + results = new LinkedHashMap<>(); } else { - results = new HashMap(); + results = new HashMap<>(); } + for (Map.Entry result : source.entrySet()) { results.put(itemConverter.convert(result.getKey()), itemConverter.convert(result.getValue())); } + return results; } diff --git a/src/main/java/org/springframework/data/redis/connection/convert/SetConverter.java b/src/main/java/org/springframework/data/redis/connection/convert/SetConverter.java index 78010c56d..f6c507e93 100644 --- a/src/main/java/org/springframework/data/redis/connection/convert/SetConverter.java +++ b/src/main/java/org/springframework/data/redis/connection/convert/SetConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2013 the original author or authors. + * Copyright 2013-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +23,7 @@ import org.springframework.core.convert.converter.Converter; /** * Converts a Set of values of one type to a Set of values of another type - * + * * @author Jennifer Hickey * @param The type of elements in the Set to convert * @param The type of elements in the converted Set @@ -40,18 +40,23 @@ public class SetConverter implements Converter, Set> { } public Set convert(Set source) { + if (source == null) { return null; } + Set results; + if (source instanceof LinkedHashSet) { - results = new LinkedHashSet(); + results = new LinkedHashSet<>(); } else { - results = new HashSet(); + results = new HashSet<>(); } + for (S result : source) { results.add(itemConverter.convert(result)); } + return results; } diff --git a/src/main/java/org/springframework/data/redis/connection/convert/StringToRedisClientInfoConverter.java b/src/main/java/org/springframework/data/redis/connection/convert/StringToRedisClientInfoConverter.java index 8c1fe7449..684b8df70 100644 --- a/src/main/java/org/springframework/data/redis/connection/convert/StringToRedisClientInfoConverter.java +++ b/src/main/java/org/springframework/data/redis/connection/convert/StringToRedisClientInfoConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2014 the original author or authors. + * Copyright 2014-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,12 +25,12 @@ import org.springframework.data.redis.core.types.RedisClientInfo.RedisClientInfo /** * {@link Converter} implementation to create one {@link RedisClientInfo} per line entry in given {@link String} array. - * + * *
  * ## sample of single line
  * addr=127.0.0.1:60311 fd=6 name= age=4059 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=32768 obl=0 oll=0 omem=0 events=r cmd=client
  * 
- * + * * @author Christoph Strobl * @since 1.3 */ @@ -42,10 +42,12 @@ public class StringToRedisClientInfoConverter implements Converter infos = new ArrayList(lines.length); + + List infos = new ArrayList<>(lines.length); for (String line : lines) { infos.add(RedisClientInfoBuilder.fromString(line)); } + return infos; } diff --git a/src/main/java/org/springframework/data/redis/connection/convert/TransactionResultConverter.java b/src/main/java/org/springframework/data/redis/connection/convert/TransactionResultConverter.java index a28bfe139..0efb608ce 100644 --- a/src/main/java/org/springframework/data/redis/connection/convert/TransactionResultConverter.java +++ b/src/main/java/org/springframework/data/redis/connection/convert/TransactionResultConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2013 the original author or authors. + * Copyright 2013-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,13 +27,13 @@ import org.springframework.data.redis.connection.FutureResult; /** * Converts the results of transaction exec using a supplied Queue of {@link FutureResult}s. Converts any Exception * objects returned in the list as well, using the supplied Exception {@link Converter} - * + * * @author Jennifer Hickey * @param The type of {@link FutureResult} of the individual tx operations */ public class TransactionResultConverter implements Converter, List> { - private Queue> txResults = new LinkedList>(); + private Queue> txResults = new LinkedList<>(); private Converter exceptionConverter; @@ -44,14 +44,18 @@ public class TransactionResultConverter implements Converter, Li } public List convert(List execResults) { + if (execResults == null) { return null; } + if (execResults.size() != txResults.size()) { throw new IllegalArgumentException("Incorrect number of transaction results. Expected: " + txResults.size() + " Actual: " + execResults.size()); } - List convertedResults = new ArrayList(); + + List convertedResults = new ArrayList<>(); + for (Object result : execResults) { FutureResult futureResult = txResults.remove(); if (result instanceof Exception) { @@ -61,6 +65,7 @@ public class TransactionResultConverter implements Converter, Li convertedResults.add(futureResult.convert(result)); } } + return convertedResults; } } diff --git a/src/main/java/org/springframework/data/redis/connection/jedis/JedisConverters.java b/src/main/java/org/springframework/data/redis/connection/jedis/JedisConverters.java index bef0ca162..61d88285a 100644 --- a/src/main/java/org/springframework/data/redis/connection/jedis/JedisConverters.java +++ b/src/main/java/org/springframework/data/redis/connection/jedis/JedisConverters.java @@ -111,29 +111,14 @@ abstract public class JedisConverters extends Converters { static { - BYTES_TO_STRING_CONVERTER = new Converter() { - - @Override - public String convert(byte[] source) { - return source == null ? null : SafeEncoder.encode(source); - } - }; + BYTES_TO_STRING_CONVERTER = source -> source == null ? null : SafeEncoder.encode(source); BYTES_LIST_TO_STRING_LIST_CONVERTER = new ListConverter<>(BYTES_TO_STRING_CONVERTER); - STRING_TO_BYTES = new Converter() { - public byte[] convert(String source) { - return source == null ? null : SafeEncoder.encode(source); - } - }; + STRING_TO_BYTES = source -> source == null ? null : SafeEncoder.encode(source); STRING_LIST_TO_BYTE_LIST = new ListConverter<>(STRING_TO_BYTES); STRING_SET_TO_BYTE_SET = new SetConverter<>(STRING_TO_BYTES); STRING_MAP_TO_BYTE_MAP = new MapConverter<>(STRING_TO_BYTES); - TUPLE_CONVERTER = new Converter() { - public Tuple convert(redis.clients.jedis.Tuple source) { - return source != null ? new DefaultTuple(source.getBinaryElement(), source.getScore()) : null; - } - - }; + TUPLE_CONVERTER = source -> source != null ? new DefaultTuple(source.getBinaryElement(), source.getScore()) : null; TUPLE_SET_TO_TUPLE_SET = new SetConverter<>(TUPLE_CONVERTER); TUPLE_LIST_TO_TUPLE_LIST_CONVERTER = new ListConverter<>(TUPLE_CONVERTER); PLUS_BYTES = toBytes("+"); @@ -141,18 +126,13 @@ abstract public class JedisConverters extends Converters { POSITIVE_INFINITY_BYTES = toBytes("+inf"); NEGATIVE_INFINITY_BYTES = toBytes("-inf"); - OBJECT_TO_CLUSTER_NODE_CONVERTER = new Converter() { + OBJECT_TO_CLUSTER_NODE_CONVERTER = infos -> { - @Override - public RedisClusterNode convert(Object infos) { - - List values = (List) infos; - RedisClusterNode.SlotRange range = new RedisClusterNode.SlotRange(((Number) values.get(0)).intValue(), - ((Number) values.get(1)).intValue()); - List nodeInfo = (List) values.get(2); - return new RedisClusterNode(JedisConverters.toString((byte[]) nodeInfo.get(0)), - ((Number) nodeInfo.get(1)).intValue(), range); - } + List values = (List) infos; + RedisClusterNode.SlotRange range = new RedisClusterNode.SlotRange(((Number) values.get(0)).intValue(), + ((Number) values.get(1)).intValue()); + List nodeInfo = (List) values.get(2); + return new RedisClusterNode(toString((byte[]) nodeInfo.get(0)), ((Number) nodeInfo.get(1)).intValue(), range); }; EX = toBytes("EX"); @@ -195,25 +175,18 @@ abstract public class JedisConverters extends Converters { }; - STRING_LIST_TO_TIME_CONVERTER = new Converter, Long>() { + STRING_LIST_TO_TIME_CONVERTER = source -> { - @Override - public Long convert(List source) { + Assert.notEmpty(source, "Received invalid result from server. Expected 2 items in collection."); + Assert.isTrue(source.size() == 2, + "Received invalid nr of arguments from redis server. Expected 2 received " + source.size()); - Assert.notEmpty(source, "Received invalid result from server. Expected 2 items in collection."); - Assert.isTrue(source.size() == 2, - "Received invalid nr of arguments from redis server. Expected 2 received " + source.size()); - - return toTimeMillis(source.get(0), source.get(1)); - } + return toTimeMillis(source.get(0), source.get(1)); }; - GEO_COORDINATE_TO_POINT_CONVERTER = new Converter() { - @Override - public Point convert(redis.clients.jedis.GeoCoordinate geoCoordinate) { - return geoCoordinate != null ? new Point(geoCoordinate.getLongitude(), geoCoordinate.getLatitude()) : null; - } - }; + GEO_COORDINATE_TO_POINT_CONVERTER = geoCoordinate -> geoCoordinate != null + ? new Point(geoCoordinate.getLongitude(), geoCoordinate.getLatitude()) + : null; LIST_GEO_COORDINATE_TO_POINT_CONVERTER = new ListConverter<>(GEO_COORDINATE_TO_POINT_CONVERTER); } @@ -620,7 +593,7 @@ abstract public class JedisConverters extends Converters { * @author Christoph Strobl * @since 1.8 */ - static enum GeoResultsConverterFactory { + enum GeoResultsConverterFactory { INSTANCE; @@ -658,7 +631,7 @@ abstract public class JedisConverters extends Converters { * @author Christoph Strobl * @since 1.8 */ - static enum GeoResultConverterFactory { + enum GeoResultConverterFactory { INSTANCE; diff --git a/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceConnection.java b/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceConnection.java index 9f0800e21..2481334e8 100644 --- a/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceConnection.java +++ b/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceConnection.java @@ -134,11 +134,11 @@ public class LettuceConnection extends AbstractRedisConnection { } } - LettuceResult newLettuceResult(Future resultHolder) { + LettuceResult newLettuceResult(Future resultHolder) { return new LettuceResult(resultHolder); } - LettuceResult newLettuceResult(Future resultHolder, Converter converter) { + LettuceResult newLettuceResult(Future resultHolder, Converter converter) { return new LettuceResult(resultHolder, converter); } @@ -150,7 +150,7 @@ public class LettuceConnection extends AbstractRedisConnection { } } - LettuceStatusResult newLettuceStatusResult(Future resultHolder) { + LettuceStatusResult newLettuceStatusResult(Future resultHolder) { return new LettuceStatusResult(resultHolder); } diff --git a/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceSetCommands.java b/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceSetCommands.java index a32e6690a..333bea2de 100644 --- a/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceSetCommands.java +++ b/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceSetCommands.java @@ -15,7 +15,6 @@ */ package org.springframework.data.redis.connection.lettuce; -import io.lettuce.core.RedisFuture; import io.lettuce.core.ScanArgs; import io.lettuce.core.ValueScanCursor; import io.lettuce.core.cluster.api.async.RedisClusterAsyncCommands; @@ -266,7 +265,7 @@ class LettuceSetCommands implements RedisSetCommands { try { if (isPipelined()) { pipeline(connection.newLettuceResult(getAsyncConnection().spop(key, count), - (Converter, List>) ArrayList::new)); + ArrayList::new)); return null; } if (isQueueing()) { @@ -309,8 +308,7 @@ class LettuceSetCommands implements RedisSetCommands { public List sRandMember(byte[] key, long count) { try { if (isPipelined()) { - pipeline(connection.newLettuceResult((RedisFuture) getAsyncConnection().srandmember(key, count), - LettuceConverters.bytesCollectionToBytesList())); + pipeline(connection.newLettuceResult(getAsyncConnection().srandmember(key, count))); return null; } if (isQueueing()) { diff --git a/src/main/java/org/springframework/data/redis/connection/util/AbstractSubscription.java b/src/main/java/org/springframework/data/redis/connection/util/AbstractSubscription.java index 9fe074689..f6f947d3b 100644 --- a/src/main/java/org/springframework/data/redis/connection/util/AbstractSubscription.java +++ b/src/main/java/org/springframework/data/redis/connection/util/AbstractSubscription.java @@ -1,12 +1,12 @@ /* * Copyright 2011-2017 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. @@ -28,13 +28,13 @@ import org.springframework.util.ObjectUtils; /** * Base implementation for a subscription handling the channel/pattern registration so subclasses only have to deal with * the actual registration/unregistration. - * + * * @author Costin Leau */ public abstract class AbstractSubscription implements Subscription { - private final Collection channels = new ArrayList(2); - private final Collection patterns = new ArrayList(2); + private final Collection channels = new ArrayList<>(2); + private final Collection patterns = new ArrayList<>(2); private final AtomicBoolean alive = new AtomicBoolean(true); private final MessageListener listener; @@ -46,7 +46,7 @@ public abstract class AbstractSubscription implements Subscription { * Constructs a new AbstractSubscription instance. Allows channels and patterns to be added to the * subscription w/o triggering a subscription action (as some clients (Jedis) require an initial call before entering * into listening mode). - * + * * @param listener * @param channels * @param patterns @@ -65,14 +65,14 @@ public abstract class AbstractSubscription implements Subscription { /** * Subscribe to the given channels. - * + * * @param channels channels to subscribe to */ protected abstract void doSubscribe(byte[]... channels); /** * Channel unsubscribe. - * + * * @param all true if all the channels are unsubscribed (used as a hint for the underlying implementation). * @param channels channels to be unsubscribed */ @@ -80,14 +80,14 @@ public abstract class AbstractSubscription implements Subscription { /** * Subscribe to the given patterns - * + * * @param patterns patterns to subscribe to */ protected abstract void doPsubscribe(byte[]... patterns); /** * Pattern unsubscribe. - * + * * @param all true if all the patterns are unsubscribed (used as a hint for the underlying implementation). * @param patterns patterns to be unsubscribed */ @@ -218,7 +218,7 @@ public abstract class AbstractSubscription implements Subscription { } private static Collection clone(Collection col) { - Collection list = new ArrayList(col.size()); + Collection list = new ArrayList<>(col.size()); for (ByteArrayWrapper wrapper : col) { list.add(wrapper.getArray().clone()); } diff --git a/src/main/java/org/springframework/data/redis/connection/util/ByteArraySet.java b/src/main/java/org/springframework/data/redis/connection/util/ByteArraySet.java index d17103621..dba4b441b 100644 --- a/src/main/java/org/springframework/data/redis/connection/util/ByteArraySet.java +++ b/src/main/java/org/springframework/data/redis/connection/util/ByteArraySet.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,7 @@ public class ByteArraySet implements Set { LinkedHashSet delegate; public ByteArraySet() { - this.delegate = new LinkedHashSet(); + this.delegate = new LinkedHashSet<>(); } public ByteArraySet(Collection values) { @@ -131,7 +131,7 @@ public class ByteArraySet implements Set { public Set asRawSet() { - Set result = new LinkedHashSet(); + Set result = new LinkedHashSet<>(); for (ByteArrayWrapper wrapper : delegate) { result.add(wrapper.getArray()); } diff --git a/src/main/java/org/springframework/data/redis/connection/util/DecodeUtils.java b/src/main/java/org/springframework/data/redis/connection/util/DecodeUtils.java index db2914473..9b7a2fa65 100644 --- a/src/main/java/org/springframework/data/redis/connection/util/DecodeUtils.java +++ b/src/main/java/org/springframework/data/redis/connection/util/DecodeUtils.java @@ -1,12 +1,12 @@ /* - * Copyright 2011-2013 the original author or authors. - * + * Copyright 2011-2017 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. @@ -25,7 +25,7 @@ import java.util.Set; /** * Simple class containing various decoding utilities. - * + * * @author Costin Leau */ public abstract class DecodeUtils { @@ -47,7 +47,7 @@ public abstract class DecodeUtils { } public static Map encodeMap(Map map) { - Map result = new LinkedHashMap(map.size()); + Map result = new LinkedHashMap<>(map.size()); for (Map.Entry entry : map.entrySet()) { result.put(encode(entry.getKey()), entry.getValue()); } @@ -55,7 +55,7 @@ public abstract class DecodeUtils { } public static Map decodeMap(Map tuple) { - Map result = new LinkedHashMap(tuple.size()); + Map result = new LinkedHashMap<>(tuple.size()); for (Map.Entry entry : tuple.entrySet()) { result.put(decode(entry.getKey()), entry.getValue()); } @@ -63,7 +63,7 @@ public abstract class DecodeUtils { } public static Set convertToSet(Collection keys) { - Set set = new LinkedHashSet(keys.size()); + Set set = new LinkedHashSet<>(keys.size()); for (String string : keys) { set.add(encode(string)); @@ -72,7 +72,7 @@ public abstract class DecodeUtils { } public static List convertToList(Collection keys) { - List set = new ArrayList(keys.size()); + List set = new ArrayList<>(keys.size()); for (String string : keys) { set.add(encode(string)); diff --git a/src/main/java/org/springframework/data/redis/core/AbstractOperations.java b/src/main/java/org/springframework/data/redis/core/AbstractOperations.java index 7c4a19a11..19e3b0153 100644 --- a/src/main/java/org/springframework/data/redis/core/AbstractOperations.java +++ b/src/main/java/org/springframework/data/redis/core/AbstractOperations.java @@ -1,12 +1,12 @@ /* - * Copyright 2011-2016 the original author or authors. - * + * Copyright 2011-2017 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. @@ -37,11 +37,12 @@ import org.springframework.util.CollectionUtils; /** * Internal base class used by various RedisTemplate XXXOperations implementations. - * + * * @author Costin Leau * @author Jennifer Hickey * @author Christoph Strobl * @author David Liu + * @author Mark Paluch */ abstract class AbstractOperations { @@ -97,10 +98,13 @@ abstract class AbstractOperations { @SuppressWarnings("unchecked") byte[] rawKey(Object key) { + Assert.notNull(key, "non null key required"); + if (keySerializer() == null && key instanceof byte[]) { return (byte[]) key; } + return keySerializer().serialize(key); } @@ -111,18 +115,22 @@ abstract class AbstractOperations { @SuppressWarnings("unchecked") byte[] rawValue(Object value) { + if (valueSerializer() == null && value instanceof byte[]) { return (byte[]) value; } + return valueSerializer().serialize(value); } byte[][] rawValues(Object... values) { - final byte[][] rawValues = new byte[values.length][]; + + byte[][] rawValues = new byte[values.length][]; int i = 0; for (Object value : values) { rawValues[i++] = rawValue(value); } + return rawValues; } @@ -155,7 +163,8 @@ abstract class AbstractOperations { } byte[][] rawHashKeys(HK... hashKeys) { - final byte[][] rawHashKeys = new byte[hashKeys.length][]; + + byte[][] rawHashKeys = new byte[hashKeys.length][]; int i = 0; for (HK hashKey : hashKeys) { rawHashKeys[i++] = rawHashKey(hashKey); @@ -165,6 +174,7 @@ abstract class AbstractOperations { @SuppressWarnings("unchecked") byte[] rawHashValue(HV value) { + if (hashValueSerializer() == null & value instanceof byte[]) { return (byte[]) value; } @@ -172,7 +182,8 @@ abstract class AbstractOperations { } byte[][] rawKeys(K key, K otherKey) { - final byte[][] rawKeys = new byte[2][]; + + byte[][] rawKeys = new byte[2][]; rawKeys[0] = rawKey(key); rawKeys[1] = rawKey(key); @@ -184,7 +195,8 @@ abstract class AbstractOperations { } byte[][] rawKeys(K key, Collection keys) { - final byte[][] rawKeys = new byte[keys.size() + (key != null ? 1 : 0)][]; + + byte[][] rawKeys = new byte[keys.size() + (key != null ? 1 : 0)][]; int i = 0; @@ -211,7 +223,7 @@ abstract class AbstractOperations { if (rawValues == null) { return null; } - Set> set = new LinkedHashSet>(rawValues.size()); + Set> set = new LinkedHashSet<>(rawValues.size()); for (Tuple rawValue : rawValues) { set.add(deserializeTuple(rawValue)); } @@ -232,7 +244,7 @@ abstract class AbstractOperations { if (values == null) { return null; } - Set rawTuples = new LinkedHashSet(values.size()); + Set rawTuples = new LinkedHashSet<>(values.size()); for (TypedTuple value : values) { byte[] rawValue; if (valueSerializer() == null && value.getValue() instanceof byte[]) { @@ -276,7 +288,7 @@ abstract class AbstractOperations { return null; } - Map map = new LinkedHashMap(entries.size()); + Map map = new LinkedHashMap<>(entries.size()); for (Map.Entry entry : entries.entrySet()) { map.put((HK) deserializeHashKey(entry.getKey()), (HV) deserializeHashValue(entry.getValue())); @@ -303,7 +315,7 @@ abstract class AbstractOperations { if (CollectionUtils.isEmpty(keys)) { return Collections.emptySet(); } - Set result = new LinkedHashSet(keys.size()); + Set result = new LinkedHashSet<>(keys.size()); for (byte[] key : keys) { result.add(deserializeKey(key)); } @@ -340,7 +352,7 @@ abstract class AbstractOperations { /** * Deserialize {@link GeoLocation} of {@link GeoResults}. - * + * * @param source can be {@literal null}. * @return converted or {@literal null}. * @since 1.8 diff --git a/src/main/java/org/springframework/data/redis/core/DefaultBoundGeoOperations.java b/src/main/java/org/springframework/data/redis/core/DefaultBoundGeoOperations.java index 49be1c3ca..a98a19406 100644 --- a/src/main/java/org/springframework/data/redis/core/DefaultBoundGeoOperations.java +++ b/src/main/java/org/springframework/data/redis/core/DefaultBoundGeoOperations.java @@ -1,12 +1,12 @@ /* - * Copyright 2016 the original author or authors. - * + * Copyright 2016-2017 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. @@ -29,7 +29,7 @@ import org.springframework.data.redis.connection.RedisGeoCommands.GeoRadiusComma /** * Default implementation of {@link BoundGeoOperations}. - * + * * @author Ninad Divadkar * @author Christoph Strobl * @since 1.8 @@ -44,7 +44,7 @@ class DefaultBoundGeoOperations extends DefaultBoundKeyOperations imple * @param key must not be {@literal null}. * @param operations must not be {@literal null}. */ - public DefaultBoundGeoOperations(K key, RedisOperations operations) { + DefaultBoundGeoOperations(K key, RedisOperations operations) { super(key, operations); this.ops = operations.opsForGeo(); diff --git a/src/main/java/org/springframework/data/redis/core/DefaultBoundHashOperations.java b/src/main/java/org/springframework/data/redis/core/DefaultBoundHashOperations.java index 9cb9a14e6..76686f95d 100644 --- a/src/main/java/org/springframework/data/redis/core/DefaultBoundHashOperations.java +++ b/src/main/java/org/springframework/data/redis/core/DefaultBoundHashOperations.java @@ -1,5 +1,5 @@ /* - * Copyright 2011-2016 the original author or authors. + * Copyright 2011-2017 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. @@ -30,8 +30,8 @@ import org.springframework.data.redis.connection.DataType; * @author Christoph Strobl * @author Ninad Divadkar */ -class DefaultBoundHashOperations extends DefaultBoundKeyOperations implements - BoundHashOperations { +class DefaultBoundHashOperations extends DefaultBoundKeyOperations + implements BoundHashOperations { private final HashOperations ops; @@ -41,74 +41,149 @@ class DefaultBoundHashOperations extends DefaultBoundKeyOperations * @param key * @param operations */ - public DefaultBoundHashOperations(H key, RedisOperations operations) { + DefaultBoundHashOperations(H key, RedisOperations operations) { super(key, operations); this.ops = operations.opsForHash(); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundHashOperations#delete(java.lang.Object[]) + */ + @Override public Long delete(Object... keys) { return ops.delete(getKey(), keys); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundHashOperations#get(java.lang.Object) + */ + @Override public HV get(Object key) { return ops.get(getKey(), key); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundHashOperations#multiGet(java.util.Collection) + */ + @Override public List multiGet(Collection hashKeys) { return ops.multiGet(getKey(), hashKeys); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundHashOperations#getOperations() + */ + @Override public RedisOperations getOperations() { return ops.getOperations(); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundHashOperations#hasKey(java.lang.Object) + */ + @Override public Boolean hasKey(Object key) { return ops.hasKey(getKey(), key); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundHashOperations#increment(java.lang.Object, long) + */ + @Override public Long increment(HK key, long delta) { return ops.increment(getKey(), key, delta); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundHashOperations#increment(java.lang.Object, double) + */ + @Override public Double increment(HK key, double delta) { return ops.increment(getKey(), key, delta); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundHashOperations#keys() + */ + @Override public Set keys() { return ops.keys(getKey()); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundHashOperations#size() + */ + @Override public Long size() { return ops.size(getKey()); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundHashOperations#putAll(java.util.Map) + */ + @Override public void putAll(Map m) { ops.putAll(getKey(), m); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundHashOperations#put(java.lang.Object, java.lang.Object) + */ + @Override public void put(HK key, HV value) { ops.put(getKey(), key, value); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundHashOperations#putIfAbsent(java.lang.Object, java.lang.Object) + */ + @Override public Boolean putIfAbsent(HK key, HV value) { return ops.putIfAbsent(getKey(), key, value); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundHashOperations#values() + */ + @Override public List values() { return ops.values(getKey()); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundHashOperations#entries() + */ + @Override public Map entries() { return ops.entries(getKey()); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundKeyOperations#getType() + */ + @Override public DataType getType() { return DataType.HASH; } /* * (non-Javadoc) - * @see org.springframework.data.redis.core.BoundHashOperations#hscan(java.lang.Object) + * @see org.springframework.data.redis.core.BoundHashOperations#scan(org.springframework.data.redis.core.ScanOptions) */ @Override public Cursor> scan(ScanOptions options) { diff --git a/src/main/java/org/springframework/data/redis/core/DefaultBoundKeyOperations.java b/src/main/java/org/springframework/data/redis/core/DefaultBoundKeyOperations.java index 816feebe4..322f07fed 100644 --- a/src/main/java/org/springframework/data/redis/core/DefaultBoundKeyOperations.java +++ b/src/main/java/org/springframework/data/redis/core/DefaultBoundKeyOperations.java @@ -1,12 +1,12 @@ /* - * Copyright 2011-2013 the original author or authors. - * + * Copyright 2011-2017 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. @@ -20,7 +20,7 @@ import java.util.concurrent.TimeUnit; /** * Default {@link BoundKeyOperations} implementation. Meant for internal usage. - * + * * @author Costin Leau */ abstract class DefaultBoundKeyOperations implements BoundKeyOperations { @@ -28,11 +28,17 @@ abstract class DefaultBoundKeyOperations implements BoundKeyOperations { private K key; private final RedisOperations ops; - public DefaultBoundKeyOperations(K key, RedisOperations operations) { + DefaultBoundKeyOperations(K key, RedisOperations operations) { + setKey(key); this.ops = operations; } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundKeyOperations#getKey() + */ + @Override public K getKey() { return key; } @@ -41,22 +47,47 @@ abstract class DefaultBoundKeyOperations implements BoundKeyOperations { this.key = key; } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundKeyOperations#expire(long, java.util.concurrent.TimeUnit) + */ + @Override public Boolean expire(long timeout, TimeUnit unit) { return ops.expire(key, timeout, unit); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundKeyOperations#expireAt(java.util.Date) + */ + @Override public Boolean expireAt(Date date) { return ops.expireAt(key, date); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundKeyOperations#getExpire() + */ + @Override public Long getExpire() { return ops.getExpire(key); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundKeyOperations#persist() + */ + @Override public Boolean persist() { return ops.persist(key); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundKeyOperations#rename(java.lang.Object) + */ + @Override public void rename(K newKey) { if (ops.hasKey(key)) { ops.rename(key, newKey); diff --git a/src/main/java/org/springframework/data/redis/core/DefaultBoundListOperations.java b/src/main/java/org/springframework/data/redis/core/DefaultBoundListOperations.java index 413b7a936..4036b0a8b 100644 --- a/src/main/java/org/springframework/data/redis/core/DefaultBoundListOperations.java +++ b/src/main/java/org/springframework/data/redis/core/DefaultBoundListOperations.java @@ -1,12 +1,12 @@ /* - * Copyright 2011-2013 the original author or authors. - * + * Copyright 2011-2017 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. @@ -22,7 +22,7 @@ import org.springframework.data.redis.connection.DataType; /** * Default implementation for {@link BoundListOperations}. - * + * * @author Costin Leau */ class DefaultBoundListOperations extends DefaultBoundKeyOperations implements BoundListOperations { @@ -31,91 +31,188 @@ class DefaultBoundListOperations extends DefaultBoundKeyOperations impl /** * Constructs a new DefaultBoundListOperations instance. - * + * * @param key * @param operations */ - public DefaultBoundListOperations(K key, RedisOperations operations) { + DefaultBoundListOperations(K key, RedisOperations operations) { + super(key, operations); this.ops = operations.opsForList(); } + @Override public RedisOperations getOperations() { return ops.getOperations(); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundListOperations#index(long) + */ + @Override public V index(long index) { return ops.index(getKey(), index); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundListOperations#leftPop() + */ + @Override public V leftPop() { return ops.leftPop(getKey()); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundListOperations#leftPop(long, java.util.concurrent.TimeUnit) + */ + @Override public V leftPop(long timeout, TimeUnit unit) { return ops.leftPop(getKey(), timeout, unit); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundListOperations#leftPush(java.lang.Object) + */ + @Override public Long leftPush(V value) { return ops.leftPush(getKey(), value); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundListOperations#leftPushAll(java.lang.Object[]) + */ + @Override public Long leftPushAll(V... values) { return ops.leftPushAll(getKey(), values); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundListOperations#leftPushIfPresent(java.lang.Object) + */ + @Override public Long leftPushIfPresent(V value) { return ops.leftPushIfPresent(getKey(), value); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundListOperations#leftPush(java.lang.Object, java.lang.Object) + */ + @Override public Long leftPush(V pivot, V value) { return ops.leftPush(getKey(), pivot, value); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundListOperations#size() + */ + @Override public Long size() { return ops.size(getKey()); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundListOperations#range(long, long) + */ + @Override public List range(long start, long end) { return ops.range(getKey(), start, end); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundListOperations#remove(long, java.lang.Object) + */ + @Override public Long remove(long i, Object value) { return ops.remove(getKey(), i, value); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundListOperations#rightPop() + */ + @Override public V rightPop() { return ops.rightPop(getKey()); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundListOperations#rightPop(long, java.util.concurrent.TimeUnit) + */ + @Override public V rightPop(long timeout, TimeUnit unit) { return ops.rightPop(getKey(), timeout, unit); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundListOperations#rightPushIfPresent(java.lang.Object) + */ + @Override public Long rightPushIfPresent(V value) { return ops.rightPushIfPresent(getKey(), value); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundListOperations#rightPush(java.lang.Object) + */ + @Override public Long rightPush(V value) { return ops.rightPush(getKey(), value); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundListOperations#rightPushAll(java.lang.Object[]) + */ + @Override public Long rightPushAll(V... values) { return ops.rightPushAll(getKey(), values); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundListOperations#rightPush(java.lang.Object, java.lang.Object) + */ + @Override public Long rightPush(V pivot, V value) { return ops.rightPush(getKey(), pivot, value); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundListOperations#trim(long, long) + */ + @Override public void trim(long start, long end) { ops.trim(getKey(), start, end); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundListOperations#set(long, java.lang.Object) + */ + @Override public void set(long index, V value) { ops.set(getKey(), index, value); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundKeyOperations#getType() + */ + @Override public DataType getType() { return DataType.LIST; } diff --git a/src/main/java/org/springframework/data/redis/core/DefaultBoundSetOperations.java b/src/main/java/org/springframework/data/redis/core/DefaultBoundSetOperations.java index 7386263d5..2e78e61ee 100644 --- a/src/main/java/org/springframework/data/redis/core/DefaultBoundSetOperations.java +++ b/src/main/java/org/springframework/data/redis/core/DefaultBoundSetOperations.java @@ -1,5 +1,5 @@ /* - * Copyright 2011-2014 the original author or authors. + * Copyright 2011-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,7 @@ import org.springframework.data.redis.connection.DataType; /** * Default implementation for {@link BoundSetOperations}. - * + * * @author Costin Leau * @author Christoph Strobl */ @@ -34,114 +34,235 @@ class DefaultBoundSetOperations extends DefaultBoundKeyOperations imple /** * Constructs a new DefaultBoundSetOperations instance. - * + * * @param key * @param operations */ DefaultBoundSetOperations(K key, RedisOperations operations) { + super(key, operations); this.ops = operations.opsForSet(); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundSetOperations#add(java.lang.Object[]) + */ + @Override public Long add(V... values) { return ops.add(getKey(), values); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundSetOperations#diff(java.lang.Object) + */ + @Override public Set diff(K key) { return ops.difference(getKey(), key); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundSetOperations#diff(java.util.Collection) + */ + @Override public Set diff(Collection keys) { return ops.difference(getKey(), keys); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundSetOperations#diffAndStore(java.lang.Object, java.lang.Object) + */ + @Override public void diffAndStore(K key, K destKey) { ops.differenceAndStore(getKey(), key, destKey); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundSetOperations#diffAndStore(java.util.Collection, java.lang.Object) + */ + @Override public void diffAndStore(Collection keys, K destKey) { ops.differenceAndStore(getKey(), keys, destKey); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundSetOperations#getOperations() + */ + @Override public RedisOperations getOperations() { return ops.getOperations(); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundSetOperations#intersect(java.lang.Object) + */ + @Override public Set intersect(K key) { return ops.intersect(getKey(), key); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundSetOperations#intersect(java.util.Collection) + */ + @Override public Set intersect(Collection keys) { return ops.intersect(getKey(), keys); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundSetOperations#intersectAndStore(java.lang.Object, java.lang.Object) + */ + @Override public void intersectAndStore(K key, K destKey) { ops.intersectAndStore(getKey(), key, destKey); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundSetOperations#intersectAndStore(java.util.Collection, java.lang.Object) + */ + @Override public void intersectAndStore(Collection keys, K destKey) { ops.intersectAndStore(getKey(), keys, destKey); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundSetOperations#isMember(java.lang.Object) + */ + @Override public Boolean isMember(Object o) { return ops.isMember(getKey(), o); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundSetOperations#members() + */ + @Override public Set members() { return ops.members(getKey()); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundSetOperations#move(java.lang.Object, java.lang.Object) + */ + @Override public Boolean move(K destKey, V value) { return ops.move(getKey(), value, destKey); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundSetOperations#randomMember() + */ + @Override public V randomMember() { return ops.randomMember(getKey()); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundSetOperations#distinctRandomMembers(long) + */ + @Override public Set distinctRandomMembers(long count) { return ops.distinctRandomMembers(getKey(), count); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundSetOperations#randomMembers(long) + */ + @Override public List randomMembers(long count) { return ops.randomMembers(getKey(), count); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundSetOperations#remove(java.lang.Object[]) + */ + @Override public Long remove(Object... values) { return ops.remove(getKey(), values); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundSetOperations#pop() + */ + @Override public V pop() { return ops.pop(getKey()); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundSetOperations#size() + */ + @Override public Long size() { return ops.size(getKey()); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundSetOperations#union(java.lang.Object) + */ + @Override public Set union(K key) { return ops.union(getKey(), key); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundSetOperations#union(java.util.Collection) + */ + @Override public Set union(Collection keys) { return ops.union(getKey(), keys); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundSetOperations#unionAndStore(java.lang.Object, java.lang.Object) + */ + @Override public void unionAndStore(K key, K destKey) { ops.unionAndStore(getKey(), key, destKey); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundSetOperations#unionAndStore(java.util.Collection, java.lang.Object) + */ + @Override public void unionAndStore(Collection keys, K destKey) { ops.unionAndStore(getKey(), keys, destKey); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundKeyOperations#getType() + */ + @Override public DataType getType() { return DataType.SET; } /* * (non-Javadoc) - * @see org.springframework.data.redis.core.BoundSetOperations#sScan(org.springframework.data.redis.core.ScanOptions) + * @see org.springframework.data.redis.core.BoundSetOperations#scan(org.springframework.data.redis.core.ScanOptions) */ @Override public Cursor scan(ScanOptions options) { diff --git a/src/main/java/org/springframework/data/redis/core/DefaultBoundValueOperations.java b/src/main/java/org/springframework/data/redis/core/DefaultBoundValueOperations.java index 8a845c11a..7df385fc4 100644 --- a/src/main/java/org/springframework/data/redis/core/DefaultBoundValueOperations.java +++ b/src/main/java/org/springframework/data/redis/core/DefaultBoundValueOperations.java @@ -1,12 +1,12 @@ /* - * Copyright 2011-2013 the original author or authors. - * + * Copyright 2011-2017 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. @@ -28,63 +28,129 @@ class DefaultBoundValueOperations extends DefaultBoundKeyOperations imp /** * Constructs a new DefaultBoundValueOperations instance. - * + * * @param key * @param operations */ - public DefaultBoundValueOperations(K key, RedisOperations operations) { + DefaultBoundValueOperations(K key, RedisOperations operations) { + super(key, operations); this.ops = operations.opsForValue(); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundValueOperations#get() + */ + @Override public V get() { return ops.get(getKey()); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundValueOperations#getAndSet(java.lang.Object) + */ + @Override public V getAndSet(V value) { return ops.getAndSet(getKey(), value); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundValueOperations#increment(long) + */ + @Override public Long increment(long delta) { return ops.increment(getKey(), delta); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundValueOperations#increment(double) + */ + @Override public Double increment(double delta) { return ops.increment(getKey(), delta); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundValueOperations#append(java.lang.String) + */ + @Override public Integer append(String value) { return ops.append(getKey(), value); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundValueOperations#get(long, long) + */ + @Override public String get(long start, long end) { return ops.get(getKey(), start, end); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundValueOperations#set(java.lang.Object, long, java.util.concurrent.TimeUnit) + */ + @Override public void set(V value, long timeout, TimeUnit unit) { ops.set(getKey(), value, timeout, unit); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundValueOperations#set(java.lang.Object) + */ + @Override public void set(V value) { ops.set(getKey(), value); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundValueOperations#setIfAbsent(java.lang.Object) + */ + @Override public Boolean setIfAbsent(V value) { return ops.setIfAbsent(getKey(), value); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundValueOperations#set(java.lang.Object, long) + */ + @Override public void set(V value, long offset) { ops.set(getKey(), value, offset); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundValueOperations#size() + */ + @Override public Long size() { return ops.size(getKey()); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundValueOperations#getOperations() + */ + @Override public RedisOperations getOperations() { return ops.getOperations(); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundKeyOperations#getType() + */ + @Override public DataType getType() { return DataType.STRING; } diff --git a/src/main/java/org/springframework/data/redis/core/DefaultBoundZSetOperations.java b/src/main/java/org/springframework/data/redis/core/DefaultBoundZSetOperations.java index 79ff62419..8db6cdd0c 100644 --- a/src/main/java/org/springframework/data/redis/core/DefaultBoundZSetOperations.java +++ b/src/main/java/org/springframework/data/redis/core/DefaultBoundZSetOperations.java @@ -1,5 +1,5 @@ /* - * Copyright 2011-2016 the original author or authors. + * Copyright 2011-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,7 +26,7 @@ import org.springframework.data.redis.core.ZSetOperations.TypedTuple; /** * Default implementation for {@link BoundZSetOperations}. - * + * * @author Costin Leau * @author Christoph Strobl * @author Mark Paluch @@ -37,63 +37,129 @@ class DefaultBoundZSetOperations extends DefaultBoundKeyOperations impl /** * Constructs a new DefaultBoundZSetOperations instance. - * + * * @param key * @param operations */ - public DefaultBoundZSetOperations(K key, RedisOperations operations) { + DefaultBoundZSetOperations(K key, RedisOperations operations) { + super(key, operations); this.ops = operations.opsForZSet(); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundZSetOperations#add(java.lang.Object, double) + */ + @Override public Boolean add(V value, double score) { return ops.add(getKey(), value, score); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundZSetOperations#add(java.util.Set) + */ + @Override public Long add(Set> tuples) { return ops.add(getKey(), tuples); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundZSetOperations#incrementScore(java.lang.Object, double) + */ + @Override public Double incrementScore(V value, double delta) { return ops.incrementScore(getKey(), value, delta); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundZSetOperations#getOperations() + */ + @Override public RedisOperations getOperations() { return ops.getOperations(); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundZSetOperations#intersectAndStore(java.lang.Object, java.lang.Object) + */ + @Override public void intersectAndStore(K otherKey, K destKey) { ops.intersectAndStore(getKey(), otherKey, destKey); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundZSetOperations#intersectAndStore(java.util.Collection, java.lang.Object) + */ + @Override public void intersectAndStore(Collection otherKeys, K destKey) { ops.intersectAndStore(getKey(), otherKeys, destKey); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundZSetOperations#range(long, long) + */ + @Override public Set range(long start, long end) { return ops.range(getKey(), start, end); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundZSetOperations#rangeByScore(double, double) + */ + @Override public Set rangeByScore(double min, double max) { return ops.rangeByScore(getKey(), min, max); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundZSetOperations#rangeByScoreWithScores(double, double) + */ + @Override public Set> rangeByScoreWithScores(double min, double max) { return ops.rangeByScoreWithScores(getKey(), min, max); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundZSetOperations#rangeWithScores(long, long) + */ + @Override public Set> rangeWithScores(long start, long end) { return ops.rangeWithScores(getKey(), start, end); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundZSetOperations#reverseRangeByScore(double, double) + */ + @Override public Set reverseRangeByScore(double min, double max) { return ops.reverseRangeByScore(getKey(), min, max); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundZSetOperations#reverseRangeByScoreWithScores(double, double) + */ + @Override public Set> reverseRangeByScoreWithScores(double min, double max) { return ops.reverseRangeByScoreWithScores(getKey(), min, max); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundZSetOperations#reverseRangeWithScores(long, long) + */ + @Override public Set> reverseRangeWithScores(long start, long end) { return ops.reverseRangeWithScores(getKey(), start, end); } @@ -116,34 +182,74 @@ class DefaultBoundZSetOperations extends DefaultBoundKeyOperations impl return ops.rangeByLex(getKey(), range, limit); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundZSetOperations#rank(java.lang.Object) + */ + @Override public Long rank(Object o) { return ops.rank(getKey(), o); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundZSetOperations#reverseRank(java.lang.Object) + */ + @Override public Long reverseRank(Object o) { return ops.reverseRank(getKey(), o); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundZSetOperations#score(java.lang.Object) + */ + @Override public Double score(Object o) { return ops.score(getKey(), o); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundZSetOperations#remove(java.lang.Object[]) + */ + @Override public Long remove(Object... values) { return ops.remove(getKey(), values); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundZSetOperations#removeRange(long, long) + */ + @Override public void removeRange(long start, long end) { ops.removeRange(getKey(), start, end); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundZSetOperations#removeRangeByScore(double, double) + */ + @Override public void removeRangeByScore(double min, double max) { ops.removeRangeByScore(getKey(), min, max); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundZSetOperations#reverseRange(long, long) + */ + @Override public Set reverseRange(long start, long end) { return ops.reverseRange(getKey(), start, end); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundZSetOperations#count(double, double) + */ + @Override public Long count(double min, double max) { return ops.count(getKey(), min, max); } @@ -166,14 +272,29 @@ class DefaultBoundZSetOperations extends DefaultBoundKeyOperations impl return ops.zCard(getKey()); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundZSetOperations#unionAndStore(java.lang.Object, java.lang.Object) + */ + @Override public void unionAndStore(K otherKey, K destKey) { ops.unionAndStore(getKey(), otherKey, destKey); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundZSetOperations#unionAndStore(java.util.Collection, java.lang.Object) + */ + @Override public void unionAndStore(Collection otherKeys, K destKey) { ops.unionAndStore(getKey(), otherKeys, destKey); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.BoundKeyOperations#getType() + */ + @Override public DataType getType() { return DataType.ZSET; } diff --git a/src/main/java/org/springframework/data/redis/core/DefaultClusterOperations.java b/src/main/java/org/springframework/data/redis/core/DefaultClusterOperations.java index 755a94bbc..5b76000c4 100644 --- a/src/main/java/org/springframework/data/redis/core/DefaultClusterOperations.java +++ b/src/main/java/org/springframework/data/redis/core/DefaultClusterOperations.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,6 @@ import java.util.Collection; import java.util.List; import java.util.Set; -import org.springframework.dao.DataAccessException; import org.springframework.data.redis.connection.RedisClusterCommands.AddSlots; import org.springframework.data.redis.connection.RedisClusterConnection; import org.springframework.data.redis.connection.RedisClusterNode; @@ -29,22 +28,22 @@ import org.springframework.util.Assert; /** * Default {@link ClusterOperations} implementation. - * + * * @author Christoph Strobl * @since 1.7 * @param * @param */ -public class DefaultClusterOperations extends AbstractOperations implements ClusterOperations { +class DefaultClusterOperations extends AbstractOperations implements ClusterOperations { private final RedisTemplate template; /** * Creates new {@link DefaultClusterOperations} delegating to the given {@link RedisTemplate}. - * + * * @param template must not be {@literal null}. */ - public DefaultClusterOperations(RedisTemplate template) { + DefaultClusterOperations(RedisTemplate template) { super(template); this.template = template; @@ -59,13 +58,7 @@ public class DefaultClusterOperations extends AbstractOperations imp Assert.notNull(node, "ClusterNode must not be null."); - return execute(new RedisClusterCallback>() { - - @Override - public Set doInRedis(RedisClusterConnection connection) throws DataAccessException { - return deserializeKeys(connection.keys(node, rawKey(pattern))); - } - }); + return execute(connection -> deserializeKeys(connection.keys(node, rawKey(pattern)))); } /* @@ -77,13 +70,7 @@ public class DefaultClusterOperations extends AbstractOperations imp Assert.notNull(node, "ClusterNode must not be null."); - return execute(new RedisClusterCallback() { - - @Override - public K doInRedis(RedisClusterConnection connection) throws DataAccessException { - return deserializeKey(connection.randomKey(node)); - } - }); + return execute(connection -> deserializeKey(connection.randomKey(node))); } /* @@ -95,13 +82,7 @@ public class DefaultClusterOperations extends AbstractOperations imp Assert.notNull(node, "ClusterNode must not be null."); - return execute(new RedisClusterCallback() { - - @Override - public String doInRedis(RedisClusterConnection connection) throws DataAccessException { - return connection.ping(node); - } - }); + return execute(connection -> connection.ping(node)); } /* @@ -113,13 +94,9 @@ public class DefaultClusterOperations extends AbstractOperations imp Assert.notNull(node, "ClusterNode must not be null."); - execute(new RedisClusterCallback() { - - @Override - public Void doInRedis(RedisClusterConnection connection) throws DataAccessException { - connection.clusterAddSlots(node, slots); - return null; - } + execute((RedisClusterCallback) connection -> { + connection.clusterAddSlots(node, slots); + return null; }); } @@ -145,13 +122,9 @@ public class DefaultClusterOperations extends AbstractOperations imp Assert.notNull(node, "ClusterNode must not be null."); - execute(new RedisClusterCallback() { - - @Override - public Void doInRedis(RedisClusterConnection connection) throws DataAccessException { - connection.bgReWriteAof(node); - return null; - } + execute((RedisClusterCallback) connection -> { + connection.bgReWriteAof(node); + return null; }); } @@ -164,13 +137,9 @@ public class DefaultClusterOperations extends AbstractOperations imp Assert.notNull(node, "ClusterNode must not be null."); - execute(new RedisClusterCallback() { - - @Override - public Void doInRedis(RedisClusterConnection connection) throws DataAccessException { - connection.bgSave(node); - return null; - } + execute((RedisClusterCallback) connection -> { + connection.bgSave(node); + return null; }); } @@ -183,13 +152,9 @@ public class DefaultClusterOperations extends AbstractOperations imp Assert.notNull(node, "ClusterNode must not be null."); - execute(new RedisClusterCallback() { - - @Override - public Void doInRedis(RedisClusterConnection connection) throws DataAccessException { - connection.clusterMeet(node); - return null; - } + execute((RedisClusterCallback) connection -> { + connection.clusterMeet(node); + return null; }); } @@ -202,13 +167,9 @@ public class DefaultClusterOperations extends AbstractOperations imp Assert.notNull(node, "ClusterNode must not be null."); - execute(new RedisClusterCallback() { - - @Override - public Void doInRedis(RedisClusterConnection connection) throws DataAccessException { - connection.clusterForget(node); - return null; - } + execute((RedisClusterCallback) connection -> { + connection.clusterForget(node); + return null; }); } @@ -221,13 +182,9 @@ public class DefaultClusterOperations extends AbstractOperations imp Assert.notNull(node, "ClusterNode must not be null."); - execute(new RedisClusterCallback() { - - @Override - public Void doInRedis(RedisClusterConnection connection) throws DataAccessException { - connection.flushDb(node); - return null; - } + execute((RedisClusterCallback) connection -> { + connection.flushDb(node); + return null; }); } @@ -240,13 +197,7 @@ public class DefaultClusterOperations extends AbstractOperations imp Assert.notNull(node, "ClusterNode must not be null."); - return execute(new RedisClusterCallback>() { - - @Override - public Collection doInRedis(RedisClusterConnection connection) throws DataAccessException { - return connection.clusterGetSlaves(node); - } - }); + return execute(connection -> connection.clusterGetSlaves(node)); } /* @@ -258,13 +209,9 @@ public class DefaultClusterOperations extends AbstractOperations imp Assert.notNull(node, "ClusterNode must not be null."); - execute(new RedisClusterCallback() { - - @Override - public Void doInRedis(RedisClusterConnection connection) throws DataAccessException { - connection.save(node); - return null; - } + execute((RedisClusterCallback) connection -> { + connection.save(node); + return null; }); } @@ -277,13 +224,9 @@ public class DefaultClusterOperations extends AbstractOperations imp Assert.notNull(node, "ClusterNode must not be null."); - execute(new RedisClusterCallback() { - - @Override - public Void doInRedis(RedisClusterConnection connection) throws DataAccessException { - connection.shutdown(node); - return null; - } + execute((RedisClusterCallback) connection -> { + connection.shutdown(node); + return null; }); } @@ -297,27 +240,23 @@ public class DefaultClusterOperations extends AbstractOperations imp Assert.notNull(source, "Source node must not be null."); Assert.notNull(target, "Target node must not be null."); - execute(new RedisClusterCallback() { + execute((RedisClusterCallback) connection -> { - @Override - public Void doInRedis(RedisClusterConnection connection) throws DataAccessException { + connection.clusterSetSlot(target, slot, AddSlots.IMPORTING); + connection.clusterSetSlot(source, slot, AddSlots.MIGRATING); + List keys = connection.clusterGetKeysInSlot(slot, Integer.MAX_VALUE); - connection.clusterSetSlot(target, slot, AddSlots.IMPORTING); - connection.clusterSetSlot(source, slot, AddSlots.MIGRATING); - List keys = connection.clusterGetKeysInSlot(slot, Integer.MAX_VALUE); - - for (byte[] key : keys) { - connection.migrate(key, source, 0, MigrateOption.COPY); - } - connection.clusterSetSlot(target, slot, AddSlots.NODE); - return null; + for (byte[] key : keys) { + connection.migrate(key, source, 0, MigrateOption.COPY); } + connection.clusterSetSlot(target, slot, AddSlots.NODE); + return null; }); } /** * Executed wrapped command upon {@link RedisClusterConnection}. - * + * * @param callback * @return */ diff --git a/src/main/java/org/springframework/data/redis/core/DefaultGeoOperations.java b/src/main/java/org/springframework/data/redis/core/DefaultGeoOperations.java index 98d87e1cc..2230ecaa9 100644 --- a/src/main/java/org/springframework/data/redis/core/DefaultGeoOperations.java +++ b/src/main/java/org/springframework/data/redis/core/DefaultGeoOperations.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2016-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,6 @@ import org.springframework.data.geo.Distance; import org.springframework.data.geo.GeoResults; import org.springframework.data.geo.Metric; import org.springframework.data.geo.Point; -import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisGeoCommands.GeoLocation; import org.springframework.data.redis.connection.RedisGeoCommands.GeoRadiusCommandArgs; @@ -36,11 +35,11 @@ import org.springframework.data.redis.connection.RedisGeoCommands.GeoRadiusComma * @author Christoph Strobl * @since 1.8 */ -public class DefaultGeoOperations extends AbstractOperations implements GeoOperations { +class DefaultGeoOperations extends AbstractOperations implements GeoOperations { /** * Creates new {@link DefaultGeoOperations}. - * + * * @param template must not be {@literal null}. */ DefaultGeoOperations(RedisTemplate template) { @@ -52,17 +51,12 @@ public class DefaultGeoOperations extends AbstractOperations impleme * @see org.springframework.data.redis.core.GeoOperations#geoAdd(java.lang.Object, org.springframework.data.geo.Point, java.lang.Object) */ @Override - public Long geoAdd(K key, final Point point, M member) { + public Long geoAdd(K key, Point point, M member) { - final byte[] rawKey = rawKey(key); - final byte[] rawMember = rawValue(member); + byte[] rawKey = rawKey(key); + byte[] rawMember = rawValue(member); - return execute(new RedisCallback() { - - public Long doInRedis(RedisConnection connection) { - return connection.geoAdd(rawKey, point, rawMember); - } - }, true); + return execute(connection -> connection.geoAdd(rawKey, point, rawMember), true); } /* @@ -81,20 +75,15 @@ public class DefaultGeoOperations extends AbstractOperations impleme @Override public Long geoAdd(K key, Map memberCoordinateMap) { - final byte[] rawKey = rawKey(key); - final Map rawMemberCoordinateMap = new HashMap(); + byte[] rawKey = rawKey(key); + Map rawMemberCoordinateMap = new HashMap<>(); for (M member : memberCoordinateMap.keySet()) { - final byte[] rawMember = rawValue(member); + byte[] rawMember = rawValue(member); rawMemberCoordinateMap.put(rawMember, memberCoordinateMap.get(member)); } - return execute(new RedisCallback() { - - public Long doInRedis(RedisConnection connection) { - return connection.geoAdd(rawKey, rawMemberCoordinateMap); - } - }, true); + return execute(connection -> connection.geoAdd(rawKey, rawMemberCoordinateMap), true); } /* @@ -104,7 +93,7 @@ public class DefaultGeoOperations extends AbstractOperations impleme @Override public Long geoAdd(K key, Iterable> locations) { - Map memberCoordinateMap = new LinkedHashMap(); + Map memberCoordinateMap = new LinkedHashMap<>(); for (GeoLocation location : locations) { memberCoordinateMap.put(location.getName(), location.getPoint()); } @@ -117,18 +106,13 @@ public class DefaultGeoOperations extends AbstractOperations impleme * @see org.springframework.data.redis.core.GeoOperations#geoDist(java.lang.Object, java.lang.Object, java.lang.Object) */ @Override - public Distance geoDist(K key, final M member1, final M member2) { + public Distance geoDist(K key, M member1, M member2) { - final byte[] rawKey = rawKey(key); - final byte[] rawMember1 = rawValue(member1); - final byte[] rawMember2 = rawValue(member2); + byte[] rawKey = rawKey(key); + byte[] rawMember1 = rawValue(member1); + byte[] rawMember2 = rawValue(member2); - return execute(new RedisCallback() { - - public Distance doInRedis(RedisConnection connection) { - return connection.geoDist(rawKey, rawMember1, rawMember2); - } - }, true); + return execute(connection -> connection.geoDist(rawKey, rawMember1, rawMember2), true); } /* @@ -136,18 +120,13 @@ public class DefaultGeoOperations extends AbstractOperations impleme * @see org.springframework.data.redis.core.GeoOperations#geoDist(java.lang.Object, java.lang.Object, java.lang.Object, org.springframework.data.geo.Metric) */ @Override - public Distance geoDist(K key, M member1, M member2, final Metric metric) { + public Distance geoDist(K key, M member1, M member2, Metric metric) { - final byte[] rawKey = rawKey(key); - final byte[] rawMember1 = rawValue(member1); - final byte[] rawMember2 = rawValue(member2); + byte[] rawKey = rawKey(key); + byte[] rawMember1 = rawValue(member1); + byte[] rawMember2 = rawValue(member2); - return execute(new RedisCallback() { - - public Distance doInRedis(RedisConnection connection) { - return connection.geoDist(rawKey, rawMember1, rawMember2, metric); - } - }, true); + return execute(connection -> connection.geoDist(rawKey, rawMember1, rawMember2, metric), true); } /* @@ -155,17 +134,12 @@ public class DefaultGeoOperations extends AbstractOperations impleme * @see org.springframework.data.redis.core.GeoOperations#geoHash(java.lang.Object, java.lang.Object[]) */ @Override - public List geoHash(K key, final M... members) { + public List geoHash(K key, M... members) { - final byte[] rawKey = rawKey(key); - final byte[][] rawMembers = rawValues(members); + byte[] rawKey = rawKey(key); + byte[][] rawMembers = rawValues(members); - return execute(new RedisCallback>() { - - public List doInRedis(RedisConnection connection) { - return connection.geoHash(rawKey, rawMembers); - } - }, true); + return execute(connection -> connection.geoHash(rawKey, rawMembers), true); } /* @@ -174,15 +148,10 @@ public class DefaultGeoOperations extends AbstractOperations impleme */ @Override public List geoPos(K key, M... members) { - final byte[] rawKey = rawKey(key); - final byte[][] rawMembers = rawValues(members); + byte[] rawKey = rawKey(key); + byte[][] rawMembers = rawValues(members); - return execute(new RedisCallback>() { - - public List doInRedis(RedisConnection connection) { - return connection.geoPos(rawKey, rawMembers); - } - }, true); + return execute(connection -> connection.geoPos(rawKey, rawMembers), true); } /* @@ -190,16 +159,11 @@ public class DefaultGeoOperations extends AbstractOperations impleme * @see org.springframework.data.redis.core.GeoOperations#geoRadius(java.lang.Object, org.springframework.data.geo.Circle) */ @Override - public GeoResults> geoRadius(K key, final Circle within) { + public GeoResults> geoRadius(K key, Circle within) { - final byte[] rawKey = rawKey(key); + byte[] rawKey = rawKey(key); - GeoResults> raw = execute(new RedisCallback>>() { - - public GeoResults> doInRedis(RedisConnection connection) { - return connection.geoRadius(rawKey, within); - } - }, true); + GeoResults> raw = execute(connection -> connection.geoRadius(rawKey, within), true); return deserializeGeoResults(raw); } @@ -209,16 +173,11 @@ public class DefaultGeoOperations extends AbstractOperations impleme * @see org.springframework.data.redis.core.GeoOperations#geoRadius(java.lang.Object, org.springframework.data.geo.Circle, org.springframework.data.redis.core.GeoRadiusCommandArgs) */ @Override - public GeoResults> geoRadius(K key, final Circle within, final GeoRadiusCommandArgs args) { + public GeoResults> geoRadius(K key, Circle within, GeoRadiusCommandArgs args) { - final byte[] rawKey = rawKey(key); + byte[] rawKey = rawKey(key); - GeoResults> raw = execute(new RedisCallback>>() { - - public GeoResults> doInRedis(RedisConnection connection) { - return connection.geoRadius(rawKey, within, args); - } - }, true); + GeoResults> raw = execute(connection -> connection.geoRadius(rawKey, within, args), true); return deserializeGeoResults(raw); } @@ -228,16 +187,12 @@ public class DefaultGeoOperations extends AbstractOperations impleme * @see org.springframework.data.redis.core.GeoOperations#geoRadiusByMember(java.lang.Object, java.lang.Object, double) */ @Override - public GeoResults> geoRadiusByMember(K key, M member, final double radius) { + public GeoResults> geoRadiusByMember(K key, M member, double radius) { - final byte[] rawKey = rawKey(key); - final byte[] rawMember = rawValue(member); - GeoResults> raw = execute(new RedisCallback>>() { - - public GeoResults> doInRedis(RedisConnection connection) { - return connection.geoRadiusByMember(rawKey, rawMember, radius); - } - }, true); + byte[] rawKey = rawKey(key); + byte[] rawMember = rawValue(member); + GeoResults> raw = execute(connection -> connection.geoRadiusByMember(rawKey, rawMember, radius), + true); return deserializeGeoResults(raw); } @@ -247,17 +202,13 @@ public class DefaultGeoOperations extends AbstractOperations impleme * @see org.springframework.data.redis.core.GeoOperations#geoRadiusByMember(java.lang.Object, java.lang.Object, org.springframework.data.geo.Distance) */ @Override - public GeoResults> geoRadiusByMember(K key, M member, final Distance distance) { + public GeoResults> geoRadiusByMember(K key, M member, Distance distance) { - final byte[] rawKey = rawKey(key); - final byte[] rawMember = rawValue(member); + byte[] rawKey = rawKey(key); + byte[] rawMember = rawValue(member); - GeoResults> raw = execute(new RedisCallback>>() { - - public GeoResults> doInRedis(RedisConnection connection) { - return connection.geoRadiusByMember(rawKey, rawMember, distance); - } - }, true); + GeoResults> raw = execute( + connection -> connection.geoRadiusByMember(rawKey, rawMember, distance), true); return deserializeGeoResults(raw); } @@ -267,18 +218,13 @@ public class DefaultGeoOperations extends AbstractOperations impleme * @see org.springframework.data.redis.core.GeoOperations#geoRadiusByMember(java.lang.Object, java.lang.Object, double, org.springframework.data.geo.Metric, org.springframework.data.redis.core.GeoRadiusCommandArgs) */ @Override - public GeoResults> geoRadiusByMember(K key, M member, final Distance distance, - final GeoRadiusCommandArgs param) { + public GeoResults> geoRadiusByMember(K key, M member, Distance distance, GeoRadiusCommandArgs param) { - final byte[] rawKey = rawKey(key); - final byte[] rawMember = rawValue(member); + byte[] rawKey = rawKey(key); + byte[] rawMember = rawValue(member); - GeoResults> raw = execute(new RedisCallback>>() { - - public GeoResults> doInRedis(RedisConnection connection) { - return connection.geoRadiusByMember(rawKey, rawMember, distance, param); - } - }, true); + GeoResults> raw = execute( + connection -> connection.geoRadiusByMember(rawKey, rawMember, distance, param), true); return deserializeGeoResults(raw); } @@ -290,14 +236,8 @@ public class DefaultGeoOperations extends AbstractOperations impleme @Override public Long geoRemove(K key, M... members) { - final byte[] rawKey = rawKey(key); - final byte[][] rawMembers = rawValues(members); - - return execute(new RedisCallback() { - - public Long doInRedis(RedisConnection connection) { - return connection.zRem(rawKey, rawMembers); - } - }, true); + byte[] rawKey = rawKey(key); + byte[][] rawMembers = rawValues(members); + return execute(connection -> connection.zRem(rawKey, rawMembers), true); } } diff --git a/src/main/java/org/springframework/data/redis/core/DefaultHashOperations.java b/src/main/java/org/springframework/data/redis/core/DefaultHashOperations.java index 25e979802..6f43705c5 100644 --- a/src/main/java/org/springframework/data/redis/core/DefaultHashOperations.java +++ b/src/main/java/org/springframework/data/redis/core/DefaultHashOperations.java @@ -1,5 +1,5 @@ /* - * Copyright 2011-2016 the original author or authors. + * Copyright 2011-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,8 +24,6 @@ import java.util.Map.Entry; import java.util.Set; import org.springframework.core.convert.converter.Converter; -import org.springframework.dao.DataAccessException; -import org.springframework.data.redis.connection.RedisConnection; /** * Default implementation of {@link HashOperations}. @@ -41,212 +39,216 @@ class DefaultHashOperations extends AbstractOperations imp super((RedisTemplate) template); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.HashOperations#get(java.lang.Object, java.lang.Object) + */ + @Override @SuppressWarnings("unchecked") public HV get(K key, Object hashKey) { - final byte[] rawKey = rawKey(key); - final byte[] rawHashKey = rawHashKey(hashKey); - byte[] rawHashValue = execute(new RedisCallback() { - - public byte[] doInRedis(RedisConnection connection) { - return connection.hGet(rawKey, rawHashKey); - } - }, true); + byte[] rawKey = rawKey(key); + byte[] rawHashKey = rawHashKey(hashKey); + byte[] rawHashValue = execute(connection -> connection.hGet(rawKey, rawHashKey), true); return (HV) deserializeHashValue(rawHashValue); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.HashOperations#hasKey(java.lang.Object, java.lang.Object) + */ + @Override public Boolean hasKey(K key, Object hashKey) { - final byte[] rawKey = rawKey(key); - final byte[] rawHashKey = rawHashKey(hashKey); - return execute(new RedisCallback() { - - public Boolean doInRedis(RedisConnection connection) { - return connection.hExists(rawKey, rawHashKey); - } - }, true); + byte[] rawKey = rawKey(key); + byte[] rawHashKey = rawHashKey(hashKey); + return execute(connection -> connection.hExists(rawKey, rawHashKey), true); } - public Long increment(K key, HK hashKey, final long delta) { - final byte[] rawKey = rawKey(key); - final byte[] rawHashKey = rawHashKey(hashKey); - - return execute(new RedisCallback() { - - public Long doInRedis(RedisConnection connection) { - return connection.hIncrBy(rawKey, rawHashKey, delta); - } - }, true); + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.HashOperations#increment(java.lang.Object, java.lang.Object, long) + */ + @Override + public Long increment(K key, HK hashKey, long delta) { + byte[] rawKey = rawKey(key); + byte[] rawHashKey = rawHashKey(hashKey); + return execute(connection -> connection.hIncrBy(rawKey, rawHashKey, delta), true); } - public Double increment(K key, HK hashKey, final double delta) { - final byte[] rawKey = rawKey(key); - final byte[] rawHashKey = rawHashKey(hashKey); + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.HashOperations#increment(java.lang.Object, java.lang.Object, double) + */ + @Override + public Double increment(K key, HK hashKey, double delta) { - return execute(new RedisCallback() { - public Double doInRedis(RedisConnection connection) { - return connection.hIncrBy(rawKey, rawHashKey, delta); - } - }, true); + byte[] rawKey = rawKey(key); + byte[] rawHashKey = rawHashKey(hashKey); + return execute(connection -> connection.hIncrBy(rawKey, rawHashKey, delta), true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.HashOperations#keys(java.lang.Object) + */ + @Override public Set keys(K key) { - final byte[] rawKey = rawKey(key); - Set rawValues = execute(new RedisCallback>() { - - public Set doInRedis(RedisConnection connection) { - return connection.hKeys(rawKey); - } - }, true); + byte[] rawKey = rawKey(key); + Set rawValues = execute(connection -> connection.hKeys(rawKey), true); return deserializeHashKeys(rawValues); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.HashOperations#size(java.lang.Object) + */ + @Override public Long size(K key) { - final byte[] rawKey = rawKey(key); - return execute(new RedisCallback() { - - public Long doInRedis(RedisConnection connection) { - return connection.hLen(rawKey); - } - }, true); + byte[] rawKey = rawKey(key); + return execute(connection -> connection.hLen(rawKey), true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.HashOperations#putAll(java.lang.Object, java.util.Map) + */ + @Override public void putAll(K key, Map m) { + if (m.isEmpty()) { return; } - final byte[] rawKey = rawKey(key); + byte[] rawKey = rawKey(key); - final Map hashes = new LinkedHashMap(m.size()); + Map hashes = new LinkedHashMap<>(m.size()); for (Map.Entry entry : m.entrySet()) { hashes.put(rawHashKey(entry.getKey()), rawHashValue(entry.getValue())); } - execute(new RedisCallback() { - - public Object doInRedis(RedisConnection connection) { - connection.hMSet(rawKey, hashes); - return null; - } + execute(connection -> { + connection.hMSet(rawKey, hashes); + return null; }, true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.HashOperations#multiGet(java.lang.Object, java.util.Collection) + */ + @Override public List multiGet(K key, Collection fields) { + if (fields.isEmpty()) { return Collections.emptyList(); } - final byte[] rawKey = rawKey(key); - - final byte[][] rawHashKeys = new byte[fields.size()][]; + byte[] rawKey = rawKey(key); + byte[][] rawHashKeys = new byte[fields.size()][]; int counter = 0; for (HK hashKey : fields) { rawHashKeys[counter++] = rawHashKey(hashKey); } - List rawValues = execute(new RedisCallback>() { - - public List doInRedis(RedisConnection connection) { - return connection.hMGet(rawKey, rawHashKeys); - } - }, true); + List rawValues = execute(connection -> connection.hMGet(rawKey, rawHashKeys), true); return deserializeHashValues(rawValues); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.HashOperations#put(java.lang.Object, java.lang.Object, java.lang.Object) + */ + @Override public void put(K key, HK hashKey, HV value) { - final byte[] rawKey = rawKey(key); - final byte[] rawHashKey = rawHashKey(hashKey); - final byte[] rawHashValue = rawHashValue(value); - execute(new RedisCallback() { + byte[] rawKey = rawKey(key); + byte[] rawHashKey = rawHashKey(hashKey); + byte[] rawHashValue = rawHashValue(value); - public Object doInRedis(RedisConnection connection) { - connection.hSet(rawKey, rawHashKey, rawHashValue); - return null; - } + execute(connection -> { + connection.hSet(rawKey, rawHashKey, rawHashValue); + return null; }, true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.HashOperations#putIfAbsent(java.lang.Object, java.lang.Object, java.lang.Object) + */ + @Override public Boolean putIfAbsent(K key, HK hashKey, HV value) { - final byte[] rawKey = rawKey(key); - final byte[] rawHashKey = rawHashKey(hashKey); - final byte[] rawHashValue = rawHashValue(value); - return execute(new RedisCallback() { + byte[] rawKey = rawKey(key); + byte[] rawHashKey = rawHashKey(hashKey); + byte[] rawHashValue = rawHashValue(value); - public Boolean doInRedis(RedisConnection connection) { - return connection.hSetNX(rawKey, rawHashKey, rawHashValue); - } - }, true); + return execute(connection -> connection.hSetNX(rawKey, rawHashKey, rawHashValue), true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.HashOperations#values(java.lang.Object) + */ + @Override public List values(K key) { - final byte[] rawKey = rawKey(key); - List rawValues = execute(new RedisCallback>() { - - public List doInRedis(RedisConnection connection) { - return connection.hVals(rawKey); - } - }, true); + byte[] rawKey = rawKey(key); + List rawValues = execute(connection -> connection.hVals(rawKey), true); return deserializeHashValues(rawValues); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.HashOperations#delete(java.lang.Object, java.lang.Object[]) + */ + @Override public Long delete(K key, Object... hashKeys) { - final byte[] rawKey = rawKey(key); - final byte[][] rawHashKeys = rawHashKeys(hashKeys); - return execute(new RedisCallback() { + byte[] rawKey = rawKey(key); + byte[][] rawHashKeys = rawHashKeys(hashKeys); - public Long doInRedis(RedisConnection connection) { - return connection.hDel(rawKey, rawHashKeys); - } - }, true); + return execute(connection -> connection.hDel(rawKey, rawHashKeys), true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.HashOperations#entries(java.lang.Object) + */ + @Override public Map entries(K key) { - final byte[] rawKey = rawKey(key); - Map entries = execute(new RedisCallback>() { - - public Map doInRedis(RedisConnection connection) { - return connection.hGetAll(rawKey); - } - }, true); + byte[] rawKey = rawKey(key); + Map entries = execute(connection -> connection.hGetAll(rawKey), true); return deserializeHashMap(entries); } /* * (non-Javadoc) - * @see org.springframework.data.redis.core.HashOperations#hscan(java.lang.Object, org.springframework.data.redis.core.ScanOptions) + * @see org.springframework.data.redis.core.HashOperations#scan(java.lang.Object, org.springframework.data.redis.core.ScanOptions) */ @Override - public Cursor> scan(K key, final ScanOptions options) { + public Cursor> scan(K key, ScanOptions options) { - final byte[] rawKey = rawKey(key); - return template.executeWithStickyConnection(new RedisCallback>>() { - - @Override - public Cursor> doInRedis(RedisConnection connection) throws DataAccessException { - - return new ConvertingCursor, Map.Entry>(connection.hScan(rawKey, options), - new Converter, Map.Entry>() { + byte[] rawKey = rawKey(key); + return template.executeWithStickyConnection( + (RedisCallback>>) connection -> new ConvertingCursor<>(connection.hScan(rawKey, options), + new Converter, Entry>() { @Override public Entry convert(final Entry source) { - return new Map.Entry() { + return new Entry() { @Override public HK getKey() { @@ -263,12 +265,8 @@ class DefaultHashOperations extends AbstractOperations imp throw new UnsupportedOperationException("Values cannot be set when scanning through entries."); } }; - } - }); - } - - }); + })); } } diff --git a/src/main/java/org/springframework/data/redis/core/DefaultHyperLogLogOperations.java b/src/main/java/org/springframework/data/redis/core/DefaultHyperLogLogOperations.java index 37b0fe8a0..26a977d0e 100644 --- a/src/main/java/org/springframework/data/redis/core/DefaultHyperLogLogOperations.java +++ b/src/main/java/org/springframework/data/redis/core/DefaultHyperLogLogOperations.java @@ -1,5 +1,5 @@ /* - * Copyright 2014 the original author or authors. + * Copyright 2014-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,18 +17,15 @@ package org.springframework.data.redis.core; import java.util.Arrays; -import org.springframework.dao.DataAccessException; -import org.springframework.data.redis.connection.RedisConnection; - /** * @author Christoph Strobl * @since 1.5 * @param * @param */ -public class DefaultHyperLogLogOperations extends AbstractOperations implements HyperLogLogOperations { +class DefaultHyperLogLogOperations extends AbstractOperations implements HyperLogLogOperations { - public DefaultHyperLogLogOperations(RedisTemplate template) { + DefaultHyperLogLogOperations(RedisTemplate template) { super(template); } @@ -39,17 +36,9 @@ public class DefaultHyperLogLogOperations extends AbstractOperations @Override public Long add(K key, V... values) { - final byte[] rawKey = rawKey(key); - final byte[][] rawValues = rawValues(values); - - return execute(new RedisCallback() { - - @Override - public Long doInRedis(RedisConnection connection) throws DataAccessException { - return connection.pfAdd(rawKey, rawValues); - } - }, true); - + byte[] rawKey = rawKey(key); + byte[][] rawValues = rawValues(values); + return execute(connection -> connection.pfAdd(rawKey, rawValues), true); } /* @@ -59,15 +48,8 @@ public class DefaultHyperLogLogOperations extends AbstractOperations @Override public Long size(K... keys) { - final byte[][] rawKeys = rawKeys(Arrays.asList(keys)); - - return execute(new RedisCallback() { - - @Override - public Long doInRedis(RedisConnection connection) throws DataAccessException { - return connection.pfCount(rawKeys); - } - }, true); + byte[][] rawKeys = rawKeys(Arrays.asList(keys)); + return execute(connection -> connection.pfCount(rawKeys), true); } /* @@ -77,17 +59,12 @@ public class DefaultHyperLogLogOperations extends AbstractOperations @Override public Long union(K destination, K... sourceKeys) { - final byte[] rawDestinationKey = rawKey(destination); - final byte[][] rawSourceKeys = rawKeys(Arrays.asList(sourceKeys)); + byte[] rawDestinationKey = rawKey(destination); + byte[][] rawSourceKeys = rawKeys(Arrays.asList(sourceKeys)); + return execute(connection -> { - return execute(new RedisCallback() { - - @Override - public Long doInRedis(RedisConnection connection) throws DataAccessException { - - connection.pfMerge(rawDestinationKey, rawSourceKeys); - return connection.pfCount(rawDestinationKey); - } + connection.pfMerge(rawDestinationKey, rawSourceKeys); + return connection.pfCount(rawDestinationKey); }, true); } diff --git a/src/main/java/org/springframework/data/redis/core/DefaultListOperations.java b/src/main/java/org/springframework/data/redis/core/DefaultListOperations.java index 743fdda24..17d1e55a0 100644 --- a/src/main/java/org/springframework/data/redis/core/DefaultListOperations.java +++ b/src/main/java/org/springframework/data/redis/core/DefaultListOperations.java @@ -1,12 +1,12 @@ /* - * Copyright 2011-2014 the original author or authors. - * + * Copyright 2011-2017 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. @@ -25,7 +25,7 @@ import org.springframework.util.CollectionUtils; /** * Default implementation of {@link ListOperations}. - * + * * @author Costin Leau * @author David Liu * @author Thomas Darimont @@ -37,28 +37,49 @@ class DefaultListOperations extends AbstractOperations implements Li super(template); } - public V index(K key, final long index) { + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ListOperations#index(java.lang.Object, long) + */ + @Override + public V index(K key, long index) { + return execute(new ValueDeserializingRedisCallback(key) { + @Override protected byte[] inRedis(byte[] rawKey, RedisConnection connection) { return connection.lIndex(rawKey, index); } }, true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ListOperations#leftPop(java.lang.Object) + */ + @Override public V leftPop(K key) { + return execute(new ValueDeserializingRedisCallback(key) { + @Override protected byte[] inRedis(byte[] rawKey, RedisConnection connection) { return connection.lPop(rawKey); } }, true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ListOperations#leftPop(java.lang.Object, long, java.util.concurrent.TimeUnit) + */ + @Override public V leftPop(K key, long timeout, TimeUnit unit) { - final int tm = (int) TimeoutUtils.toSeconds(timeout, unit); + + int tm = (int) TimeoutUtils.toSeconds(timeout, unit); return execute(new ValueDeserializingRedisCallback(key) { + @Override protected byte[] inRedis(byte[] rawKey, RedisConnection connection) { List lPop = connection.bLPop(tm, rawKey); return (CollectionUtils.isEmpty(lPop) ? null : lPop.get(1)); @@ -66,25 +87,28 @@ class DefaultListOperations extends AbstractOperations implements Li }, true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ListOperations#leftPush(java.lang.Object, java.lang.Object) + */ + @Override public Long leftPush(K key, V value) { - final byte[] rawKey = rawKey(key); - final byte[] rawValue = rawValue(value); - return execute(new RedisCallback() { - public Long doInRedis(RedisConnection connection) { - return connection.lPush(rawKey, rawValue); - } - }, true); + byte[] rawKey = rawKey(key); + byte[] rawValue = rawValue(value); + return execute(connection -> connection.lPush(rawKey, rawValue), true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ListOperations#leftPushAll(java.lang.Object, java.lang.Object[]) + */ + @Override public Long leftPushAll(K key, V... values) { - final byte[] rawKey = rawKey(key); - final byte[][] rawValues = rawValues(values); - return execute(new RedisCallback() { - public Long doInRedis(RedisConnection connection) { - return connection.lPush(rawKey, rawValues); - } - }, true); + + byte[] rawKey = rawKey(key); + byte[][] rawValues = rawValues(values); + return execute(connection -> connection.lPush(rawKey, rawValues), true); } /* @@ -94,83 +118,99 @@ class DefaultListOperations extends AbstractOperations implements Li @Override public Long leftPushAll(K key, Collection values) { - final byte[] rawKey = rawKey(key); - final byte[][] rawValues = rawValues(values); + byte[] rawKey = rawKey(key); + byte[][] rawValues = rawValues(values); - return execute(new RedisCallback() { - public Long doInRedis(RedisConnection connection) { - return connection.lPush(rawKey, rawValues); - } - }, true); + return execute(connection -> connection.lPush(rawKey, rawValues), true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ListOperations#leftPushIfPresent(java.lang.Object, java.lang.Object) + */ + @Override public Long leftPushIfPresent(K key, V value) { - final byte[] rawKey = rawKey(key); - final byte[] rawValue = rawValue(value); - return execute(new RedisCallback() { - public Long doInRedis(RedisConnection connection) { - return connection.lPushX(rawKey, rawValue); - } - }, true); + byte[] rawKey = rawKey(key); + byte[] rawValue = rawValue(value); + return execute(connection -> connection.lPushX(rawKey, rawValue), true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ListOperations#leftPush(java.lang.Object, java.lang.Object, java.lang.Object) + */ + @Override public Long leftPush(K key, V pivot, V value) { - final byte[] rawKey = rawKey(key); - final byte[] rawPivot = rawValue(pivot); - final byte[] rawValue = rawValue(value); - return execute(new RedisCallback() { - public Long doInRedis(RedisConnection connection) { - return connection.lInsert(rawKey, Position.BEFORE, rawPivot, rawValue); - } - }, true); + byte[] rawKey = rawKey(key); + byte[] rawPivot = rawValue(pivot); + byte[] rawValue = rawValue(value); + return execute(connection -> connection.lInsert(rawKey, Position.BEFORE, rawPivot, rawValue), true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ListOperations#size(java.lang.Object) + */ + @Override public Long size(K key) { - final byte[] rawKey = rawKey(key); - return execute(new RedisCallback() { - public Long doInRedis(RedisConnection connection) { - return connection.lLen(rawKey); - } - }, true); + byte[] rawKey = rawKey(key); + return execute(connection -> connection.lLen(rawKey), true); } - public List range(K key, final long start, final long end) { - final byte[] rawKey = rawKey(key); - return execute(new RedisCallback>() { - public List doInRedis(RedisConnection connection) { - return deserializeValues(connection.lRange(rawKey, start, end)); - } - }, true); + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ListOperations#range(java.lang.Object, long, long) + */ + @Override + public List range(K key, long start, long end) { + + byte[] rawKey = rawKey(key); + return execute(connection -> deserializeValues(connection.lRange(rawKey, start, end)), true); } - public Long remove(K key, final long count, Object value) { - final byte[] rawKey = rawKey(key); - final byte[] rawValue = rawValue(value); - return execute(new RedisCallback() { + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ListOperations#remove(java.lang.Object, long, java.lang.Object) + */ + @Override + public Long remove(K key, long count, Object value) { - public Long doInRedis(RedisConnection connection) { - return connection.lRem(rawKey, count, rawValue); - } - }, true); + byte[] rawKey = rawKey(key); + byte[] rawValue = rawValue(value); + return execute(connection -> connection.lRem(rawKey, count, rawValue), true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ListOperations#rightPop(java.lang.Object) + */ + @Override public V rightPop(K key) { + return execute(new ValueDeserializingRedisCallback(key) { + @Override protected byte[] inRedis(byte[] rawKey, RedisConnection connection) { return connection.rPop(rawKey); } }, true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ListOperations#rightPop(java.lang.Object, long, java.util.concurrent.TimeUnit) + */ + @Override public V rightPop(K key, long timeout, TimeUnit unit) { - final int tm = (int) TimeoutUtils.toSeconds(timeout, unit); + + int tm = (int) TimeoutUtils.toSeconds(timeout, unit); return execute(new ValueDeserializingRedisCallback(key) { + @Override protected byte[] inRedis(byte[] rawKey, RedisConnection connection) { List bRPop = connection.bRPop(tm, rawKey); return (CollectionUtils.isEmpty(bRPop) ? null : bRPop.get(1)); @@ -178,25 +218,28 @@ class DefaultListOperations extends AbstractOperations implements Li }, true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ListOperations#rightPush(java.lang.Object, java.lang.Object) + */ + @Override public Long rightPush(K key, V value) { - final byte[] rawKey = rawKey(key); - final byte[] rawValue = rawValue(value); - return execute(new RedisCallback() { - public Long doInRedis(RedisConnection connection) { - return connection.rPush(rawKey, rawValue); - } - }, true); + byte[] rawKey = rawKey(key); + byte[] rawValue = rawValue(value); + return execute(connection -> connection.rPush(rawKey, rawValue), true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ListOperations#rightPushAll(java.lang.Object, java.lang.Object[]) + */ + @Override public Long rightPushAll(K key, V... values) { - final byte[] rawKey = rawKey(key); - final byte[][] rawValues = rawValues(values); - return execute(new RedisCallback() { - public Long doInRedis(RedisConnection connection) { - return connection.rPush(rawKey, rawValues); - } - }, true); + + byte[] rawKey = rawKey(key); + byte[][] rawValues = rawValues(values); + return execute(connection -> connection.rPush(rawKey, rawValues), true); } /* @@ -206,67 +249,82 @@ class DefaultListOperations extends AbstractOperations implements Li @Override public Long rightPushAll(K key, Collection values) { - final byte[] rawKey = rawKey(key); - final byte[][] rawValues = rawValues(values); - - return execute(new RedisCallback() { - public Long doInRedis(RedisConnection connection) { - return connection.rPush(rawKey, rawValues); - } - }, true); + byte[] rawKey = rawKey(key); + byte[][] rawValues = rawValues(values); + return execute(connection -> connection.rPush(rawKey, rawValues), true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ListOperations#rightPushIfPresent(java.lang.Object, java.lang.Object) + */ + @Override public Long rightPushIfPresent(K key, V value) { - final byte[] rawKey = rawKey(key); - final byte[] rawValue = rawValue(value); - return execute(new RedisCallback() { - public Long doInRedis(RedisConnection connection) { - return connection.rPushX(rawKey, rawValue); - } - }, true); + byte[] rawKey = rawKey(key); + byte[] rawValue = rawValue(value); + return execute(connection -> connection.rPushX(rawKey, rawValue), true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ListOperations#rightPush(java.lang.Object, java.lang.Object, java.lang.Object) + */ + @Override public Long rightPush(K key, V pivot, V value) { - final byte[] rawKey = rawKey(key); - final byte[] rawPivot = rawValue(pivot); - final byte[] rawValue = rawValue(value); - return execute(new RedisCallback() { - - public Long doInRedis(RedisConnection connection) { - return connection.lInsert(rawKey, Position.AFTER, rawPivot, rawValue); - } - }, true); + byte[] rawKey = rawKey(key); + byte[] rawPivot = rawValue(pivot); + byte[] rawValue = rawValue(value); + return execute(connection -> connection.lInsert(rawKey, Position.AFTER, rawPivot, rawValue), true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ListOperations#rightPopAndLeftPush(java.lang.Object, java.lang.Object) + */ + @Override public V rightPopAndLeftPush(K sourceKey, K destinationKey) { - final byte[] rawDestKey = rawKey(destinationKey); + byte[] rawDestKey = rawKey(destinationKey); return execute(new ValueDeserializingRedisCallback(sourceKey) { + @Override protected byte[] inRedis(byte[] rawSourceKey, RedisConnection connection) { return connection.rPopLPush(rawSourceKey, rawDestKey); } }, true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ListOperations#rightPopAndLeftPush(java.lang.Object, java.lang.Object, long, java.util.concurrent.TimeUnit) + */ + @Override public V rightPopAndLeftPush(K sourceKey, K destinationKey, long timeout, TimeUnit unit) { - final int tm = (int) TimeoutUtils.toSeconds(timeout, unit); - final byte[] rawDestKey = rawKey(destinationKey); + int tm = (int) TimeoutUtils.toSeconds(timeout, unit); + byte[] rawDestKey = rawKey(destinationKey); return execute(new ValueDeserializingRedisCallback(sourceKey) { + @Override protected byte[] inRedis(byte[] rawSourceKey, RedisConnection connection) { return connection.bRPopLPush(tm, rawSourceKey, rawDestKey); } }, true); } - public void set(K key, final long index, V value) { - final byte[] rawValue = rawValue(value); + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ListOperations#set(java.lang.Object, long, java.lang.Object) + */ + @Override + public void set(K key, long index, V value) { + + byte[] rawValue = rawValue(value); execute(new ValueDeserializingRedisCallback(key) { + @Override protected byte[] inRedis(byte[] rawKey, RedisConnection connection) { connection.lSet(rawKey, index, rawValue); return null; @@ -274,14 +332,20 @@ class DefaultListOperations extends AbstractOperations implements Li }, true); } - public void trim(K key, final long start, final long end) { + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ListOperations#trim(java.lang.Object, long, long) + */ + @Override + public void trim(K key, long start, long end) { + execute(new ValueDeserializingRedisCallback(key) { + @Override protected byte[] inRedis(byte[] rawKey, RedisConnection connection) { connection.lTrim(rawKey, start, end); return null; } }, true); } - } diff --git a/src/main/java/org/springframework/data/redis/core/DefaultReactiveGeoOperations.java b/src/main/java/org/springframework/data/redis/core/DefaultReactiveGeoOperations.java index acaee8013..d80b1a394 100644 --- a/src/main/java/org/springframework/data/redis/core/DefaultReactiveGeoOperations.java +++ b/src/main/java/org/springframework/data/redis/core/DefaultReactiveGeoOperations.java @@ -44,7 +44,7 @@ import org.springframework.util.Assert; * @author Christoph Strobl * @since 2.0 */ -public class DefaultReactiveGeoOperations implements ReactiveGeoOperations { +class DefaultReactiveGeoOperations implements ReactiveGeoOperations { private final ReactiveRedisTemplate template; private final RedisSerializationContext serializationContext; @@ -55,7 +55,7 @@ public class DefaultReactiveGeoOperations implements ReactiveGeoOperations * @param template must not be {@literal null}. * @param serializationContext must not be {@literal null}. */ - public DefaultReactiveGeoOperations(ReactiveRedisTemplate template, + DefaultReactiveGeoOperations(ReactiveRedisTemplate template, RedisSerializationContext serializationContext) { Assert.notNull(template, "ReactiveRedisTemplate must not be null!"); diff --git a/src/main/java/org/springframework/data/redis/core/DefaultReactiveHashOperations.java b/src/main/java/org/springframework/data/redis/core/DefaultReactiveHashOperations.java index 2b3a2dcff..2cc9e4414 100644 --- a/src/main/java/org/springframework/data/redis/core/DefaultReactiveHashOperations.java +++ b/src/main/java/org/springframework/data/redis/core/DefaultReactiveHashOperations.java @@ -22,7 +22,6 @@ import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.Function; @@ -39,7 +38,7 @@ import org.springframework.util.Assert; * @author Christoph Strobl * @since 2.0 */ -public class DefaultReactiveHashOperations implements ReactiveHashOperations { +class DefaultReactiveHashOperations implements ReactiveHashOperations { private final ReactiveRedisTemplate template; private final RedisSerializationContext serializationContext; @@ -50,7 +49,7 @@ public class DefaultReactiveHashOperations implements ReactiveHashOpe * @param template must not be {@literal null}. * @param serializationContext must not be {@literal null}. */ - public DefaultReactiveHashOperations(ReactiveRedisTemplate template, + DefaultReactiveHashOperations(ReactiveRedisTemplate template, RedisSerializationContext serializationContext) { Assert.notNull(template, "ReactiveRedisTemplate must not be null!"); @@ -289,7 +288,7 @@ public class DefaultReactiveHashOperations implements ReactiveHashOpe private List deserializeHashValues(List source) { - List values = new ArrayList(source.size()); + List values = new ArrayList<>(source.size()); for (ByteBuffer byteBuffer : source) { values.add(readHashValue(byteBuffer)); } diff --git a/src/main/java/org/springframework/data/redis/core/DefaultReactiveHyperLogLogOperations.java b/src/main/java/org/springframework/data/redis/core/DefaultReactiveHyperLogLogOperations.java index aaf448b26..e4ba3d417 100644 --- a/src/main/java/org/springframework/data/redis/core/DefaultReactiveHyperLogLogOperations.java +++ b/src/main/java/org/springframework/data/redis/core/DefaultReactiveHyperLogLogOperations.java @@ -15,7 +15,6 @@ */ package org.springframework.data.redis.core; -import org.springframework.data.redis.serializer.RedisSerializationContext; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -24,16 +23,17 @@ import java.util.function.Function; import org.reactivestreams.Publisher; import org.springframework.data.redis.connection.ReactiveHyperLogLogCommands; +import org.springframework.data.redis.serializer.RedisSerializationContext; import org.springframework.util.Assert; /** * Default implementation of {@link ReactiveHyperLogLogOperations}. * * @author Mark Paluch - * @auhtor Christoph Strobl + * @author Christoph Strobl * @since 2.0 */ -public class DefaultReactiveHyperLogLogOperations implements ReactiveHyperLogLogOperations { +class DefaultReactiveHyperLogLogOperations implements ReactiveHyperLogLogOperations { private final ReactiveRedisTemplate template; private final RedisSerializationContext serializationContext; @@ -44,7 +44,7 @@ public class DefaultReactiveHyperLogLogOperations implements ReactiveHyper * @param template must not be {@literal null}. * @param serializationContext must not be {@literal null}. */ - public DefaultReactiveHyperLogLogOperations(ReactiveRedisTemplate template, + DefaultReactiveHyperLogLogOperations(ReactiveRedisTemplate template, RedisSerializationContext serializationContext) { Assert.notNull(template, "ReactiveRedisTemplate must not be null!"); diff --git a/src/main/java/org/springframework/data/redis/core/DefaultReactiveListOperations.java b/src/main/java/org/springframework/data/redis/core/DefaultReactiveListOperations.java index 7c9ed5778..b9d2a7e06 100644 --- a/src/main/java/org/springframework/data/redis/core/DefaultReactiveListOperations.java +++ b/src/main/java/org/springframework/data/redis/core/DefaultReactiveListOperations.java @@ -39,7 +39,7 @@ import org.springframework.util.Assert; * @author Christoph Strobl * @since 2.0 */ -public class DefaultReactiveListOperations implements ReactiveListOperations { +class DefaultReactiveListOperations implements ReactiveListOperations { private final ReactiveRedisTemplate template; private final RedisSerializationContext serializationContext; @@ -50,7 +50,7 @@ public class DefaultReactiveListOperations implements ReactiveListOperatio * @param template must not be {@literal null}. * @param serializationContext must not be {@literal null}. */ - public DefaultReactiveListOperations(ReactiveRedisTemplate template, + DefaultReactiveListOperations(ReactiveRedisTemplate template, RedisSerializationContext serializationContext) { Assert.notNull(template, "ReactiveRedisTemplate must not be null!"); diff --git a/src/main/java/org/springframework/data/redis/core/DefaultReactiveSetOperations.java b/src/main/java/org/springframework/data/redis/core/DefaultReactiveSetOperations.java index 068ba7bcd..e1cfbd88f 100644 --- a/src/main/java/org/springframework/data/redis/core/DefaultReactiveSetOperations.java +++ b/src/main/java/org/springframework/data/redis/core/DefaultReactiveSetOperations.java @@ -37,7 +37,7 @@ import org.springframework.util.Assert; * @author Christoph Strobl * @since 2.0 */ -public class DefaultReactiveSetOperations implements ReactiveSetOperations { +class DefaultReactiveSetOperations implements ReactiveSetOperations { private final ReactiveRedisTemplate template; private final RedisSerializationContext serializationContext; @@ -48,7 +48,7 @@ public class DefaultReactiveSetOperations implements ReactiveSetOperations * @param template must not be {@literal null}. * @param serializationContext must not be {@literal null}. */ - public DefaultReactiveSetOperations(ReactiveRedisTemplate template, + DefaultReactiveSetOperations(ReactiveRedisTemplate template, RedisSerializationContext serializationContext) { Assert.notNull(template, "ReactiveRedisTemplate must not be null!"); diff --git a/src/main/java/org/springframework/data/redis/core/DefaultReactiveValueOperations.java b/src/main/java/org/springframework/data/redis/core/DefaultReactiveValueOperations.java index f214a3305..977d62384 100644 --- a/src/main/java/org/springframework/data/redis/core/DefaultReactiveValueOperations.java +++ b/src/main/java/org/springframework/data/redis/core/DefaultReactiveValueOperations.java @@ -41,7 +41,7 @@ import org.springframework.util.Assert; * @author Christoph Strobl * @since 2.0 */ -public class DefaultReactiveValueOperations implements ReactiveValueOperations { +class DefaultReactiveValueOperations implements ReactiveValueOperations { private final ReactiveRedisTemplate template; private final RedisSerializationContext serializationContext; @@ -52,7 +52,7 @@ public class DefaultReactiveValueOperations implements ReactiveValueOperat * @param template must not be {@literal null}. * @param serializationContext must not be {@literal null}. */ - public DefaultReactiveValueOperations(ReactiveRedisTemplate template, + DefaultReactiveValueOperations(ReactiveRedisTemplate template, RedisSerializationContext serializationContext) { Assert.notNull(template, "ReactiveRedisTemplate must not be null!"); diff --git a/src/main/java/org/springframework/data/redis/core/DefaultReactiveZSetOperations.java b/src/main/java/org/springframework/data/redis/core/DefaultReactiveZSetOperations.java index e6abb5af4..80dc51c2a 100644 --- a/src/main/java/org/springframework/data/redis/core/DefaultReactiveZSetOperations.java +++ b/src/main/java/org/springframework/data/redis/core/DefaultReactiveZSetOperations.java @@ -43,7 +43,7 @@ import org.springframework.util.Assert; * @author Christoph Strobl * @since 2.0 */ -public class DefaultReactiveZSetOperations implements ReactiveZSetOperations { +class DefaultReactiveZSetOperations implements ReactiveZSetOperations { private final ReactiveRedisTemplate template; private final RedisSerializationContext serializationContext; @@ -54,7 +54,7 @@ public class DefaultReactiveZSetOperations implements ReactiveZSetOperatio * @param template must not be {@literal null}. * @param serializationContext must not be {@literal null}. */ - public DefaultReactiveZSetOperations(ReactiveRedisTemplate template, + DefaultReactiveZSetOperations(ReactiveRedisTemplate template, RedisSerializationContext serializationContext) { Assert.notNull(template, "ReactiveRedisTemplate must not be null!"); diff --git a/src/main/java/org/springframework/data/redis/core/DefaultSetOperations.java b/src/main/java/org/springframework/data/redis/core/DefaultSetOperations.java index ca274c1b0..effc6bfaf 100644 --- a/src/main/java/org/springframework/data/redis/core/DefaultSetOperations.java +++ b/src/main/java/org/springframework/data/redis/core/DefaultSetOperations.java @@ -1,12 +1,12 @@ /* * Copyright 2011-2017 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. @@ -22,16 +22,18 @@ import java.util.List; import java.util.Set; import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.util.Assert; /** * Default implementation of {@link SetOperations}. - * + * * @author Costin Leau * @author Christoph Strobl + * @author Mark Paluch */ class DefaultSetOperations extends AbstractOperations implements SetOperations { - public DefaultSetOperations(RedisTemplate template) { + DefaultSetOperations(RedisTemplate template) { super(template); } @@ -39,9 +41,11 @@ class DefaultSetOperations extends AbstractOperations implements Set * (non-Javadoc) * @see org.springframework.data.redis.core.SetOperations#add(java.lang.Object, java.lang.Object[]) */ + @Override public Long add(K key, V... values) { - final byte[] rawKey = rawKey(key); - final byte[][] rawValues = rawValues(values); + + byte[] rawKey = rawKey(key); + byte[][] rawValues = rawValues((Object[]) values); return execute(connection -> connection.sAdd(rawKey, rawValues), true); } @@ -49,6 +53,7 @@ class DefaultSetOperations extends AbstractOperations implements Set * (non-Javadoc) * @see org.springframework.data.redis.core.SetOperations#difference(java.lang.Object, java.lang.Object) */ + @Override public Set difference(K key, K otherKey) { return difference(key, Collections.singleton(otherKey)); } @@ -57,9 +62,10 @@ class DefaultSetOperations extends AbstractOperations implements Set * (non-Javadoc) * @see org.springframework.data.redis.core.SetOperations#difference(java.lang.Object, java.util.Collection) */ - public Set difference(final K key, final Collection otherKeys) { + @Override + public Set difference(K key, Collection otherKeys) { - final byte[][] rawKeys = rawKeys(key, otherKeys); + byte[][] rawKeys = rawKeys(key, otherKeys); Set rawValues = execute(connection -> connection.sDiff(rawKeys), true); return deserializeValues(rawValues); @@ -69,6 +75,7 @@ class DefaultSetOperations extends AbstractOperations implements Set * (non-Javadoc) * @see org.springframework.data.redis.core.SetOperations#differenceAndStore(java.lang.Object, java.lang.Object, java.lang.Object) */ + @Override public Long differenceAndStore(K key, K otherKey, K destKey) { return differenceAndStore(key, Collections.singleton(otherKey), destKey); } @@ -77,10 +84,11 @@ class DefaultSetOperations extends AbstractOperations implements Set * (non-Javadoc) * @see org.springframework.data.redis.core.SetOperations#differenceAndStore(java.lang.Object, java.util.Collection, java.lang.Object) */ - public Long differenceAndStore(final K key, final Collection otherKeys, K destKey) { + @Override + public Long differenceAndStore(K key, Collection otherKeys, K destKey) { - final byte[][] rawKeys = rawKeys(key, otherKeys); - final byte[] rawDestKey = rawKey(destKey); + byte[][] rawKeys = rawKeys(key, otherKeys); + byte[] rawDestKey = rawKey(destKey); return execute(connection -> connection.sDiffStore(rawDestKey, rawKeys), true); } @@ -88,6 +96,7 @@ class DefaultSetOperations extends AbstractOperations implements Set * (non-Javadoc) * @see org.springframework.data.redis.core.SetOperations#intersect(java.lang.Object, java.lang.Object) */ + @Override public Set intersect(K key, K otherKey) { return intersect(key, Collections.singleton(otherKey)); } @@ -96,9 +105,10 @@ class DefaultSetOperations extends AbstractOperations implements Set * (non-Javadoc) * @see org.springframework.data.redis.core.SetOperations#intersect(java.lang.Object, java.util.Collection) */ + @Override public Set intersect(K key, Collection otherKeys) { - final byte[][] rawKeys = rawKeys(key, otherKeys); + byte[][] rawKeys = rawKeys(key, otherKeys); Set rawValues = execute(connection -> connection.sInter(rawKeys), true); return deserializeValues(rawValues); @@ -108,6 +118,7 @@ class DefaultSetOperations extends AbstractOperations implements Set * (non-Javadoc) * @see org.springframework.data.redis.core.SetOperations#intersectAndStore(java.lang.Object, java.lang.Object, java.lang.Object) */ + @Override public Long intersectAndStore(K key, K otherKey, K destKey) { return intersectAndStore(key, Collections.singleton(otherKey), destKey); } @@ -116,10 +127,11 @@ class DefaultSetOperations extends AbstractOperations implements Set * (non-Javadoc) * @see org.springframework.data.redis.core.SetOperations#intersectAndStore(java.lang.Object, java.util.Collection, java.lang.Object) */ + @Override public Long intersectAndStore(K key, Collection otherKeys, K destKey) { - final byte[][] rawKeys = rawKeys(key, otherKeys); - final byte[] rawDestKey = rawKey(destKey); + byte[][] rawKeys = rawKeys(key, otherKeys); + byte[] rawDestKey = rawKey(destKey); return execute(connection -> connection.sInterStore(rawDestKey, rawKeys), true); } @@ -127,10 +139,11 @@ class DefaultSetOperations extends AbstractOperations implements Set * (non-Javadoc) * @see org.springframework.data.redis.core.SetOperations#isMember(java.lang.Object, java.lang.Object) */ + @Override public Boolean isMember(K key, Object o) { - final byte[] rawKey = rawKey(key); - final byte[] rawValue = rawValue(o); + byte[] rawKey = rawKey(key); + byte[] rawValue = rawValue(o); return execute(connection -> connection.sIsMember(rawKey, rawValue), true); } @@ -138,9 +151,10 @@ class DefaultSetOperations extends AbstractOperations implements Set * (non-Javadoc) * @see org.springframework.data.redis.core.SetOperations#members(java.lang.Object) */ + @Override public Set members(K key) { - final byte[] rawKey = rawKey(key); + byte[] rawKey = rawKey(key); Set rawValues = execute(connection -> connection.sMembers(rawKey), true); return deserializeValues(rawValues); @@ -150,11 +164,12 @@ class DefaultSetOperations extends AbstractOperations implements Set * (non-Javadoc) * @see org.springframework.data.redis.core.SetOperations#move(java.lang.Object, java.lang.Object, java.lang.Object) */ + @Override public Boolean move(K key, V value, K destKey) { - final byte[] rawKey = rawKey(key); - final byte[] rawDestKey = rawKey(destKey); - final byte[] rawValue = rawValue(value); + byte[] rawKey = rawKey(key); + byte[] rawDestKey = rawKey(destKey); + byte[] rawValue = rawValue(value); return execute(connection -> connection.sMove(rawKey, rawDestKey, rawValue), true); } @@ -163,10 +178,12 @@ class DefaultSetOperations extends AbstractOperations implements Set * (non-Javadoc) * @see org.springframework.data.redis.core.SetOperations#randomMember(java.lang.Object) */ + @Override public V randomMember(K key) { return execute(new ValueDeserializingRedisCallback(key) { + @Override protected byte[] inRedis(byte[] rawKey, RedisConnection connection) { return connection.sRandMember(rawKey); } @@ -177,14 +194,12 @@ class DefaultSetOperations extends AbstractOperations implements Set * (non-Javadoc) * @see org.springframework.data.redis.core.SetOperations#distinctRandomMembers(java.lang.Object, long) */ - public Set distinctRandomMembers(K key, final long count) { + @Override + public Set distinctRandomMembers(K key, long count) { - if (count < 0) { - throw new IllegalArgumentException( - "Negative count not supported. " + "Use randomMembers to allow duplicate elements."); - } + Assert.isTrue(count >= 0, "Negative count not supported. " + "Use randomMembers to allow duplicate elements."); - final byte[] rawKey = rawKey(key); + byte[] rawKey = rawKey(key); Set rawValues = execute( (RedisCallback>) connection -> new HashSet<>(connection.sRandMember(rawKey, count)), true); @@ -195,14 +210,13 @@ class DefaultSetOperations extends AbstractOperations implements Set * (non-Javadoc) * @see org.springframework.data.redis.core.SetOperations#randomMembers(java.lang.Object, long) */ - public List randomMembers(K key, final long count) { + @Override + public List randomMembers(K key, long count) { - if (count < 0) { - throw new IllegalArgumentException( - "Use a positive number for count. " + "This method is already allowing duplicate elements."); - } + Assert.isTrue(count >= 0, + "Use a positive number for count. " + "This method is already allowing duplicate elements."); - final byte[] rawKey = rawKey(key); + byte[] rawKey = rawKey(key); List rawValues = execute(connection -> connection.sRandMember(rawKey, -count), true); return deserializeValues(rawValues); @@ -212,10 +226,11 @@ class DefaultSetOperations extends AbstractOperations implements Set * (non-Javadoc) * @see org.springframework.data.redis.core.SetOperations#remove(java.lang.Object, java.lang.Object[]) */ + @Override public Long remove(K key, Object... values) { - final byte[] rawKey = rawKey(key); - final byte[][] rawValues = rawValues(values); + byte[] rawKey = rawKey(key); + byte[][] rawValues = rawValues(values); return execute(connection -> connection.sRem(rawKey, rawValues), true); } @@ -223,9 +238,12 @@ class DefaultSetOperations extends AbstractOperations implements Set * (non-Javadoc) * @see org.springframework.data.redis.core.SetOperations#pop(java.lang.Object) */ + @Override public V pop(K key) { + return execute(new ValueDeserializingRedisCallback(key) { + @Override protected byte[] inRedis(byte[] rawKey, RedisConnection connection) { return connection.sPop(rawKey); } @@ -239,9 +257,9 @@ class DefaultSetOperations extends AbstractOperations implements Set @Override public List pop(K key, long count) { - final byte[] rawKey = rawKey(key); - + byte[] rawKey = rawKey(key); List rawValues = execute(connection -> connection.sPop(rawKey, count), true); + return deserializeValues(rawValues); } @@ -249,8 +267,10 @@ class DefaultSetOperations extends AbstractOperations implements Set * (non-Javadoc) * @see org.springframework.data.redis.core.SetOperations#size(java.lang.Object) */ + @Override public Long size(K key) { - final byte[] rawKey = rawKey(key); + + byte[] rawKey = rawKey(key); return execute(connection -> connection.sCard(rawKey), true); } @@ -258,13 +278,19 @@ class DefaultSetOperations extends AbstractOperations implements Set * (non-Javadoc) * @see org.springframework.data.redis.core.SetOperations#union(java.lang.Object, java.lang.Object) */ + @Override public Set union(K key, K otherKey) { return union(key, Collections.singleton(otherKey)); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.SetOperations#union(java.lang.Object, java.util.Collection) + */ + @Override public Set union(K key, Collection otherKeys) { - final byte[][] rawKeys = rawKeys(key, otherKeys); + byte[][] rawKeys = rawKeys(key, otherKeys); Set rawValues = execute(connection -> connection.sUnion(rawKeys), true); return deserializeValues(rawValues); @@ -274,6 +300,7 @@ class DefaultSetOperations extends AbstractOperations implements Set * (non-Javadoc) * @see org.springframework.data.redis.core.SetOperations#union(java.lang.Object, java.lang.Object, java.lang.Object) */ + @Override public Long unionAndStore(K key, K otherKey, K destKey) { return unionAndStore(key, Collections.singleton(otherKey), destKey); } @@ -282,9 +309,11 @@ class DefaultSetOperations extends AbstractOperations implements Set * (non-Javadoc) * @see org.springframework.data.redis.core.SetOperations#unionAndStore(java.lang.Object, java.util.Collection, java.lang.Object) */ + @Override public Long unionAndStore(K key, Collection otherKeys, K destKey) { - final byte[][] rawKeys = rawKeys(key, otherKeys); - final byte[] rawDestKey = rawKey(destKey); + + byte[][] rawKeys = rawKeys(key, otherKeys); + byte[] rawDestKey = rawKey(destKey); return execute(connection -> connection.sUnionStore(rawDestKey, rawKeys), true); } @@ -293,12 +322,11 @@ class DefaultSetOperations extends AbstractOperations implements Set * @see org.springframework.data.redis.core.SetOperations#sScan(java.lang.Object, org.springframework.data.redis.core.ScanOptions) */ @Override - public Cursor scan(K key, final ScanOptions options) { + public Cursor scan(K key, ScanOptions options) { - final byte[] rawKey = rawKey(key); + byte[] rawKey = rawKey(key); return template.executeWithStickyConnection( (RedisCallback>) connection -> new ConvertingCursor<>(connection.sScan(rawKey, options), - source -> deserializeValue(source))); - + this::deserializeValue)); } } diff --git a/src/main/java/org/springframework/data/redis/core/DefaultValueOperations.java b/src/main/java/org/springframework/data/redis/core/DefaultValueOperations.java index 1e4fa7db4..36a7cfd57 100644 --- a/src/main/java/org/springframework/data/redis/core/DefaultValueOperations.java +++ b/src/main/java/org/springframework/data/redis/core/DefaultValueOperations.java @@ -1,12 +1,12 @@ /* - * Copyright 2011-2014 the original author or authors. - * + * Copyright 2011-2017 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. @@ -27,7 +27,7 @@ import org.springframework.data.redis.connection.RedisConnection; /** * Default implementation of {@link ValueOperations}. - * + * * @author Costin Leau * @author Jennifer Hickey * @author Christoph Strobl @@ -38,136 +38,166 @@ class DefaultValueOperations extends AbstractOperations implements V super(template); } - public V get(final Object key) { + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ValueOperations#get(java.lang.Object) + */ + @Override + public V get(Object key) { return execute(new ValueDeserializingRedisCallback(key) { + @Override protected byte[] inRedis(byte[] rawKey, RedisConnection connection) { return connection.get(rawKey); } }, true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ValueOperations#getAndSet(java.lang.Object, java.lang.Object) + */ + @Override public V getAndSet(K key, V newValue) { - final byte[] rawValue = rawValue(newValue); + + byte[] rawValue = rawValue(newValue); return execute(new ValueDeserializingRedisCallback(key) { + @Override protected byte[] inRedis(byte[] rawKey, RedisConnection connection) { return connection.getSet(rawKey, rawValue); } }, true); } - public Long increment(K key, final long delta) { - final byte[] rawKey = rawKey(key); - return execute(new RedisCallback() { + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ValueOperations#increment(java.lang.Object, long) + */ + @Override + public Long increment(K key, long delta) { - public Long doInRedis(RedisConnection connection) { - return connection.incrBy(rawKey, delta); - } - }, true); + byte[] rawKey = rawKey(key); + return execute(connection -> connection.incrBy(rawKey, delta), true); } - public Double increment(K key, final double delta) { - final byte[] rawKey = rawKey(key); - return execute(new RedisCallback() { - public Double doInRedis(RedisConnection connection) { - return connection.incrBy(rawKey, delta); - } - }, true); + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ValueOperations#increment(java.lang.Object, double) + */ + @Override + public Double increment(K key, double delta) { + + byte[] rawKey = rawKey(key); + return execute(connection -> connection.incrBy(rawKey, delta), true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ValueOperations#append(java.lang.Object, java.lang.String) + */ + @Override public Integer append(K key, String value) { - final byte[] rawKey = rawKey(key); - final byte[] rawString = rawString(value); - return execute(new RedisCallback() { + byte[] rawKey = rawKey(key); + byte[] rawString = rawString(value); - public Integer doInRedis(RedisConnection connection) { - final Long result = connection.append(rawKey, rawString); - return ( result != null ) ? result.intValue() : null; - } + return execute(connection -> { + Long result = connection.append(rawKey, rawString); + return (result != null) ? result.intValue() : null; }, true); } - public String get(K key, final long start, final long end) { - final byte[] rawKey = rawKey(key); - - byte[] rawReturn = execute(new RedisCallback() { - - public byte[] doInRedis(RedisConnection connection) { - return connection.getRange(rawKey, start, end); - } - }, true); + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ValueOperations#get(java.lang.Object, long, long) + */ + @Override + public String get(K key, long start, long end) { + byte[] rawKey = rawKey(key); + byte[] rawReturn = execute(connection -> connection.getRange(rawKey, start, end), true); return deserializeString(rawReturn); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ValueOperations#multiGet(java.util.Collection) + */ + @Override public List multiGet(Collection keys) { + if (keys.isEmpty()) { return Collections.emptyList(); } - final byte[][] rawKeys = new byte[keys.size()][]; + byte[][] rawKeys = new byte[keys.size()][]; int counter = 0; for (K hashKey : keys) { rawKeys[counter++] = rawKey(hashKey); } - List rawValues = execute(new RedisCallback>() { - - public List doInRedis(RedisConnection connection) { - return connection.mGet(rawKeys); - } - }, true); + List rawValues = execute(connection -> connection.mGet(rawKeys), true); return deserializeValues(rawValues); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ValueOperations#multiSet(java.util.Map) + */ + @Override public void multiSet(Map m) { + if (m.isEmpty()) { return; } - final Map rawKeys = new LinkedHashMap(m.size()); + Map rawKeys = new LinkedHashMap<>(m.size()); for (Map.Entry entry : m.entrySet()) { rawKeys.put(rawKey(entry.getKey()), rawValue(entry.getValue())); } - execute(new RedisCallback() { - - public Object doInRedis(RedisConnection connection) { - connection.mSet(rawKeys); - return null; - } + execute(connection -> { + connection.mSet(rawKeys); + return null; }, true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ValueOperations#multiSetIfAbsent(java.util.Map) + */ + @Override public Boolean multiSetIfAbsent(Map m) { + if (m.isEmpty()) { return true; } - final Map rawKeys = new LinkedHashMap(m.size()); + Map rawKeys = new LinkedHashMap<>(m.size()); for (Map.Entry entry : m.entrySet()) { rawKeys.put(rawKey(entry.getKey()), rawValue(entry.getValue())); } - return execute(new RedisCallback() { - - public Boolean doInRedis(RedisConnection connection) { - return connection.mSetNX(rawKeys); - } - }, true); + return execute(connection -> connection.mSetNX(rawKeys), true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ValueOperations#set(java.lang.Object, java.lang.Object) + */ + @Override public void set(K key, V value) { - final byte[] rawValue = rawValue(value); + + byte[] rawValue = rawValue(value); execute(new ValueDeserializingRedisCallback(key) { + @Override protected byte[] inRedis(byte[] rawKey, RedisConnection connection) { connection.set(rawKey, rawValue); return null; @@ -175,12 +205,19 @@ class DefaultValueOperations extends AbstractOperations implements V }, true); } - public void set(K key, V value, final long timeout, final TimeUnit unit) { - final byte[] rawKey = rawKey(key); - final byte[] rawValue = rawValue(value); + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ValueOperations#set(java.lang.Object, java.lang.Object, long, java.util.concurrent.TimeUnit) + */ + @Override + public void set(K key, V value, long timeout, TimeUnit unit) { + + byte[] rawKey = rawKey(key); + byte[] rawValue = rawValue(value); execute(new RedisCallback() { + @Override public Object doInRedis(RedisConnection connection) throws DataAccessException { potentiallyUsePsetEx(connection); @@ -209,64 +246,64 @@ class DefaultValueOperations extends AbstractOperations implements V }, true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ValueOperations#setIfAbsent(java.lang.Object, java.lang.Object) + */ + @Override public Boolean setIfAbsent(K key, V value) { - final byte[] rawKey = rawKey(key); - final byte[] rawValue = rawValue(value); - return execute(new RedisCallback() { + byte[] rawKey = rawKey(key); + byte[] rawValue = rawValue(value); + return execute(connection -> connection.setNX(rawKey, rawValue), true); + } - public Boolean doInRedis(RedisConnection connection) throws DataAccessException { - return connection.setNX(rawKey, rawValue); - } - }, true); - } - - public void set(K key, final V value, final long offset) { - final byte[] rawKey = rawKey(key); - final byte[] rawValue = rawValue(value); - - execute(new RedisCallback() { - - public Object doInRedis(RedisConnection connection) { - connection.setRange(rawKey, rawValue, offset); - return null; - } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ValueOperations#set(java.lang.Object, java.lang.Object, long) + */ + @Override + public void set(K key, V value, long offset) { + + byte[] rawKey = rawKey(key); + byte[] rawValue = rawValue(value); + + execute(connection -> { + connection.setRange(rawKey, rawValue, offset); + return null; }, true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ValueOperations#size(java.lang.Object) + */ + @Override public Long size(K key) { - final byte[] rawKey = rawKey(key); - return execute(new RedisCallback() { - - public Long doInRedis(RedisConnection connection) { - return connection.strLen(rawKey); - } - }, true); + byte[] rawKey = rawKey(key); + return execute(connection -> connection.strLen(rawKey), true); } - + + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ValueOperations#setBit(java.lang.Object, long, boolean) + */ @Override - public Boolean setBit(K key, final long offset, final boolean value) { - - final byte[] rawKey = rawKey(key); - return execute(new RedisCallback() { + public Boolean setBit(K key, long offset, boolean value) { - public Boolean doInRedis(RedisConnection connection) { - return connection.setBit(rawKey, offset, value); - } - }, true); + byte[] rawKey = rawKey(key); + return execute(connection -> connection.setBit(rawKey, offset, value), true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ValueOperations#getBit(java.lang.Object, long) + */ @Override - public Boolean getBit(K key, final long offset) { - - final byte[] rawKey = rawKey(key); - return execute(new RedisCallback() { + public Boolean getBit(K key, long offset) { - public Boolean doInRedis(RedisConnection connection) { - return connection.getBit(rawKey, offset); - } - }, true); + byte[] rawKey = rawKey(key); + return execute(connection -> connection.getBit(rawKey, offset), true); } - } diff --git a/src/main/java/org/springframework/data/redis/core/DefaultZSetOperations.java b/src/main/java/org/springframework/data/redis/core/DefaultZSetOperations.java index bc252a3f5..5724a8fed 100644 --- a/src/main/java/org/springframework/data/redis/core/DefaultZSetOperations.java +++ b/src/main/java/org/springframework/data/redis/core/DefaultZSetOperations.java @@ -1,12 +1,12 @@ /* - * Copyright 2011-2016 the original author or authors. - * + * Copyright 2011-2017 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. @@ -19,16 +19,13 @@ import java.util.Collection; import java.util.Collections; import java.util.Set; -import org.springframework.core.convert.converter.Converter; -import org.springframework.dao.DataAccessException; -import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisZSetCommands.Limit; import org.springframework.data.redis.connection.RedisZSetCommands.Range; import org.springframework.data.redis.connection.RedisZSetCommands.Tuple; /** * Default implementation of {@link ZSetOperations}. - * + * * @author Costin Leau * @author Christoph Strobl * @author Thomas Darimont @@ -41,105 +38,111 @@ class DefaultZSetOperations extends AbstractOperations implements ZS super(template); } - public Boolean add(final K key, final V value, final double score) { - final byte[] rawKey = rawKey(key); - final byte[] rawValue = rawValue(value); + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ZSetOperations#add(java.lang.Object, java.lang.Object, double) + */ + @Override + public Boolean add(K key, V value, double score) { - return execute(new RedisCallback() { - - public Boolean doInRedis(RedisConnection connection) { - return connection.zAdd(rawKey, score, rawValue); - } - }, true); + byte[] rawKey = rawKey(key); + byte[] rawValue = rawValue(value); + return execute(connection -> connection.zAdd(rawKey, score, rawValue), true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ZSetOperations#add(java.lang.Object, java.util.Set) + */ + @Override public Long add(K key, Set> tuples) { - final byte[] rawKey = rawKey(key); - final Set rawValues = rawTupleValues(tuples); - return execute(new RedisCallback() { - - public Long doInRedis(RedisConnection connection) { - return connection.zAdd(rawKey, rawValues); - } - }, true); + byte[] rawKey = rawKey(key); + Set rawValues = rawTupleValues(tuples); + return execute(connection -> connection.zAdd(rawKey, rawValues), true); } - public Double incrementScore(K key, V value, final double delta) { - final byte[] rawKey = rawKey(key); - final byte[] rawValue = rawValue(value); + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ZSetOperations#incrementScore(java.lang.Object, java.lang.Object, double) + */ + @Override + public Double incrementScore(K key, V value, double delta) { - return execute(new RedisCallback() { - - public Double doInRedis(RedisConnection connection) { - return connection.zIncrBy(rawKey, delta, rawValue); - } - }, true); + byte[] rawKey = rawKey(key); + byte[] rawValue = rawValue(value); + return execute(connection -> connection.zIncrBy(rawKey, delta, rawValue), true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ZSetOperations#intersectAndStore(java.lang.Object, java.lang.Object, java.lang.Object) + */ + @Override public Long intersectAndStore(K key, K otherKey, K destKey) { return intersectAndStore(key, Collections.singleton(otherKey), destKey); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ZSetOperations#intersectAndStore(java.lang.Object, java.util.Collection, java.lang.Object) + */ + @Override public Long intersectAndStore(K key, Collection otherKeys, K destKey) { - final byte[][] rawKeys = rawKeys(key, otherKeys); - final byte[] rawDestKey = rawKey(destKey); - return execute(new RedisCallback() { - public Long doInRedis(RedisConnection connection) { - return connection.zInterStore(rawDestKey, rawKeys); - } - }, true); + byte[][] rawKeys = rawKeys(key, otherKeys); + byte[] rawDestKey = rawKey(destKey); + return execute(connection -> connection.zInterStore(rawDestKey, rawKeys), true); } - public Set range(K key, final long start, final long end) { - final byte[] rawKey = rawKey(key); + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ZSetOperations#range(java.lang.Object, long, long) + */ + @Override + public Set range(K key, long start, long end) { - Set rawValues = execute(new RedisCallback>() { - - public Set doInRedis(RedisConnection connection) { - return connection.zRange(rawKey, start, end); - } - }, true); + byte[] rawKey = rawKey(key); + Set rawValues = execute(connection -> connection.zRange(rawKey, start, end), true); return deserializeValues(rawValues); } - public Set reverseRange(K key, final long start, final long end) { - final byte[] rawKey = rawKey(key); + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ZSetOperations#reverseRange(java.lang.Object, long, long) + */ + @Override + public Set reverseRange(K key, long start, long end) { - Set rawValues = execute(new RedisCallback>() { - - public Set doInRedis(RedisConnection connection) { - return connection.zRevRange(rawKey, start, end); - } - }, true); + byte[] rawKey = rawKey(key); + Set rawValues = execute(connection -> connection.zRevRange(rawKey, start, end), true); return deserializeValues(rawValues); } - public Set> rangeWithScores(K key, final long start, final long end) { - final byte[] rawKey = rawKey(key); + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ZSetOperations#rangeWithScores(java.lang.Object, long, long) + */ + @Override + public Set> rangeWithScores(K key, long start, long end) { - Set rawValues = execute(new RedisCallback>() { - - public Set doInRedis(RedisConnection connection) { - return connection.zRangeWithScores(rawKey, start, end); - } - }, true); + byte[] rawKey = rawKey(key); + Set rawValues = execute(connection -> connection.zRangeWithScores(rawKey, start, end), true); return deserializeTupleValues(rawValues); } - public Set> reverseRangeWithScores(K key, final long start, final long end) { - final byte[] rawKey = rawKey(key); + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ZSetOperations#reverseRangeWithScores(java.lang.Object, long, long) + */ + @Override + public Set> reverseRangeWithScores(K key, long start, long end) { - Set rawValues = execute(new RedisCallback>() { - - public Set doInRedis(RedisConnection connection) { - return connection.zRevRangeWithScores(rawKey, start, end); - } - }, true); + byte[] rawKey = rawKey(key); + Set rawValues = execute(connection -> connection.zRevRangeWithScores(rawKey, start, end), true); return deserializeTupleValues(rawValues); } @@ -149,7 +152,7 @@ class DefaultZSetOperations extends AbstractOperations implements ZS * @see org.springframework.data.redis.core.ZSetOperations#rangeByLex(java.lang.Object, org.springframework.data.redis.connection.RedisZSetCommands.Range) */ @Override - public Set rangeByLex(K key, final Range range) { + public Set rangeByLex(K key, Range range) { return rangeByLex(key, range, null); } @@ -158,207 +161,208 @@ class DefaultZSetOperations extends AbstractOperations implements ZS * @see org.springframework.data.redis.core.ZSetOperations#rangeByLex(java.lang.Object, org.springframework.data.redis.connection.RedisZSetCommands.Range, org.springframework.data.redis.connection.RedisZSetCommands.Limit) */ @Override - public Set rangeByLex(K key, final Range range, final Limit limit) { + public Set rangeByLex(K key, Range range, Limit limit) { - final byte[] rawKey = rawKey(key); - - Set rawValues = execute(new RedisCallback>() { - - public Set doInRedis(RedisConnection connection) { - return connection.zRangeByLex(rawKey, range, limit); - } - }, true); + byte[] rawKey = rawKey(key); + Set rawValues = execute(connection -> connection.zRangeByLex(rawKey, range, limit), true); return deserializeValues(rawValues); } - public Set rangeByScore(K key, final double min, final double max) { - final byte[] rawKey = rawKey(key); + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ZSetOperations#rangeByScore(java.lang.Object, double, double) + */ + @Override + public Set rangeByScore(K key, double min, double max) { - Set rawValues = execute(new RedisCallback>() { - - public Set doInRedis(RedisConnection connection) { - return connection.zRangeByScore(rawKey, min, max); - } - }, true); + byte[] rawKey = rawKey(key); + Set rawValues = execute(connection -> connection.zRangeByScore(rawKey, min, max), true); return deserializeValues(rawValues); } - public Set rangeByScore(K key, final double min, final double max, final long offset, final long count) { - final byte[] rawKey = rawKey(key); + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ZSetOperations#rangeByScore(java.lang.Object, double, double, long, long) + */ + @Override + public Set rangeByScore(K key, double min, double max, long offset, long count) { - Set rawValues = execute(new RedisCallback>() { - - public Set doInRedis(RedisConnection connection) { - return connection.zRangeByScore(rawKey, min, max, offset, count); - } - }, true); + byte[] rawKey = rawKey(key); + Set rawValues = execute(connection -> connection.zRangeByScore(rawKey, min, max, offset, count), true); return deserializeValues(rawValues); } - public Set reverseRangeByScore(K key, final double min, final double max) { - final byte[] rawKey = rawKey(key); + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ZSetOperations#reverseRangeByScore(java.lang.Object, double, double) + */ + @Override + public Set reverseRangeByScore(K key, double min, double max) { - Set rawValues = execute(new RedisCallback>() { - - public Set doInRedis(RedisConnection connection) { - return connection.zRevRangeByScore(rawKey, min, max); - } - }, true); + byte[] rawKey = rawKey(key); + Set rawValues = execute(connection -> connection.zRevRangeByScore(rawKey, min, max), true); return deserializeValues(rawValues); } - public Set reverseRangeByScore(K key, final double min, final double max, final long offset, final long count) { - final byte[] rawKey = rawKey(key); + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ZSetOperations#reverseRangeByScore(java.lang.Object, double, double, long, long) + */ + @Override + public Set reverseRangeByScore(K key, double min, double max, long offset, long count) { - Set rawValues = execute(new RedisCallback>() { - - public Set doInRedis(RedisConnection connection) { - return connection.zRevRangeByScore(rawKey, min, max, offset, count); - } - }, true); + byte[] rawKey = rawKey(key); + Set rawValues = execute(connection -> connection.zRevRangeByScore(rawKey, min, max, offset, count), true); return deserializeValues(rawValues); } - public Set> rangeByScoreWithScores(K key, final double min, final double max) { - final byte[] rawKey = rawKey(key); + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ZSetOperations#rangeByScoreWithScores(java.lang.Object, double, double) + */ + @Override + public Set> rangeByScoreWithScores(K key, double min, double max) { - Set rawValues = execute(new RedisCallback>() { - - public Set doInRedis(RedisConnection connection) { - return connection.zRangeByScoreWithScores(rawKey, min, max); - } - }, true); + byte[] rawKey = rawKey(key); + Set rawValues = execute(connection -> connection.zRangeByScoreWithScores(rawKey, min, max), true); return deserializeTupleValues(rawValues); } - public Set> rangeByScoreWithScores(K key, final double min, final double max, final long offset, - final long count) { - final byte[] rawKey = rawKey(key); + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ZSetOperations#rangeByScoreWithScores(java.lang.Object, double, double, long, long) + */ + @Override + public Set> rangeByScoreWithScores(K key, double min, double max, long offset, long count) { - Set rawValues = execute(new RedisCallback>() { - - public Set doInRedis(RedisConnection connection) { - return connection.zRangeByScoreWithScores(rawKey, min, max, offset, count); - } - }, true); + byte[] rawKey = rawKey(key); + Set rawValues = execute(connection -> connection.zRangeByScoreWithScores(rawKey, min, max, offset, count), + true); return deserializeTupleValues(rawValues); } - public Set> reverseRangeByScoreWithScores(K key, final double min, final double max) { - final byte[] rawKey = rawKey(key); + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ZSetOperations#reverseRangeByScoreWithScores(java.lang.Object, double, double) + */ + @Override + public Set> reverseRangeByScoreWithScores(K key, double min, double max) { - Set rawValues = execute(new RedisCallback>() { - - public Set doInRedis(RedisConnection connection) { - return connection.zRevRangeByScoreWithScores(rawKey, min, max); - - } - }, true); + byte[] rawKey = rawKey(key); + Set rawValues = execute(connection -> connection.zRevRangeByScoreWithScores(rawKey, min, max), true); return deserializeTupleValues(rawValues); } - public Set> reverseRangeByScoreWithScores(K key, final double min, final double max, final long offset, - final long count) { - final byte[] rawKey = rawKey(key); + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ZSetOperations#reverseRangeByScoreWithScores(java.lang.Object, double, double, long, long) + */ + @Override + public Set> reverseRangeByScoreWithScores(K key, double min, double max, long offset, long count) { - Set rawValues = execute(new RedisCallback>() { - - public Set doInRedis(RedisConnection connection) { - return connection.zRevRangeByScoreWithScores(rawKey, min, max, offset, count); - - } - }, true); + byte[] rawKey = rawKey(key); + Set rawValues = execute(connection -> connection.zRevRangeByScoreWithScores(rawKey, min, max, offset, count), + true); return deserializeTupleValues(rawValues); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ZSetOperations#rank(java.lang.Object, java.lang.Object) + */ + @Override public Long rank(K key, Object o) { - final byte[] rawKey = rawKey(key); - final byte[] rawValue = rawValue(o); - return execute(new RedisCallback() { + byte[] rawKey = rawKey(key); + byte[] rawValue = rawValue(o); - public Long doInRedis(RedisConnection connection) { - Long zRank = connection.zRank(rawKey, rawValue); - return (zRank != null && zRank.longValue() >= 0 ? zRank : null); - } + return execute(connection -> { + Long zRank = connection.zRank(rawKey, rawValue); + return (zRank != null && zRank.longValue() >= 0 ? zRank : null); }, true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ZSetOperations#reverseRank(java.lang.Object, java.lang.Object) + */ + @Override public Long reverseRank(K key, Object o) { - final byte[] rawKey = rawKey(key); - final byte[] rawValue = rawValue(o); - return execute(new RedisCallback() { + byte[] rawKey = rawKey(key); + byte[] rawValue = rawValue(o); - public Long doInRedis(RedisConnection connection) { - Long zRank = connection.zRevRank(rawKey, rawValue); - return (zRank != null && zRank.longValue() >= 0 ? zRank : null); - } + return execute(connection -> { + Long zRank = connection.zRevRank(rawKey, rawValue); + return (zRank != null && zRank.longValue() >= 0 ? zRank : null); }, true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ZSetOperations#remove(java.lang.Object, java.lang.Object[]) + */ + @Override public Long remove(K key, Object... values) { - final byte[] rawKey = rawKey(key); - final byte[][] rawValues = rawValues(values); - return execute(new RedisCallback() { + byte[] rawKey = rawKey(key); + byte[][] rawValues = rawValues(values); - public Long doInRedis(RedisConnection connection) { - return connection.zRem(rawKey, rawValues); - } - }, true); + return execute(connection -> connection.zRem(rawKey, rawValues), true); } - public Long removeRange(K key, final long start, final long end) { - final byte[] rawKey = rawKey(key); - return execute(new RedisCallback() { + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ZSetOperations#removeRange(java.lang.Object, long, long) + */ + @Override + public Long removeRange(K key, long start, long end) { - public Long doInRedis(RedisConnection connection) { - return connection.zRemRange(rawKey, start, end); - } - }, true); + byte[] rawKey = rawKey(key); + return execute(connection -> connection.zRemRange(rawKey, start, end), true); } - public Long removeRangeByScore(K key, final double min, final double max) { - final byte[] rawKey = rawKey(key); - return execute(new RedisCallback() { + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ZSetOperations#removeRangeByScore(java.lang.Object, double, double) + */ + @Override + public Long removeRangeByScore(K key, double min, double max) { - public Long doInRedis(RedisConnection connection) { - return connection.zRemRangeByScore(rawKey, min, max); - } - }, true); + byte[] rawKey = rawKey(key); + return execute(connection -> connection.zRemRangeByScore(rawKey, min, max), true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ZSetOperations#score(java.lang.Object, java.lang.Object) + */ + @Override public Double score(K key, Object o) { - final byte[] rawKey = rawKey(key); - final byte[] rawValue = rawValue(o); - return execute(new RedisCallback() { - - public Double doInRedis(RedisConnection connection) { - return connection.zScore(rawKey, rawValue); - } - }, true); + byte[] rawKey = rawKey(key); + byte[] rawValue = rawValue(o); + return execute(connection -> connection.zScore(rawKey, rawValue), true); } - public Long count(K key, final double min, final double max) { - final byte[] rawKey = rawKey(key); + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ZSetOperations#count(java.lang.Object, double, double) + */ + @Override + public Long count(K key, double min, double max) { - return execute(new RedisCallback() { - - public Long doInRedis(RedisConnection connection) { - return connection.zCount(rawKey, min, max); - } - }, true); + byte[] rawKey = rawKey(key); + return execute(connection -> connection.zCount(rawKey, min, max), true); } /* @@ -377,28 +381,29 @@ class DefaultZSetOperations extends AbstractOperations implements ZS @Override public Long zCard(K key) { - final byte[] rawKey = rawKey(key); - return execute(new RedisCallback() { - - public Long doInRedis(RedisConnection connection) { - return connection.zCard(rawKey); - } - }, true); + byte[] rawKey = rawKey(key); + return execute(connection -> connection.zCard(rawKey), true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ZSetOperations#unionAndStore(java.lang.Object, java.lang.Object, java.lang.Object) + */ + @Override public Long unionAndStore(K key, K otherKey, K destKey) { return unionAndStore(key, Collections.singleton(otherKey), destKey); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.ZSetOperations#unionAndStore(java.lang.Object, java.util.Collection, java.lang.Object) + */ + @Override public Long unionAndStore(K key, Collection otherKeys, K destKey) { - final byte[][] rawKeys = rawKeys(key, otherKeys); - final byte[] rawDestKey = rawKey(destKey); - return execute(new RedisCallback() { - public Long doInRedis(RedisConnection connection) { - return connection.zUnionStore(rawDestKey, rawKeys); - } - }, true); + byte[][] rawKeys = rawKeys(key, otherKeys); + byte[] rawDestKey = rawKey(destKey); + return execute(connection -> connection.zUnionStore(rawDestKey, rawKeys), true); } /* @@ -406,51 +411,24 @@ class DefaultZSetOperations extends AbstractOperations implements ZS * @see org.springframework.data.redis.core.ZSetOperations#scan(java.lang.Object, org.springframework.data.redis.core.ScanOptions) */ @Override - public Cursor> scan(K key, final ScanOptions options) { + public Cursor> scan(K key, ScanOptions options) { - final byte[] rawKey = rawKey(key); - Cursor cursor = template.executeWithStickyConnection(new RedisCallback>() { + byte[] rawKey = rawKey(key); + Cursor cursor = template.executeWithStickyConnection(connection -> connection.zScan(rawKey, options)); - @Override - public Cursor doInRedis(RedisConnection connection) throws DataAccessException { - return connection.zScan(rawKey, options); - } - }); - - return new ConvertingCursor>(cursor, new Converter>() { - - @Override - public TypedTuple convert(Tuple source) { - return deserializeTuple(source); - } - }); + return new ConvertingCursor<>(cursor, this::deserializeTuple); } - public Set rangeByScore(K key, final String min, final String max) { + public Set rangeByScore(K key, String min, String max) { - final byte[] rawKey = rawKey(key); - - Set rawValues = execute(new RedisCallback>() { - - public Set doInRedis(RedisConnection connection) { - return connection.zRangeByScore(rawKey, min, max); - } - }, true); - - return rawValues; + byte[] rawKey = rawKey(key); + return execute(connection -> connection.zRangeByScore(rawKey, min, max), true); } - public Set rangeByScore(K key, final String min, final String max, final long offset, final long count) { + public Set rangeByScore(K key, String min, String max, long offset, long count) { - final byte[] rawKey = rawKey(key); + byte[] rawKey = rawKey(key); - Set rawValues = execute(new RedisCallback>() { - - public Set doInRedis(RedisConnection connection) { - return connection.zRangeByScore(rawKey, min, max, offset, count); - } - }, true); - - return rawValues; + return execute(connection -> connection.zRangeByScore(rawKey, min, max, offset, count), true); } } diff --git a/src/main/java/org/springframework/data/redis/core/PartialUpdate.java b/src/main/java/org/springframework/data/redis/core/PartialUpdate.java index a8913614f..18705df34 100644 --- a/src/main/java/org/springframework/data/redis/core/PartialUpdate.java +++ b/src/main/java/org/springframework/data/redis/core/PartialUpdate.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2016-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,7 +38,7 @@ public class PartialUpdate { private final T value; private boolean refreshTtl = false; - private final List propertyUpdates = new ArrayList(); + private final List propertyUpdates = new ArrayList<>(); private PartialUpdate(Object id, Class target, T value, boolean refreshTtl, List propertyUpdates) { @@ -90,7 +90,7 @@ public class PartialUpdate { * @param targetType must not be {@literal null}. */ public static PartialUpdate newPartialUpdate(Object id, Class targetType) { - return new PartialUpdate(id, targetType); + return new PartialUpdate<>(id, targetType); } /** @@ -111,7 +111,7 @@ public class PartialUpdate { Assert.hasText(path, "Path to set must not be null or empty!"); - PartialUpdate update = new PartialUpdate(this.id, this.target, this.value, this.refreshTtl, + PartialUpdate update = new PartialUpdate<>(this.id, this.target, this.value, this.refreshTtl, this.propertyUpdates); update.propertyUpdates.add(new PropertyUpdate(UpdateCommand.SET, path, value)); @@ -128,7 +128,7 @@ public class PartialUpdate { Assert.hasText(path, "Path to remove must not be null or empty!"); - PartialUpdate update = new PartialUpdate(this.id, this.target, this.value, this.refreshTtl, + PartialUpdate update = new PartialUpdate<>(this.id, this.target, this.value, this.refreshTtl, this.propertyUpdates); update.propertyUpdates.add(new PropertyUpdate(UpdateCommand.DEL, path)); @@ -176,7 +176,7 @@ public class PartialUpdate { * @return a new {@link PartialUpdate}. */ public PartialUpdate refreshTtl(boolean refreshTtl) { - return new PartialUpdate(this.id, this.target, this.value, refreshTtl, this.propertyUpdates); + return new PartialUpdate<>(this.id, this.target, this.value, refreshTtl, this.propertyUpdates); } /** diff --git a/src/main/java/org/springframework/data/redis/core/ReactiveSetOperations.java b/src/main/java/org/springframework/data/redis/core/ReactiveSetOperations.java index 36df4192a..d7f3c6f94 100644 --- a/src/main/java/org/springframework/data/redis/core/ReactiveSetOperations.java +++ b/src/main/java/org/springframework/data/redis/core/ReactiveSetOperations.java @@ -63,7 +63,7 @@ public interface ReactiveSetOperations { * Remove and return {@code count} random members from set at {@code key}. * * @param key must not be {@literal null}. - * @param count nr of members to return + * @param count number of random members to pop from the set. * @return {@link Flux} emitting random members. * @see Redis Documentation: SPOP */ @@ -247,7 +247,7 @@ public interface ReactiveSetOperations { * Get {@code count} distinct random elements from set at {@code key}. * * @param key must not be {@literal null}. - * @param count + * @param count number of members to return. * @return * @see Redis Documentation: SRANDMEMBER */ @@ -257,7 +257,7 @@ public interface ReactiveSetOperations { * Get {@code count} random elements from set at {@code key}. * * @param key must not be {@literal null}. - * @param count + * @param count number of members to return. * @return * @see Redis Documentation: SRANDMEMBER */ diff --git a/src/main/java/org/springframework/data/redis/core/RedisCommand.java b/src/main/java/org/springframework/data/redis/core/RedisCommand.java index 902e7f97e..6606cec24 100644 --- a/src/main/java/org/springframework/data/redis/core/RedisCommand.java +++ b/src/main/java/org/springframework/data/redis/core/RedisCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2017 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. @@ -211,7 +211,7 @@ public enum RedisCommand { private boolean read = true; private boolean write = true; - private Set alias = new HashSet(1); + private Set alias = new HashSet<>(1); private int minArgs = -1; private int maxArgs = -1; @@ -225,7 +225,7 @@ public enum RedisCommand { private static Map buildCommandLookupTable() { RedisCommand[] cmds = RedisCommand.values(); - Map map = new HashMap(cmds.length, 1.0F); + Map map = new HashMap<>(cmds.length, 1.0F); for (RedisCommand cmd : cmds) { @@ -256,7 +256,7 @@ public enum RedisCommand { /** * Creates a new {@link RedisCommand}. - * + * * @param mode * @param minArgs * @param maxArgs @@ -309,7 +309,7 @@ public enum RedisCommand { /** * {@link String#equalsIgnoreCase(String)} compare the given string representation of {@literal command} against the * {@link #toString()} representation of the command as well as its given {@link #alias}. - * + * * @param command * @return true if positive match. */ @@ -328,7 +328,7 @@ public enum RedisCommand { /** * Validates given argument count against expected ones. - * + * * @param nrArguments * @exception IllegalArgumentException in case argument count does not match expected. */ @@ -351,7 +351,7 @@ public enum RedisCommand { /** * Returns the command represented by the given {@code key}. Returns {@link #UNKNOWN} if no matching command could be * found. - * + * * @param key * @return */ diff --git a/src/main/java/org/springframework/data/redis/core/RedisKeyValueAdapter.java b/src/main/java/org/springframework/data/redis/core/RedisKeyValueAdapter.java index fbbaff8c0..7502ebc30 100644 --- a/src/main/java/org/springframework/data/redis/core/RedisKeyValueAdapter.java +++ b/src/main/java/org/springframework/data/redis/core/RedisKeyValueAdapter.java @@ -104,7 +104,7 @@ public class RedisKeyValueAdapter extends AbstractKeyValueAdapter private RedisOperations redisOps; private RedisConverter converter; private RedisMessageListenerContainer messageListenerContainer; - private final AtomicReference expirationListener = new AtomicReference( + private final AtomicReference expirationListener = new AtomicReference<>( null); private ApplicationEventPublisher eventPublisher; diff --git a/src/main/java/org/springframework/data/redis/core/RedisKeyValueTemplate.java b/src/main/java/org/springframework/data/redis/core/RedisKeyValueTemplate.java index 8824eb4bb..18a4fa290 100644 --- a/src/main/java/org/springframework/data/redis/core/RedisKeyValueTemplate.java +++ b/src/main/java/org/springframework/data/redis/core/RedisKeyValueTemplate.java @@ -95,7 +95,7 @@ public class RedisKeyValueTemplate extends KeyValueTemplate { ? (Iterable) callbackResult : Collections.singleton(callbackResult); - List result = new ArrayList(); + List result = new ArrayList<>(); for (Object id : ids) { String idToUse = adapter.getConverter().getConversionService().canConvert(id.getClass(), String.class) diff --git a/src/main/java/org/springframework/data/redis/core/RedisTemplate.java b/src/main/java/org/springframework/data/redis/core/RedisTemplate.java index dddc36126..bf1eaf2e9 100644 --- a/src/main/java/org/springframework/data/redis/core/RedisTemplate.java +++ b/src/main/java/org/springframework/data/redis/core/RedisTemplate.java @@ -1,12 +1,12 @@ /* - * Copyright 2011-2016 the original author or authors. - * + * Copyright 2011-2017 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. @@ -28,12 +28,14 @@ import java.util.Set; import java.util.concurrent.TimeUnit; import org.springframework.beans.factory.BeanClassLoaderAware; -import org.springframework.dao.DataAccessException; import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.data.redis.RedisSystemException; import org.springframework.data.redis.connection.DataType; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.connection.RedisKeyCommands; +import org.springframework.data.redis.connection.RedisServerCommands; +import org.springframework.data.redis.connection.RedisTxCommands; import org.springframework.data.redis.connection.RedisZSetCommands.Tuple; import org.springframework.data.redis.connection.SortParameters; import org.springframework.data.redis.core.ZSetOperations.TypedTuple; @@ -70,7 +72,7 @@ import org.springframework.util.CollectionUtils; * Objects to and from binary data. *

* This is the central class in Redis support. - * + * * @author Costin Leau * @author Christoph Strobl * @author Ninad Divadkar @@ -89,10 +91,10 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation private RedisSerializer defaultSerializer; private ClassLoader classLoader; - private RedisSerializer keySerializer = null; - private RedisSerializer valueSerializer = null; - private RedisSerializer hashKeySerializer = null; - private RedisSerializer hashValueSerializer = null; + @SuppressWarnings("rawtypes") private RedisSerializer keySerializer = null; + @SuppressWarnings("rawtypes") private RedisSerializer valueSerializer = null; + @SuppressWarnings("rawtypes") private RedisSerializer hashKeySerializer = null; + @SuppressWarnings("rawtypes") private RedisSerializer hashValueSerializer = null; private RedisSerializer stringSerializer = new StringRedisSerializer(); private ScriptExecutor scriptExecutor; @@ -110,6 +112,11 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation */ public RedisTemplate() {} + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisAccessor#afterPropertiesSet() + */ + @Override public void afterPropertiesSet() { super.afterPropertiesSet(); @@ -147,19 +154,24 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation } if (scriptExecutor == null) { - this.scriptExecutor = new DefaultScriptExecutor(this); + this.scriptExecutor = new DefaultScriptExecutor<>(this); } initialized = true; } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#execute(org.springframework.data.redis.core.RedisCallback) + */ + @Override public T execute(RedisCallback action) { return execute(action, isExposeConnection()); } /** * Executes the given action object within a connection, which can be exposed or not. - * + * * @param return type * @param action callback object that specifies the Redis action * @param exposeConnection whether to enforce exposure of the native Redis Connection to callback code @@ -172,7 +184,7 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation /** * Executes the given action object within a connection that can be exposed or not. Additionally, the connection can * be pipelined. Note the results of the pipeline are discarded (making it suitable for write-only scenarios). - * + * * @param return type * @param action callback object to execute * @param exposeConnection whether to enforce exposure of the native Redis Connection to callback code @@ -180,6 +192,7 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation * @return object returned by the action */ public T execute(RedisCallback action, boolean exposeConnection, boolean pipeline) { + Assert.isTrue(initialized, "template not initialized; call afterPropertiesSet() before using it"); Assert.notNull(action, "Callback object must not be null"); @@ -218,7 +231,13 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation } } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#execute(org.springframework.data.redis.core.SessionCallback) + */ + @Override public T execute(SessionCallback session) { + Assert.isTrue(initialized, "template not initialized; call afterPropertiesSet() before using it"); Assert.notNull(session, "Callback object must not be null"); @@ -232,11 +251,22 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation } } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#executePipelined(org.springframework.data.redis.core.SessionCallback) + */ + @Override public List executePipelined(final SessionCallback session) { return executePipelined(session, valueSerializer); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#executePipelined(org.springframework.data.redis.core.SessionCallback, org.springframework.data.redis.serializer.RedisSerializer) + */ + @Override public List executePipelined(final SessionCallback session, final RedisSerializer resultSerializer) { + Assert.isTrue(initialized, "template not initialized; call afterPropertiesSet() before using it"); Assert.notNull(session, "Callback object must not be null"); @@ -244,42 +274,11 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation // bind connection RedisConnectionUtils.bindConnection(factory, enableTransactionSupport); try { - return execute(new RedisCallback>() { - public List doInRedis(RedisConnection connection) throws DataAccessException { - connection.openPipeline(); - boolean pipelinedClosed = false; - try { - Object result = executeSession(session); - if (result != null) { - throw new InvalidDataAccessApiUsageException( - "Callback cannot return a non-null value as it gets overwritten by the pipeline"); - } - List closePipeline = connection.closePipeline(); - pipelinedClosed = true; - return deserializeMixedResults(closePipeline, resultSerializer, hashKeySerializer, hashValueSerializer); - } finally { - if (!pipelinedClosed) { - connection.closePipeline(); - } - } - } - }); - } finally { - RedisConnectionUtils.unbindConnection(factory); - } - } - - public List executePipelined(final RedisCallback action) { - return executePipelined(action, valueSerializer); - } - - public List executePipelined(final RedisCallback action, final RedisSerializer resultSerializer) { - return execute(new RedisCallback>() { - public List doInRedis(RedisConnection connection) throws DataAccessException { + return execute((RedisCallback>) connection -> { connection.openPipeline(); boolean pipelinedClosed = false; try { - Object result = action.doInRedis(connection); + Object result = executeSession(session); if (result != null) { throw new InvalidDataAccessApiUsageException( "Callback cannot return a non-null value as it gets overwritten by the pipeline"); @@ -292,14 +291,62 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation connection.closePipeline(); } } + }); + } finally { + RedisConnectionUtils.unbindConnection(factory); + } + } + + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#executePipelined(org.springframework.data.redis.core.RedisCallback) + */ + @Override + public List executePipelined(final RedisCallback action) { + return executePipelined(action, valueSerializer); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#executePipelined(org.springframework.data.redis.core.RedisCallback, org.springframework.data.redis.serializer.RedisSerializer) + */ + @Override + public List executePipelined(final RedisCallback action, final RedisSerializer resultSerializer) { + + return execute((RedisCallback>) connection -> { + connection.openPipeline(); + boolean pipelinedClosed = false; + try { + Object result = action.doInRedis(connection); + if (result != null) { + throw new InvalidDataAccessApiUsageException( + "Callback cannot return a non-null value as it gets overwritten by the pipeline"); + } + List closePipeline = connection.closePipeline(); + pipelinedClosed = true; + return deserializeMixedResults(closePipeline, resultSerializer, hashKeySerializer, hashValueSerializer); + } finally { + if (!pipelinedClosed) { + connection.closePipeline(); + } } }); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#execute(org.springframework.data.redis.core.script.RedisScript, java.util.List, java.lang.Object[]) + */ + @Override public T execute(RedisScript script, List keys, Object... args) { return scriptExecutor.execute(script, keys, args); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#execute(org.springframework.data.redis.core.script.RedisScript, org.springframework.data.redis.serializer.RedisSerializer, org.springframework.data.redis.serializer.RedisSerializer, java.util.List, java.lang.Object[]) + */ + @Override public T execute(RedisScript script, RedisSerializer argsSerializer, RedisSerializer resultSerializer, List keys, Object... args) { return scriptExecutor.execute(script, argsSerializer, resultSerializer, keys, args); @@ -309,6 +356,7 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation * (non-Javadoc) * @see org.springframework.data.redis.core.RedisOperations#executeWithStickyConnection(org.springframework.data.redis.core.RedisCallback) */ + @Override public T executeWithStickyConnection(RedisCallback callback) { Assert.isTrue(initialized, "template not initialized; call afterPropertiesSet() before using it"); @@ -335,7 +383,7 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation /** * Processes the connection (before any settings are executed on it). Default implementation returns the connection as * is. - * + * * @param connection redis connection */ protected RedisConnection preProcessConnection(RedisConnection connection, boolean existingConnection) { @@ -349,7 +397,7 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation /** * Returns whether to expose the native Redis connection to RedisCallback code, or rather a connection proxy (the * default). - * + * * @return whether to expose the native Redis connection or not */ public boolean isExposeConnection() { @@ -359,7 +407,7 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation /** * Sets whether to expose the Redis connection to {@link RedisCallback} code. Default is "false": a proxy will be * returned, suppressing quit and disconnect calls. - * + * * @param exposeConnection */ public void setExposeConnection(boolean exposeConnection) { @@ -384,7 +432,7 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation /** * Returns the default serializer used by this template. - * + * * @return template default serializer */ public RedisSerializer getDefaultSerializer() { @@ -395,7 +443,7 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation * Sets the default serializer to use for this template. All serializers (expect the * {@link #setStringSerializer(RedisSerializer)}) are initialized to this value unless explicitly set. Defaults to * {@link JdkSerializationRedisSerializer}. - * + * * @param serializer default serializer to use */ public void setDefaultSerializer(RedisSerializer serializer) { @@ -404,7 +452,7 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation /** * Sets the key serializer to be used by this template. Defaults to {@link #getDefaultSerializer()}. - * + * * @param serializer the key serializer to be used by this template. */ public void setKeySerializer(RedisSerializer serializer) { @@ -413,16 +461,17 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation /** * Returns the key serializer used by this template. - * + * * @return the key serializer used by this template. */ + @Override public RedisSerializer getKeySerializer() { return keySerializer; } /** * Sets the value serializer to be used by this template. Defaults to {@link #getDefaultSerializer()}. - * + * * @param serializer the value serializer to be used by this template. */ public void setValueSerializer(RedisSerializer serializer) { @@ -431,25 +480,27 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation /** * Returns the value serializer used by this template. - * + * * @return the value serializer used by this template. */ + @Override public RedisSerializer getValueSerializer() { return valueSerializer; } /** * Returns the hashKeySerializer. - * + * * @return Returns the hashKeySerializer */ + @Override public RedisSerializer getHashKeySerializer() { return hashKeySerializer; } /** * Sets the hash key (or field) serializer to be used by this template. Defaults to {@link #getDefaultSerializer()}. - * + * * @param hashKeySerializer The hashKeySerializer to set. */ public void setHashKeySerializer(RedisSerializer hashKeySerializer) { @@ -458,16 +509,17 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation /** * Returns the hashValueSerializer. - * + * * @return Returns the hashValueSerializer */ + @Override public RedisSerializer getHashValueSerializer() { return hashValueSerializer; } /** * Sets the hash value serializer to be used by this template. Defaults to {@link #getDefaultSerializer()}. - * + * * @param hashValueSerializer The hashValueSerializer to set. */ public void setHashValueSerializer(RedisSerializer hashValueSerializer) { @@ -476,7 +528,7 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation /** * Returns the stringSerializer. - * + * * @return Returns the stringSerializer */ public RedisSerializer getStringSerializer() { @@ -486,7 +538,7 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation /** * Sets the string value serializer to be used by this template (when the arguments or return types are always * strings). Defaults to {@link StringRedisSerializer}. - * + * * @see ValueOperations#get(Object, long, long) * @param stringSerializer The stringValueSerializer to set. */ @@ -541,11 +593,14 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation @SuppressWarnings({ "unchecked", "rawtypes" }) private List deserializeMixedResults(List rawValues, RedisSerializer valueSerializer, RedisSerializer hashKeySerializer, RedisSerializer hashValueSerializer) { + if (rawValues == null) { return null; } - List values = new ArrayList(); + + List values = new ArrayList<>(); for (Object rawValue : rawValues) { + if (rawValue instanceof byte[] && valueSerializer != null) { values.add(valueSerializer.deserialize((byte[]) rawValue)); } else if (rawValue instanceof List) { @@ -560,17 +615,21 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation values.add(rawValue); } } + return values; } @SuppressWarnings({ "rawtypes", "unchecked" }) private Set deserializeSet(Set rawSet, RedisSerializer valueSerializer) { + if (rawSet.isEmpty()) { return rawSet; } + Object setValue = rawSet.iterator().next(); + if (setValue instanceof byte[] && valueSerializer != null) { - return (SerializationUtils.deserialize((Set) rawSet, valueSerializer)); + return (SerializationUtils.deserialize(rawSet, valueSerializer)); } else if (setValue instanceof Tuple) { return convertTupleValues(rawSet, valueSerializer); } else { @@ -580,7 +639,8 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation @SuppressWarnings({ "unchecked", "rawtypes" }) private Set> convertTupleValues(Set rawValues, RedisSerializer valueSerializer) { - Set> set = new LinkedHashSet>(rawValues.size()); + + Set> set = new LinkedHashSet<>(rawValues.size()); for (Tuple rawValue : rawValues) { Object value = rawValue.getValue(); if (valueSerializer != null) { @@ -600,10 +660,12 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation * Collections or Maps of byte[]s or Tuples. Other result types (Long, Boolean, etc) are left as-is in the converted * results. If conversion of tx results has been disabled in the {@link RedisConnectionFactory}, the results of exec * will be returned without deserialization. This check is mostly for backwards compatibility with 1.0. - * + * * @return The (possibly deserialized) results of transaction exec */ + @Override public List exec() { + List results = execRaw(); if (getConnectionFactory().getConvertPipelineAndTxResults()) { return deserializeMixedResults(results, valueSerializer, hashKeySerializer, hashValueSerializer); @@ -612,101 +674,118 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation } } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#exec(org.springframework.data.redis.serializer.RedisSerializer) + */ + @Override public List exec(RedisSerializer valueSerializer) { return deserializeMixedResults(execRaw(), valueSerializer, valueSerializer, valueSerializer); } protected List execRaw() { - return execute(new RedisCallback>() { - public List doInRedis(RedisConnection connection) throws DataAccessException { - return connection.exec(); - } - }); + return execute(RedisTxCommands::exec); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#delete(java.lang.Object) + */ + @Override public void delete(K key) { - final byte[] rawKey = rawKey(key); - execute(new RedisCallback() { + byte[] rawKey = rawKey(key); - public Object doInRedis(RedisConnection connection) { - connection.del(rawKey); - return null; - } + execute(connection -> { + connection.del(rawKey); + return null; }, true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#delete(java.util.Collection) + */ + @Override public void delete(Collection keys) { + if (CollectionUtils.isEmpty(keys)) { return; } - final byte[][] rawKeys = rawKeys(keys); + byte[][] rawKeys = rawKeys(keys); - execute(new RedisCallback() { - - public Object doInRedis(RedisConnection connection) { - connection.del(rawKeys); - return null; - } + execute(connection -> { + connection.del(rawKeys); + return null; }, true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#hasKey(java.lang.Object) + */ + @Override public Boolean hasKey(K key) { - final byte[] rawKey = rawKey(key); - return execute(new RedisCallback() { + byte[] rawKey = rawKey(key); - public Boolean doInRedis(RedisConnection connection) { - return connection.exists(rawKey); - } - }, true); + return execute(connection -> connection.exists(rawKey), true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#expire(java.lang.Object, long, java.util.concurrent.TimeUnit) + */ + @Override public Boolean expire(K key, final long timeout, final TimeUnit unit) { - final byte[] rawKey = rawKey(key); - final long rawTimeout = TimeoutUtils.toMillis(timeout, unit); - return execute(new RedisCallback() { + byte[] rawKey = rawKey(key); + long rawTimeout = TimeoutUtils.toMillis(timeout, unit); - public Boolean doInRedis(RedisConnection connection) { - try { - return connection.pExpire(rawKey, rawTimeout); - } catch (Exception e) { - // Driver may not support pExpire or we may be running on Redis 2.4 - return connection.expire(rawKey, TimeoutUtils.toSeconds(timeout, unit)); - } + return execute(connection -> { + try { + return connection.pExpire(rawKey, rawTimeout); + } catch (Exception e) { + // Driver may not support pExpire or we may be running on Redis 2.4 + return connection.expire(rawKey, TimeoutUtils.toSeconds(timeout, unit)); } }, true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#expireAt(java.lang.Object, java.util.Date) + */ + @Override public Boolean expireAt(K key, final Date date) { - final byte[] rawKey = rawKey(key); - return execute(new RedisCallback() { + byte[] rawKey = rawKey(key); - public Boolean doInRedis(RedisConnection connection) { - try { - return connection.pExpireAt(rawKey, date.getTime()); - } catch (Exception e) { - return connection.expireAt(rawKey, date.getTime() / 1000); - } + return execute(connection -> { + try { + return connection.pExpireAt(rawKey, date.getTime()); + } catch (Exception e) { + return connection.expireAt(rawKey, date.getTime() / 1000); } }, true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#convertAndSend(java.lang.String, java.lang.Object) + */ + @Override public void convertAndSend(String channel, Object message) { + Assert.hasText(channel, "a non-empty channel is required"); - final byte[] rawChannel = rawString(channel); - final byte[] rawMessage = rawValue(message); + byte[] rawChannel = rawString(channel); + byte[] rawMessage = rawValue(message); - execute(new RedisCallback() { - - public Object doInRedis(RedisConnection connection) { - connection.publish(rawChannel, rawMessage); - return null; - } + execute(connection -> { + connection.publish(rawChannel, rawMessage); + return null; }, true); } @@ -714,237 +793,270 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation // Value operations // + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#getExpire(java.lang.Object) + */ + @Override public Long getExpire(K key) { - final byte[] rawKey = rawKey(key); - return execute(new RedisCallback() { - - public Long doInRedis(RedisConnection connection) { - return connection.ttl(rawKey); - } - }, true); + byte[] rawKey = rawKey(key); + return execute(connection -> connection.ttl(rawKey), true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#getExpire(java.lang.Object, java.util.concurrent.TimeUnit) + */ + @Override public Long getExpire(K key, final TimeUnit timeUnit) { - final byte[] rawKey = rawKey(key); - return execute(new RedisCallback() { - - public Long doInRedis(RedisConnection connection) { - try { - return connection.pTtl(rawKey, timeUnit); - } catch (Exception e) { - // Driver may not support pTtl or we may be running on Redis 2.4 - return connection.ttl(rawKey, timeUnit); - } + byte[] rawKey = rawKey(key); + return execute(connection -> { + try { + return connection.pTtl(rawKey, timeUnit); + } catch (Exception e) { + // Driver may not support pTtl or we may be running on Redis 2.4 + return connection.ttl(rawKey, timeUnit); } }, true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#keys(java.lang.Object) + */ + @Override @SuppressWarnings("unchecked") public Set keys(K pattern) { - final byte[] rawKey = rawKey(pattern); - Set rawKeys = execute(new RedisCallback>() { - - public Set doInRedis(RedisConnection connection) { - return connection.keys(rawKey); - } - }, true); + byte[] rawKey = rawKey(pattern); + Set rawKeys = execute(connection -> connection.keys(rawKey), true); return keySerializer != null ? SerializationUtils.deserialize(rawKeys, keySerializer) : (Set) rawKeys; } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#persist(java.lang.Object) + */ + @Override public Boolean persist(K key) { - final byte[] rawKey = rawKey(key); - return execute(new RedisCallback() { - - public Boolean doInRedis(RedisConnection connection) { - return connection.persist(rawKey); - } - }, true); + byte[] rawKey = rawKey(key); + return execute(connection -> connection.persist(rawKey), true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#move(java.lang.Object, int) + */ + @Override public Boolean move(K key, final int dbIndex) { - final byte[] rawKey = rawKey(key); - return execute(new RedisCallback() { - - public Boolean doInRedis(RedisConnection connection) { - return connection.move(rawKey, dbIndex); - } - }, true); + byte[] rawKey = rawKey(key); + return execute(connection -> connection.move(rawKey, dbIndex), true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#randomKey() + */ + @Override public K randomKey() { - byte[] rawKey = execute(new RedisCallback() { - - public byte[] doInRedis(RedisConnection connection) { - return connection.randomKey(); - } - }, true); + byte[] rawKey = execute(RedisKeyCommands::randomKey, true); return deserializeKey(rawKey); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#rename(java.lang.Object, java.lang.Object) + */ + @Override public void rename(K oldKey, K newKey) { - final byte[] rawOldKey = rawKey(oldKey); - final byte[] rawNewKey = rawKey(newKey); - execute(new RedisCallback() { + byte[] rawOldKey = rawKey(oldKey); + byte[] rawNewKey = rawKey(newKey); - public Object doInRedis(RedisConnection connection) { - connection.rename(rawOldKey, rawNewKey); - return null; - } + execute(connection -> { + connection.rename(rawOldKey, rawNewKey); + return null; }, true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#renameIfAbsent(java.lang.Object, java.lang.Object) + */ + @Override public Boolean renameIfAbsent(K oldKey, K newKey) { - final byte[] rawOldKey = rawKey(oldKey); - final byte[] rawNewKey = rawKey(newKey); - return execute(new RedisCallback() { - - public Boolean doInRedis(RedisConnection connection) { - return connection.renameNX(rawOldKey, rawNewKey); - } - }, true); + byte[] rawOldKey = rawKey(oldKey); + byte[] rawNewKey = rawKey(newKey); + return execute(connection -> connection.renameNX(rawOldKey, rawNewKey), true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#type(java.lang.Object) + */ + @Override public DataType type(K key) { - final byte[] rawKey = rawKey(key); - return execute(new RedisCallback() { - - public DataType doInRedis(RedisConnection connection) { - return connection.type(rawKey); - } - }, true); + byte[] rawKey = rawKey(key); + return execute(connection -> connection.type(rawKey), true); } /** * Executes the Redis dump command and returns the results. Redis uses a non-standard serialization mechanism and * includes checksum information, thus the raw bytes are returned as opposed to deserializing with valueSerializer. * Use the return value of dump as the value argument to restore - * + * * @param key The key to dump * @return results The results of the dump operation */ + @Override public byte[] dump(K key) { - final byte[] rawKey = rawKey(key); - return execute(new RedisCallback() { - public byte[] doInRedis(RedisConnection connection) { - return connection.dump(rawKey); - } - }, true); + byte[] rawKey = rawKey(key); + return execute(connection -> connection.dump(rawKey), true); } /** * Executes the Redis restore command. The value passed in should be the exact serialized data returned from * {@link #dump(Object)}, since Redis uses a non-standard serialization mechanism. - * + * * @param key The key to restore * @param value The value to restore, as returned by {@link #dump(Object)} * @param timeToLive An expiration for the restored key, or 0 for no expiration * @param unit The time unit for timeToLive * @throws RedisSystemException if the key you are attempting to restore already exists. */ + @Override public void restore(K key, final byte[] value, long timeToLive, TimeUnit unit) { - final byte[] rawKey = rawKey(key); - final long rawTimeout = TimeoutUtils.toMillis(timeToLive, unit); - execute(new RedisCallback() { - public Boolean doInRedis(RedisConnection connection) { - connection.restore(rawKey, rawTimeout, value); - return null; - } + byte[] rawKey = rawKey(key); + long rawTimeout = TimeoutUtils.toMillis(timeToLive, unit); + + execute(connection -> { + connection.restore(rawKey, rawTimeout, value); + return null; }, true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#multi() + */ + @Override public void multi() { - execute(new RedisCallback() { - - public Object doInRedis(RedisConnection connection) throws DataAccessException { - connection.multi(); - return null; - } + execute(connection -> { + connection.multi(); + return null; }, true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#discard() + */ + @Override public void discard() { - execute(new RedisCallback() { - public Object doInRedis(RedisConnection connection) throws DataAccessException { - connection.discard(); - return null; - } + execute(connection -> { + connection.discard(); + return null; }, true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#watch(java.lang.Object) + */ + @Override public void watch(K key) { - final byte[] rawKey = rawKey(key); - execute(new RedisCallback() { + byte[] rawKey = rawKey(key); - public Object doInRedis(RedisConnection connection) { - connection.watch(rawKey); - return null; - } + execute(connection -> { + connection.watch(rawKey); + return null; }, true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#watch(java.util.Collection) + */ + @Override public void watch(Collection keys) { - final byte[][] rawKeys = rawKeys(keys); - execute(new RedisCallback() { + byte[][] rawKeys = rawKeys(keys); - public Object doInRedis(RedisConnection connection) { - connection.watch(rawKeys); - return null; - } + execute(connection -> { + connection.watch(rawKeys); + return null; }, true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#unwatch() + */ + @Override public void unwatch() { - execute(new RedisCallback() { - public Object doInRedis(RedisConnection connection) throws DataAccessException { - connection.unwatch(); - return null; - } + execute(connection -> { + connection.unwatch(); + return null; }, true); } // Sort operations + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#sort(org.springframework.data.redis.core.query.SortQuery) + */ + @Override @SuppressWarnings("unchecked") public List sort(SortQuery query) { return sort(query, valueSerializer); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#sort(org.springframework.data.redis.core.query.SortQuery, org.springframework.data.redis.serializer.RedisSerializer) + */ + @Override public List sort(SortQuery query, RedisSerializer resultSerializer) { - final byte[] rawKey = rawKey(query.getKey()); - final SortParameters params = QueryUtils.convertQuery(query, stringSerializer); - List vals = execute(new RedisCallback>() { + byte[] rawKey = rawKey(query.getKey()); + SortParameters params = QueryUtils.convertQuery(query, stringSerializer); - public List doInRedis(RedisConnection connection) throws DataAccessException { - return connection.sort(rawKey, params); - } - }, true); + List vals = execute(connection -> connection.sort(rawKey, params), true); return SerializationUtils.deserialize(vals, resultSerializer); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#sort(org.springframework.data.redis.core.query.SortQuery, org.springframework.data.redis.core.BulkMapper) + */ + @Override @SuppressWarnings("unchecked") public List sort(SortQuery query, BulkMapper bulkMapper) { return sort(query, bulkMapper, valueSerializer); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#sort(org.springframework.data.redis.core.query.SortQuery, org.springframework.data.redis.core.BulkMapper, org.springframework.data.redis.serializer.RedisSerializer) + */ + @Override public List sort(SortQuery query, BulkMapper bulkMapper, RedisSerializer resultSerializer) { + List values = sort(query, resultSerializer); if (values == null || values.isEmpty()) { @@ -952,75 +1064,120 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation } int bulkSize = query.getGetPattern().size(); - List result = new ArrayList(values.size() / bulkSize + 1); + List result = new ArrayList<>(values.size() / bulkSize + 1); - List bulk = new ArrayList(bulkSize); + List bulk = new ArrayList<>(bulkSize); for (S s : values) { bulk.add(s); if (bulk.size() == bulkSize) { result.add(bulkMapper.mapBulk(Collections.unmodifiableList(bulk))); // create a new list (we could reuse the old one but the client might hang on to it for some reason) - bulk = new ArrayList(bulkSize); + bulk = new ArrayList<>(bulkSize); } } return result; } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#sort(org.springframework.data.redis.core.query.SortQuery, java.lang.Object) + */ + @Override public Long sort(SortQuery query, K storeKey) { - final byte[] rawStoreKey = rawKey(storeKey); - final byte[] rawKey = rawKey(query.getKey()); - final SortParameters params = QueryUtils.convertQuery(query, stringSerializer); - return execute(new RedisCallback() { + byte[] rawStoreKey = rawKey(storeKey); + byte[] rawKey = rawKey(query.getKey()); + SortParameters params = QueryUtils.convertQuery(query, stringSerializer); - public Long doInRedis(RedisConnection connection) throws DataAccessException { - return connection.sort(rawKey, params, rawStoreKey); - } - }, true); + return execute(connection -> connection.sort(rawKey, params, rawStoreKey), true); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#boundValueOps(java.lang.Object) + */ + @Override public BoundValueOperations boundValueOps(K key) { - return new DefaultBoundValueOperations(key, this); + return new DefaultBoundValueOperations<>(key, this); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#opsForValue() + */ + @Override public ValueOperations opsForValue() { + if (valueOps == null) { - valueOps = new DefaultValueOperations(this); + valueOps = new DefaultValueOperations<>(this); } return valueOps; } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#opsForList() + */ + @Override public ListOperations opsForList() { + if (listOps == null) { - listOps = new DefaultListOperations(this); + listOps = new DefaultListOperations<>(this); } return listOps; } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#boundListOps(java.lang.Object) + */ + @Override public BoundListOperations boundListOps(K key) { - return new DefaultBoundListOperations(key, this); + return new DefaultBoundListOperations<>(key, this); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#boundSetOps(java.lang.Object) + */ + @Override public BoundSetOperations boundSetOps(K key) { - return new DefaultBoundSetOperations(key, this); + return new DefaultBoundSetOperations<>(key, this); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#opsForSet() + */ + @Override public SetOperations opsForSet() { + if (setOps == null) { - setOps = new DefaultSetOperations(this); + setOps = new DefaultSetOperations<>(this); } return setOps; } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#boundZSetOps(java.lang.Object) + */ + @Override public BoundZSetOperations boundZSetOps(K key) { - return new DefaultBoundZSetOperations(key, this); + return new DefaultBoundZSetOperations<>(key, this); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#opsForZSet() + */ + @Override public ZSetOperations opsForZSet() { + if (zSetOps == null) { - zSetOps = new DefaultZSetOperations(this); + zSetOps = new DefaultZSetOperations<>(this); } return zSetOps; } @@ -1033,7 +1190,7 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation public GeoOperations opsForGeo() { if (geoOps == null) { - geoOps = new DefaultGeoOperations(this); + geoOps = new DefaultGeoOperations<>(this); } return geoOps; } @@ -1044,7 +1201,7 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation */ @Override public BoundGeoOperations boundGeoOps(K key) { - return new DefaultBoundGeoOperations(key, this); + return new DefaultBoundGeoOperations<>(key, this); } /* @@ -1055,25 +1212,36 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation public HyperLogLogOperations opsForHyperLogLog() { if (hllOps == null) { - hllOps = new DefaultHyperLogLogOperations(this); + hllOps = new DefaultHyperLogLogOperations<>(this); } return hllOps; } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#boundHashOps(java.lang.Object) + */ + @Override public BoundHashOperations boundHashOps(K key) { - return new DefaultBoundHashOperations(key, this); + return new DefaultBoundHashOperations<>(key, this); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#opsForHash() + */ + @Override public HashOperations opsForHash() { - return new DefaultHashOperations(this); + return new DefaultHashOperations<>(this); } /* * (non-Javadoc) * @see org.springframework.data.redis.core.RedisOperations#opsForCluster() */ + @Override public ClusterOperations opsForCluster() { - return new DefaultClusterOperations(this); + return new DefaultClusterOperations<>(this); } /* @@ -1083,25 +1251,19 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation @Override public void killClient(final String host, final int port) { - execute(new RedisCallback() { - - @Override - public Void doInRedis(RedisConnection connection) throws DataAccessException { - connection.killClient(host, port); - return null; - } + execute((RedisCallback) connection -> { + connection.killClient(host, port); + return null; }); } + /* + * (non-Javadoc) + * @see org.springframework.data.redis.core.RedisOperations#getClientList() + */ @Override public List getClientList() { - return execute(new RedisCallback>() { - - @Override - public List doInRedis(RedisConnection connection) throws DataAccessException { - return connection.getClientList(); - } - }); + return execute(RedisServerCommands::getClientList); } /* @@ -1110,14 +1272,10 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation @Override public void slaveOf(final String host, final int port) { - execute(new RedisCallback() { - @Override - public Void doInRedis(RedisConnection connection) throws DataAccessException { - - connection.slaveOf(host, port); - return null; - } + execute((RedisCallback) connection -> { + connection.slaveOf(host, port); + return null; }); } @@ -1128,19 +1286,15 @@ public class RedisTemplate extends RedisAccessor implements RedisOperation @Override public void slaveOfNoOne() { - execute(new RedisCallback() { - - @Override - public Void doInRedis(RedisConnection connection) throws DataAccessException { - connection.slaveOfNoOne(); - return null; - } + execute((RedisCallback) connection -> { + connection.slaveOfNoOne(); + return null; }); } /** * If set to {@code true} {@link RedisTemplate} will use {@literal MULTI...EXEC|DISCARD} to keep track of operations. - * + * * @param enableTransactionSupport * @since 1.3 */ diff --git a/src/main/java/org/springframework/data/redis/core/ScanIteration.java b/src/main/java/org/springframework/data/redis/core/ScanIteration.java index edbc7e6ca..444fa747d 100644 --- a/src/main/java/org/springframework/data/redis/core/ScanIteration.java +++ b/src/main/java/org/springframework/data/redis/core/ScanIteration.java @@ -1,5 +1,5 @@ /* - * Copyright 2014 the original author or authors. + * Copyright 2014-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +23,7 @@ import java.util.Iterator; /** * {@link ScanIteration} holds the values contained in Redis {@literal Multibulk reply} on exectuting {@literal SCAN} * command. - * + * * @author Christoph Strobl * @since 1.4 */ @@ -39,12 +39,12 @@ public class ScanIteration implements Iterable { public ScanIteration(long cursorId, Collection items) { this.cursorId = cursorId; - this.items = (items != null ? new ArrayList(items) : Collections. emptyList()); + this.items = (items != null ? new ArrayList<>(items) : Collections. emptyList()); } /** * The cursor id to be used for subsequent requests. - * + * * @return */ public long getCursorId() { @@ -53,7 +53,7 @@ public class ScanIteration implements Iterable { /** * Get the items returned. - * + * * @return */ public Collection getItems() { diff --git a/src/main/java/org/springframework/data/redis/core/SetOperations.java b/src/main/java/org/springframework/data/redis/core/SetOperations.java index ce5c9c58e..00c119f43 100644 --- a/src/main/java/org/springframework/data/redis/core/SetOperations.java +++ b/src/main/java/org/springframework/data/redis/core/SetOperations.java @@ -21,7 +21,7 @@ import java.util.Set; /** * Redis set specific operations. - * + * * @author Costin Leau * @author Christoph Strobl * @author Mark Paluch @@ -61,7 +61,7 @@ public interface SetOperations { * Remove and return {@code count} random members from set at {@code key}. * * @param key must not be {@literal null}. - * @param count nr of members to return. + * @param count number of random members to pop from the set. * @return empty {@link List} if key does not exist. Never {@literal null}. * @see Redis Documentation: SPOP * @since 2.0 diff --git a/src/main/java/org/springframework/data/redis/core/convert/BinaryConverters.java b/src/main/java/org/springframework/data/redis/core/convert/BinaryConverters.java index ed6c20d34..efc43ada3 100644 --- a/src/main/java/org/springframework/data/redis/core/convert/BinaryConverters.java +++ b/src/main/java/org/springframework/data/redis/core/convert/BinaryConverters.java @@ -181,7 +181,7 @@ final class BinaryConverters { @Override public Converter getConverter(Class targetType) { - return new BytesToNumberConverter(targetType); + return new BytesToNumberConverter<>(targetType); } private static final class BytesToNumberConverter extends StringBasedConverter @@ -212,8 +212,8 @@ final class BinaryConverters { @WritingConverter static class BooleanToBytesConverter extends StringBasedConverter implements Converter { - final byte[] _true = fromString("1"); - final byte[] _false = fromString("0"); + byte[] _true = fromString("1"); + byte[] _false = fromString("0"); @Override public byte[] convert(Boolean source) { diff --git a/src/main/java/org/springframework/data/redis/core/convert/Bucket.java b/src/main/java/org/springframework/data/redis/core/convert/Bucket.java index 7a928fdd1..0d290ac68 100644 --- a/src/main/java/org/springframework/data/redis/core/convert/Bucket.java +++ b/src/main/java/org/springframework/data/redis/core/convert/Bucket.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2017 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. @@ -31,8 +31,9 @@ import org.springframework.util.StringUtils; /** * Bucket is the data bag for Redis hash structures to be used with {@link RedisData}. - * + * * @author Christoph Strobl + * @author Mark Paluch * @since 1.7 */ public class Bucket { @@ -48,19 +49,19 @@ public class Bucket { * Creates new empty bucket */ public Bucket() { - data = new LinkedHashMap(); + data = new LinkedHashMap<>(); } Bucket(Map data) { Assert.notNull(data, "Inital data must not be null!"); - this.data = new LinkedHashMap(data.size()); + this.data = new LinkedHashMap<>(data.size()); this.data.putAll(data); } /** * Add {@link String} representation of property dot path with given value. - * + * * @param path must not be {@literal null} or {@link String#isEmpty()}. * @param value can be {@literal null}. */ @@ -72,7 +73,7 @@ public class Bucket { /** * Get value assigned with path. - * + * * @param path path must not be {@literal null} or {@link String#isEmpty()}. * @return {@literal null} if not set. */ @@ -84,7 +85,7 @@ public class Bucket { /** * A set view of the mappings contained in this bucket. - * + * * @return never {@literal null}. */ public Set> entrySet() { @@ -121,7 +122,7 @@ public class Bucket { /** * Key/value pairs contained in the {@link Bucket}. - * + * * @return never {@literal null}. */ public Map asMap() { @@ -130,7 +131,7 @@ public class Bucket { /** * Extracts a bucket containing key/value pairs with the {@code prefix}. - * + * * @param prefix * @return */ @@ -148,7 +149,7 @@ public class Bucket { /** * Get all the keys matching a given path. - * + * * @param path the path to look for. Can be {@literal null}. * @return all keys if path is {@null} or empty. */ @@ -160,7 +161,7 @@ public class Bucket { Pattern pattern = Pattern.compile("(" + Pattern.quote(path) + ")\\.\\[.*?\\]"); - Set keys = new LinkedHashSet(); + Set keys = new LinkedHashSet<>(); for (Map.Entry entry : data.entrySet()) { Matcher matcher = pattern.matcher(entry.getKey()); @@ -174,12 +175,12 @@ public class Bucket { /** * Get keys and values in binary format. - * + * * @return never {@literal null}. */ public Map rawMap() { - Map raw = new LinkedHashMap(data.size()); + Map raw = new LinkedHashMap<>(data.size()); for (Map.Entry entry : data.entrySet()) { if (entry.getValue() != null) { raw.put(entry.getKey().getBytes(CHARSET), entry.getValue()); @@ -190,7 +191,7 @@ public class Bucket { /** * Creates a new Bucket from a given raw map. - * + * * @param source can be {@literal null}. * @return never {@literal null}. */ @@ -209,7 +210,7 @@ public class Bucket { /** * Creates a new Bucket from a given {@link String} map. - * + * * @param source can be {@literal null}. * @return never {@literal null}. */ @@ -238,7 +239,7 @@ public class Bucket { private String safeToString() { - Map serialized = new LinkedHashMap(); + Map serialized = new LinkedHashMap<>(); for (Map.Entry entry : data.entrySet()) { if (entry.getValue() != null) { serialized.put(entry.getKey(), toUtf8String(entry.getValue())); diff --git a/src/main/java/org/springframework/data/redis/core/convert/CompositeIndexResolver.java b/src/main/java/org/springframework/data/redis/core/convert/CompositeIndexResolver.java index 7ef63c103..107811b8d 100644 --- a/src/main/java/org/springframework/data/redis/core/convert/CompositeIndexResolver.java +++ b/src/main/java/org/springframework/data/redis/core/convert/CompositeIndexResolver.java @@ -32,7 +32,7 @@ import org.springframework.util.CollectionUtils; *
* NOTE {@link IndexedData} created by an {@link IndexResolver} can be overwritten by subsequent * {@link IndexResolver}. - * + * * @author Christoph Strobl * @since 1.7 */ @@ -42,7 +42,7 @@ public class CompositeIndexResolver implements IndexResolver { /** * Create new {@link CompositeIndexResolver}. - * + * * @param resolvers must not be {@literal null}. */ public CompositeIndexResolver(Collection resolvers) { @@ -51,7 +51,7 @@ public class CompositeIndexResolver implements IndexResolver { if (CollectionUtils.contains(resolvers.iterator(), null)) { throw new IllegalArgumentException("Resolvers must no contain null values"); } - this.resolvers = new ArrayList(resolvers); + this.resolvers = new ArrayList<>(resolvers); } /* @@ -65,7 +65,7 @@ public class CompositeIndexResolver implements IndexResolver { return Collections.emptySet(); } - Set data = new LinkedHashSet(); + Set data = new LinkedHashSet<>(); for (IndexResolver resolver : resolvers) { data.addAll(resolver.resolveIndexesFor(typeInformation, value)); } @@ -79,7 +79,7 @@ public class CompositeIndexResolver implements IndexResolver { public Set resolveIndexesFor(String keyspace, String path, TypeInformation typeInformation, Object value) { - Set data = new LinkedHashSet(); + Set data = new LinkedHashSet<>(); for (IndexResolver resolver : resolvers) { data.addAll(resolver.resolveIndexesFor(keyspace, path, typeInformation, value)); } diff --git a/src/main/java/org/springframework/data/redis/core/convert/Jsr310Converters.java b/src/main/java/org/springframework/data/redis/core/convert/Jsr310Converters.java index dcebe1953..e236cb498 100644 --- a/src/main/java/org/springframework/data/redis/core/convert/Jsr310Converters.java +++ b/src/main/java/org/springframework/data/redis/core/convert/Jsr310Converters.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2016-2017 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. @@ -57,7 +57,7 @@ public abstract class Jsr310Converters { return Collections.emptySet(); } - List> converters = new ArrayList>(); + List> converters = new ArrayList<>(); converters.add(new LocalDateTimeToBytesConverter()); converters.add(new BytesToLocalDateTimeConverter()); converters.add(new LocalDateToBytesConverter()); diff --git a/src/main/java/org/springframework/data/redis/core/convert/KeyspaceConfiguration.java b/src/main/java/org/springframework/data/redis/core/convert/KeyspaceConfiguration.java index dd026fb18..215aa4b9b 100644 --- a/src/main/java/org/springframework/data/redis/core/convert/KeyspaceConfiguration.java +++ b/src/main/java/org/springframework/data/redis/core/convert/KeyspaceConfiguration.java @@ -39,7 +39,7 @@ public class KeyspaceConfiguration { public KeyspaceConfiguration() { - this.settingsMap = new ConcurrentHashMap, KeyspaceSettings>(); + this.settingsMap = new ConcurrentHashMap<>(); for (KeyspaceSettings initial : initialConfiguration()) { settingsMap.put(initial.type, initial); } diff --git a/src/main/java/org/springframework/data/redis/core/convert/MappingRedisConverter.java b/src/main/java/org/springframework/data/redis/core/convert/MappingRedisConverter.java index df94d57aa..d01243700 100644 --- a/src/main/java/org/springframework/data/redis/core/convert/MappingRedisConverter.java +++ b/src/main/java/org/springframework/data/redis/core/convert/MappingRedisConverter.java @@ -44,7 +44,6 @@ import org.springframework.data.convert.TypeAliasAccessor; import org.springframework.data.convert.TypeMapper; import org.springframework.data.keyvalue.core.mapping.KeySpaceResolver; import org.springframework.data.mapping.Alias; -import org.springframework.data.mapping.Association; import org.springframework.data.mapping.AssociationHandler; import org.springframework.data.mapping.MappingException; import org.springframework.data.mapping.PersistentPropertyAccessor; @@ -122,8 +121,8 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean { private final GenericConversionService conversionService; private final EntityInstantiators entityInstantiators; private final TypeMapper typeMapper; - private final Comparator listKeyComparator = new NullSafeComparator( - NaturalOrderingKeyComparator.INSTANCE, true); + private final Comparator listKeyComparator = new NullSafeComparator<>(NaturalOrderingKeyComparator.INSTANCE, + true); private ReferenceResolver referenceResolver; private IndexResolver indexResolver; @@ -155,7 +154,7 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean { this.conversionService = new DefaultConversionService(); this.customConversions = new RedisCustomConversions(); - typeMapper = new DefaultTypeMapper(new RedisTypeAliasAccessor(this.conversionService)); + typeMapper = new DefaultTypeMapper<>(new RedisTypeAliasAccessor(this.conversionService)); this.referenceResolver = referenceResolver; @@ -167,12 +166,12 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean { * @see org.springframework.data.convert.EntityReader#read(java.lang.Class, java.lang.Object) */ @Override - public R read(Class type, final RedisData source) { + public R read(Class type, RedisData source) { return readInternal("", type, source); } @SuppressWarnings("unchecked") - private R readInternal(final String path, Class type, final RedisData source) { + private R readInternal(String path, Class type, RedisData source) { if (source.getBucket() == null || source.getBucket().isEmpty()) { return null; @@ -187,7 +186,7 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean { if (customConversions.hasCustomReadTarget(Map.class, readType.getType())) { - Map partial = new HashMap(); + Map partial = new HashMap<>(); if (!path.isEmpty()) { @@ -217,86 +216,81 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean { new PersistentEntityParameterValueProvider<>(entity, new ConverterAwareParameterValueProvider(path, source, conversionService), this.conversionService)); - final PersistentPropertyAccessor accessor = entity.getPropertyAccessor(instance); + PersistentPropertyAccessor accessor = entity.getPropertyAccessor(instance); - entity.doWithProperties(new PropertyHandler() { + entity.doWithProperties((PropertyHandler) persistentProperty -> { - @Override - public void doWithPersistentProperty(RedisPersistentProperty persistentProperty) { + String currentPath = !path.isEmpty() ? path + "." + persistentProperty.getName() : persistentProperty.getName(); - String currentPath = !path.isEmpty() ? path + "." + persistentProperty.getName() : persistentProperty.getName(); + PreferredConstructor constructor = entity.getPersistenceConstructor(); - PreferredConstructor constructor = entity.getPersistenceConstructor(); + if (constructor.isConstructorParameter(persistentProperty)) { + return; + } - if (constructor.isConstructorParameter(persistentProperty)) { - return; + if (persistentProperty.isMap()) { + + Map targetValue = null; + Class mapValueType = persistentProperty.getMapValueType(); + + if (mapValueType == null) { + throw new IllegalArgumentException("Unable to retrieve MapValueType!"); } - if (persistentProperty.isMap()) { - - Map targetValue = null; - Class mapValueType = persistentProperty.getMapValueType(); - - if (mapValueType == null) { - throw new IllegalArgumentException("Unable to retrieve MapValueType!"); - } - - if (conversionService.canConvert(byte[].class, mapValueType)) { - targetValue = readMapOfSimpleTypes(currentPath, persistentProperty.getType(), - persistentProperty.getComponentType(), mapValueType, source); - } else { - targetValue = readMapOfComplexTypes(currentPath, persistentProperty.getType(), - persistentProperty.getComponentType(), mapValueType, source); - } - - if (targetValue != null) { - accessor.setProperty(persistentProperty, targetValue); - } - } - - else if (persistentProperty.isCollectionLike()) { - - Object targetValue = readCollectionOrArray(currentPath, persistentProperty.getType(), - persistentProperty.getTypeInformation().getRequiredComponentType().getActualType().getType(), - source.getBucket()); - if (targetValue != null) { - accessor.setProperty(persistentProperty, targetValue); - } - - } else if (persistentProperty.isEntity() && !conversionService.canConvert(byte[].class, - persistentProperty.getTypeInformation().getActualType().getType())) { - - Class targetType = (Class) persistentProperty.getTypeInformation().getActualType().getType(); - - Bucket bucket = source.getBucket().extract(currentPath + "."); - - RedisData newBucket = new RedisData(bucket); - - byte[] type = bucket.get(currentPath + "." + TYPE_HINT_ALIAS); - if (type != null && type.length > 0) { - newBucket.getBucket().put(TYPE_HINT_ALIAS, type); - } - - R val = readInternal(currentPath, targetType, newBucket); - - accessor.setProperty(persistentProperty, val); + if (conversionService.canConvert(byte[].class, mapValueType)) { + targetValue = readMapOfSimpleTypes(currentPath, persistentProperty.getType(), + persistentProperty.getComponentType(), mapValueType, source); } else { + targetValue = readMapOfComplexTypes(currentPath, persistentProperty.getType(), + persistentProperty.getComponentType(), mapValueType, source); + } - if (persistentProperty.isIdProperty() && StringUtils.isEmpty(path.isEmpty())) { - - if (source.getBucket().get(currentPath) == null) { - accessor.setProperty(persistentProperty, - fromBytes(source.getBucket().get(currentPath), persistentProperty.getActualType())); - } else { - accessor.setProperty(persistentProperty, source.getId()); - } - } - - Class typeToUse = getTypeHint(currentPath, source.getBucket(), persistentProperty.getActualType()); - accessor.setProperty(persistentProperty, fromBytes(source.getBucket().get(currentPath), typeToUse)); + if (targetValue != null) { + accessor.setProperty(persistentProperty, targetValue); } } + else if (persistentProperty.isCollectionLike()) { + + Object targetValue = readCollectionOrArray(currentPath, persistentProperty.getType(), + persistentProperty.getTypeInformation().getRequiredComponentType().getActualType().getType(), + source.getBucket()); + if (targetValue != null) { + accessor.setProperty(persistentProperty, targetValue); + } + + } else if (persistentProperty.isEntity() && !conversionService.canConvert(byte[].class, + persistentProperty.getTypeInformation().getActualType().getType())) { + + Class targetType = (Class) persistentProperty.getTypeInformation().getActualType().getType(); + + Bucket bucket = source.getBucket().extract(currentPath + "."); + + RedisData newBucket = new RedisData(bucket); + + byte[] type1 = bucket.get(currentPath + "." + TYPE_HINT_ALIAS); + if (type1 != null && type1.length > 0) { + newBucket.getBucket().put(TYPE_HINT_ALIAS, type1); + } + + R val = readInternal(currentPath, targetType, newBucket); + + accessor.setProperty(persistentProperty, val); + } else { + + if (persistentProperty.isIdProperty() && StringUtils.isEmpty(path.isEmpty())) { + + if (source.getBucket().get(currentPath) == null) { + accessor.setProperty(persistentProperty, + fromBytes(source.getBucket().get(currentPath), persistentProperty.getActualType())); + } else { + accessor.setProperty(persistentProperty, source.getId()); + } + } + + Class typeToUse = getTypeHint(currentPath, source.getBucket(), persistentProperty.getActualType()); + accessor.setProperty(persistentProperty, fromBytes(source.getBucket().get(currentPath), typeToUse)); + } }); readAssociation(path, source, entity, accessor); @@ -304,56 +298,52 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean { return (R) instance; } - private void readAssociation(final String path, final RedisData source, final RedisPersistentEntity entity, - final PersistentPropertyAccessor accessor) { + private void readAssociation(String path, RedisData source, RedisPersistentEntity entity, + PersistentPropertyAccessor accessor) { - entity.doWithAssociations(new AssociationHandler() { + entity.doWithAssociations((AssociationHandler) association -> { - @Override - public void doWithAssociation(Association association) { + String currentPath = !path.isEmpty() ? path + "." + association.getInverse().getName() + : association.getInverse().getName(); - String currentPath = !path.isEmpty() ? path + "." + association.getInverse().getName() - : association.getInverse().getName(); + if (association.getInverse().isCollectionLike()) { - if (association.getInverse().isCollectionLike()) { + Bucket bucket = source.getBucket().extract(currentPath + ".["); - Bucket bucket = source.getBucket().extract(currentPath + ".["); + Collection target = CollectionFactory.createCollection(association.getInverse().getType(), + association.getInverse().getComponentType(), bucket.size()); - Collection target = CollectionFactory.createCollection(association.getInverse().getType(), - association.getInverse().getComponentType(), bucket.size()); + for (Entry entry : bucket.entrySet()) { - for (Entry entry : bucket.entrySet()) { - - String referenceKey = fromBytes(entry.getValue(), String.class); - String[] args = referenceKey.split(":"); - - Map rawHash = referenceResolver.resolveReference(args[1], args[0]); - - if (!CollectionUtils.isEmpty(rawHash)) { - target.add(read(association.getInverse().getActualType(), new RedisData(rawHash))); - } - } - - accessor.setProperty(association.getInverse(), target); - - } else { - - byte[] binKey = source.getBucket().get(currentPath); - if (binKey == null || binKey.length == 0) { - return; - } - - String key = fromBytes(binKey, String.class); - - String[] args = key.split(":"); + String referenceKey = fromBytes(entry.getValue(), String.class); + String[] args = referenceKey.split(":"); Map rawHash = referenceResolver.resolveReference(args[1], args[0]); if (!CollectionUtils.isEmpty(rawHash)) { - accessor.setProperty(association.getInverse(), - read(association.getInverse().getActualType(), new RedisData(rawHash))); + target.add(read(association.getInverse().getActualType(), new RedisData(rawHash))); } } + + accessor.setProperty(association.getInverse(), target); + + } else { + + byte[] binKey = source.getBucket().get(currentPath); + if (binKey == null || binKey.length == 0) { + return; + } + + String key = fromBytes(binKey, String.class); + + String[] args = key.split(":"); + + Map rawHash = referenceResolver.resolveReference(args[1], args[0]); + + if (!CollectionUtils.isEmpty(rawHash)) { + accessor.setProperty(association.getInverse(), + read(association.getInverse().getActualType(), new RedisData(rawHash))); + } } }); } @@ -364,7 +354,7 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean { */ @Override @SuppressWarnings({ "rawtypes" }) - public void write(Object source, final RedisData sink) { + public void write(Object source, RedisData sink) { if (source == null) { return; @@ -452,10 +442,9 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean { targetProperty = getTargetPropertyOrNullForPath(path.replaceAll("\\.\\[.*\\]", ""), update.getTarget()); TypeInformation ti = targetProperty == null ? ClassTypeInformation.OBJECT - : (targetProperty.isMap() - ? (targetProperty.getTypeInformation().getMapValueType() != null - ? targetProperty.getTypeInformation().getRequiredMapValueType() : ClassTypeInformation.OBJECT) - : targetProperty.getTypeInformation().getActualType()); + : (targetProperty.isMap() ? (targetProperty.getTypeInformation().getMapValueType() != null + ? targetProperty.getTypeInformation().getRequiredMapValueType() + : ClassTypeInformation.OBJECT) : targetProperty.getTypeInformation().getActualType()); writeInternal(entity.getKeySpace(), pUpdate.getPropertyPath(), pUpdate.getValue(), ti, sink); return; @@ -495,7 +484,7 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean { targetProperty.getTypeInformation().getActualType(), sink); } else if (targetProperty.isMap()) { - Map map = new HashMap(); + Map map = new HashMap<>(); if (pUpdate.getValue() instanceof Map) { map.putAll((Map) pUpdate.getValue()); @@ -547,8 +536,7 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean { * @param typeHint * @param sink */ - private void writeInternal(final String keyspace, final String path, final Object value, TypeInformation typeHint, - final RedisData sink) { + private void writeInternal(String keyspace, String path, Object value, TypeInformation typeHint, RedisData sink) { if (value == null) { return; @@ -574,63 +562,58 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean { toBytes(value.getClass().getName())); } - final RedisPersistentEntity entity = mappingContext.getRequiredPersistentEntity(value.getClass()); - final PersistentPropertyAccessor accessor = entity.getPropertyAccessor(value); + RedisPersistentEntity entity = mappingContext.getRequiredPersistentEntity(value.getClass()); + PersistentPropertyAccessor accessor = entity.getPropertyAccessor(value); - entity.doWithProperties(new PropertyHandler() { + entity.doWithProperties((PropertyHandler) persistentProperty -> { - @Override - public void doWithPersistentProperty(RedisPersistentProperty persistentProperty) { + String propertyStringPath = (!path.isEmpty() ? path + "." : "") + persistentProperty.getName(); - String propertyStringPath = (!path.isEmpty() ? path + "." : "") + persistentProperty.getName(); + Object propertyValue = accessor.getProperty(persistentProperty); + if (persistentProperty.isIdProperty()) { - Object propertyValue = accessor.getProperty(persistentProperty); - if (persistentProperty.isIdProperty()) { - - if (propertyValue != null) { - sink.getBucket().put(propertyStringPath, toBytes(propertyValue)); - } - return; + if (propertyValue != null) { + sink.getBucket().put(propertyStringPath, toBytes(propertyValue)); } + return; + } - if (persistentProperty.isMap()) { + if (persistentProperty.isMap()) { - if (propertyValue != null) { - writeMap(keyspace, propertyStringPath, persistentProperty.getMapValueType(), (Map) propertyValue, - sink); - } - } else if (persistentProperty.isCollectionLike()) { + if (propertyValue != null) { + writeMap(keyspace, propertyStringPath, persistentProperty.getMapValueType(), (Map) propertyValue, sink); + } + } else if (persistentProperty.isCollectionLike()) { - if (propertyValue == null) { - writeCollection(keyspace, propertyStringPath, (Iterable) null, + if (propertyValue == null) { + writeCollection(keyspace, propertyStringPath, (Iterable) null, + persistentProperty.getTypeInformation().getRequiredComponentType(), sink); + } else { + + if (Iterable.class.isAssignableFrom(propertyValue.getClass())) { + + writeCollection(keyspace, propertyStringPath, (Iterable) propertyValue, + persistentProperty.getTypeInformation().getRequiredComponentType(), sink); + } else if (propertyValue.getClass().isArray()) { + + writeCollection(keyspace, propertyStringPath, CollectionUtils.arrayToList(propertyValue), persistentProperty.getTypeInformation().getRequiredComponentType(), sink); } else { - if (Iterable.class.isAssignableFrom(propertyValue.getClass())) { - - writeCollection(keyspace, propertyStringPath, (Iterable) propertyValue, - persistentProperty.getTypeInformation().getRequiredComponentType(), sink); - } else if (propertyValue.getClass().isArray()) { - - writeCollection(keyspace, propertyStringPath, CollectionUtils.arrayToList(propertyValue), - persistentProperty.getTypeInformation().getRequiredComponentType(), sink); - } else { - - throw new RuntimeException("Don't know how to handle " + propertyValue.getClass() + " type collection"); - } + throw new RuntimeException("Don't know how to handle " + propertyValue.getClass() + " type collection"); } + } - } else if (persistentProperty.isEntity()) { + } else if (persistentProperty.isEntity()) { - if (propertyValue != null) { - writeInternal(keyspace, propertyStringPath, propertyValue, - persistentProperty.getTypeInformation().getActualType(), sink); - } - } else { + if (propertyValue != null) { + writeInternal(keyspace, propertyStringPath, propertyValue, + persistentProperty.getTypeInformation().getActualType(), sink); + } + } else { - if (propertyValue != null) { - writeToBucket(propertyStringPath, propertyValue, sink, persistentProperty.getType()); - } + if (propertyValue != null) { + writeToBucket(propertyStringPath, propertyValue, sink, persistentProperty.getType()); } } }); @@ -638,55 +621,50 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean { writeAssociation(path, entity, value, sink); } - private void writeAssociation(final String path, final RedisPersistentEntity entity, final Object value, - final RedisData sink) { + private void writeAssociation(String path, RedisPersistentEntity entity, Object value, RedisData sink) { if (value == null) { return; } - final PersistentPropertyAccessor accessor = entity.getPropertyAccessor(value); + PersistentPropertyAccessor accessor = entity.getPropertyAccessor(value); - entity.doWithAssociations(new AssociationHandler() { + entity.doWithAssociations((AssociationHandler) association -> { - @Override - public void doWithAssociation(Association association) { + Object refObject = accessor.getProperty(association.getInverse()); + if (refObject == null) { + return; + } - Object refObject = accessor.getProperty(association.getInverse()); - if (refObject == null) { - return; + if (association.getInverse().isCollectionLike()) { + + RedisPersistentEntity ref = mappingContext.getRequiredPersistentEntity( + association.getInverse().getTypeInformation().getRequiredComponentType().getActualType()); + + String keyspace = ref.getKeySpace(); + String propertyStringPath = (!path.isEmpty() ? path + "." : "") + association.getInverse().getName(); + + int i = 0; + for (Object o : (Collection) refObject) { + + Object refId = ref.getPropertyAccessor(o).getProperty(ref.getRequiredIdProperty()); + if (refId != null) { + sink.getBucket().put(propertyStringPath + ".[" + i + "]", toBytes(keyspace + ":" + refId)); + i++; + } } - if (association.getInverse().isCollectionLike()) { + } else { - RedisPersistentEntity ref = mappingContext.getRequiredPersistentEntity( - association.getInverse().getTypeInformation().getRequiredComponentType().getActualType()); + RedisPersistentEntity ref = mappingContext + .getRequiredPersistentEntity(association.getInverse().getTypeInformation()); + String keyspace = ref.getKeySpace(); - String keyspace = ref.getKeySpace(); + Object refId = ref.getPropertyAccessor(refObject).getProperty(ref.getIdProperty()); + + if (refId != null) { String propertyStringPath = (!path.isEmpty() ? path + "." : "") + association.getInverse().getName(); - - int i = 0; - for (Object o : (Collection) refObject) { - - Object refId = ref.getPropertyAccessor(o).getProperty(ref.getRequiredIdProperty()); - if (refId != null) { - sink.getBucket().put(propertyStringPath + ".[" + i + "]", toBytes(keyspace + ":" + refId)); - i++; - } - } - - } else { - - RedisPersistentEntity ref = mappingContext - .getRequiredPersistentEntity(association.getInverse().getTypeInformation()); - String keyspace = ref.getKeySpace(); - - Object refId = ref.getPropertyAccessor(refObject).getProperty(ref.getIdProperty()); - - if (refId != null) { - String propertyStringPath = (!path.isEmpty() ? path + "." : "") + association.getInverse().getName(); - sink.getBucket().put(propertyStringPath, toBytes(keyspace + ":" + refId)); - } + sink.getBucket().put(propertyStringPath, toBytes(keyspace + ":" + refId)); } } }); @@ -764,7 +742,7 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean { private Object readCollectionOrArray(String path, Class collectionType, Class valueType, Bucket bucket) { - List keys = new ArrayList(bucket.extractAllKeysFor(path)); + List keys = new ArrayList<>(bucket.extractAllKeysFor(path)); Collections.sort(keys, listKeyComparator); boolean isArray = collectionType.isArray(); diff --git a/src/main/java/org/springframework/data/redis/core/convert/PathIndexResolver.java b/src/main/java/org/springframework/data/redis/core/convert/PathIndexResolver.java index 0222c2be0..f7627833b 100644 --- a/src/main/java/org/springframework/data/redis/core/convert/PathIndexResolver.java +++ b/src/main/java/org/springframework/data/redis/core/convert/PathIndexResolver.java @@ -55,8 +55,7 @@ import org.springframework.util.CollectionUtils; */ public class PathIndexResolver implements IndexResolver { - private final Set> VALUE_TYPES = new HashSet>( - Arrays.> asList(Point.class, GeoLocation.class)); + private final Set> VALUE_TYPES = new HashSet<>(Arrays.> asList(Point.class, GeoLocation.class)); private ConfigurableIndexDefinitionProvider indexConfiguration; private RedisMappingContext mappingContext; @@ -117,7 +116,7 @@ public class PathIndexResolver implements IndexResolver { } final PersistentPropertyAccessor accessor = entity.getPropertyAccessor(value); - final Set indexes = new LinkedHashSet(); + final Set indexes = new LinkedHashSet<>(); entity.doWithProperties(new PropertyHandler() { @@ -202,7 +201,7 @@ public class PathIndexResolver implements IndexResolver { String path = normalizeIndexPath(propertyPath, property); - Set data = new LinkedHashSet(); + Set data = new LinkedHashSet<>(); if (indexConfiguration.hasIndexFor(keyspace, path)) { diff --git a/src/main/java/org/springframework/data/redis/core/convert/RedisData.java b/src/main/java/org/springframework/data/redis/core/convert/RedisData.java index e3a700487..5774d0551 100644 --- a/src/main/java/org/springframework/data/redis/core/convert/RedisData.java +++ b/src/main/java/org/springframework/data/redis/core/convert/RedisData.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2016 the original author or authors. + * Copyright 2015-2017 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. @@ -66,7 +66,7 @@ public class RedisData { Assert.notNull(bucket, "Bucket must not be null!"); this.bucket = bucket; - this.indexedData = new HashSet(); + this.indexedData = new HashSet<>(); } /** diff --git a/src/main/java/org/springframework/data/redis/core/convert/SpelIndexResolver.java b/src/main/java/org/springframework/data/redis/core/convert/SpelIndexResolver.java index d9c9a8f35..a08515727 100644 --- a/src/main/java/org/springframework/data/redis/core/convert/SpelIndexResolver.java +++ b/src/main/java/org/springframework/data/redis/core/convert/SpelIndexResolver.java @@ -72,7 +72,7 @@ public class SpelIndexResolver implements IndexResolver { Assert.notNull(parser, "SpelExpressionParser must not be null!"); this.mappingContext = mappingContext; this.settings = mappingContext.getMappingConfiguration().getIndexConfiguration(); - this.expressionCache = new HashMap(); + this.expressionCache = new HashMap<>(); this.parser = parser; } @@ -93,7 +93,7 @@ public class SpelIndexResolver implements IndexResolver { String keyspace = entity.getKeySpace(); - Set indexes = new HashSet(); + Set indexes = new HashSet<>(); for (IndexDefinition setting : settings.getIndexDefinitionsFor(keyspace)) { diff --git a/src/main/java/org/springframework/data/redis/core/index/IndexConfiguration.java b/src/main/java/org/springframework/data/redis/core/index/IndexConfiguration.java index 614f996aa..3d8aff978 100644 --- a/src/main/java/org/springframework/data/redis/core/index/IndexConfiguration.java +++ b/src/main/java/org/springframework/data/redis/core/index/IndexConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2016 the original author or authors. + * Copyright 2015-2017 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. @@ -42,7 +42,7 @@ public class IndexConfiguration implements ConfigurableIndexDefinitionProvider { */ public IndexConfiguration() { - this.definitions = new CopyOnWriteArraySet(); + this.definitions = new CopyOnWriteArraySet<>(); for (IndexDefinition initial : initialConfiguration()) { addIndexDefinition(initial); } @@ -79,7 +79,7 @@ public class IndexConfiguration implements ConfigurableIndexDefinitionProvider { */ public Set getIndexDefinitionsFor(Serializable keyspace) { - Set indexDefinitions = new LinkedHashSet(); + Set indexDefinitions = new LinkedHashSet<>(); for (IndexDefinition indexDef : definitions) { if (indexDef.getKeyspace().equals(keyspace)) { @@ -102,7 +102,7 @@ public class IndexConfiguration implements ConfigurableIndexDefinitionProvider { private Set getIndexDefinitions(Serializable keyspace, String path, Class type) { - Set def = new LinkedHashSet(); + Set def = new LinkedHashSet<>(); for (IndexDefinition indexDef : definitions) { if (ClassUtils.isAssignable(type, indexDef.getClass()) && indexDef.getKeyspace().equals(keyspace)) { diff --git a/src/main/java/org/springframework/data/redis/core/index/RedisIndexDefinition.java b/src/main/java/org/springframework/data/redis/core/index/RedisIndexDefinition.java index 96a628f4c..08563c315 100644 --- a/src/main/java/org/springframework/data/redis/core/index/RedisIndexDefinition.java +++ b/src/main/java/org/springframework/data/redis/core/index/RedisIndexDefinition.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2016-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,7 +26,7 @@ import org.springframework.util.StringUtils; /** * Base {@link IndexDefinition} implementation. - * + * * @author Christoph Strobl * @since 1.7 */ @@ -40,7 +40,7 @@ public abstract class RedisIndexDefinition implements IndexDefinition { /** * Creates new {@link RedisIndexDefinition}. - * + * * @param keyspace * @param path * @param indexName @@ -50,7 +50,7 @@ public abstract class RedisIndexDefinition implements IndexDefinition { this.keyspace = keyspace; this.indexName = indexName; this.path = path; - this.conditions = new ArrayList>(); + this.conditions = new ArrayList<>(); } /* @@ -183,7 +183,7 @@ public abstract class RedisIndexDefinition implements IndexDefinition { */ public static class CompositeValueTransformer implements IndexValueTransformer { - private final List transformers = new ArrayList(); + private final List transformers = new ArrayList<>(); public CompositeValueTransformer(Collection transformers) { this.transformers.addAll(transformers); @@ -212,7 +212,7 @@ public abstract class RedisIndexDefinition implements IndexDefinition { */ public static class OrCondition implements Condition { - private final List> conditions = new ArrayList>(); + private final List> conditions = new ArrayList<>(); public OrCondition(Collection> conditions) { this.conditions.addAll(conditions); diff --git a/src/main/java/org/springframework/data/redis/core/mapping/RedisMappingContext.java b/src/main/java/org/springframework/data/redis/core/mapping/RedisMappingContext.java index 27fbe9fc2..27e274500 100644 --- a/src/main/java/org/springframework/data/redis/core/mapping/RedisMappingContext.java +++ b/src/main/java/org/springframework/data/redis/core/mapping/RedisMappingContext.java @@ -45,8 +45,6 @@ import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.NumberUtils; import org.springframework.util.ReflectionUtils; -import org.springframework.util.ReflectionUtils.MethodCallback; -import org.springframework.util.ReflectionUtils.MethodFilter; import org.springframework.util.StringUtils; /** @@ -99,7 +97,7 @@ public class RedisMappingContext extends KeyValueMappingContext RedisPersistentEntity createPersistentEntity(TypeInformation typeInformation) { - return new BasicRedisPersistentEntity(typeInformation, fallbackKeySpaceResolver, timeToLiveAccessor); + return new BasicRedisPersistentEntity<>(typeInformation, fallbackKeySpaceResolver, timeToLiveAccessor); } @Override @@ -199,9 +197,9 @@ public class RedisMappingContext extends KeyValueMappingContext, Long>(); - this.timeoutProperties = new HashMap, PersistentProperty>(); - this.timeoutMethods = new HashMap, Method>(); + this.defaultTimeouts = new HashMap<>(); + this.timeoutProperties = new HashMap<>(); + this.timeoutMethods = new HashMap<>(); this.keyspaceConfig = keyspaceConfig; this.mappingContext = mappingContext; } @@ -340,20 +338,9 @@ public class RedisMappingContext extends KeyValueMappingContext timeoutMethods.put(type, method), + method -> ClassUtils.isAssignable(Number.class, method.getReturnType()) + && AnnotationUtils.findAnnotation(method, TimeToLive.class) != null); return timeoutMethods.get(type); } diff --git a/src/main/java/org/springframework/data/redis/core/mapping/RedisPersistentProperty.java b/src/main/java/org/springframework/data/redis/core/mapping/RedisPersistentProperty.java index 49bf9684c..f0d476465 100644 --- a/src/main/java/org/springframework/data/redis/core/mapping/RedisPersistentProperty.java +++ b/src/main/java/org/springframework/data/redis/core/mapping/RedisPersistentProperty.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2016 the original author or authors. + * Copyright 2015-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,13 +26,13 @@ import org.springframework.data.mapping.model.SimpleTypeHolder; /** * Redis specific {@link PersistentProperty} implementation. - * + * * @author Christoph Strobl * @since 1.7 */ public class RedisPersistentProperty extends KeyValuePersistentProperty { - private static final Set SUPPORTED_ID_PROPERTY_NAMES = new HashSet(); + private static final Set SUPPORTED_ID_PROPERTY_NAMES = new HashSet<>(); static { SUPPORTED_ID_PROPERTY_NAMES.add("id"); @@ -40,7 +40,7 @@ public class RedisPersistentProperty extends KeyValuePersistentProperty implements SortCriterion { private final K key; private String by; - private final List getKeys = new ArrayList(4); + private final List getKeys = new ArrayList<>(4); private Range limit; private Order order; @@ -41,12 +41,12 @@ class DefaultSortCriterion implements SortCriterion { } public SortCriterion alphabetical(boolean alpha) { - this.alpha = Boolean.valueOf(alpha); + this.alpha = alpha; return this; } public SortQuery build() { - return new DefaultSortQuery(key, by, limit, order, alpha, getKeys); + return new DefaultSortQuery<>(key, by, limit, order, alpha, getKeys); } public SortCriterion limit(long offset, long count) { diff --git a/src/main/java/org/springframework/data/redis/core/query/QueryUtils.java b/src/main/java/org/springframework/data/redis/core/query/QueryUtils.java index d412bd6fb..2bf8400fe 100644 --- a/src/main/java/org/springframework/data/redis/core/query/QueryUtils.java +++ b/src/main/java/org/springframework/data/redis/core/query/QueryUtils.java @@ -1,12 +1,12 @@ /* - * Copyright 2011-2013 the original author or authors. - * + * Copyright 2011-2017 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. @@ -25,7 +25,7 @@ import org.springframework.data.redis.serializer.RedisSerializer; /** * Utilities for {@link SortQuery} implementations. - * + * * @author Costin Leau */ public abstract class QueryUtils { @@ -42,7 +42,7 @@ public abstract class QueryUtils { if (strings == null) { raw = Collections.emptyList(); } else { - raw = new ArrayList(strings.size()); + raw = new ArrayList<>(strings.size()); for (String key : strings) { raw.add(stringSerializer.serialize(key)); } diff --git a/src/main/java/org/springframework/data/redis/core/query/SortQueryBuilder.java b/src/main/java/org/springframework/data/redis/core/query/SortQueryBuilder.java index eac83a829..82f1b311d 100644 --- a/src/main/java/org/springframework/data/redis/core/query/SortQueryBuilder.java +++ b/src/main/java/org/springframework/data/redis/core/query/SortQueryBuilder.java @@ -1,12 +1,12 @@ /* - * Copyright 2011-2013 the original author or authors. - * + * Copyright 2011-2017 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. @@ -17,7 +17,7 @@ package org.springframework.data.redis.core.query; /** * Simple builder class for constructing {@link SortQuery}. - * + * * @author Costin Leau */ public class SortQueryBuilder extends DefaultSortCriterion { @@ -29,7 +29,7 @@ public class SortQueryBuilder extends DefaultSortCriterion { } public static SortQueryBuilder sort(K key) { - return new SortQueryBuilder(key); + return new SortQueryBuilder<>(key); } public SortCriterion by(String keyPattern) { diff --git a/src/main/java/org/springframework/data/redis/core/script/DefaultScriptExecutor.java b/src/main/java/org/springframework/data/redis/core/script/DefaultScriptExecutor.java index 85c3ff2fc..4bb513ea4 100644 --- a/src/main/java/org/springframework/data/redis/core/script/DefaultScriptExecutor.java +++ b/src/main/java/org/springframework/data/redis/core/script/DefaultScriptExecutor.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,6 @@ package org.springframework.data.redis.core.script; import java.util.ArrayList; import java.util.List; -import org.springframework.dao.DataAccessException; import org.springframework.dao.NonTransientDataAccessException; import org.springframework.data.redis.RedisSystemException; import org.springframework.data.redis.connection.RedisConnection; @@ -31,7 +30,7 @@ import org.springframework.data.redis.serializer.RedisSerializer; * Default implementation of {@link ScriptExecutor}. Optimizes performance by attempting to execute script first using * evalsha, then falling back to eval if Redis has not yet cached the script. Evalsha is not attempted if the script is * executed in a pipeline or transaction. - * + * * @author Jennifer Hickey * @author Christoph Strobl * @author Thomas Darimont @@ -57,19 +56,17 @@ public class DefaultScriptExecutor implements ScriptExecutor { public T execute(final RedisScript script, final RedisSerializer argsSerializer, final RedisSerializer resultSerializer, final List keys, final Object... args) { - return template.execute(new RedisCallback() { - public T doInRedis(RedisConnection connection) throws DataAccessException { - final ReturnType returnType = ReturnType.fromJavaType(script.getResultType()); - final byte[][] keysAndArgs = keysAndArgs(argsSerializer, keys, args); - final int keySize = keys != null ? keys.size() : 0; - if (connection.isPipelined() || connection.isQueueing()) { - // We could script load first and then do evalsha to ensure sha is present, - // but this adds a sha1 to exec/closePipeline results. Instead, just eval - connection.eval(scriptBytes(script), returnType, keySize, keysAndArgs); - return null; - } - return eval(connection, script, returnType, keySize, keysAndArgs, resultSerializer); + return template.execute((RedisCallback) connection -> { + final ReturnType returnType = ReturnType.fromJavaType(script.getResultType()); + final byte[][] keysAndArgs = keysAndArgs(argsSerializer, keys, args); + final int keySize = keys != null ? keys.size() : 0; + if (connection.isPipelined() || connection.isQueueing()) { + // We could script load first and then do evalsha to ensure sha is present, + // but this adds a sha1 to exec/closePipeline results. Instead, just eval + connection.eval(scriptBytes(script), returnType, keySize, keysAndArgs); + return null; } + return eval(connection, script, returnType, keySize, keysAndArgs, resultSerializer); }); } diff --git a/src/main/java/org/springframework/data/redis/hash/BeanUtilsHashMapper.java b/src/main/java/org/springframework/data/redis/hash/BeanUtilsHashMapper.java index 9e87109ae..b9784c256 100644 --- a/src/main/java/org/springframework/data/redis/hash/BeanUtilsHashMapper.java +++ b/src/main/java/org/springframework/data/redis/hash/BeanUtilsHashMapper.java @@ -1,12 +1,12 @@ /* - * Copyright 2011-2015 the original author or authors. - * + * Copyright 2011-2017 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. @@ -23,7 +23,7 @@ import org.apache.commons.beanutils.BeanUtils; /** * HashMapper based on Apache Commons BeanUtils project. Does NOT supports nested properties. - * + * * @author Costin Leau * @author Christoph Strobl */ @@ -56,7 +56,7 @@ public class BeanUtilsHashMapper implements HashMapper { Map map = BeanUtils.describe(object); - Map result = new LinkedHashMap(); + Map result = new LinkedHashMap<>(); for (Entry entry : map.entrySet()) { if (entry.getValue() != null) { result.put(entry.getKey(), entry.getValue()); diff --git a/src/main/java/org/springframework/data/redis/hash/DecoratingStringHashMapper.java b/src/main/java/org/springframework/data/redis/hash/DecoratingStringHashMapper.java index 5905e05e3..4897a6269 100644 --- a/src/main/java/org/springframework/data/redis/hash/DecoratingStringHashMapper.java +++ b/src/main/java/org/springframework/data/redis/hash/DecoratingStringHashMapper.java @@ -1,12 +1,12 @@ /* - * Copyright 2011-2013 the original author or authors. - * + * Copyright 2011-2017 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. @@ -21,7 +21,7 @@ import java.util.Map; /** * Delegating hash mapper used for flattening objects into Strings. Suitable when dealing with mappers that support * Strings and type conversion. - * + * * @author Costin Leau */ public class DecoratingStringHashMapper implements HashMapper { @@ -40,7 +40,7 @@ public class DecoratingStringHashMapper implements HashMapper toHash(T object) { Map hash = delegate.toHash(object); - Map flatten = new LinkedHashMap(hash.size()); + Map flatten = new LinkedHashMap<>(hash.size()); for (Map.Entry entry : hash.entrySet()) { flatten.put(String.valueOf(entry.getKey()), String.valueOf(entry.getValue())); } diff --git a/src/main/java/org/springframework/data/redis/hash/Jackson2HashMapper.java b/src/main/java/org/springframework/data/redis/hash/Jackson2HashMapper.java index f79931d60..d6720dbe5 100644 --- a/src/main/java/org/springframework/data/redis/hash/Jackson2HashMapper.java +++ b/src/main/java/org/springframework/data/redis/hash/Jackson2HashMapper.java @@ -166,8 +166,8 @@ public class Jackson2HashMapper implements HashMapper { @SuppressWarnings("unchecked") private Map doUnflatten(Map source) { - Map result = new LinkedHashMap(); - Set treatSeperate = new LinkedHashSet(); + Map result = new LinkedHashMap<>(); + Set treatSeperate = new LinkedHashSet<>(); for (Entry entry : source.entrySet()) { String key = entry.getKey(); @@ -193,7 +193,7 @@ public class Jackson2HashMapper implements HashMapper { for (String partial : treatSeperate) { - Map newSource = new LinkedHashMap(); + Map newSource = new LinkedHashMap<>(); for (Entry entry : source.entrySet()) { if (entry.getKey().startsWith(partial)) { @@ -220,7 +220,7 @@ public class Jackson2HashMapper implements HashMapper { private Map flattenMap(Iterator> source) { - Map resultMap = new HashMap(); + Map resultMap = new HashMap<>(); this.doFlatten("", source, resultMap); return resultMap; } @@ -291,9 +291,9 @@ public class Jackson2HashMapper implements HashMapper { private List createTypedListWithValue(Object value) { - List listWithTypeHint = new ArrayList(); + List listWithTypeHint = new ArrayList<>(); listWithTypeHint.add(ArrayList.class.getName()); // why jackson? why? - List values = new ArrayList(); + List values = new ArrayList<>(); values.add(value); listWithTypeHint.add(values); return listWithTypeHint; diff --git a/src/main/java/org/springframework/data/redis/listener/RedisMessageListenerContainer.java b/src/main/java/org/springframework/data/redis/listener/RedisMessageListenerContainer.java index 1bcba13f0..db4110601 100644 --- a/src/main/java/org/springframework/data/redis/listener/RedisMessageListenerContainer.java +++ b/src/main/java/org/springframework/data/redis/listener/RedisMessageListenerContainer.java @@ -1,12 +1,12 @@ /* - * Copyright 2011-2016 the original author or authors. - * + * Copyright 2011-2017 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. @@ -62,7 +62,7 @@ import org.springframework.util.ErrorHandler; *

* Adding and removing listeners at the same time has undefined results. It is strongly recommended to synchronize/order * these methods accordingly. - * + * * @author Costin Leau * @author Jennifer Hickey * @author Way Joke @@ -118,11 +118,11 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab // contract) // lookup map between patterns and listeners - private final Map> patternMapping = new ConcurrentHashMap>(); + private final Map> patternMapping = new ConcurrentHashMap<>(); // lookup map between channels and listeners - private final Map> channelMapping = new ConcurrentHashMap>(); + private final Map> channelMapping = new ConcurrentHashMap<>(); // lookup map between listeners and channels - private final Map> listenerTopics = new ConcurrentHashMap>(); + private final Map> listenerTopics = new ConcurrentHashMap<>(); private final SubscriptionTask subscriptionTask = new SubscriptionTask(); @@ -150,7 +150,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab *

* The default implementation builds a {@link org.springframework.core.task.SimpleAsyncTaskExecutor} with the * specified bean name (or the class name, if no bean name specified) as thread name prefix. - * + * * @see org.springframework.core.task.SimpleAsyncTaskExecutor#SimpleAsyncTaskExecutor(String) */ protected TaskExecutor createDefaultTaskExecutor() { @@ -231,7 +231,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab /** * Process a message received from the provider. - * + * * @param message * @param pattern */ @@ -241,7 +241,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab /** * Execute the specified listener. - * + * * @see #handleListenerException */ protected void executeListener(MessageListener listener, Message message, byte[] pattern) { @@ -263,7 +263,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab * Handle the given exception that arose during listener execution. *

* The default implementation logs the exception at error level. This can be overridden in subclasses. - * + * * @param ex the exception to handle */ protected void handleListenerException(Throwable ex) { @@ -280,7 +280,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab /** * Invoke the registered ErrorHandler, if any. Log at error level otherwise. - * + * * @param ex the uncaught error that arose during message processing. * @see #setErrorHandler */ @@ -294,7 +294,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab /** * Returns the connectionFactory. - * + * * @return Returns the connectionFactory */ public RedisConnectionFactory getConnectionFactory() { @@ -316,7 +316,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab * Sets the task executor used for running the message listeners when messages are received. If no task executor is * set, an instance of {@link SimpleAsyncTaskExecutor} will be used by default. The task executor can be adjusted * depending on the work done by the listeners and the number of messages coming in. - * + * * @param taskExecutor The taskExecutor to set. */ public void setTaskExecutor(Executor taskExecutor) { @@ -330,7 +330,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab *

* Note: This implementation uses at most one long running thread (depending on whether there are any listeners * registered or not) and up to two threads during the initial registration. - * + * * @param subscriptionExecutor The subscriptionExecutor to set. */ public void setSubscriptionExecutor(Executor subscriptionExecutor) { @@ -340,7 +340,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab /** * Sets the serializer for converting the {@link Topic}s into low-level channels and patterns. By default, * {@link StringRedisSerializer} is used. - * + * * @param serializer The serializer to set. */ public void setTopicSerializer(RedisSerializer serializer) { @@ -361,7 +361,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab * Note: it's possible to call this method while the container is running forcing a reinitialization of the container. * Note however that this might cause some messages to be lost (while the container reinitializes) - hence calling * this method at runtime is considered advanced usage. - * + * * @param listeners map of message listeners and their associated topics */ public void setMessageListeners(Map> listeners) { @@ -371,7 +371,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab /** * Adds a message listener to the (potentially running) container. If the container is running, the listener starts * receiving (matching) messages as soon as possible. - * + * * @param listener message listener * @param topics message listener topic */ @@ -383,7 +383,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab /** * Adds a message listener to the (potentially running) container. If the container is running, the listener starts * receiving (matching) messages as soon as possible. - * + * * @param listener message listener * @param topic message topic */ @@ -397,7 +397,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab *

* Note that this method obeys the Redis (p)unsubscribe semantics - meaning an empty/null collection will remove * listener from all channels. Similarly a null listener will unsubscribe all listeners from the given topic. - * + * * @param listener message listener * @param topics message listener topics */ @@ -411,7 +411,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab *

* Note that this method obeys the Redis (p)unsubscribe semantics - meaning an empty/null collection will remove * listener from all channels. Similarly a null listener will unsubscribe all listeners from the given topic. - * + * * @param listener message listener * @param topic message topic */ @@ -423,7 +423,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab * Removes the given message listener completely (from all topics). If the container is running, the listener stops * receiving (matching) messages as soon as possible. Similarly a null listener will unsubscribe all listeners from * the given topic. - * + * * @param listener message listener */ public void removeMessageListener(MessageListener listener) { @@ -485,15 +485,15 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab Assert.notNull(listener, "a valid listener is required"); Assert.notEmpty(topics, "at least one topic is required"); - List channels = new ArrayList(topics.size()); - List patterns = new ArrayList(topics.size()); + List channels = new ArrayList<>(topics.size()); + List patterns = new ArrayList<>(topics.size()); boolean trace = logger.isTraceEnabled(); // add listener mapping Set set = listenerTopics.get(listener); if (set == null) { - set = new CopyOnWriteArraySet(); + set = new CopyOnWriteArraySet<>(); listenerTopics.put(listener, set); } set.addAll(topics); @@ -505,7 +505,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab if (topic instanceof ChannelTopic) { Collection collection = channelMapping.get(holder); if (collection == null) { - collection = new CopyOnWriteArraySet(); + collection = new CopyOnWriteArraySet<>(); channelMapping.put(holder, collection); } collection.add(listener); @@ -518,7 +518,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab else if (topic instanceof PatternTopic) { Collection collection = patternMapping.get(holder); if (collection == null) { - collection = new CopyOnWriteArraySet(); + collection = new CopyOnWriteArraySet<>(); patternMapping.put(holder, collection); } collection.add(listener); @@ -549,8 +549,8 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab return; } - List channelsToRemove = new ArrayList(); - List patternsToRemove = new ArrayList(); + List channelsToRemove = new ArrayList<>(); + List patternsToRemove = new ArrayList<>(); // check unsubscribe all topics case if (CollectionUtils.isEmpty(topics)) { @@ -636,7 +636,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab /** * Handle subscription task exception. Will attempt to restart the subscription if the Exception is a connection * failure (for example, Redis was restarted). - * + * * @param ex Throwable exception */ protected void handleSubscriptionException(Throwable ex) { @@ -670,7 +670,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab /** * Runnable used for Redis subscription. Implemented as a dedicated class to provide as many hints as possible to the * underlying thread pool. - * + * * @author Costin Leau */ private class SubscriptionTask implements SchedulingAwareRunnable { @@ -679,7 +679,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab * Runnable used, on a parallel thread, to do the initial pSubscribe. This is required since, during initialization, * both subscribe and pSubscribe might be needed but since the first call is blocking, the second call needs to * executed in parallel. - * + * * @author Costin Leau */ private class PatternSubscriptionTask implements SchedulingAwareRunnable { @@ -766,7 +766,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab /** * Performs a potentially asynchronous registration of a subscription. - * + * * @return #SubscriptionPresentCondition that can serve as a handle to check whether the subscription is ready. */ private SubscriptionPresentCondition eventuallyPerformSubscription() { @@ -795,7 +795,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab /** * Checks whether the current connection has an associated subscription. - * + * * @author Thomas Darimont */ private class SubscriptionPresentCondition implements Condition { @@ -807,7 +807,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab /** * Checks whether the current connection has an associated pattern subscription. - * + * * @author Thomas Darimont * @see org.springframework.data.redis.listener.RedisMessageListenerContainer.SubscriptionTask.SubscriptionPresentTestCondition */ @@ -935,7 +935,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab /** * Actual message dispatcher/multiplexer. - * + * * @author Costin Leau */ private class DispatchMessageListener implements MessageListener { @@ -962,17 +962,13 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab final byte[] source = (pattern != null ? pattern.clone() : message.getChannel()); for (final MessageListener messageListener : listeners) { - taskExecutor.execute(new Runnable() { - public void run() { - processMessage(messageListener, message, source); - } - }); + taskExecutor.execute(() -> processMessage(messageListener, message, source)); } } /** * Specify the interval between recovery attempts, in milliseconds. The default is 5000 ms, that is, 5 seconds. - * + * * @see #handleSubscriptionException */ public void setRecoveryInterval(long recoveryInterval) { @@ -986,7 +982,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab /** * Specify the max time to wait for subscription registrations, in milliseconds. The default is 2000ms, that * is, 2 second. - * + * * @param maxSubscriptionRegistrationWaitingTime * @see #DEFAULT_SUBSCRIPTION_REGISTRATION_WAIT_TIME */ @@ -1002,7 +998,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab /** * Periodically tests, in 100ms intervals, for a condition until it is met or a timeout occurs. - * + * * @param condition The condition to periodically test * @param timeout The timeout * @return true if condition passes, false if condition does not pass within timeout @@ -1034,7 +1030,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab /** * A condition to test periodically, used in conjunction with * {@link org.springframework.data.redis.listener.RedisMessageListenerContainer.SpinBarrier} - * + * * @author Jennifer Hickey * @author Thomas Darimont Note: Placed here to avoid API exposure. */ diff --git a/src/main/java/org/springframework/data/redis/listener/adapter/MessageListenerAdapter.java b/src/main/java/org/springframework/data/redis/listener/adapter/MessageListenerAdapter.java index 1953ccb7f..18b9a6a8a 100644 --- a/src/main/java/org/springframework/data/redis/listener/adapter/MessageListenerAdapter.java +++ b/src/main/java/org/springframework/data/redis/listener/adapter/MessageListenerAdapter.java @@ -1,12 +1,12 @@ /* - * Copyright 2011-2014 the original author or authors. - * + * Copyright 2011-2017 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. @@ -35,7 +35,6 @@ import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.ReflectionUtils; -import org.springframework.util.ReflectionUtils.MethodCallback; import org.springframework.util.ReflectionUtils.MethodFilter; import org.springframework.util.StringUtils; @@ -60,33 +59,33 @@ import org.springframework.util.StringUtils; *

* Find below some examples of method signatures compliant with this adapter class. This first example handles all * Message types and gets passed the contents of each Message type as an argument. - * + * *

  * public interface MessageContentsDelegate {
  * 	void handleMessage(String text);
- * 
+ *
  * 	void handleMessage(byte[] bytes);
- * 
+ *
  * 	void handleMessage(Person obj);
  * }
  * 
*

* In addition, the channel or pattern to which a message is sent can be passed in to the method as a second argument of * type String: - * + * *

  * public interface MessageContentsDelegate {
  * 	void handleMessage(String text, String channel);
- * 
+ *
  * 	void handleMessage(byte[] bytes, String pattern);
  * }
  * 
- * + * * For further examples and discussion please do refer to the Spring Data reference documentation which describes this * class (and its attendant configuration) in detail. Important: Due to the nature of messages, the default * serializer used by the adapter is {@link StringRedisSerializer}. If the messages are of a different type, change them * accordingly through {@link #setSerializer(RedisSerializer)}. - * + * * @author Juergen Hoeller * @author Costin Leau * @author Greg Turnquist @@ -109,17 +108,13 @@ public class MessageListenerAdapter implements InitializingBean, MessageListener this.delegate = delegate; this.methodName = methodName; this.lenient = delegate instanceof MessageListener; - this.methods = new HashSet(); + this.methods = new HashSet<>(); final Class c = delegate.getClass(); - ReflectionUtils.doWithMethods(c, new MethodCallback() { - - public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { - ReflectionUtils.makeAccessible(method); - methods.add(method); - } - + ReflectionUtils.doWithMethods(c, method -> { + ReflectionUtils.makeAccessible(method); + methods.add(method); }, new MostSpecificMethodFilter(methodName, c)); Assert.isTrue(lenient || !methods.isEmpty(), "Cannot find a suitable method named [" + c.getName() + "#" @@ -150,14 +145,14 @@ public class MessageListenerAdapter implements InitializingBean, MessageListener /** * Returns the current methodName. - * + * * @return the methodName */ public String getMethodName() { return methodName; } } - + /** * Out-of-the-box value for the default listener method: "handleMessage". */ @@ -186,7 +181,7 @@ public class MessageListenerAdapter implements InitializingBean, MessageListener /** * Create a new {@link MessageListenerAdapter} for the given delegate. - * + * * @param delegate the delegate object */ public MessageListenerAdapter(Object delegate) { @@ -196,7 +191,7 @@ public class MessageListenerAdapter implements InitializingBean, MessageListener /** * Create a new {@link MessageListenerAdapter} for the given delegate. - * + * * @param delegate the delegate object * @param defaultListenerMethod method to call when a message comes * @see #getListenerMethodName @@ -212,7 +207,7 @@ public class MessageListenerAdapter implements InitializingBean, MessageListener *

* If no explicit delegate object has been specified, listener methods are expected to present on this adapter * instance, that is, on a custom subclass of this adapter, defining listener methods. - * + * * @param delegate delegate object */ public void setDelegate(Object delegate) { @@ -222,7 +217,7 @@ public class MessageListenerAdapter implements InitializingBean, MessageListener /** * Returns the target object to delegate message listening to. - * + * * @return message listening delegation */ public Object getDelegate() { @@ -232,7 +227,7 @@ public class MessageListenerAdapter implements InitializingBean, MessageListener /** * Specify the name of the default listener method to delegate to, for the case where no specific listener method has * been determined. Out-of-the-box value is {@link #ORIGINAL_DEFAULT_LISTENER_METHOD "handleMessage"}. - * + * * @see #getListenerMethodName */ public void setDefaultListenerMethod(String defaultListenerMethod) { @@ -250,7 +245,7 @@ public class MessageListenerAdapter implements InitializingBean, MessageListener * Set the serializer that will convert incoming raw Redis messages to listener method arguments. *

* The default converter is a {@link StringRedisSerializer}. - * + * * @param serializer */ public void setSerializer(RedisSerializer serializer) { @@ -261,7 +256,7 @@ public class MessageListenerAdapter implements InitializingBean, MessageListener * Sets the serializer used for converting the channel/pattern to a String. *

* The default converter is a {@link StringRedisSerializer}. - * + * * @param serializer */ public void setStringSerializer(RedisSerializer serializer) { @@ -285,7 +280,7 @@ public class MessageListenerAdapter implements InitializingBean, MessageListener *

* Delegates the message to the target listener method, with appropriate conversion of the message argument. In case * of an exception, the {@link #handleListenerException(Throwable)} method will be invoked. - * + * * @param message the incoming Redis message * @see #handleListenerException */ @@ -315,7 +310,7 @@ public class MessageListenerAdapter implements InitializingBean, MessageListener /** * Initialize the default implementations for the adapter's strategies. - * + * * @see #setSerializer(RedisSerializer) * @see JdkSerializationRedisSerializer */ @@ -328,7 +323,7 @@ public class MessageListenerAdapter implements InitializingBean, MessageListener /** * Handle the given exception that arose during listener execution. The default implementation logs the exception at * error level. - * + * * @param ex the exception to handle */ protected void handleListenerException(Throwable ex) { @@ -337,7 +332,7 @@ public class MessageListenerAdapter implements InitializingBean, MessageListener /** * Extract the message body from the given Redis message. - * + * * @param message the Redis Message * @return the content of the message, to be passed into the listener method as argument */ @@ -352,7 +347,7 @@ public class MessageListenerAdapter implements InitializingBean, MessageListener * Determine the name of the listener method that is supposed to handle the given message. *

* The default implementation simply returns the configured default listener method, if any. - * + * * @param originalMessage the Redis request message * @param extractedMessage the converted Redis request message, to be passed into the listener method as argument * @return the name of the listener method (never null) @@ -364,7 +359,7 @@ public class MessageListenerAdapter implements InitializingBean, MessageListener /** * Invoke the specified listener method. - * + * * @param methodName the name of the listener method * @param arguments the message arguments to be passed in * @see #getListenerMethodName diff --git a/src/main/java/org/springframework/data/redis/repository/cdi/CdiBean.java b/src/main/java/org/springframework/data/redis/repository/cdi/CdiBean.java index 9c9a630d8..893819166 100644 --- a/src/main/java/org/springframework/data/redis/repository/cdi/CdiBean.java +++ b/src/main/java/org/springframework/data/redis/repository/cdi/CdiBean.java @@ -98,7 +98,7 @@ public abstract class CdiBean implements Bean, PassivationCapable { */ private final String createPassivationId(Set qualifiers, Class repositoryType) { - List qualifierNames = new ArrayList(qualifiers.size()); + List qualifierNames = new ArrayList<>(qualifiers.size()); for (Annotation qualifier : qualifiers) { qualifierNames.add(qualifier.annotationType().getName()); @@ -118,7 +118,7 @@ public abstract class CdiBean implements Bean, PassivationCapable { */ public Set getTypes() { - Set types = new HashSet(); + Set types = new HashSet<>(); types.add(beanClass); types.addAll(Arrays.asList(beanClass.getInterfaces())); types.addAll(this.types); @@ -187,7 +187,7 @@ public abstract class CdiBean implements Bean, PassivationCapable { */ public Set> getStereotypes() { - Set> stereotypes = new HashSet>(); + Set> stereotypes = new HashSet<>(); for (Annotation annotation : beanClass.getAnnotations()) { Class annotationType = annotation.annotationType(); diff --git a/src/main/java/org/springframework/data/redis/repository/cdi/RedisRepositoryExtension.java b/src/main/java/org/springframework/data/redis/repository/cdi/RedisRepositoryExtension.java index b3bd09c40..ab79cbe9f 100644 --- a/src/main/java/org/springframework/data/redis/repository/cdi/RedisRepositoryExtension.java +++ b/src/main/java/org/springframework/data/redis/repository/cdi/RedisRepositoryExtension.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2016-2017 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. @@ -53,9 +53,9 @@ public class RedisRepositoryExtension extends CdiRepositoryExtensionSupport { private static final Logger LOG = LoggerFactory.getLogger(RedisRepositoryExtension.class); - private final Map, Bean> redisKeyValueAdapters = new HashMap, Bean>(); - private final Map, Bean> redisKeyValueTemplates = new HashMap, Bean>(); - private final Map, Bean>> redisOperations = new HashMap, Bean>>(); + private final Map, Bean> redisKeyValueAdapters = new HashMap<>(); + private final Map, Bean> redisKeyValueTemplates = new HashMap<>(); + private final Map, Bean>> redisOperations = new HashMap<>(); public RedisRepositoryExtension() { LOG.info("Activating CDI extension for Spring Data Redis repositories."); @@ -86,7 +86,7 @@ public class RedisRepositoryExtension extends CdiRepositoryExtensionSupport { } // Store the Key-Value Templates bean using its qualifiers. - redisKeyValueTemplates.put(new HashSet(bean.getQualifiers()), (Bean) bean); + redisKeyValueTemplates.put(new HashSet<>(bean.getQualifiers()), (Bean) bean); } if (beanType instanceof Class && RedisKeyValueAdapter.class.isAssignableFrom((Class) beanType)) { @@ -96,7 +96,7 @@ public class RedisRepositoryExtension extends CdiRepositoryExtensionSupport { } // Store the RedisKeyValueAdapter bean using its qualifiers. - redisKeyValueAdapters.put(new HashSet(bean.getQualifiers()), (Bean) bean); + redisKeyValueAdapters.put(new HashSet<>(bean.getQualifiers()), (Bean) bean); } if (beanType instanceof Class && RedisOperations.class.isAssignableFrom((Class) beanType)) { @@ -106,7 +106,7 @@ public class RedisRepositoryExtension extends CdiRepositoryExtensionSupport { } // Store the RedisOperations bean using its qualifiers. - redisOperations.put(new HashSet(bean.getQualifiers()), (Bean>) bean); + redisOperations.put(new HashSet<>(bean.getQualifiers()), (Bean>) bean); } } } @@ -192,7 +192,7 @@ public class RedisRepositoryExtension extends CdiRepositoryExtensionSupport { } // Construct and return the repository bean. - return new RedisRepositoryBean(redisKeyValueTemplate, qualifiers, repositoryType, beanManager, + return new RedisRepositoryBean<>(redisKeyValueTemplate, qualifiers, repositoryType, beanManager, getCustomImplementationDetector()); } diff --git a/src/main/java/org/springframework/data/redis/repository/query/RedisOperationChain.java b/src/main/java/org/springframework/data/redis/repository/query/RedisOperationChain.java index edf535902..e34418f81 100644 --- a/src/main/java/org/springframework/data/redis/repository/query/RedisOperationChain.java +++ b/src/main/java/org/springframework/data/redis/repository/query/RedisOperationChain.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,14 +28,14 @@ import org.springframework.util.ObjectUtils; /** * Simple set of operations required to run queries against Redis. - * + * * @author Christoph Strobl * @since 1.7 */ public class RedisOperationChain { - private Set sismember = new LinkedHashSet(); - private Set orSismember = new LinkedHashSet(); + private Set sismember = new LinkedHashSet<>(); + private Set orSismember = new LinkedHashSet<>(); private NearPath near; public void sismember(String path, Object value) { diff --git a/src/main/java/org/springframework/data/redis/repository/query/RedisQueryCreator.java b/src/main/java/org/springframework/data/redis/repository/query/RedisQueryCreator.java index ddcef5f06..fbb82cd61 100644 --- a/src/main/java/org/springframework/data/redis/repository/query/RedisQueryCreator.java +++ b/src/main/java/org/springframework/data/redis/repository/query/RedisQueryCreator.java @@ -96,7 +96,7 @@ public class RedisQueryCreator extends AbstractQueryCreator complete(final RedisOperationChain criteria, Sort sort) { - KeyValueQuery query = new KeyValueQuery(criteria); + KeyValueQuery query = new KeyValueQuery<>(criteria); if (query.getCriteria() != null && !CollectionUtils.isEmpty(query.getCriteria().getSismember()) && !CollectionUtils.isEmpty(query.getCriteria().getOrSismember())) diff --git a/src/main/java/org/springframework/data/redis/serializer/DefaultRedisSerializationContext.java b/src/main/java/org/springframework/data/redis/serializer/DefaultRedisSerializationContext.java index 3a53c9acf..2fc1de814 100644 --- a/src/main/java/org/springframework/data/redis/serializer/DefaultRedisSerializationContext.java +++ b/src/main/java/org/springframework/data/redis/serializer/DefaultRedisSerializationContext.java @@ -170,7 +170,7 @@ class DefaultRedisSerializationContext implements RedisSerializationContex Assert.notNull(hashKeyTuple, "HashKey SerializationPair must not be null!"); Assert.notNull(hashValueTuple, "ValueKey SerializationPair must not be null!"); - return new DefaultRedisSerializationContext(keyTuple, valueTuple, hashKeyTuple, hashValueTuple, + return new DefaultRedisSerializationContext<>(keyTuple, valueTuple, hashKeyTuple, hashValueTuple, stringTuple); } } diff --git a/src/main/java/org/springframework/data/redis/serializer/RedisSerializationContext.java b/src/main/java/org/springframework/data/redis/serializer/RedisSerializationContext.java index aac24fb0e..4daa61bfc 100644 --- a/src/main/java/org/springframework/data/redis/serializer/RedisSerializationContext.java +++ b/src/main/java/org/springframework/data/redis/serializer/RedisSerializationContext.java @@ -161,7 +161,7 @@ public interface RedisSerializationContext { Assert.notNull(serializer, "RedisSerializer must not be null!"); - return new RedisSerializerToSerializationPairAdapter(serializer); + return new RedisSerializerToSerializationPairAdapter<>(serializer); } /** diff --git a/src/main/java/org/springframework/data/redis/serializer/SerializationUtils.java b/src/main/java/org/springframework/data/redis/serializer/SerializationUtils.java index 36b7566d3..59be7f1c4 100644 --- a/src/main/java/org/springframework/data/redis/serializer/SerializationUtils.java +++ b/src/main/java/org/springframework/data/redis/serializer/SerializationUtils.java @@ -1,12 +1,12 @@ /* - * Copyright 2011-2013 the original author or authors. - * + * Copyright 2011-2017 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. @@ -25,7 +25,7 @@ import java.util.Set; /** * Utility class with various serialization-related methods. - * + * * @author Costin Leau */ public abstract class SerializationUtils { @@ -44,8 +44,8 @@ public abstract class SerializationUtils { return null; } - Collection values = (List.class.isAssignableFrom(type) ? new ArrayList(rawValues.size()) - : new LinkedHashSet(rawValues.size())); + Collection values = (List.class.isAssignableFrom(type) ? new ArrayList<>(rawValues.size()) + : new LinkedHashSet<>(rawValues.size())); for (byte[] bs : rawValues) { values.add(redisSerializer.deserialize(bs)); } @@ -72,7 +72,7 @@ public abstract class SerializationUtils { if (rawValues == null) { return null; } - Map ret = new LinkedHashMap(rawValues.size()); + Map ret = new LinkedHashMap<>(rawValues.size()); for (Map.Entry entry : rawValues.entrySet()) { ret.put(redisSerializer.deserialize(entry.getKey()), redisSerializer.deserialize(entry.getValue())); } @@ -85,7 +85,7 @@ public abstract class SerializationUtils { if (rawValues == null) { return null; } - Map map = new LinkedHashMap(rawValues.size()); + Map map = new LinkedHashMap<>(rawValues.size()); for (Map.Entry entry : rawValues.entrySet()) { // May want to deserialize only key or value HK key = hashKeySerializer != null ? (HK) hashKeySerializer.deserialize(entry.getKey()) : (HK) entry.getKey(); diff --git a/src/main/java/org/springframework/data/redis/support/atomic/RedisAtomicDouble.java b/src/main/java/org/springframework/data/redis/support/atomic/RedisAtomicDouble.java index d47c75809..ecd275c4a 100644 --- a/src/main/java/org/springframework/data/redis/support/atomic/RedisAtomicDouble.java +++ b/src/main/java/org/springframework/data/redis/support/atomic/RedisAtomicDouble.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2017 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. @@ -75,9 +75,9 @@ public class RedisAtomicDouble extends Number implements Serializable, BoundKeyO Assert.hasText(redisCounter, "a valid counter name is required"); Assert.notNull(factory, "a valid factory is required"); - RedisTemplate redisTemplate = new RedisTemplate(); + RedisTemplate redisTemplate = new RedisTemplate<>(); redisTemplate.setKeySerializer(new StringRedisSerializer()); - redisTemplate.setValueSerializer(new GenericToStringSerializer(Double.class)); + redisTemplate.setValueSerializer(new GenericToStringSerializer<>(Double.class)); redisTemplate.setExposeConnection(true); redisTemplate.setConnectionFactory(factory); redisTemplate.afterPropertiesSet(); diff --git a/src/main/java/org/springframework/data/redis/support/atomic/RedisAtomicInteger.java b/src/main/java/org/springframework/data/redis/support/atomic/RedisAtomicInteger.java index a2e44270f..e1b185863 100644 --- a/src/main/java/org/springframework/data/redis/support/atomic/RedisAtomicInteger.java +++ b/src/main/java/org/springframework/data/redis/support/atomic/RedisAtomicInteger.java @@ -1,5 +1,5 @@ /* - * Copyright 2011-2016 the original author or authors. + * Copyright 2011-2017 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. @@ -98,9 +98,9 @@ public class RedisAtomicInteger extends Number implements Serializable, BoundKey } private RedisAtomicInteger(String redisCounter, RedisConnectionFactory factory, Integer initialValue) { - RedisTemplate redisTemplate = new RedisTemplate(); + RedisTemplate redisTemplate = new RedisTemplate<>(); redisTemplate.setKeySerializer(new StringRedisSerializer()); - redisTemplate.setValueSerializer(new GenericToStringSerializer(Integer.class)); + redisTemplate.setValueSerializer(new GenericToStringSerializer<>(Integer.class)); redisTemplate.setExposeConnection(true); redisTemplate.setConnectionFactory(factory); redisTemplate.afterPropertiesSet(); diff --git a/src/main/java/org/springframework/data/redis/support/atomic/RedisAtomicLong.java b/src/main/java/org/springframework/data/redis/support/atomic/RedisAtomicLong.java index 2f78d25a1..4b9f0452a 100644 --- a/src/main/java/org/springframework/data/redis/support/atomic/RedisAtomicLong.java +++ b/src/main/java/org/springframework/data/redis/support/atomic/RedisAtomicLong.java @@ -1,5 +1,5 @@ /* - * Copyright 2011-2016 the original author or authors. + * Copyright 2011-2017 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. @@ -76,9 +76,9 @@ public class RedisAtomicLong extends Number implements Serializable, BoundKeyOpe Assert.hasText(redisCounter, "a valid counter name is required"); Assert.notNull(factory, "a valid factory is required"); - RedisTemplate redisTemplate = new RedisTemplate(); + RedisTemplate redisTemplate = new RedisTemplate<>(); redisTemplate.setKeySerializer(new StringRedisSerializer()); - redisTemplate.setValueSerializer(new GenericToStringSerializer(Long.class)); + redisTemplate.setValueSerializer(new GenericToStringSerializer<>(Long.class)); redisTemplate.setExposeConnection(true); redisTemplate.setConnectionFactory(factory); redisTemplate.afterPropertiesSet(); diff --git a/src/main/java/org/springframework/data/redis/support/collections/CollectionUtils.java b/src/main/java/org/springframework/data/redis/support/collections/CollectionUtils.java index 8f0084950..e8ae66b1c 100644 --- a/src/main/java/org/springframework/data/redis/support/collections/CollectionUtils.java +++ b/src/main/java/org/springframework/data/redis/support/collections/CollectionUtils.java @@ -1,12 +1,12 @@ /* * Copyright 2011-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. @@ -26,7 +26,7 @@ import org.springframework.data.redis.core.SessionCallback; /** * Utility class used mainly for type conversion by the default collection implementations. Meant for internal use. - * + * * @author Costin Leau */ abstract class CollectionUtils { @@ -43,7 +43,7 @@ abstract class CollectionUtils { } static Collection extractKeys(Collection stores) { - Collection keys = new ArrayList(stores.size()); + Collection keys = new ArrayList<>(stores.size()); for (RedisStore store : stores) { keys.add(store.getKey()); diff --git a/src/main/java/org/springframework/data/redis/support/collections/DefaultRedisMap.java b/src/main/java/org/springframework/data/redis/support/collections/DefaultRedisMap.java index 88439273b..cdeaef4f2 100644 --- a/src/main/java/org/springframework/data/redis/support/collections/DefaultRedisMap.java +++ b/src/main/java/org/springframework/data/redis/support/collections/DefaultRedisMap.java @@ -1,12 +1,12 @@ /* - * Copyright 2011-2013 the original author or authors. - * + * Copyright 2011-2017 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. @@ -34,7 +34,7 @@ import org.springframework.data.redis.core.SessionCallback; /** * Default implementation for {@link RedisMap}. Note that the current implementation doesn't provide the same locking * semantics across all methods. In highly concurrent environments, race conditions might appear. - * + * * @author Costin Leau */ public class DefaultRedisMap implements RedisMap { @@ -66,7 +66,7 @@ public class DefaultRedisMap implements RedisMap { /** * Constructs a new DefaultRedisMap instance. - * + * * @param key * @param operations */ @@ -76,7 +76,7 @@ public class DefaultRedisMap implements RedisMap { /** * Constructs a new DefaultRedisMap instance. - * + * * @param boundOps */ public DefaultRedisMap(BoundHashOperations boundOps) { @@ -117,7 +117,7 @@ public class DefaultRedisMap implements RedisMap { Iterator keys = keySet.iterator(); Iterator values = multiGet.iterator(); - Set> entries = new LinkedHashSet>(); + Set> entries = new LinkedHashSet<>(); while (keys.hasNext()) { entries.add(new DefaultRedisMapEntry(keys.next(), values.next())); } diff --git a/src/main/java/org/springframework/data/redis/support/collections/DefaultRedisSet.java b/src/main/java/org/springframework/data/redis/support/collections/DefaultRedisSet.java index 82d08e394..7fb0b6ede 100644 --- a/src/main/java/org/springframework/data/redis/support/collections/DefaultRedisSet.java +++ b/src/main/java/org/springframework/data/redis/support/collections/DefaultRedisSet.java @@ -1,12 +1,12 @@ /* - * Copyright 2011-2014 the original author or authors. - * + * Copyright 2011-2017 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. @@ -30,7 +30,7 @@ import org.springframework.data.redis.core.ScanOptions; /** * Default implementation for {@link RedisSet}. Note that the collection support works only with normal, * non-pipeline/multi-exec connections as it requires a reply to be sent right away. - * + * * @author Costin Leau * @author Christoph Strobl */ @@ -51,7 +51,7 @@ public class DefaultRedisSet extends AbstractRedisCollection implements Re /** * Constructs a new DefaultRedisSet instance. - * + * * @param key * @param operations */ @@ -62,7 +62,7 @@ public class DefaultRedisSet extends AbstractRedisCollection implements Re /** * Constructs a new DefaultRedisSet instance. - * + * * @param boundOps */ public DefaultRedisSet(BoundSetOperations boundOps) { @@ -80,12 +80,12 @@ public class DefaultRedisSet extends AbstractRedisCollection implements Re public RedisSet diffAndStore(RedisSet set, String destKey) { boundSetOps.diffAndStore(set.getKey(), destKey); - return new DefaultRedisSet(boundSetOps.getOperations().boundSetOps(destKey)); + return new DefaultRedisSet<>(boundSetOps.getOperations().boundSetOps(destKey)); } public RedisSet diffAndStore(Collection> sets, String destKey) { boundSetOps.diffAndStore(CollectionUtils.extractKeys(sets), destKey); - return new DefaultRedisSet(boundSetOps.getOperations().boundSetOps(destKey)); + return new DefaultRedisSet<>(boundSetOps.getOperations().boundSetOps(destKey)); } public Set intersect(RedisSet set) { @@ -98,12 +98,12 @@ public class DefaultRedisSet extends AbstractRedisCollection implements Re public RedisSet intersectAndStore(RedisSet set, String destKey) { boundSetOps.intersectAndStore(set.getKey(), destKey); - return new DefaultRedisSet(boundSetOps.getOperations().boundSetOps(destKey)); + return new DefaultRedisSet<>(boundSetOps.getOperations().boundSetOps(destKey)); } public RedisSet intersectAndStore(Collection> sets, String destKey) { boundSetOps.intersectAndStore(CollectionUtils.extractKeys(sets), destKey); - return new DefaultRedisSet(boundSetOps.getOperations().boundSetOps(destKey)); + return new DefaultRedisSet<>(boundSetOps.getOperations().boundSetOps(destKey)); } public Set union(RedisSet set) { @@ -116,12 +116,12 @@ public class DefaultRedisSet extends AbstractRedisCollection implements Re public RedisSet unionAndStore(RedisSet set, String destKey) { boundSetOps.unionAndStore(set.getKey(), destKey); - return new DefaultRedisSet(boundSetOps.getOperations().boundSetOps(destKey)); + return new DefaultRedisSet<>(boundSetOps.getOperations().boundSetOps(destKey)); } public RedisSet unionAndStore(Collection> sets, String destKey) { boundSetOps.unionAndStore(CollectionUtils.extractKeys(sets), destKey); - return new DefaultRedisSet(boundSetOps.getOperations().boundSetOps(destKey)); + return new DefaultRedisSet<>(boundSetOps.getOperations().boundSetOps(destKey)); } @SuppressWarnings("unchecked") diff --git a/src/main/java/org/springframework/data/redis/support/collections/DefaultRedisZSet.java b/src/main/java/org/springframework/data/redis/support/collections/DefaultRedisZSet.java index 4bf94a699..97e164467 100644 --- a/src/main/java/org/springframework/data/redis/support/collections/DefaultRedisZSet.java +++ b/src/main/java/org/springframework/data/redis/support/collections/DefaultRedisZSet.java @@ -1,12 +1,12 @@ /* - * Copyright 2011-2016 the original author or authors. - * + * Copyright 2011-2017 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. @@ -20,7 +20,6 @@ import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; -import org.springframework.core.convert.converter.Converter; import org.springframework.data.redis.connection.DataType; import org.springframework.data.redis.connection.RedisZSetCommands.Limit; import org.springframework.data.redis.connection.RedisZSetCommands.Range; @@ -34,7 +33,7 @@ import org.springframework.data.redis.core.ZSetOperations.TypedTuple; /** * Default implementation for {@link RedisZSet}. Note that the collection support works only with normal, * non-pipeline/multi-exec connections as it requires a reply to be sent right away. - * + * * @author Costin Leau * @author Christoph Strobl * @author Mark Paluch @@ -57,7 +56,7 @@ public class DefaultRedisZSet extends AbstractRedisCollection implements R /** * Constructs a new DefaultRedisZSet instance with a default score of '1'. - * + * * @param key * @param operations */ @@ -67,7 +66,7 @@ public class DefaultRedisZSet extends AbstractRedisCollection implements R /** * Constructs a new DefaultRedisSortedSet instance. - * + * * @param key * @param operations * @param defaultScore @@ -80,7 +79,7 @@ public class DefaultRedisZSet extends AbstractRedisCollection implements R /** * Constructs a new DefaultRedisZSet instance with a default score of '1'. - * + * * @param boundOps */ public DefaultRedisZSet(BoundZSetOperations boundOps) { @@ -89,7 +88,7 @@ public class DefaultRedisZSet extends AbstractRedisCollection implements R /** * Constructs a new DefaultRedisZSet instance. - * + * * @param boundOps * @param defaultScore */ @@ -101,12 +100,12 @@ public class DefaultRedisZSet extends AbstractRedisCollection implements R public RedisZSet intersectAndStore(RedisZSet set, String destKey) { boundZSetOps.intersectAndStore(set.getKey(), destKey); - return new DefaultRedisZSet(boundZSetOps.getOperations().boundZSetOps(destKey), getDefaultScore()); + return new DefaultRedisZSet<>(boundZSetOps.getOperations().boundZSetOps(destKey), getDefaultScore()); } public RedisZSet intersectAndStore(Collection> sets, String destKey) { boundZSetOps.intersectAndStore(CollectionUtils.extractKeys(sets), destKey); - return new DefaultRedisZSet(boundZSetOps.getOperations().boundZSetOps(destKey), getDefaultScore()); + return new DefaultRedisZSet<>(boundZSetOps.getOperations().boundZSetOps(destKey), getDefaultScore()); } public Set range(long start, long end) { @@ -171,12 +170,12 @@ public class DefaultRedisZSet extends AbstractRedisCollection implements R public RedisZSet unionAndStore(RedisZSet set, String destKey) { boundZSetOps.unionAndStore(set.getKey(), destKey); - return new DefaultRedisZSet(boundZSetOps.getOperations().boundZSetOps(destKey), getDefaultScore()); + return new DefaultRedisZSet<>(boundZSetOps.getOperations().boundZSetOps(destKey), getDefaultScore()); } public RedisZSet unionAndStore(Collection> sets, String destKey) { boundZSetOps.unionAndStore(CollectionUtils.extractKeys(sets), destKey); - return new DefaultRedisZSet(boundZSetOps.getOperations().boundZSetOps(destKey), getDefaultScore()); + return new DefaultRedisZSet<>(boundZSetOps.getOperations().boundZSetOps(destKey), getDefaultScore()); } public boolean add(E e) { @@ -262,13 +261,7 @@ public class DefaultRedisZSet extends AbstractRedisCollection implements R */ @Override public Cursor scan() { - return new ConvertingCursor, E>(scan(ScanOptions.NONE), new Converter, E>() { - - @Override - public E convert(TypedTuple source) { - return source.getValue(); - } - }); + return new ConvertingCursor<>(scan(ScanOptions.NONE), TypedTuple::getValue); } /** diff --git a/src/main/java/org/springframework/data/redis/support/collections/RedisProperties.java b/src/main/java/org/springframework/data/redis/support/collections/RedisProperties.java index 8d332e718..af7d56806 100644 --- a/src/main/java/org/springframework/data/redis/support/collections/RedisProperties.java +++ b/src/main/java/org/springframework/data/redis/support/collections/RedisProperties.java @@ -1,12 +1,12 @@ /* - * Copyright 2011-2013 the original author or authors. - * + * Copyright 2011-2017 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. @@ -39,7 +39,7 @@ import org.springframework.data.redis.core.RedisOperations; * {@link org.springframework.beans.factory.config.PropertiesFactoryBean}. *

* Note that this implementation only accepts Strings - objects of other type are not supported. - * + * * @see Properties * @see org.springframework.core.io.support.PropertiesLoaderSupport * @author Costin Leau @@ -58,7 +58,7 @@ public class RedisProperties extends Properties implements RedisMapRedisProperties instance. - * + * * @param key * @param operations */ @@ -68,19 +68,19 @@ public class RedisProperties extends Properties implements RedisMapRedisProperties instance. - * + * * @param defaults * @param boundOps */ public RedisProperties(Properties defaults, BoundHashOperations boundOps) { super(defaults); this.hashOps = boundOps; - this.delegate = new DefaultRedisMap(boundOps); + this.delegate = new DefaultRedisMap<>(boundOps); } /** * Constructs a new RedisProperties instance. - * + * * @param defaults * @param key * @param operations @@ -103,7 +103,7 @@ public class RedisProperties extends Properties implements RedisMap propertyNames() { - Set keys = new LinkedHashSet(delegate.keySet()); + Set keys = new LinkedHashSet<>(delegate.keySet()); if (defaults != null) { keys.addAll(defaults.stringPropertyNames()); } diff --git a/src/main/java/org/springframework/data/redis/support/collections/RedisZSet.java b/src/main/java/org/springframework/data/redis/support/collections/RedisZSet.java index f3ce4b3d8..13114a016 100644 --- a/src/main/java/org/springframework/data/redis/support/collections/RedisZSet.java +++ b/src/main/java/org/springframework/data/redis/support/collections/RedisZSet.java @@ -1,12 +1,12 @@ /* - * Copyright 2011-2016 the original author or authors. - * + * Copyright 2011-2017 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. @@ -32,10 +32,10 @@ import org.springframework.data.redis.core.ZSetOperations.TypedTuple; * associated with each item. *

* Since using a {@link Comparator} does not apply, a ZSet implements the {@link SortedSet} methods where applicable. - * + * * @author Costin Leau * @author Mark Paluch - * @auhtor Christoph Strobl + * @author Christoph Strobl */ public interface RedisZSet extends RedisCollection, Set { @@ -54,7 +54,7 @@ public interface RedisZSet extends RedisCollection, Set { /** * Get all elements with lexicographical ordering with a value between {@link Range#getMin()} and * {@link Range#getMax()}. - * + * * @param range must not be {@literal null}. * @return * @see BoundZSetOperations#rangeByLex(Range) @@ -66,7 +66,7 @@ public interface RedisZSet extends RedisCollection, Set { * Get all elements {@literal n} elements, where {@literal n = } {@link Limit#getCount()}, starting at * {@link Limit#getOffset()} with lexicographical ordering having a value between {@link Range#getMin()} and * {@link Range#getMax()}. - * + * * @param range must not be {@literal null}. * @param limit can be {@literal null}. * @return @@ -93,7 +93,7 @@ public interface RedisZSet extends RedisCollection, Set { /** * Adds an element to the set with the given score, or updates the score if the element exists. - * + * * @param e element to add * @param score element score * @return true if a new element was added, false otherwise (only the score has been updated) @@ -108,7 +108,7 @@ public interface RedisZSet extends RedisCollection, Set { /** * Returns the score of the given element. Returns null if the element is not contained by the set. - * + * * @param o object * @return the score associated with the given object */ @@ -117,7 +117,7 @@ public interface RedisZSet extends RedisCollection, Set { /** * Returns the rank (position) of the given element in the set, in ascending order. Returns null if the element is not * contained by the set. - * + * * @param o object * @return rank of the given object */ @@ -126,7 +126,7 @@ public interface RedisZSet extends RedisCollection, Set { /** * Returns the rank (position) of the given element in the set, in descending order. Returns null if the element is * not contained by the set. - * + * * @param o object * @return reverse rank of the given object */ @@ -134,14 +134,14 @@ public interface RedisZSet extends RedisCollection, Set { /** * Returns the default score used by this set. - * + * * @return the default score used by the implementation. */ Double getDefaultScore(); /** * Returns the first (lowest) element currently in this sorted set. - * + * * @return the first (lowest) element currently in this sorted set. * @throws NoSuchElementException sorted set is empty. */ @@ -149,7 +149,7 @@ public interface RedisZSet extends RedisCollection, Set { /** * Returns the last (highest) element currently in this sorted set. - * + * * @return the last (highest) element currently in this sorted set. * @throws NoSuchElementException sorted set is empty. */ diff --git a/src/main/java/org/springframework/data/redis/util/ByteUtils.java b/src/main/java/org/springframework/data/redis/util/ByteUtils.java index f7ef523d9..36d966c1f 100644 --- a/src/main/java/org/springframework/data/redis/util/ByteUtils.java +++ b/src/main/java/org/springframework/data/redis/util/ByteUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2016 the original author or authors. + * Copyright 2015-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,7 +63,7 @@ public final class ByteUtils { return new byte[][] {}; } - List bytes = new ArrayList(); + List bytes = new ArrayList<>(); int offset = 0; for (int i = 0; i <= source.length; i++) { diff --git a/src/test/java/org/springframework/data/redis/ConnectionFactoryTracker.java b/src/test/java/org/springframework/data/redis/ConnectionFactoryTracker.java index d0b03b3bf..8540c237f 100644 --- a/src/test/java/org/springframework/data/redis/ConnectionFactoryTracker.java +++ b/src/test/java/org/springframework/data/redis/ConnectionFactoryTracker.java @@ -32,7 +32,7 @@ import org.springframework.data.redis.connection.RedisConnectionFactory; */ public abstract class ConnectionFactoryTracker { - private static Set connFactories = new LinkedHashSet(); + private static Set connFactories = new LinkedHashSet<>(); public static void add(RedisConnectionFactory factory) { connFactories.add(factory); diff --git a/src/test/java/org/springframework/data/redis/cache/LegacyRedisCacheTests.java b/src/test/java/org/springframework/data/redis/cache/LegacyRedisCacheTests.java index 450698181..c7a1c2bac 100644 --- a/src/test/java/org/springframework/data/redis/cache/LegacyRedisCacheTests.java +++ b/src/test/java/org/springframework/data/redis/cache/LegacyRedisCacheTests.java @@ -88,7 +88,7 @@ public class LegacyRedisCacheTests { Collection params = AbstractOperationsTestParams.testParams(); - Collection target = new ArrayList(); + Collection target = new ArrayList<>(); for (Object[] source : params) { Object[] cacheNullDisabled = Arrays.copyOf(source, source.length + 1); @@ -179,14 +179,12 @@ public class LegacyRedisCacheTests { cache.put(key1, value1); cache.put(key2, value2); - Thread th = new Thread(new Runnable() { - public void run() { - cache.clear(); - cache.put(k1, v1); - cache.put(k2, v2); - failed.set(v1.equals(cache.get(k1))); + Thread th = new Thread(() -> { + cache.clear(); + cache.put(k1, v1); + cache.put(k2, v2); + failed.set(v1.equals(cache.get(k1))); - } }, "concurrent-cache-access"); th.start(); th.join(); @@ -216,20 +214,14 @@ public class LegacyRedisCacheTests { int numTries = 10; final AtomicBoolean monitorStateException = new AtomicBoolean(false); final CountDownLatch latch = new CountDownLatch(numTries); - Runnable clearCache = new Runnable() { - public void run() { - cache.clear(); - } - }; - Runnable putCache = new Runnable() { - public void run() { - try { - cache.put(key1, value1); - } catch (IllegalMonitorStateException e) { - monitorStateException.set(true); - } finally { - latch.countDown(); - } + Runnable clearCache = cache::clear; + Runnable putCache = () -> { + try { + cache.put(key1, value1); + } catch (IllegalMonitorStateException e) { + monitorStateException.set(true); + } finally { + latch.countDown(); } }; for (int i = 0; i < numTries; i++) { @@ -355,12 +347,7 @@ public class LegacyRedisCacheTests { assumeThat("Only suitable when cache does allow null values.", allowCacheNullValues, is(true)); Object key = getKey(); - Object value = cache.get(key, new Callable() { - @Override - public Object call() throws Exception { - return null; - } - }); + Object value = cache.get(key, () -> null); assertThat(value, is(nullValue())); assertThat(cache.get(key).get(), is(nullValue())); @@ -372,23 +359,15 @@ public class LegacyRedisCacheTests { assumeThat("Only suitable when cache does NOT allow null values.", allowCacheNullValues, is(false)); Object key = getKey(); - Object value = cache.get(key, new Callable() { - @Override - public Object call() throws Exception { - return null; - } - }); + Object value = cache.get(key, () -> null); } @Test(expected = ValueRetrievalException.class) public void testCacheGetSynchronizedThrowsExceptionInValueLoader() { Object key = getKey(); - Object value = cache.get(key, new Callable() { - @Override - public Object call() throws Exception { - throw new RuntimeException("doh!"); - } + Object value = cache.get(key, () -> { + throw new RuntimeException("doh!"); }); } @@ -400,12 +379,7 @@ public class LegacyRedisCacheTests { Object key = getKey(); cache.put(key, null); - Object cachedValue = cache.get(key, new Callable() { - @Override - public Object call() throws Exception { - return null; - } - }); + Object cachedValue = cache.get(key, () -> null); assertThat(cachedValue, is(nullValue())); } @@ -440,7 +414,7 @@ public class LegacyRedisCacheTests { public void thread2() { waitForTick(1); - assertThat(redisCache.get("key", new TestCacheLoader("illegal value")), equalTo("test")); + assertThat(redisCache.get("key", new TestCacheLoader<>("illegal value")), equalTo("test")); assertTick(2); } } diff --git a/src/test/java/org/springframework/data/redis/config/StubErrorHandler.java b/src/test/java/org/springframework/data/redis/config/StubErrorHandler.java index c5b4fae9d..a0e583911 100644 --- a/src/test/java/org/springframework/data/redis/config/StubErrorHandler.java +++ b/src/test/java/org/springframework/data/redis/config/StubErrorHandler.java @@ -1,12 +1,12 @@ /* - * Copyright 2011-2013 the original author or authors. - * + * Copyright 2011-2017 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. @@ -25,7 +25,7 @@ import org.springframework.util.ErrorHandler; */ public class StubErrorHandler implements ErrorHandler { - public BlockingDeque throwables = new LinkedBlockingDeque(); + public BlockingDeque throwables = new LinkedBlockingDeque<>(); public void handleError(Throwable t) { throwables.add(t); diff --git a/src/test/java/org/springframework/data/redis/connection/AbstractConnectionIntegrationTests.java b/src/test/java/org/springframework/data/redis/connection/AbstractConnectionIntegrationTests.java index 3c98884e4..7a211ee15 100644 --- a/src/test/java/org/springframework/data/redis/connection/AbstractConnectionIntegrationTests.java +++ b/src/test/java/org/springframework/data/redis/connection/AbstractConnectionIntegrationTests.java @@ -27,18 +27,7 @@ import static org.springframework.data.redis.connection.RedisGeoCommands.Distanc import static org.springframework.data.redis.connection.RedisGeoCommands.GeoRadiusCommandArgs.*; import static org.springframework.data.redis.core.ScanOptions.*; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.UUID; +import java.util.*; import java.util.concurrent.BlockingDeque; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingDeque; @@ -650,7 +639,7 @@ public abstract class AbstractConnectionIntegrationTests { public void testPubSubWithNamedChannels() throws Exception { final String expectedChannel = "channel1"; final String expectedMessage = "msg"; - final BlockingDeque messages = new LinkedBlockingDeque(); + final BlockingDeque messages = new LinkedBlockingDeque<>(); MessageListener listener = (message, pattern) -> { messages.add(message); @@ -659,12 +648,7 @@ public abstract class AbstractConnectionIntegrationTests { Thread th = new Thread(() -> { // sync to let the registration happen - waitFor(new TestCondition() { - @Override - public boolean passes() { - return connection.isSubscribed(); - } - }, 2000); + waitFor(connection::isSubscribed, 2000); try { Thread.sleep(500); } catch (InterruptedException o_O) {} @@ -706,12 +690,7 @@ public abstract class AbstractConnectionIntegrationTests { Thread th = new Thread(() -> { // sync to let the registration happen - waitFor(new TestCondition() { - @Override - public boolean passes() { - return connection.isSubscribed(); - } - }, 2000); + waitFor(connection::isSubscribed, 2000); try { Thread.sleep(500); @@ -1101,7 +1080,7 @@ public abstract class AbstractConnectionIntegrationTests { @Test public void testMSet() { - Map vals = new HashMap(); + Map vals = new HashMap<>(); vals.put("color", "orange"); vals.put("size", "1"); connection.mSetString(vals); @@ -1111,7 +1090,7 @@ public abstract class AbstractConnectionIntegrationTests { @Test public void testMSetNx() { - Map vals = new HashMap(); + Map vals = new HashMap<>(); vals.put("height", "5"); vals.put("width", "1"); actual.add(connection.mSetNXString(vals)); @@ -1122,7 +1101,7 @@ public abstract class AbstractConnectionIntegrationTests { @Test public void testMSetNxFailure() { connection.set("height", "2"); - Map vals = new HashMap(); + Map vals = new HashMap<>(); vals.put("height", "5"); vals.put("width", "1"); actual.add(connection.mSetNXString(vals)); @@ -1376,7 +1355,7 @@ public abstract class AbstractConnectionIntegrationTests { actual.add(connection.sAdd("myset", "bar")); actual.add(connection.sMembers("myset")); verifyResults( - Arrays.asList(new Object[] { 1l, 1l, new HashSet(Arrays.asList(new String[] { "foo", "bar" })) })); + Arrays.asList(new Object[] { 1l, 1l, new HashSet<>(Arrays.asList(new String[] { "foo", "bar" })) })); } @Test @@ -1385,7 +1364,7 @@ public abstract class AbstractConnectionIntegrationTests { actual.add(connection.sAdd("myset", "baz")); actual.add(connection.sMembers("myset")); verifyResults(Arrays - .asList(new Object[] { 2l, 1l, new HashSet(Arrays.asList(new String[] { "foo", "bar", "baz" })) })); + .asList(new Object[] { 2l, 1l, new HashSet<>(Arrays.asList(new String[] { "foo", "bar", "baz" })) })); } @Test @@ -1402,7 +1381,7 @@ public abstract class AbstractConnectionIntegrationTests { actual.add(connection.sAdd("myset", "bar")); actual.add(connection.sAdd("otherset", "bar")); actual.add(connection.sDiff("myset", "otherset")); - verifyResults(Arrays.asList(new Object[] { 1l, 1l, 1l, new HashSet(Collections.singletonList("foo")) })); + verifyResults(Arrays.asList(new Object[] { 1l, 1l, 1l, new HashSet<>(Collections.singletonList("foo")) })); } @Test @@ -1413,7 +1392,7 @@ public abstract class AbstractConnectionIntegrationTests { actual.add(connection.sDiffStore("thirdset", "myset", "otherset")); actual.add(connection.sMembers("thirdset")); verifyResults( - Arrays.asList(new Object[] { 1l, 1l, 1l, 1l, new HashSet(Collections.singletonList("foo")) })); + Arrays.asList(new Object[] { 1l, 1l, 1l, 1l, new HashSet<>(Collections.singletonList("foo")) })); } @Test @@ -1422,7 +1401,7 @@ public abstract class AbstractConnectionIntegrationTests { actual.add(connection.sAdd("myset", "bar")); actual.add(connection.sAdd("otherset", "bar")); actual.add(connection.sInter("myset", "otherset")); - verifyResults(Arrays.asList(new Object[] { 1l, 1l, 1l, new HashSet(Collections.singletonList("bar")) })); + verifyResults(Arrays.asList(new Object[] { 1l, 1l, 1l, new HashSet<>(Collections.singletonList("bar")) })); } @Test @@ -1433,7 +1412,7 @@ public abstract class AbstractConnectionIntegrationTests { actual.add(connection.sInterStore("thirdset", "myset", "otherset")); actual.add(connection.sMembers("thirdset")); verifyResults( - Arrays.asList(new Object[] { 1l, 1l, 1l, 1l, new HashSet(Collections.singletonList("bar")) })); + Arrays.asList(new Object[] { 1l, 1l, 1l, 1l, new HashSet<>(Collections.singletonList("bar")) })); } @Test @@ -1460,7 +1439,7 @@ public abstract class AbstractConnectionIntegrationTests { actual.add(connection.sAdd("myset", "bar")); actual.add(connection.sPop("myset")); assertTrue( - new HashSet(Arrays.asList(new String[] { "foo", "bar" })).contains((String) getResults().get(2))); + new HashSet<>(Arrays.asList(new String[] { "foo", "bar" })).contains((String) getResults().get(2))); } @Test // DATAREDIS-688 @@ -1479,7 +1458,7 @@ public abstract class AbstractConnectionIntegrationTests { actual.add(connection.sAdd("myset", "foo")); actual.add(connection.sAdd("myset", "bar")); actual.add(connection.sRandMember("myset")); - assertTrue(new HashSet(Arrays.asList(new String[] { "foo", "bar" })).contains(getResults().get(2))); + assertTrue(new HashSet<>(Arrays.asList(new String[] { "foo", "bar" })).contains(getResults().get(2))); } @Test @@ -1572,10 +1551,10 @@ public abstract class AbstractConnectionIntegrationTests { @Test public void testZAddMultiple() { - Set strTuples = new HashSet(); + Set strTuples = new HashSet<>(); strTuples.add(new DefaultStringTuple("Bob".getBytes(), "Bob", 2.0)); strTuples.add(new DefaultStringTuple("James".getBytes(), "James", 1.0)); - Set tuples = new HashSet(); + Set tuples = new HashSet<>(); tuples.add(new DefaultTuple("Joe".getBytes(), 2.5)); actual.add(connection.zAdd("myset", strTuples)); actual.add(connection.zAdd("myset".getBytes(), tuples)); @@ -1665,7 +1644,7 @@ public abstract class AbstractConnectionIntegrationTests { actual.add(connection.zAdd("myset", 1, "James")); actual.add(connection.zRangeByScore("myset", 1d, 3d, 1, -1)); verifyResults( - Arrays.asList(new Object[] { true, true, new LinkedHashSet(Arrays.asList(new String[] { "Bob" })) })); + Arrays.asList(new Object[] { true, true, new LinkedHashSet<>(Arrays.asList(new String[] { "Bob" })) })); } @Test @@ -1673,7 +1652,7 @@ public abstract class AbstractConnectionIntegrationTests { actual.add(connection.zAdd("myset", 2, "Bob")); actual.add(connection.zAdd("myset", 1, "James")); actual.add(connection.zRangeByScoreWithScores("myset", 2d, 5d)); - verifyResults(Arrays.asList(new Object[] { true, true, new LinkedHashSet( + verifyResults(Arrays.asList(new Object[] { true, true, new LinkedHashSet<>( Arrays.asList(new StringTuple[] { new DefaultStringTuple("Bob".getBytes(), "Bob", 2d) })) })); } @@ -1682,7 +1661,7 @@ public abstract class AbstractConnectionIntegrationTests { actual.add(connection.zAdd("myset", 2, "Bob")); actual.add(connection.zAdd("myset", 1, "James")); actual.add(connection.zRangeByScoreWithScores("myset", 1d, 5d, 0, 1)); - verifyResults(Arrays.asList(new Object[] { true, true, new LinkedHashSet( + verifyResults(Arrays.asList(new Object[] { true, true, new LinkedHashSet<>( Arrays.asList(new StringTuple[] { new DefaultStringTuple("James".getBytes(), "James", 1d) })) })); } @@ -1728,7 +1707,7 @@ public abstract class AbstractConnectionIntegrationTests { actual.add(connection.zAdd("myset".getBytes(), 2, "Bob".getBytes())); actual.add(connection.zAdd("myset".getBytes(), 1, "James".getBytes())); actual.add(connection.zRevRangeByScoreWithScores("myset", 0d, 3d, 0, 1)); - verifyResults(Arrays.asList(new Object[] { true, true, new LinkedHashSet( + verifyResults(Arrays.asList(new Object[] { true, true, new LinkedHashSet<>( Arrays.asList(new StringTuple[] { new DefaultStringTuple("Bob".getBytes(), "Bob", 2d) })) })); } @@ -1921,7 +1900,7 @@ public abstract class AbstractConnectionIntegrationTests { @Test public void testHMGetSet() { - Map tuples = new HashMap(); + Map tuples = new HashMap<>(); tuples.put("key", "foo"); tuples.put("key2", "bar"); connection.hMSet("test", tuples); diff --git a/src/test/java/org/springframework/data/redis/connection/AbstractConnectionPipelineIntegrationTests.java b/src/test/java/org/springframework/data/redis/connection/AbstractConnectionPipelineIntegrationTests.java index 93c4d4bf2..0d1f8075d 100644 --- a/src/test/java/org/springframework/data/redis/connection/AbstractConnectionPipelineIntegrationTests.java +++ b/src/test/java/org/springframework/data/redis/connection/AbstractConnectionPipelineIntegrationTests.java @@ -31,7 +31,7 @@ import org.springframework.test.annotation.IfProfileValue; *

* Pipelined results are generally native to the provider and not transformed by our {@link RedisConnection}, so this * test overrides {@link AbstractConnectionIntegrationTests} when result types are different - * + * * @author Jennifer Hickey * @author Christoph Strobl */ @@ -132,7 +132,7 @@ abstract public class AbstractConnectionPipelineIntegrationTests extends Abstrac } protected void verifyResults(List expected) { - List expectedPipeline = new ArrayList(); + List expectedPipeline = new ArrayList<>(); for (int i = 0; i < actual.size(); i++) { expectedPipeline.add(null); } diff --git a/src/test/java/org/springframework/data/redis/connection/AbstractConnectionTransactionIntegrationTests.java b/src/test/java/org/springframework/data/redis/connection/AbstractConnectionTransactionIntegrationTests.java index 8517fdd25..b8029f5d0 100644 --- a/src/test/java/org/springframework/data/redis/connection/AbstractConnectionTransactionIntegrationTests.java +++ b/src/test/java/org/springframework/data/redis/connection/AbstractConnectionTransactionIntegrationTests.java @@ -123,7 +123,7 @@ abstract public class AbstractConnectionTransactionIntegrationTests extends Abst } protected void verifyResults(List expected) { - List expectedTx = new ArrayList(); + List expectedTx = new ArrayList<>(); for (int i = 0; i < actual.size(); i++) { expectedTx.add(null); } diff --git a/src/test/java/org/springframework/data/redis/connection/ClusterCommandExecutorUnitTests.java b/src/test/java/org/springframework/data/redis/connection/ClusterCommandExecutorUnitTests.java index 2f590e02b..8aaefa064 100644 --- a/src/test/java/org/springframework/data/redis/connection/ClusterCommandExecutorUnitTests.java +++ b/src/test/java/org/springframework/data/redis/connection/ClusterCommandExecutorUnitTests.java @@ -82,37 +82,18 @@ public class ClusterCommandExecutorUnitTests { private ClusterCommandExecutor executor; - private static final ConnectionCommandCallback COMMAND_CALLBACK = new ConnectionCommandCallback() { + private static final ConnectionCommandCallback COMMAND_CALLBACK = Connection::theWheelWeavesAsTheWheelWills; - @Override - public String doInCluster(Connection connection) { - return connection.theWheelWeavesAsTheWheelWills(); - } - }; + private static final Converter exceptionConverter = source -> { - private static final Converter exceptionConverter = new Converter() { - - @Override - public DataAccessException convert(Exception source) { - - if (source instanceof MovedException) { - return new ClusterRedirectException(1000, ((MovedException) source).host, ((MovedException) source).port, - source); - } - - return new InvalidDataAccessApiUsageException(source.getMessage(), source); + if (source instanceof MovedException) { + return new ClusterRedirectException(1000, ((MovedException) source).host, ((MovedException) source).port, source); } + return new InvalidDataAccessApiUsageException(source.getMessage(), source); }; - private static final MultiKeyConnectionCommandCallback MULTIKEY_CALLBACK = new MultiKeyConnectionCommandCallback() { - - @Override - public String doInCluster(Connection connection, byte[] key) { - return connection.bloodAndAshes(key); - } - - }; + private static final MultiKeyConnectionCommandCallback MULTIKEY_CALLBACK = Connection::bloodAndAshes; @Mock Connection con1; @Mock Connection con2; @@ -282,7 +263,8 @@ public class ClusterCommandExecutorUnitTests { when(con2.bloodAndAshes(any(byte[].class))).thenReturn("mat"); when(con3.bloodAndAshes(any(byte[].class))).thenReturn("perrin"); - MulitNodeResult result = executor.executeMuliKeyCommand(MULTIKEY_CALLBACK, new HashSet( + MulitNodeResult result = executor.executeMuliKeyCommand(MULTIKEY_CALLBACK, + new HashSet<>( Arrays.asList("key-1".getBytes(), "key-2".getBytes(), "key-3".getBytes(), "key-9".getBytes()))); assertThat(result.resultsAsList(), hasItems("rand", "mat", "perrin", "egwene")); @@ -335,7 +317,7 @@ public class ClusterCommandExecutorUnitTests { @Override public ClusterTopology getTopology() { return new ClusterTopology( - new LinkedHashSet(Arrays.asList(CLUSTER_NODE_1, CLUSTER_NODE_2, CLUSTER_NODE_3))); + new LinkedHashSet<>(Arrays.asList(CLUSTER_NODE_1, CLUSTER_NODE_2, CLUSTER_NODE_3))); } } diff --git a/src/test/java/org/springframework/data/redis/connection/DefaultStringRedisConnectionTests.java b/src/test/java/org/springframework/data/redis/connection/DefaultStringRedisConnectionTests.java index d1b1ed85a..cd3a7c277 100644 --- a/src/test/java/org/springframework/data/redis/connection/DefaultStringRedisConnectionTests.java +++ b/src/test/java/org/springframework/data/redis/connection/DefaultStringRedisConnectionTests.java @@ -55,13 +55,13 @@ import org.springframework.data.redis.serializer.StringRedisSerializer; * Unit test of {@link DefaultStringRedisConnection} * * @author Jennifer Hickey - * @auhtor Christoph Strobl + * @author Christoph Strobl * @author Ninad Divadkar * @author Mark Paluch */ public class DefaultStringRedisConnectionTests { - protected List actual = new ArrayList(); + protected List actual = new ArrayList<>(); @Mock protected RedisConnection nativeConnection; @@ -85,25 +85,25 @@ public class DefaultStringRedisConnectionTests { protected List stringList = Collections.singletonList(bar); - protected Set bytesSet = new LinkedHashSet(Collections.singletonList(barBytes)); + protected Set bytesSet = new LinkedHashSet<>(Collections.singletonList(barBytes)); - protected Set stringSet = new LinkedHashSet(Collections.singletonList(bar)); + protected Set stringSet = new LinkedHashSet<>(Collections.singletonList(bar)); - protected Map bytesMap = new HashMap(); + protected Map bytesMap = new HashMap<>(); - protected Map stringMap = new HashMap(); + protected Map stringMap = new HashMap<>(); - protected Set tupleSet = new HashSet(Collections.singletonList(new DefaultTuple(barBytes, 3d))); + protected Set tupleSet = new HashSet<>(Collections.singletonList(new DefaultTuple(barBytes, 3d))); - protected Set stringTupleSet = new HashSet( + protected Set stringTupleSet = new HashSet<>( Collections.singletonList(new DefaultStringTuple(new DefaultTuple(barBytes, 3d), bar))); protected Point point = new Point(213.00, 324.343); - protected List points = new ArrayList(); + protected List points = new ArrayList<>(); protected List>> geoResultList = Collections - .singletonList(new GeoResult>(new GeoLocation(barBytes, null), new Distance(0D))); - protected GeoResults> geoResults = new GeoResults>(geoResultList); + .singletonList(new GeoResult<>(new GeoLocation<>(barBytes, null), new Distance(0D))); + protected GeoResults> geoResults = new GeoResults<>(geoResultList); @Before public void setUp() { @@ -1233,7 +1233,7 @@ public class DefaultStringRedisConnectionTests { @Test public void testZAddMultipleBytes() { - Set tuples = new HashSet(); + Set tuples = new HashSet<>(); tuples.add(new DefaultTuple(barBytes, 3.0)); doReturn(1l).when(nativeConnection).zAdd(fooBytes, tuples); actual.add(connection.zAdd(fooBytes, tuples)); @@ -1242,9 +1242,9 @@ public class DefaultStringRedisConnectionTests { @Test public void testZAddMultiple() { - Set tuples = new HashSet(); + Set tuples = new HashSet<>(); tuples.add(new DefaultTuple(barBytes, 3.0)); - Set strTuples = new HashSet(); + Set strTuples = new HashSet<>(); strTuples.add(new DefaultStringTuple(barBytes, bar, 3.0)); doReturn(1l).when(nativeConnection).zAdd(fooBytes, tuples); actual.add(connection.zAdd(foo, strTuples)); @@ -1795,9 +1795,9 @@ public class DefaultStringRedisConnectionTests { public void testGeoAddWithGeoLocationBytes() { doReturn(1l).when(nativeConnection).geoAdd(fooBytes, - new GeoLocation(barBytes, new Point(1.23232, 34.2342434))); + new GeoLocation<>(barBytes, new Point(1.23232, 34.2342434))); - actual.add(connection.geoAdd(fooBytes, new GeoLocation(barBytes, new Point(1.23232, 34.2342434)))); + actual.add(connection.geoAdd(fooBytes, new GeoLocation<>(barBytes, new Point(1.23232, 34.2342434)))); verifyResults(Collections.singletonList(1L)); } @@ -1806,7 +1806,7 @@ public class DefaultStringRedisConnectionTests { doReturn(1l).when(nativeConnection).geoAdd(fooBytes, new Point(1.23232, 34.2342434), barBytes); - actual.add(connection.geoAdd(foo, new GeoLocation(bar, new Point(1.23232, 34.2342434)))); + actual.add(connection.geoAdd(foo, new GeoLocation<>(bar, new Point(1.23232, 34.2342434)))); verifyResults(Collections.singletonList(1L)); } @@ -1832,7 +1832,7 @@ public class DefaultStringRedisConnectionTests { @Test // DATAREDIS-438 public void testGeoAddWithIterableOfGeoLocationBytes() { - List> values = Collections.singletonList(new GeoLocation(barBytes, new Point(1, 2))); + List> values = Collections.singletonList(new GeoLocation<>(barBytes, new Point(1, 2))); doReturn(1l).when(nativeConnection).geoAdd(fooBytes, values); actual.add(connection.geoAdd(fooBytes, values)); @@ -1844,7 +1844,7 @@ public class DefaultStringRedisConnectionTests { doReturn(1l).when(nativeConnection).geoAdd(eq(fooBytes), anyMap()); - actual.add(connection.geoAdd(foo, Collections.singletonList(new GeoLocation(bar, new Point(1, 2))))); + actual.add(connection.geoAdd(foo, Collections.singletonList(new GeoLocation<>(bar, new Point(1, 2))))); verifyResults(Collections.singletonList(1L)); } diff --git a/src/test/java/org/springframework/data/redis/connection/RedisClusterConfigurationUnitTests.java b/src/test/java/org/springframework/data/redis/connection/RedisClusterConfigurationUnitTests.java index 695db800c..3e46c7d00 100644 --- a/src/test/java/org/springframework/data/redis/connection/RedisClusterConfigurationUnitTests.java +++ b/src/test/java/org/springframework/data/redis/connection/RedisClusterConfigurationUnitTests.java @@ -53,7 +53,8 @@ public class RedisClusterConfigurationUnitTests { @Test // DATAREDIS-315 public void shouldCreateRedisClusterConfigurationCorrectlyGivenMultipleHostAndPortStrings() { - RedisClusterConfiguration config = new RedisClusterConfiguration(new HashSet(Arrays.asList(HOST_AND_PORT_1, + RedisClusterConfiguration config = new RedisClusterConfiguration( + new HashSet<>(Arrays.asList(HOST_AND_PORT_1, HOST_AND_PORT_2, HOST_AND_PORT_3))); assertThat(config.getClusterNodes().size(), is(3)); diff --git a/src/test/java/org/springframework/data/redis/connection/RedisSentinelConfigurationUnitTests.java b/src/test/java/org/springframework/data/redis/connection/RedisSentinelConfigurationUnitTests.java index 1d0b282c6..785abd193 100644 --- a/src/test/java/org/springframework/data/redis/connection/RedisSentinelConfigurationUnitTests.java +++ b/src/test/java/org/springframework/data/redis/connection/RedisSentinelConfigurationUnitTests.java @@ -52,7 +52,8 @@ public class RedisSentinelConfigurationUnitTests { @Test // DATAREDIS-372 public void shouldCreateRedisSentinelConfigurationCorrectlyGivenMasterAndMultipleHostAndPortStrings() { - RedisSentinelConfiguration config = new RedisSentinelConfiguration("mymaster", new HashSet(Arrays.asList( + RedisSentinelConfiguration config = new RedisSentinelConfiguration("mymaster", + new HashSet<>(Arrays.asList( HOST_AND_PORT_1, HOST_AND_PORT_2, HOST_AND_PORT_3))); assertThat(config.getSentinels().size(), is(3)); diff --git a/src/test/java/org/springframework/data/redis/connection/jedis/JedisClusterConnectionTests.java b/src/test/java/org/springframework/data/redis/connection/jedis/JedisClusterConnectionTests.java index ca9d9b4b8..07d9475c3 100644 --- a/src/test/java/org/springframework/data/redis/connection/jedis/JedisClusterConnectionTests.java +++ b/src/test/java/org/springframework/data/redis/connection/jedis/JedisClusterConnectionTests.java @@ -91,11 +91,11 @@ public class JedisClusterConnectionTests implements ClusterConnectionTests { static final byte[] VALUE_2_BYTES = JedisConverters.toBytes(VALUE_2); static final byte[] VALUE_3_BYTES = JedisConverters.toBytes(VALUE_3); - static final GeoLocation ARIGENTO = new GeoLocation("arigento".getBytes(Charset.forName("UTF-8")), + static final GeoLocation ARIGENTO = new GeoLocation<>("arigento".getBytes(Charset.forName("UTF-8")), POINT_ARIGENTO); - static final GeoLocation CATANIA = new GeoLocation("catania".getBytes(Charset.forName("UTF-8")), + static final GeoLocation CATANIA = new GeoLocation<>("catania".getBytes(Charset.forName("UTF-8")), POINT_CATANIA); - static final GeoLocation PALERMO = new GeoLocation("palermo".getBytes(Charset.forName("UTF-8")), + static final GeoLocation PALERMO = new GeoLocation<>("palermo".getBytes(Charset.forName("UTF-8")), POINT_PALERMO); JedisCluster nativeConnection; @@ -114,7 +114,7 @@ public class JedisClusterConnectionTests implements ClusterConnectionTests { @Before public void setUp() throws IOException { - nativeConnection = new JedisCluster(new HashSet(CLUSTER_NODES)); + nativeConnection = new JedisCluster(new HashSet<>(CLUSTER_NODES)); clusterConnection = new JedisClusterConnection(this.nativeConnection); } @@ -523,7 +523,7 @@ public class JedisClusterConnectionTests implements ClusterConnectionTests { @Test // DATAREDIS-315 public void mSetShouldWorkWhenKeysMapToSameSlot() { - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put(SAME_SLOT_KEY_1_BYTES, VALUE_1_BYTES); map.put(SAME_SLOT_KEY_2_BYTES, VALUE_2_BYTES); @@ -536,7 +536,7 @@ public class JedisClusterConnectionTests implements ClusterConnectionTests { @Test // DATAREDIS-315 public void mSetShouldWorkWhenKeysDoNotMapToSameSlot() { - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put(KEY_1_BYTES, VALUE_1_BYTES); map.put(KEY_2_BYTES, VALUE_2_BYTES); @@ -549,7 +549,7 @@ public class JedisClusterConnectionTests implements ClusterConnectionTests { @Test // DATAREDIS-315 public void mSetNXShouldReturnTrueIfAllKeysSet() { - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put(KEY_1_BYTES, VALUE_1_BYTES); map.put(KEY_2_BYTES, VALUE_2_BYTES); @@ -563,7 +563,7 @@ public class JedisClusterConnectionTests implements ClusterConnectionTests { public void mSetNXShouldReturnFalseIfNotAllKeysSet() { nativeConnection.set(KEY_2_BYTES, VALUE_3_BYTES); - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put(KEY_1_BYTES, VALUE_1_BYTES); map.put(KEY_2_BYTES, VALUE_2_BYTES); @@ -576,7 +576,7 @@ public class JedisClusterConnectionTests implements ClusterConnectionTests { @Test // DATAREDIS-315 public void mSetNXShouldWorkForOnSameSlotKeys() { - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put(SAME_SLOT_KEY_1_BYTES, VALUE_1_BYTES); map.put(SAME_SLOT_KEY_2_BYTES, VALUE_2_BYTES); @@ -1483,7 +1483,7 @@ public class JedisClusterConnectionTests implements ClusterConnectionTests { @Test // DATAREDIS-315 public void hMSetShouldAddValuesCorrectly() { - Map hashes = new HashMap(); + Map hashes = new HashMap<>(); hashes.put(KEY_2_BYTES, VALUE_1_BYTES); hashes.put(KEY_3_BYTES, VALUE_2_BYTES); @@ -1566,7 +1566,7 @@ public class JedisClusterConnectionTests implements ClusterConnectionTests { @Test // DATAREDIS-315 public void hGetAllShouldRetrieveEntriesCorrectly() { - Map hashes = new HashMap(); + Map hashes = new HashMap<>(); hashes.put(KEY_2_BYTES, VALUE_1_BYTES); hashes.put(KEY_3_BYTES, VALUE_2_BYTES); diff --git a/src/test/java/org/springframework/data/redis/connection/jedis/JedisClusterConnectionUnitTests.java b/src/test/java/org/springframework/data/redis/connection/jedis/JedisClusterConnectionUnitTests.java index fdabb28a9..8183e40e0 100644 --- a/src/test/java/org/springframework/data/redis/connection/jedis/JedisClusterConnectionUnitTests.java +++ b/src/test/java/org/springframework/data/redis/connection/jedis/JedisClusterConnectionUnitTests.java @@ -21,6 +21,11 @@ import static org.mockito.Mockito.*; import static org.springframework.data.redis.connection.ClusterTestVariables.*; import static org.springframework.data.redis.test.util.MockitoUtils.*; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisCluster; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.exceptions.JedisConnectionException; + import java.io.IOException; import java.util.Arrays; import java.util.LinkedHashMap; @@ -40,11 +45,6 @@ import org.springframework.data.redis.connection.RedisClusterCommands.AddSlots; import org.springframework.data.redis.connection.RedisClusterNode; import org.springframework.data.redis.connection.jedis.JedisClusterConnection.JedisClusterTopologyProvider; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisCluster; -import redis.clients.jedis.JedisPool; -import redis.clients.jedis.exceptions.JedisConnectionException; - /** * @author Christoph Strobl * @author Mark Paluch @@ -87,7 +87,7 @@ public class JedisClusterConnectionUnitTests { @Before public void setUp() { - Map nodes = new LinkedHashMap(3); + Map nodes = new LinkedHashMap<>(3); nodes.put(CLUSTER_HOST + ":" + MASTER_NODE_1_PORT, node1PoolMock); nodes.put(CLUSTER_HOST + ":" + MASTER_NODE_2_PORT, node2PoolMock); nodes.put(CLUSTER_HOST + ":" + MASTER_NODE_3_PORT, node3PoolMock); diff --git a/src/test/java/org/springframework/data/redis/connection/jedis/JedisConnectionIntegrationTests.java b/src/test/java/org/springframework/data/redis/connection/jedis/JedisConnectionIntegrationTests.java index 90712a9fa..118341e93 100644 --- a/src/test/java/org/springframework/data/redis/connection/jedis/JedisConnectionIntegrationTests.java +++ b/src/test/java/org/springframework/data/redis/connection/jedis/JedisConnectionIntegrationTests.java @@ -18,6 +18,8 @@ package org.springframework.data.redis.connection.jedis; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; +import redis.clients.jedis.JedisPoolConfig; + import java.util.Arrays; import java.util.HashSet; import java.util.List; @@ -51,11 +53,9 @@ import org.springframework.data.redis.test.util.RequiresRedisSentinel; import org.springframework.test.annotation.IfProfileValue; import org.springframework.test.context.ContextConfiguration; -import redis.clients.jedis.JedisPoolConfig; - /** * Integration test of {@link JedisConnection} - * + * * @author Costin Leau * @author Jennifer Hickey * @author Thomas Darimont @@ -142,7 +142,7 @@ public class JedisConnectionIntegrationTests extends AbstractConnectionIntegrati @Test public void testZAddSameScores() { - Set strTuples = new HashSet(); + Set strTuples = new HashSet<>(); strTuples.add(new DefaultStringTuple("Bob".getBytes(), "Bob", 2.0)); strTuples.add(new DefaultStringTuple("James".getBytes(), "James", 2.0)); Long added = connection.zAdd("myset", strTuples); @@ -204,13 +204,11 @@ public class JedisConnectionIntegrationTests extends AbstractConnectionIntegrati final String expectedChannel = "channel1"; final String expectedMessage = "msg"; - final BlockingDeque messages = new LinkedBlockingDeque(); + final BlockingDeque messages = new LinkedBlockingDeque<>(); - MessageListener listener = new MessageListener() { - public void onMessage(Message message, byte[] pattern) { - messages.add(message); - System.out.println("Received message '" + new String(message.getBody()) + "'"); - } + MessageListener listener = (message, pattern) -> { + messages.add(message); + System.out.println("Received message '" + new String(message.getBody()) + "'"); }; Thread t = new Thread() { @@ -263,14 +261,12 @@ public class JedisConnectionIntegrationTests extends AbstractConnectionIntegrati final String expectedPattern = "channel*"; final String expectedMessage = "msg"; - final BlockingDeque messages = new LinkedBlockingDeque(); + final BlockingDeque messages = new LinkedBlockingDeque<>(); - final MessageListener listener = new MessageListener() { - public void onMessage(Message message, byte[] pattern) { - assertEquals(expectedPattern, new String(pattern)); - messages.add(message); - System.out.println("Received message '" + new String(message.getBody()) + "'"); - } + final MessageListener listener = (message, pattern) -> { + assertEquals(expectedPattern, new String(pattern)); + messages.add(message); + System.out.println("Received message '" + new String(message.getBody()) + "'"); }; Thread th = new Thread() { diff --git a/src/test/java/org/springframework/data/redis/connection/jedis/JedisConnectionUnitTestSuite.java b/src/test/java/org/springframework/data/redis/connection/jedis/JedisConnectionUnitTestSuite.java index 1a58509ff..dc9d6fe6a 100644 --- a/src/test/java/org/springframework/data/redis/connection/jedis/JedisConnectionUnitTestSuite.java +++ b/src/test/java/org/springframework/data/redis/connection/jedis/JedisConnectionUnitTestSuite.java @@ -19,6 +19,11 @@ import static org.hamcrest.core.IsEqual.*; import static org.junit.Assert.*; import static org.mockito.Mockito.*; +import redis.clients.jedis.Client; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.ScanParams; +import redis.clients.jedis.ScanResult; + import java.io.IOException; import java.util.Collections; import java.util.Map.Entry; @@ -38,11 +43,6 @@ import org.springframework.data.redis.connection.jedis.JedisConnectionUnitTestSu import org.springframework.data.redis.core.Cursor; import org.springframework.data.redis.core.ScanOptions; -import redis.clients.jedis.Client; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.ScanParams; -import redis.clients.jedis.ScanResult; - /** * @author Christoph Strobl */ @@ -168,7 +168,7 @@ public class JedisConnectionUnitTestSuite { @Test // DATAREDIS-531 public void scanShouldKeepTheConnectionOpen() { - doReturn(new ScanResult("0", Collections. emptyList())).when(jedisSpy).scan(anyString(), + doReturn(new ScanResult<>("0", Collections. emptyList())).when(jedisSpy).scan(anyString(), any(ScanParams.class)); connection.scan(ScanOptions.NONE); @@ -179,7 +179,7 @@ public class JedisConnectionUnitTestSuite { @Test // DATAREDIS-531 public void scanShouldCloseTheConnectionWhenCursorIsClosed() throws IOException { - doReturn(new ScanResult("0", Collections. emptyList())).when(jedisSpy).scan(anyString(), + doReturn(new ScanResult<>("0", Collections. emptyList())).when(jedisSpy).scan(anyString(), any(ScanParams.class)); Cursor cursor = connection.scan(ScanOptions.NONE); @@ -191,7 +191,7 @@ public class JedisConnectionUnitTestSuite { @Test // DATAREDIS-531 public void sScanShouldKeepTheConnectionOpen() { - doReturn(new ScanResult("0", Collections. emptyList())).when(jedisSpy).sscan(any(byte[].class), + doReturn(new ScanResult<>("0", Collections. emptyList())).when(jedisSpy).sscan(any(byte[].class), any(byte[].class), any(ScanParams.class)); connection.sScan("foo".getBytes(), ScanOptions.NONE); @@ -202,7 +202,7 @@ public class JedisConnectionUnitTestSuite { @Test // DATAREDIS-531 public void sScanShouldCloseTheConnectionWhenCursorIsClosed() throws IOException { - doReturn(new ScanResult("0", Collections. emptyList())).when(jedisSpy).sscan(any(byte[].class), + doReturn(new ScanResult<>("0", Collections. emptyList())).when(jedisSpy).sscan(any(byte[].class), any(byte[].class), any(ScanParams.class)); Cursor cursor = connection.sScan("foo".getBytes(), ScanOptions.NONE); @@ -214,7 +214,7 @@ public class JedisConnectionUnitTestSuite { @Test // DATAREDIS-531 public void zScanShouldKeepTheConnectionOpen() { - doReturn(new ScanResult("0", Collections. emptyList())).when(jedisSpy).zscan(any(byte[].class), + doReturn(new ScanResult<>("0", Collections. emptyList())).when(jedisSpy).zscan(any(byte[].class), any(byte[].class), any(ScanParams.class)); connection.zScan("foo".getBytes(), ScanOptions.NONE); @@ -225,7 +225,7 @@ public class JedisConnectionUnitTestSuite { @Test // DATAREDIS-531 public void zScanShouldCloseTheConnectionWhenCursorIsClosed() throws IOException { - doReturn(new ScanResult("0", Collections. emptyList())).when(jedisSpy).zscan(any(byte[].class), + doReturn(new ScanResult<>("0", Collections. emptyList())).when(jedisSpy).zscan(any(byte[].class), any(byte[].class), any(ScanParams.class)); Cursor cursor = connection.zScan("foo".getBytes(), ScanOptions.NONE); @@ -237,7 +237,7 @@ public class JedisConnectionUnitTestSuite { @Test // DATAREDIS-531 public void hScanShouldKeepTheConnectionOpen() { - doReturn(new ScanResult("0", Collections. emptyList())).when(jedisSpy).hscan(any(byte[].class), + doReturn(new ScanResult<>("0", Collections. emptyList())).when(jedisSpy).hscan(any(byte[].class), any(byte[].class), any(ScanParams.class)); connection.hScan("foo".getBytes(), ScanOptions.NONE); @@ -248,7 +248,7 @@ public class JedisConnectionUnitTestSuite { @Test // DATAREDIS-531 public void hScanShouldCloseTheConnectionWhenCursorIsClosed() throws IOException { - doReturn(new ScanResult("0", Collections. emptyList())).when(jedisSpy).hscan(any(byte[].class), + doReturn(new ScanResult<>("0", Collections. emptyList())).when(jedisSpy).hscan(any(byte[].class), any(byte[].class), any(ScanParams.class)); Cursor> cursor = connection.hScan("foo".getBytes(), ScanOptions.NONE); diff --git a/src/test/java/org/springframework/data/redis/connection/jedis/JedisConvertersUnitTests.java b/src/test/java/org/springframework/data/redis/connection/jedis/JedisConvertersUnitTests.java index b618ef62b..45183431e 100644 --- a/src/test/java/org/springframework/data/redis/connection/jedis/JedisConvertersUnitTests.java +++ b/src/test/java/org/springframework/data/redis/connection/jedis/JedisConvertersUnitTests.java @@ -239,7 +239,7 @@ public class JedisConvertersUnitTests { } private Map getRedisServerInfoMap(String name, int port) { - Map map = new HashMap(); + Map map = new HashMap<>(); map.put("name", name); map.put("ip", "127.0.0.1"); map.put("port", Integer.toString(port)); diff --git a/src/test/java/org/springframework/data/redis/connection/jedis/ScanTests.java b/src/test/java/org/springframework/data/redis/connection/jedis/ScanTests.java index 2cca48a33..b8fd9f0d3 100644 --- a/src/test/java/org/springframework/data/redis/connection/jedis/ScanTests.java +++ b/src/test/java/org/springframework/data/redis/connection/jedis/ScanTests.java @@ -53,7 +53,7 @@ public class ScanTests { RedisTemplate redisOperations; ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10, 1, TimeUnit.MINUTES, - new LinkedBlockingDeque()); + new LinkedBlockingDeque<>()); public ScanTests(RedisConnectionFactory factory) { @@ -94,7 +94,7 @@ public class ScanTests { public void contextLoads() throws InterruptedException { BoundHashOperations hash = redisOperations.boundHashOps("hash"); - final AtomicReference exception = new AtomicReference(); + final AtomicReference exception = new AtomicReference<>(); // Create some keys so that SCAN requires a while to return all data. for (int i = 0; i < 10000; i++) { @@ -104,22 +104,19 @@ public class ScanTests { // Concurrent access for (int i = 0; i < 10; i++) { - executor.submit(new Runnable() { - @Override - public void run() { - try { + executor.submit(() -> { + try { - Cursor> cursorMap = redisOperations.boundHashOps("hash") - .scan(ScanOptions.scanOptions().match("*").count(100).build()); + Cursor> cursorMap = redisOperations.boundHashOps("hash") + .scan(ScanOptions.scanOptions().match("*").count(100).build()); - // This line invokes the lazy SCAN invocation - while (cursorMap.hasNext()) { - cursorMap.next(); - } - cursorMap.close(); - } catch (Exception e) { - exception.set(e); + // This line invokes the lazy SCAN invocation + while (cursorMap.hasNext()) { + cursorMap.next(); } + cursorMap.close(); + } catch (Exception e) { + exception.set(e); } }); } diff --git a/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceClusterConnectionTests.java b/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceClusterConnectionTests.java index 07c911ed8..6c5ec5325 100644 --- a/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceClusterConnectionTests.java +++ b/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceClusterConnectionTests.java @@ -88,15 +88,15 @@ public class LettuceClusterConnectionTests implements ClusterConnectionTests { static final byte[] VALUE_2_BYTES = LettuceConverters.toBytes(VALUE_2); static final byte[] VALUE_3_BYTES = LettuceConverters.toBytes(VALUE_3); - static final GeoLocation ARIGENTO = new GeoLocation("arigento", POINT_ARIGENTO); - static final GeoLocation CATANIA = new GeoLocation("catania", POINT_CATANIA); - static final GeoLocation PALERMO = new GeoLocation("palermo", POINT_PALERMO); + static final GeoLocation ARIGENTO = new GeoLocation<>("arigento", POINT_ARIGENTO); + static final GeoLocation CATANIA = new GeoLocation<>("catania", POINT_CATANIA); + static final GeoLocation PALERMO = new GeoLocation<>("palermo", POINT_PALERMO); - static final GeoLocation ARIGENTO_BYTES = new GeoLocation( + static final GeoLocation ARIGENTO_BYTES = new GeoLocation<>( "arigento".getBytes(Charset.forName("UTF-8")), POINT_ARIGENTO); - static final GeoLocation CATANIA_BYTES = new GeoLocation("catania".getBytes(Charset.forName("UTF-8")), + static final GeoLocation CATANIA_BYTES = new GeoLocation<>("catania".getBytes(Charset.forName("UTF-8")), POINT_CATANIA); - static final GeoLocation PALERMO_BYTES = new GeoLocation("palermo".getBytes(Charset.forName("UTF-8")), + static final GeoLocation PALERMO_BYTES = new GeoLocation<>("palermo".getBytes(Charset.forName("UTF-8")), POINT_PALERMO); RedisClusterClient client; @@ -529,7 +529,7 @@ public class LettuceClusterConnectionTests implements ClusterConnectionTests { @Test // DATAREDIS-315 public void mSetShouldWorkWhenKeysMapToSameSlot() { - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put(SAME_SLOT_KEY_1_BYTES, VALUE_1_BYTES); map.put(SAME_SLOT_KEY_2_BYTES, VALUE_2_BYTES); @@ -542,7 +542,7 @@ public class LettuceClusterConnectionTests implements ClusterConnectionTests { @Test // DATAREDIS-315 public void mSetShouldWorkWhenKeysDoNotMapToSameSlot() { - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put(KEY_1_BYTES, VALUE_1_BYTES); map.put(KEY_2_BYTES, VALUE_2_BYTES); @@ -555,7 +555,7 @@ public class LettuceClusterConnectionTests implements ClusterConnectionTests { @Test // DATAREDIS-315 public void mSetNXShouldReturnTrueIfAllKeysSet() { - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put(KEY_1_BYTES, VALUE_1_BYTES); map.put(KEY_2_BYTES, VALUE_2_BYTES); @@ -569,7 +569,7 @@ public class LettuceClusterConnectionTests implements ClusterConnectionTests { public void mSetNXShouldReturnFalseIfNotAllKeysSet() { nativeConnection.set(KEY_2, VALUE_3); - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put(KEY_1_BYTES, VALUE_1_BYTES); map.put(KEY_2_BYTES, VALUE_2_BYTES); @@ -582,7 +582,7 @@ public class LettuceClusterConnectionTests implements ClusterConnectionTests { @Test // DATAREDIS-315 public void mSetNXShouldWorkForOnSameSlotKeys() { - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put(SAME_SLOT_KEY_1_BYTES, VALUE_1_BYTES); map.put(SAME_SLOT_KEY_2_BYTES, VALUE_2_BYTES); @@ -1488,7 +1488,7 @@ public class LettuceClusterConnectionTests implements ClusterConnectionTests { @Test // DATAREDIS-315 public void hMSetShouldAddValuesCorrectly() { - Map hashes = new HashMap(); + Map hashes = new HashMap<>(); hashes.put(KEY_2_BYTES, VALUE_1_BYTES); hashes.put(KEY_3_BYTES, VALUE_2_BYTES); @@ -1571,7 +1571,7 @@ public class LettuceClusterConnectionTests implements ClusterConnectionTests { @Test // DATAREDIS-315 public void hGetAllShouldRetrieveEntriesCorrectly() { - Map hashes = new HashMap(); + Map hashes = new HashMap<>(); hashes.put(KEY_2, VALUE_1); hashes.put(KEY_3, VALUE_2); diff --git a/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceConnectionFactoryTests.java b/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceConnectionFactoryTests.java index 6ebc26bd2..aff5e93ba 100644 --- a/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceConnectionFactoryTests.java +++ b/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceConnectionFactoryTests.java @@ -257,11 +257,7 @@ public class LettuceConnectionFactoryTests { ConnectionFactoryTracker.add(factory2); for (int i = 1; i < 1000; i++) { - Thread th = new Thread(new Runnable() { - public void run() { - factory2.getConnection().bRPop(50000, "foo".getBytes()); - } - }); + Thread th = new Thread(() -> factory2.getConnection().bRPop(50000, "foo".getBytes())); th.start(); } Thread.sleep(234234234); diff --git a/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceConnectionIntegrationTests.java b/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceConnectionIntegrationTests.java index 3f1b759ad..811d5c791 100644 --- a/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceConnectionIntegrationTests.java +++ b/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceConnectionIntegrationTests.java @@ -38,7 +38,6 @@ import org.springframework.dao.DataAccessException; import org.springframework.data.redis.RedisSystemException; import org.springframework.data.redis.RedisVersionUtils; import org.springframework.data.redis.SettingsUtils; -import org.springframework.data.redis.TestCondition; import org.springframework.data.redis.connection.AbstractConnectionIntegrationTests; import org.springframework.data.redis.connection.DefaultStringRedisConnection; import org.springframework.data.redis.connection.RedisConnection; @@ -53,7 +52,7 @@ import org.springframework.test.context.ContextConfiguration; /** * Integration test of {@link LettuceConnection} - * + * * @author Costin Leau * @author Jennifer Hickey * @author Thomas Darimont @@ -70,14 +69,12 @@ public class LettuceConnectionIntegrationTests extends AbstractConnectionIntegra @Test @IfProfileValue(name = "runLongTests", value = "true") public void testMultiThreadsOneBlocking() throws Exception { - Thread th = new Thread(new Runnable() { - public void run() { - DefaultStringRedisConnection conn2 = new DefaultStringRedisConnection(connectionFactory.getConnection()); - conn2.openPipeline(); - conn2.bLPop(3, "multilist"); - conn2.closePipeline(); - conn2.close(); - } + Thread th = new Thread(() -> { + DefaultStringRedisConnection conn2 = new DefaultStringRedisConnection(connectionFactory.getConnection()); + conn2.openPipeline(); + conn2.bLPop(3, "multilist"); + conn2.closePipeline(); + conn2.close(); }); th.start(); Thread.sleep(1000); @@ -247,32 +244,26 @@ public class LettuceConnectionIntegrationTests extends AbstractConnectionIntegra getResults(); assumeTrue(RedisVersionUtils.atLeast("2.6", byteConnection)); final AtomicBoolean scriptDead = new AtomicBoolean(false); - Thread th = new Thread(new Runnable() { - public void run() { - // Use a different factory to get a non-shared native conn for blocking script - final LettuceConnectionFactory factory2 = new LettuceConnectionFactory(SettingsUtils.getHost(), - SettingsUtils.getPort()); - factory2.setClientResources(LettuceTestClientResources.getSharedClientResources()); - factory2.setShutdownTimeout(0); - factory2.afterPropertiesSet(); - DefaultStringRedisConnection conn2 = new DefaultStringRedisConnection(factory2.getConnection()); - try { - conn2.eval("local time=1 while time < 10000000000 do time=time+1 end", ReturnType.BOOLEAN, 0); - } catch (DataAccessException e) { - scriptDead.set(true); - } - conn2.close(); - factory2.destroy(); + Thread th = new Thread(() -> { + // Use a different factory to get a non-shared native conn for blocking script + final LettuceConnectionFactory factory2 = new LettuceConnectionFactory(SettingsUtils.getHost(), + SettingsUtils.getPort()); + factory2.setClientResources(LettuceTestClientResources.getSharedClientResources()); + factory2.setShutdownTimeout(0); + factory2.afterPropertiesSet(); + DefaultStringRedisConnection conn2 = new DefaultStringRedisConnection(factory2.getConnection()); + try { + conn2.eval("local time=1 while time < 10000000000 do time=time+1 end", ReturnType.BOOLEAN, 0); + } catch (DataAccessException e) { + scriptDead.set(true); } + conn2.close(); + factory2.destroy(); }); th.start(); Thread.sleep(1000); connection.scriptKill(); - assertTrue(waitFor(new TestCondition() { - public boolean passes() { - return scriptDead.get(); - } - }, 3000l)); + assertTrue(waitFor(scriptDead::get, 3000l)); } @Test diff --git a/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceConnectionPipelineIntegrationTests.java b/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceConnectionPipelineIntegrationTests.java index 1ca2346c8..28b50e514 100644 --- a/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceConnectionPipelineIntegrationTests.java +++ b/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceConnectionPipelineIntegrationTests.java @@ -27,7 +27,6 @@ import org.junit.runner.RunWith; import org.springframework.dao.DataAccessException; import org.springframework.data.redis.RedisVersionUtils; import org.springframework.data.redis.SettingsUtils; -import org.springframework.data.redis.TestCondition; import org.springframework.data.redis.connection.AbstractConnectionPipelineIntegrationTests; import org.springframework.data.redis.connection.DefaultStringRedisConnection; import org.springframework.data.redis.connection.ReturnType; @@ -38,7 +37,7 @@ import org.springframework.test.context.ContextConfiguration; /** * Integration test of {@link LettuceConnection} pipeline functionality - * + * * @author Jennifer Hickey * @author Thomas Darimont * @author Christoph Strobl @@ -60,32 +59,26 @@ public class LettuceConnectionPipelineIntegrationTests extends AbstractConnectio assumeTrue(RedisVersionUtils.atLeast("2.6", byteConnection)); initConnection(); final AtomicBoolean scriptDead = new AtomicBoolean(false); - Thread th = new Thread(new Runnable() { - public void run() { - // Use separate conn factory to avoid using the underlying shared native conn on blocking script - final LettuceConnectionFactory factory2 = new LettuceConnectionFactory(SettingsUtils.getHost(), - SettingsUtils.getPort()); - factory2.setClientResources(LettuceTestClientResources.getSharedClientResources()); - factory2.afterPropertiesSet(); - DefaultStringRedisConnection conn2 = new DefaultStringRedisConnection(factory2.getConnection()); - try { - conn2.eval("local time=1 while time < 10000000000 do time=time+1 end", ReturnType.BOOLEAN, 0); - } catch (DataAccessException e) { - scriptDead.set(true); - } - conn2.close(); - factory2.destroy(); + Thread th = new Thread(() -> { + // Use separate conn factory to avoid using the underlying shared native conn on blocking script + final LettuceConnectionFactory factory2 = new LettuceConnectionFactory(SettingsUtils.getHost(), + SettingsUtils.getPort()); + factory2.setClientResources(LettuceTestClientResources.getSharedClientResources()); + factory2.afterPropertiesSet(); + DefaultStringRedisConnection conn2 = new DefaultStringRedisConnection(factory2.getConnection()); + try { + conn2.eval("local time=1 while time < 10000000000 do time=time+1 end", ReturnType.BOOLEAN, 0); + } catch (DataAccessException e) { + scriptDead.set(true); } + conn2.close(); + factory2.destroy(); }); th.start(); Thread.sleep(1000); connection.scriptKill(); getResults(); - assertTrue(waitFor(new TestCondition() { - public boolean passes() { - return scriptDead.get(); - } - }, 3000l)); + assertTrue(waitFor(scriptDead::get, 3000l)); } @Test diff --git a/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceConvertersUnitTests.java b/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceConvertersUnitTests.java index 9604a16a8..4e286bc61 100644 --- a/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceConvertersUnitTests.java +++ b/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceConvertersUnitTests.java @@ -84,7 +84,7 @@ public class LettuceConvertersUnitTests { io.lettuce.core.cluster.models.partitions.RedisClusterNode partition = new io.lettuce.core.cluster.models.partitions.RedisClusterNode(); partition.setNodeId(CLUSTER_NODE_1.getId()); partition.setConnected(true); - partition.setFlags(new HashSet(Arrays.asList(NodeFlag.MASTER, NodeFlag.MYSELF))); + partition.setFlags(new HashSet<>(Arrays.asList(NodeFlag.MASTER, NodeFlag.MYSELF))); partition.setUri(RedisURI.create("redis://" + CLUSTER_HOST + ":" + MASTER_NODE_1_PORT)); partition.setSlots(Arrays. asList(1, 2, 3, 4, 5)); diff --git a/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceReactiveZSetCommandsTests.java b/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceReactiveZSetCommandsTests.java index 253bc5008..7d245a82f 100644 --- a/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceReactiveZSetCommandsTests.java +++ b/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceReactiveZSetCommandsTests.java @@ -87,7 +87,7 @@ public class LettuceReactiveZSetCommandsTests extends LettuceReactiveCommandsTes nativeCommands.zadd(KEY_1, 2D, VALUE_2); nativeCommands.zadd(KEY_1, 3D, VALUE_3); - StepVerifier.create(connection.zSetCommands().zRange(KEY_1_BBUFFER, new Range(1L, 2L))) // + StepVerifier.create(connection.zSetCommands().zRange(KEY_1_BBUFFER, new Range<>(1L, 2L))) // .expectNext(VALUE_2_BBUFFER, VALUE_3_BBUFFER) // .verifyComplete(); } @@ -99,7 +99,7 @@ public class LettuceReactiveZSetCommandsTests extends LettuceReactiveCommandsTes nativeCommands.zadd(KEY_1, 2D, VALUE_2); nativeCommands.zadd(KEY_1, 3D, VALUE_3); - StepVerifier.create(connection.zSetCommands().zRangeWithScores(KEY_1_BBUFFER, new Range(1L, 2L))) // + StepVerifier.create(connection.zSetCommands().zRangeWithScores(KEY_1_BBUFFER, new Range<>(1L, 2L))) // .expectNext(new DefaultTuple(VALUE_2_BBUFFER.array(), 2D), new DefaultTuple(VALUE_3_BBUFFER.array(), 3D)) // .verifyComplete(); } @@ -111,7 +111,7 @@ public class LettuceReactiveZSetCommandsTests extends LettuceReactiveCommandsTes nativeCommands.zadd(KEY_1, 2D, VALUE_2); nativeCommands.zadd(KEY_1, 3D, VALUE_3); - StepVerifier.create(connection.zSetCommands().zRevRange(KEY_1_BBUFFER, new Range(1L, 2L))) // + StepVerifier.create(connection.zSetCommands().zRevRange(KEY_1_BBUFFER, new Range<>(1L, 2L))) // .expectNext(VALUE_2_BBUFFER, VALUE_1_BBUFFER) // .verifyComplete(); } @@ -123,7 +123,7 @@ public class LettuceReactiveZSetCommandsTests extends LettuceReactiveCommandsTes nativeCommands.zadd(KEY_1, 2D, VALUE_2); nativeCommands.zadd(KEY_1, 3D, VALUE_3); - StepVerifier.create(connection.zSetCommands().zRevRangeWithScores(KEY_1_BBUFFER, new Range(1L, 2L))) // + StepVerifier.create(connection.zSetCommands().zRevRangeWithScores(KEY_1_BBUFFER, new Range<>(1L, 2L))) // .expectNext(new DefaultTuple(VALUE_2_BBUFFER.array(), 2D), new DefaultTuple(VALUE_1_BBUFFER.array(), 1D)) // .verifyComplete(); } diff --git a/src/test/java/org/springframework/data/redis/connection/lettuce/TestEventLoopGroupProvider.java b/src/test/java/org/springframework/data/redis/connection/lettuce/TestEventLoopGroupProvider.java index 05383c3f5..8bb56e03e 100644 --- a/src/test/java/org/springframework/data/redis/connection/lettuce/TestEventLoopGroupProvider.java +++ b/src/test/java/org/springframework/data/redis/connection/lettuce/TestEventLoopGroupProvider.java @@ -27,7 +27,7 @@ import java.util.concurrent.TimeUnit; * A {@link io.lettuce.core.resource.EventLoopGroupProvider} suitable for testing. Preserves the event loop groups * between tests. Every time a new {@link TestEventLoopGroupProvider} instance is created, a * {@link Runtime#addShutdownHook(Thread) shutdown hook} is added to close the resources. - * + * * @author Mark Paluch * @author Christoph Strobl */ @@ -54,7 +54,7 @@ class TestEventLoopGroupProvider extends DefaultEventLoopGroupProvider { @Override public Promise release(EventExecutorGroup eventLoopGroup, long quietPeriod, long timeout, TimeUnit unit) { - DefaultPromise result = new DefaultPromise(ImmediateEventExecutor.INSTANCE); + DefaultPromise result = new DefaultPromise<>(ImmediateEventExecutor.INSTANCE); result.setSuccess(true); return result; diff --git a/src/test/java/org/springframework/data/redis/core/AbstractOperationsTestParams.java b/src/test/java/org/springframework/data/redis/core/AbstractOperationsTestParams.java index 05918c0f3..cf844c846 100644 --- a/src/test/java/org/springframework/data/redis/core/AbstractOperationsTestParams.java +++ b/src/test/java/org/springframework/data/redis/core/AbstractOperationsTestParams.java @@ -104,7 +104,7 @@ abstract public class AbstractOperationsTestParams { xstreamPersonTemplate.setValueSerializer(serializer); xstreamPersonTemplate.afterPropertiesSet(); - Jackson2JsonRedisSerializer jackson2JsonSerializer = new Jackson2JsonRedisSerializer(Person.class); + Jackson2JsonRedisSerializer jackson2JsonSerializer = new Jackson2JsonRedisSerializer<>(Person.class); RedisTemplate jackson2JsonPersonTemplate = new RedisTemplate<>(); jackson2JsonPersonTemplate.setConnectionFactory(jedisConnectionFactory); jackson2JsonPersonTemplate.setValueSerializer(jackson2JsonSerializer); diff --git a/src/test/java/org/springframework/data/redis/core/DefaultClusterOperationsUnitTests.java b/src/test/java/org/springframework/data/redis/core/DefaultClusterOperationsUnitTests.java index a187e2a74..8803eeae0 100644 --- a/src/test/java/org/springframework/data/redis/core/DefaultClusterOperationsUnitTests.java +++ b/src/test/java/org/springframework/data/redis/core/DefaultClusterOperationsUnitTests.java @@ -32,7 +32,6 @@ import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.dao.DataAccessException; import org.springframework.data.redis.connection.RedisClusterCommands.AddSlots; import org.springframework.data.redis.connection.RedisClusterConnection; import org.springframework.data.redis.connection.RedisClusterNode; @@ -69,19 +68,19 @@ public class DefaultClusterOperationsUnitTests { serializer = new StringRedisSerializer(); - RedisTemplate template = new RedisTemplate(); + RedisTemplate template = new RedisTemplate<>(); template.setConnectionFactory(connectionFactory); template.setValueSerializer(serializer); template.setKeySerializer(serializer); template.afterPropertiesSet(); - this.clusterOps = new DefaultClusterOperations(template); + this.clusterOps = new DefaultClusterOperations<>(template); } @Test // DATAREDIS-315 public void keysShouldDelegateToConnectionCorrectly() { - Set keys = new HashSet(Arrays.asList(serializer.serialize("key-1"), serializer.serialize("key-2"))); + Set keys = new HashSet<>(Arrays.asList(serializer.serialize("key-1"), serializer.serialize("key-2"))); when(connection.keys(any(RedisClusterNode.class), any(byte[].class))).thenReturn(keys); assertThat(clusterOps.keys(NODE_1, "*"), hasItems("key-1", "key-2")); @@ -255,13 +254,7 @@ public class DefaultClusterOperationsUnitTests { public void executeShouldDelegateToConnection() { final byte[] key = serializer.serialize("foo"); - clusterOps.execute(new RedisClusterCallback() { - - @Override - public String doInRedis(RedisClusterConnection connection) throws DataAccessException { - return serializer.deserialize(connection.get(key)); - } - }); + clusterOps.execute(connection -> serializer.deserialize(connection.get(key))); verify(connection, times(1)).get(eq(key)); } diff --git a/src/test/java/org/springframework/data/redis/core/DefaultGeoOperationsTests.java b/src/test/java/org/springframework/data/redis/core/DefaultGeoOperationsTests.java index 95b003841..c6f53cbab 100644 --- a/src/test/java/org/springframework/data/redis/core/DefaultGeoOperationsTests.java +++ b/src/test/java/org/springframework/data/redis/core/DefaultGeoOperationsTests.java @@ -43,7 +43,6 @@ import org.springframework.data.geo.GeoResults; import org.springframework.data.geo.Point; import org.springframework.data.redis.ConnectionFactoryTracker; import org.springframework.data.redis.ObjectFactory; -import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisGeoCommands.DistanceUnit; import org.springframework.data.redis.connection.RedisGeoCommands.GeoLocation; import org.springframework.data.redis.serializer.RedisSerializer; @@ -105,11 +104,9 @@ public class DefaultGeoOperationsTests { @After public void tearDown() { - redisTemplate.execute(new RedisCallback() { - public Object doInRedis(RedisConnection connection) { - connection.flushDb(); - return null; - } + redisTemplate.execute((RedisCallback) connection -> { + connection.flushDb(); + return null; }); } @@ -124,7 +121,7 @@ public class DefaultGeoOperationsTests { @Test // DATAREDIS-438 public void testGeoAddWithLocationMap() { - Map memberCoordinateMap = new HashMap(); + Map memberCoordinateMap = new HashMap<>(); memberCoordinateMap.put(valueFactory.instance(), POINT_PALERMO); memberCoordinateMap.put(valueFactory.instance(), POINT_CATANIA); diff --git a/src/test/java/org/springframework/data/redis/core/DefaultHashOperationsTests.java b/src/test/java/org/springframework/data/redis/core/DefaultHashOperationsTests.java index 9418ba06d..465082ea0 100644 --- a/src/test/java/org/springframework/data/redis/core/DefaultHashOperationsTests.java +++ b/src/test/java/org/springframework/data/redis/core/DefaultHashOperationsTests.java @@ -36,14 +36,13 @@ import org.springframework.data.redis.ObjectFactory; import org.springframework.data.redis.RawObjectFactory; import org.springframework.data.redis.SettingsUtils; import org.springframework.data.redis.StringObjectFactory; -import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.test.util.MinimumRedisVersionRule; import org.springframework.test.annotation.IfProfileValue; /** * Integration test of {@link DefaultHashOperations} - * + * * @author Jennifer Hickey * @author Christoph Strobl * @param Key type @@ -90,7 +89,7 @@ public class DefaultHashOperationsTests { stringTemplate.setConnectionFactory(jedisConnectionFactory); stringTemplate.afterPropertiesSet(); - RedisTemplate rawTemplate = new RedisTemplate(); + RedisTemplate rawTemplate = new RedisTemplate<>(); rawTemplate.setConnectionFactory(jedisConnectionFactory); rawTemplate.setEnableDefaultSerializer(false); rawTemplate.afterPropertiesSet(); @@ -111,11 +110,9 @@ public class DefaultHashOperationsTests { @After public void tearDown() { - redisTemplate.execute(new RedisCallback() { - public Object doInRedis(RedisConnection connection) { - connection.flushDb(); - return null; - } + redisTemplate.execute((RedisCallback) connection -> { + connection.flushDb(); + return null; }); } diff --git a/src/test/java/org/springframework/data/redis/core/DefaultHyperLogLogOperationsTests.java b/src/test/java/org/springframework/data/redis/core/DefaultHyperLogLogOperationsTests.java index 23520e5a4..14570b1c3 100644 --- a/src/test/java/org/springframework/data/redis/core/DefaultHyperLogLogOperationsTests.java +++ b/src/test/java/org/springframework/data/redis/core/DefaultHyperLogLogOperationsTests.java @@ -30,7 +30,6 @@ import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.springframework.data.redis.ConnectionFactoryTracker; import org.springframework.data.redis.ObjectFactory; -import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.test.util.MinimumRedisVersionRule; import org.springframework.test.annotation.IfProfileValue; @@ -78,11 +77,9 @@ public class DefaultHyperLogLogOperationsTests { @After public void tearDown() { - redisTemplate.execute(new RedisCallback() { - public Object doInRedis(RedisConnection connection) { - connection.flushDb(); - return null; - } + redisTemplate.execute((RedisCallback) connection -> { + connection.flushDb(); + return null; }); } diff --git a/src/test/java/org/springframework/data/redis/core/DefaultListOperationsTests.java b/src/test/java/org/springframework/data/redis/core/DefaultListOperationsTests.java index 9038870aa..e2f5280b8 100644 --- a/src/test/java/org/springframework/data/redis/core/DefaultListOperationsTests.java +++ b/src/test/java/org/springframework/data/redis/core/DefaultListOperationsTests.java @@ -34,11 +34,10 @@ import org.junit.runners.Parameterized.Parameters; import org.springframework.data.redis.ConnectionFactoryTracker; import org.springframework.data.redis.ObjectFactory; import org.springframework.data.redis.RedisTestProfileValueSource; -import org.springframework.data.redis.connection.RedisConnection; /** * Integration test of {@link DefaultListOperations} - * + * * @author Jennifer Hickey * @author Thomas Darimont * @author Christoph Strobl @@ -83,11 +82,9 @@ public class DefaultListOperationsTests { @After public void tearDown() { - redisTemplate.execute(new RedisCallback() { - public Object doInRedis(RedisConnection connection) { - connection.flushDb(); - return null; - } + redisTemplate.execute((RedisCallback) connection -> { + connection.flushDb(); + return null; }); } diff --git a/src/test/java/org/springframework/data/redis/core/DefaultReactiveValueOperationsIntegrationTests.java b/src/test/java/org/springframework/data/redis/core/DefaultReactiveValueOperationsIntegrationTests.java index 246d8e3f5..3ca5a29eb 100644 --- a/src/test/java/org/springframework/data/redis/core/DefaultReactiveValueOperationsIntegrationTests.java +++ b/src/test/java/org/springframework/data/redis/core/DefaultReactiveValueOperationsIntegrationTests.java @@ -158,7 +158,7 @@ public class DefaultReactiveValueOperationsIntegrationTests { V value1 = valueFactory.instance(); V value2 = valueFactory.instance(); - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put(key1, value1); map.put(key2, value2); @@ -176,7 +176,7 @@ public class DefaultReactiveValueOperationsIntegrationTests { V value1 = valueFactory.instance(); V value2 = valueFactory.instance(); - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put(key1, value1); @@ -235,7 +235,7 @@ public class DefaultReactiveValueOperationsIntegrationTests { absentValue = (V) ByteBuffer.wrap(new byte[0]); } - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put(key1, value1); map.put(key2, value2); diff --git a/src/test/java/org/springframework/data/redis/core/DefaultReactiveZSetOperationsIntegrationTests.java b/src/test/java/org/springframework/data/redis/core/DefaultReactiveZSetOperationsIntegrationTests.java index d365a6974..f2203a0b1 100644 --- a/src/test/java/org/springframework/data/redis/core/DefaultReactiveZSetOperationsIntegrationTests.java +++ b/src/test/java/org/springframework/data/redis/core/DefaultReactiveZSetOperationsIntegrationTests.java @@ -344,7 +344,7 @@ public class DefaultReactiveZSetOperationsIntegrationTests { StepVerifier.create(zSetOperations.add(key, value2, 10)).expectNext(true).verifyComplete(); StepVerifier.create(zSetOperations.reverseRangeByScoreWithScores(key, new Range<>(9d, 11d))) // - .expectNext(new DefaultTypedTuple(value2, 10d)) // + .expectNext(new DefaultTypedTuple<>(value2, 10d)) // .verifyComplete(); } @@ -396,9 +396,9 @@ public class DefaultReactiveZSetOperationsIntegrationTests { StepVerifier.create(zSetOperations.add(key, value1, 42.1)).expectNext(true).verifyComplete(); StepVerifier.create(zSetOperations.add(key, value2, 10)).expectNext(true).verifyComplete(); - StepVerifier.create(zSetOperations.count(key, new Range(0d, 100d))).expectNext(2L).expectComplete() + StepVerifier.create(zSetOperations.count(key, new Range<>(0d, 100d))).expectNext(2L).expectComplete() .verify(); - StepVerifier.create(zSetOperations.count(key, new Range(0d, 10d))).expectNext(1L).verifyComplete(); + StepVerifier.create(zSetOperations.count(key, new Range<>(0d, 10d))).expectNext(1L).verifyComplete(); } @Test // DATAREDIS-602 diff --git a/src/test/java/org/springframework/data/redis/core/DefaultSetOperationsTests.java b/src/test/java/org/springframework/data/redis/core/DefaultSetOperationsTests.java index d1cf4988b..6208c1a75 100644 --- a/src/test/java/org/springframework/data/redis/core/DefaultSetOperationsTests.java +++ b/src/test/java/org/springframework/data/redis/core/DefaultSetOperationsTests.java @@ -16,7 +16,7 @@ package org.springframework.data.redis.core; import static org.hamcrest.CoreMatchers.*; -import static org.hamcrest.collection.IsCollectionWithSize.hasSize; +import static org.hamcrest.collection.IsCollectionWithSize.*; import static org.junit.Assert.*; import static org.junit.Assume.*; import static org.springframework.data.redis.matcher.RedisTestMatchers.*; @@ -29,7 +29,6 @@ import java.util.List; import java.util.Set; import org.hamcrest.CoreMatchers; -import org.hamcrest.collection.IsCollectionWithSize; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; @@ -41,13 +40,12 @@ import org.junit.runners.Parameterized.Parameters; import org.springframework.data.redis.ConnectionFactoryTracker; import org.springframework.data.redis.ObjectFactory; import org.springframework.data.redis.RedisTestProfileValueSource; -import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.test.util.MinimumRedisVersionRule; import org.springframework.test.annotation.IfProfileValue; /** * Integration test of {@link DefaultSetOperations} - * + * * @author Jennifer Hickey * @author Christoph Strobl * @author Thomas Darimont @@ -92,11 +90,9 @@ public class DefaultSetOperationsTests { @After public void tearDown() { - redisTemplate.execute(new RedisCallback() { - public Object doInRedis(RedisConnection connection) { - connection.flushDb(); - return null; - } + redisTemplate.execute((RedisCallback) connection -> { + connection.flushDb(); + return null; }); } @@ -113,7 +109,7 @@ public class DefaultSetOperationsTests { setOps.add(setKey, v3); Set members = setOps.distinctRandomMembers(setKey, 2); assertEquals(2, members.size()); - Set expected = new HashSet(); + Set expected = new HashSet<>(); expected.add(v1); expected.add(v2); expected.add(v3); @@ -163,8 +159,8 @@ public class DefaultSetOperationsTests { setOps.add(key1, v1); setOps.add(key1, v2); setOps.move(key1, v1, key2); - assertThat(setOps.members(key1), isEqual(new HashSet(Collections.singletonList(v2)))); - assertThat(setOps.members(key2), isEqual(new HashSet(Collections.singletonList(v1)))); + assertThat(setOps.members(key1), isEqual(new HashSet<>(Collections.singletonList(v2)))); + assertThat(setOps.members(key2), isEqual(new HashSet<>(Collections.singletonList(v1)))); } @SuppressWarnings("unchecked") @@ -207,7 +203,7 @@ public class DefaultSetOperationsTests { V v1 = valueFactory.instance(); V v2 = valueFactory.instance(); assertEquals(Long.valueOf(2), setOps.add(key, v1, v2)); - Set expected = new HashSet(); + Set expected = new HashSet<>(); expected.add(v1); expected.add(v2); assertThat(setOps.members(key), isEqual(expected)); diff --git a/src/test/java/org/springframework/data/redis/core/DefaultTypedTupleUnitTests.java b/src/test/java/org/springframework/data/redis/core/DefaultTypedTupleUnitTests.java index bb1f5bba2..481cf8c41 100644 --- a/src/test/java/org/springframework/data/redis/core/DefaultTypedTupleUnitTests.java +++ b/src/test/java/org/springframework/data/redis/core/DefaultTypedTupleUnitTests.java @@ -26,10 +26,10 @@ import org.springframework.data.redis.core.ZSetOperations.TypedTuple; */ public class DefaultTypedTupleUnitTests { - private static final TypedTuple WITH_SCORE_1 = new DefaultTypedTuple("foo", 1D); - private static final TypedTuple ANOTHER_ONE_WITH_SCORE_1 = new DefaultTypedTuple("another", 1D); - private static final TypedTuple WITH_SCORE_2 = new DefaultTypedTuple("bar", 2D); - private static final TypedTuple WITH_SCORE_NULL = new DefaultTypedTuple("foo", null); + private static final TypedTuple WITH_SCORE_1 = new DefaultTypedTuple<>("foo", 1D); + private static final TypedTuple ANOTHER_ONE_WITH_SCORE_1 = new DefaultTypedTuple<>("another", 1D); + private static final TypedTuple WITH_SCORE_2 = new DefaultTypedTuple<>("bar", 2D); + private static final TypedTuple WITH_SCORE_NULL = new DefaultTypedTuple<>("foo", null); @Test // DATAREDIS-294 public void compareToShouldUseScore() { diff --git a/src/test/java/org/springframework/data/redis/core/DefaultValueOperationsTests.java b/src/test/java/org/springframework/data/redis/core/DefaultValueOperationsTests.java index b417b2b1f..a3d5d516b 100644 --- a/src/test/java/org/springframework/data/redis/core/DefaultValueOperationsTests.java +++ b/src/test/java/org/springframework/data/redis/core/DefaultValueOperationsTests.java @@ -39,12 +39,10 @@ import org.junit.runners.Parameterized.Parameters; import org.springframework.data.redis.ConnectionFactoryTracker; import org.springframework.data.redis.ObjectFactory; import org.springframework.data.redis.RedisTestProfileValueSource; -import org.springframework.data.redis.TestCondition; -import org.springframework.data.redis.connection.RedisConnection; /** * Integration test of {@link DefaultValueOperations} - * + * * @author Jennifer Hickey * @author Christoph Strobl * @author David Liu @@ -88,11 +86,9 @@ public class DefaultValueOperationsTests { @After public void tearDown() { - redisTemplate.execute(new RedisCallback() { - public Object doInRedis(RedisConnection connection) { - connection.flushDb(); - return null; - } + redisTemplate.execute((RedisCallback) connection -> { + connection.flushDb(); + return null; }); } @@ -126,7 +122,7 @@ public class DefaultValueOperationsTests { @Test public void testMultiSetIfAbsent() { - Map keysAndValues = new HashMap(); + Map keysAndValues = new HashMap<>(); K key1 = keyFactory.instance(); K key2 = keyFactory.instance(); V value1 = valueFactory.instance(); @@ -134,7 +130,7 @@ public class DefaultValueOperationsTests { keysAndValues.put(key1, value1); keysAndValues.put(key2, value2); assertTrue(valueOps.multiSetIfAbsent(keysAndValues)); - assertThat(valueOps.multiGet(keysAndValues.keySet()), isEqual(new ArrayList(keysAndValues.values()))); + assertThat(valueOps.multiGet(keysAndValues.keySet()), isEqual(new ArrayList<>(keysAndValues.values()))); } @Test @@ -145,7 +141,7 @@ public class DefaultValueOperationsTests { V value2 = valueFactory.instance(); V value3 = valueFactory.instance(); valueOps.set(key1, value1); - Map keysAndValues = new HashMap(); + Map keysAndValues = new HashMap<>(); keysAndValues.put(key1, value2); keysAndValues.put(key2, value3); assertFalse(valueOps.multiSetIfAbsent(keysAndValues)); @@ -153,7 +149,7 @@ public class DefaultValueOperationsTests { @Test public void testMultiSet() { - Map keysAndValues = new HashMap(); + Map keysAndValues = new HashMap<>(); K key1 = keyFactory.instance(); K key2 = keyFactory.instance(); V value1 = valueFactory.instance(); @@ -161,7 +157,7 @@ public class DefaultValueOperationsTests { keysAndValues.put(key1, value1); keysAndValues.put(key2, value2); valueOps.multiSet(keysAndValues); - assertThat(valueOps.multiGet(keysAndValues.keySet()), isEqual(new ArrayList(keysAndValues.values()))); + assertThat(valueOps.multiGet(keysAndValues.keySet()), isEqual(new ArrayList<>(keysAndValues.values()))); } @Test @@ -187,11 +183,7 @@ public class DefaultValueOperationsTests { final K key1 = keyFactory.instance(); V value1 = valueFactory.instance(); valueOps.set(key1, value1, 1, TimeUnit.SECONDS); - waitFor(new TestCondition() { - public boolean passes() { - return (!redisTemplate.hasKey(key1)); - } - }, 1000); + waitFor(() -> (!redisTemplate.hasKey(key1)), 1000); } @Test // DATAREDIS-271 @@ -201,11 +193,7 @@ public class DefaultValueOperationsTests { final K key1 = keyFactory.instance(); V value1 = valueFactory.instance(); valueOps.set(key1, value1, 1, TimeUnit.MILLISECONDS); - waitFor(new TestCondition() { - public boolean passes() { - return (!redisTemplate.hasKey(key1)); - } - }, 500); + waitFor(() -> (!redisTemplate.hasKey(key1)), 500); } @Test diff --git a/src/test/java/org/springframework/data/redis/core/DefaultZSetOperationsTests.java b/src/test/java/org/springframework/data/redis/core/DefaultZSetOperationsTests.java index 78cdac62c..41ca55c79 100644 --- a/src/test/java/org/springframework/data/redis/core/DefaultZSetOperationsTests.java +++ b/src/test/java/org/springframework/data/redis/core/DefaultZSetOperationsTests.java @@ -43,7 +43,6 @@ import org.springframework.data.redis.DoubleObjectFactory; import org.springframework.data.redis.LongAsStringObjectFactory; import org.springframework.data.redis.LongObjectFactory; import org.springframework.data.redis.ObjectFactory; -import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisZSetCommands; import org.springframework.data.redis.core.ZSetOperations.TypedTuple; import org.springframework.data.redis.test.util.MinimumRedisVersionRule; @@ -51,7 +50,7 @@ import org.springframework.test.annotation.IfProfileValue; /** * Integration test of {@link DefaultZSetOperations} - * + * * @author Jennifer Hickey * @author Christoph Strobl * @author Mark Paluch @@ -98,11 +97,9 @@ public class DefaultZSetOperationsTests { @After public void tearDown() { - redisTemplate.execute(new RedisCallback() { - public Object doInRedis(RedisConnection connection) { - connection.flushDb(); - return null; - } + redisTemplate.execute((RedisCallback) connection -> { + connection.flushDb(); + return null; }); } @@ -125,7 +122,7 @@ public class DefaultZSetOperationsTests { Set> values = zSetOps.rangeWithScores(key1, 0, -1); assertEquals(1, values.size()); TypedTuple tuple = values.iterator().next(); - assertEquals(new DefaultTypedTuple(value1, 5.7), tuple); + assertEquals(new DefaultTypedTuple<>(value1, 5.7), tuple); } @Test @@ -153,7 +150,7 @@ public class DefaultZSetOperationsTests { Set> tuples = zSetOps.rangeByScoreWithScores(key, 1.5, 4.7, 0, 1); assertEquals(1, tuples.size()); TypedTuple tuple = tuples.iterator().next(); - assertThat(tuple, isEqual(new DefaultTypedTuple(value1, 1.9))); + assertThat(tuple, isEqual(new DefaultTypedTuple<>(value1, 1.9))); } @Test @@ -180,7 +177,7 @@ public class DefaultZSetOperationsTests { Set> tuples = zSetOps.reverseRangeByScoreWithScores(key, 1.5, 4.7, 0, 1); assertEquals(1, tuples.size()); TypedTuple tuple = tuples.iterator().next(); - assertThat(tuple, isEqual(new DefaultTypedTuple(value2, 3.7))); + assertThat(tuple, isEqual(new DefaultTypedTuple<>(value2, 3.7))); } @Test // DATAREDIS-407 @@ -275,12 +272,12 @@ public class DefaultZSetOperationsTests { V value1 = valueFactory.instance(); V value2 = valueFactory.instance(); V value3 = valueFactory.instance(); - Set> values = new HashSet>(); - values.add(new DefaultTypedTuple(value1, 1.7)); - values.add(new DefaultTypedTuple(value2, 3.2)); - values.add(new DefaultTypedTuple(value3, 0.8)); + Set> values = new HashSet<>(); + values.add(new DefaultTypedTuple<>(value1, 1.7)); + values.add(new DefaultTypedTuple<>(value2, 3.2)); + values.add(new DefaultTypedTuple<>(value3, 0.8)); assertEquals(Long.valueOf(3), zSetOps.add(key, values)); - Set expected = new LinkedHashSet(); + Set expected = new LinkedHashSet<>(); expected.add(value3); expected.add(value1); expected.add(value2); @@ -293,13 +290,13 @@ public class DefaultZSetOperationsTests { V value1 = valueFactory.instance(); V value2 = valueFactory.instance(); V value3 = valueFactory.instance(); - Set> values = new HashSet>(); - values.add(new DefaultTypedTuple(value1, 1.7)); - values.add(new DefaultTypedTuple(value2, 3.2)); - values.add(new DefaultTypedTuple(value3, 0.8)); + Set> values = new HashSet<>(); + values.add(new DefaultTypedTuple<>(value1, 1.7)); + values.add(new DefaultTypedTuple<>(value2, 3.2)); + values.add(new DefaultTypedTuple<>(value3, 0.8)); assertEquals(Long.valueOf(3), zSetOps.add(key, values)); assertEquals(Long.valueOf(2), zSetOps.remove(key, value1, value3)); - Set expected = new LinkedHashSet(); + Set expected = new LinkedHashSet<>(); expected.add(value2); assertThat(zSetOps.range(key, 0, -1), isEqual(expected)); } @@ -312,10 +309,10 @@ public class DefaultZSetOperationsTests { V value2 = valueFactory.instance(); V value3 = valueFactory.instance(); - Set> values = new HashSet>(); - values.add(new DefaultTypedTuple(value1, 1.7)); - values.add(new DefaultTypedTuple(value2, 3.2)); - values.add(new DefaultTypedTuple(value3, 0.8)); + Set> values = new HashSet<>(); + values.add(new DefaultTypedTuple<>(value1, 1.7)); + values.add(new DefaultTypedTuple<>(value2, 3.2)); + values.add(new DefaultTypedTuple<>(value3, 0.8)); zSetOps.add(key, values); assertThat(zSetOps.zCard(key), equalTo(3L)); @@ -329,10 +326,10 @@ public class DefaultZSetOperationsTests { V value2 = valueFactory.instance(); V value3 = valueFactory.instance(); - Set> values = new HashSet>(); - values.add(new DefaultTypedTuple(value1, 1.7)); - values.add(new DefaultTypedTuple(value2, 3.2)); - values.add(new DefaultTypedTuple(value3, 0.8)); + Set> values = new HashSet<>(); + values.add(new DefaultTypedTuple<>(value1, 1.7)); + values.add(new DefaultTypedTuple<>(value2, 3.2)); + values.add(new DefaultTypedTuple<>(value3, 0.8)); zSetOps.add(key, values); assertThat(zSetOps.size(key), equalTo(3L)); @@ -344,9 +341,9 @@ public class DefaultZSetOperationsTests { K key = keyFactory.instance(); - final TypedTuple tuple1 = new DefaultTypedTuple(valueFactory.instance(), 1.7); - final TypedTuple tuple2 = new DefaultTypedTuple(valueFactory.instance(), 3.2); - final TypedTuple tuple3 = new DefaultTypedTuple(valueFactory.instance(), 0.8); + final TypedTuple tuple1 = new DefaultTypedTuple<>(valueFactory.instance(), 1.7); + final TypedTuple tuple2 = new DefaultTypedTuple<>(valueFactory.instance(), 3.2); + final TypedTuple tuple3 = new DefaultTypedTuple<>(valueFactory.instance(), 0.8); Set> values = new HashSet>() { { diff --git a/src/test/java/org/springframework/data/redis/core/IndexWriterUnitTests.java b/src/test/java/org/springframework/data/redis/core/IndexWriterUnitTests.java index 0b1bc8388..ffa7bcd82 100644 --- a/src/test/java/org/springframework/data/redis/core/IndexWriterUnitTests.java +++ b/src/test/java/org/springframework/data/redis/core/IndexWriterUnitTests.java @@ -45,7 +45,7 @@ import org.springframework.util.ObjectUtils; /** * @author Christoph Strobl - * @auhtor Rob Winch + * @author Rob Winch */ @RunWith(MockitoJUnitRunner.Silent.class) public class IndexWriterUnitTests { @@ -100,7 +100,7 @@ public class IndexWriterUnitTests { byte[] indexKey2 = "persons:firstname:mat".getBytes(CHARSET); when(connectionMock.keys(any(byte[].class))) - .thenReturn(new LinkedHashSet(Arrays.asList(indexKey1, indexKey2))); + .thenReturn(new LinkedHashSet<>(Arrays.asList(indexKey1, indexKey2))); writer.removeKeyFromExistingIndexes(KEY_BIN, new StubIndxedData()); @@ -120,7 +120,7 @@ public class IndexWriterUnitTests { byte[] indexKey2 = "persons:firstname:mat".getBytes(CHARSET); when(connectionMock.keys(any(byte[].class))) - .thenReturn(new LinkedHashSet(Arrays.asList(indexKey1, indexKey2))); + .thenReturn(new LinkedHashSet<>(Arrays.asList(indexKey1, indexKey2))); writer.removeAllIndexes(KEYSPACE); @@ -159,7 +159,7 @@ public class IndexWriterUnitTests { public void createIndexShouldNotTryToRemoveExistingValues() { when(connectionMock.keys(any(byte[].class))) - .thenReturn(new LinkedHashSet(Arrays.asList("persons:firstname:rand".getBytes(CHARSET)))); + .thenReturn(new LinkedHashSet<>(Arrays.asList("persons:firstname:rand".getBytes(CHARSET)))); writer.createIndexes(KEY_BIN, Collections. singleton(new SimpleIndexedPropertyValue(KEYSPACE, "firstname", "Rand"))); @@ -174,7 +174,7 @@ public class IndexWriterUnitTests { public void updateIndexShouldRemoveExistingValues() { when(connectionMock.keys(any(byte[].class))) - .thenReturn(new LinkedHashSet(Arrays.asList("persons:firstname:rand".getBytes(CHARSET)))); + .thenReturn(new LinkedHashSet<>(Arrays.asList("persons:firstname:rand".getBytes(CHARSET)))); writer.updateIndexes(KEY_BIN, Collections. singleton(new SimpleIndexedPropertyValue(KEYSPACE, "firstname", "Rand"))); @@ -190,7 +190,7 @@ public class IndexWriterUnitTests { byte[] indexKey1 = "persons:location".getBytes(CHARSET); - when(connectionMock.keys(any(byte[].class))).thenReturn(new LinkedHashSet(Arrays.asList(indexKey1))); + when(connectionMock.keys(any(byte[].class))).thenReturn(new LinkedHashSet<>(Arrays.asList(indexKey1))); writer.removeKeyFromExistingIndexes(KEY_BIN, new GeoIndexedPropertyValue(KEYSPACE, "address.city", null)); diff --git a/src/test/java/org/springframework/data/redis/core/MultithreadedRedisTemplateTests.java b/src/test/java/org/springframework/data/redis/core/MultithreadedRedisTemplateTests.java index 73ddd4eac..9bd3f5a50 100644 --- a/src/test/java/org/springframework/data/redis/core/MultithreadedRedisTemplateTests.java +++ b/src/test/java/org/springframework/data/redis/core/MultithreadedRedisTemplateTests.java @@ -72,20 +72,14 @@ public class MultithreadedRedisTemplateTests { @Test // DATAREDIS-300 public void assertResouresAreReleasedProperlyWhenSharingRedisTemplate() throws InterruptedException { - final RedisTemplate template = new RedisTemplate(); + final RedisTemplate template = new RedisTemplate<>(); template.setConnectionFactory(factory); template.afterPropertiesSet(); ExecutorService executor = Executors.newCachedThreadPool(); for (int i = 0; i < 9; i++) { - executor.execute(new Runnable() { - - @Override - public void run() { - template.boundValueOps("foo").get(); - } - }); + executor.execute(template.boundValueOps("foo")::get); } executor.shutdown(); diff --git a/src/test/java/org/springframework/data/redis/core/RedisClusterTemplateTests.java b/src/test/java/org/springframework/data/redis/core/RedisClusterTemplateTests.java index ee491d755..86b4e637d 100644 --- a/src/test/java/org/springframework/data/redis/core/RedisClusterTemplateTests.java +++ b/src/test/java/org/springframework/data/redis/core/RedisClusterTemplateTests.java @@ -157,7 +157,7 @@ public class RedisClusterTemplateTests extends RedisTemplateTests { } OxmSerializer serializer = new OxmSerializer(xstream, xstream); - Jackson2JsonRedisSerializer jackson2JsonSerializer = new Jackson2JsonRedisSerializer(Person.class); + Jackson2JsonRedisSerializer jackson2JsonSerializer = new Jackson2JsonRedisSerializer<>(Person.class); // JEDIS JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(new RedisClusterConfiguration( @@ -165,32 +165,32 @@ public class RedisClusterTemplateTests extends RedisTemplateTests { jedisConnectionFactory.afterPropertiesSet(); - RedisTemplate jedisStringTemplate = new RedisTemplate(); + RedisTemplate jedisStringTemplate = new RedisTemplate<>(); jedisStringTemplate.setDefaultSerializer(new StringRedisSerializer()); jedisStringTemplate.setConnectionFactory(jedisConnectionFactory); jedisStringTemplate.afterPropertiesSet(); - RedisTemplate jedisLongTemplate = new RedisTemplate(); + RedisTemplate jedisLongTemplate = new RedisTemplate<>(); jedisLongTemplate.setKeySerializer(new StringRedisSerializer()); - jedisLongTemplate.setValueSerializer(new GenericToStringSerializer(Long.class)); + jedisLongTemplate.setValueSerializer(new GenericToStringSerializer<>(Long.class)); jedisLongTemplate.setConnectionFactory(jedisConnectionFactory); jedisLongTemplate.afterPropertiesSet(); - RedisTemplate jedisRawTemplate = new RedisTemplate(); + RedisTemplate jedisRawTemplate = new RedisTemplate<>(); jedisRawTemplate.setEnableDefaultSerializer(false); jedisRawTemplate.setConnectionFactory(jedisConnectionFactory); jedisRawTemplate.afterPropertiesSet(); - RedisTemplate jedisPersonTemplate = new RedisTemplate(); + RedisTemplate jedisPersonTemplate = new RedisTemplate<>(); jedisPersonTemplate.setConnectionFactory(jedisConnectionFactory); jedisPersonTemplate.afterPropertiesSet(); - RedisTemplate jedisXstreamStringTemplate = new RedisTemplate(); + RedisTemplate jedisXstreamStringTemplate = new RedisTemplate<>(); jedisXstreamStringTemplate.setConnectionFactory(jedisConnectionFactory); jedisXstreamStringTemplate.setDefaultSerializer(serializer); jedisXstreamStringTemplate.afterPropertiesSet(); - RedisTemplate jedisJackson2JsonPersonTemplate = new RedisTemplate(); + RedisTemplate jedisJackson2JsonPersonTemplate = new RedisTemplate<>(); jedisJackson2JsonPersonTemplate.setConnectionFactory(jedisConnectionFactory); jedisJackson2JsonPersonTemplate.setValueSerializer(jackson2JsonSerializer); jedisJackson2JsonPersonTemplate.afterPropertiesSet(); @@ -203,32 +203,32 @@ public class RedisClusterTemplateTests extends RedisTemplateTests { lettuceConnectionFactory.afterPropertiesSet(); - RedisTemplate lettuceStringTemplate = new RedisTemplate(); + RedisTemplate lettuceStringTemplate = new RedisTemplate<>(); lettuceStringTemplate.setDefaultSerializer(new StringRedisSerializer()); lettuceStringTemplate.setConnectionFactory(lettuceConnectionFactory); lettuceStringTemplate.afterPropertiesSet(); - RedisTemplate lettuceLongTemplate = new RedisTemplate(); + RedisTemplate lettuceLongTemplate = new RedisTemplate<>(); lettuceLongTemplate.setKeySerializer(new StringRedisSerializer()); - lettuceLongTemplate.setValueSerializer(new GenericToStringSerializer(Long.class)); + lettuceLongTemplate.setValueSerializer(new GenericToStringSerializer<>(Long.class)); lettuceLongTemplate.setConnectionFactory(lettuceConnectionFactory); lettuceLongTemplate.afterPropertiesSet(); - RedisTemplate lettuceRawTemplate = new RedisTemplate(); + RedisTemplate lettuceRawTemplate = new RedisTemplate<>(); lettuceRawTemplate.setEnableDefaultSerializer(false); lettuceRawTemplate.setConnectionFactory(lettuceConnectionFactory); lettuceRawTemplate.afterPropertiesSet(); - RedisTemplate lettucePersonTemplate = new RedisTemplate(); + RedisTemplate lettucePersonTemplate = new RedisTemplate<>(); lettucePersonTemplate.setConnectionFactory(lettuceConnectionFactory); lettucePersonTemplate.afterPropertiesSet(); - RedisTemplate lettuceXstreamStringTemplate = new RedisTemplate(); + RedisTemplate lettuceXstreamStringTemplate = new RedisTemplate<>(); lettuceXstreamStringTemplate.setConnectionFactory(lettuceConnectionFactory); lettuceXstreamStringTemplate.setDefaultSerializer(serializer); lettuceXstreamStringTemplate.afterPropertiesSet(); - RedisTemplate lettuceJackson2JsonPersonTemplate = new RedisTemplate(); + RedisTemplate lettuceJackson2JsonPersonTemplate = new RedisTemplate<>(); lettuceJackson2JsonPersonTemplate.setConnectionFactory(lettuceConnectionFactory); lettuceJackson2JsonPersonTemplate.setValueSerializer(jackson2JsonSerializer); lettuceJackson2JsonPersonTemplate.afterPropertiesSet(); diff --git a/src/test/java/org/springframework/data/redis/core/RedisKeyValueAdapterTests.java b/src/test/java/org/springframework/data/redis/core/RedisKeyValueAdapterTests.java index 605a79c70..9b04e5ff2 100644 --- a/src/test/java/org/springframework/data/redis/core/RedisKeyValueAdapterTests.java +++ b/src/test/java/org/springframework/data/redis/core/RedisKeyValueAdapterTests.java @@ -38,7 +38,6 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.springframework.beans.factory.InitializingBean; -import org.springframework.dao.DataAccessException; import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Reference; import org.springframework.data.geo.Point; @@ -65,7 +64,7 @@ import org.springframework.data.redis.core.mapping.RedisMappingContext; @RunWith(Parameterized.class) public class RedisKeyValueAdapterTests { - private static Set initializedFactories = new HashSet(); + private static Set initializedFactories = new HashSet<>(); RedisKeyValueAdapter adapter; StringRedisTemplate template; @@ -109,13 +108,9 @@ public class RedisKeyValueAdapterTests { adapter.setEnableKeyspaceEvents(EnableKeyspaceEvents.ON_STARTUP); adapter.afterPropertiesSet(); - template.execute(new RedisCallback() { - - @Override - public Void doInRedis(RedisConnection connection) throws DataAccessException { - connection.flushDb(); - return null; - } + template.execute((RedisCallback) connection -> { + connection.flushDb(); + return null; }); RedisConnection connection = template.getConnectionFactory().getConnection(); @@ -192,7 +187,7 @@ public class RedisKeyValueAdapterTests { @Test // DATAREDIS-425 public void getShouldReadSimpleObjectCorrectly() { - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put("_class", Person.class.getName()); map.put("age", "24"); template.opsForHash().putAll("persons:load-1", map); @@ -206,7 +201,7 @@ public class RedisKeyValueAdapterTests { @Test // DATAREDIS-425 public void getShouldReadNestedObjectCorrectly() { - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put("_class", Person.class.getName()); map.put("address.country", "Andor"); template.opsForHash().putAll("persons:load-1", map); @@ -220,7 +215,7 @@ public class RedisKeyValueAdapterTests { @Test // DATAREDIS-425 public void couldReadsKeyspaceSizeCorrectly() { - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put("_class", Person.class.getName()); map.put("address.country", "Andor"); template.opsForHash().putAll("persons:load-1", map); @@ -233,7 +228,7 @@ public class RedisKeyValueAdapterTests { @Test // DATAREDIS-425 public void deleteRemovesEntriesCorrectly() { - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put("_class", Person.class.getName()); map.put("address.country", "Andor"); template.opsForHash().putAll("persons:1", map); @@ -248,7 +243,7 @@ public class RedisKeyValueAdapterTests { @Test // DATAREDIS-425 public void deleteCleansIndexedDataCorrectly() { - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put("_class", Person.class.getName()); map.put("firstname", "rand"); map.put("address.country", "Andor"); @@ -267,7 +262,7 @@ public class RedisKeyValueAdapterTests { assumeTrue(RedisTestProfileValueSource.matches("runLongTests", "true")); - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put("_class", Person.class.getName()); map.put("firstname", "rand"); map.put("address.country", "Andor"); @@ -295,7 +290,7 @@ public class RedisKeyValueAdapterTests { assumeTrue(RedisTestProfileValueSource.matches("runLongTests", "true")); - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put("_class", Person.class.getName()); map.put("firstname", "rand"); map.put("address.country", "Andor"); @@ -363,7 +358,7 @@ public class RedisKeyValueAdapterTests { assertThat(template.hasKey("persons:firstname:rand"), is(true)); - PartialUpdate update = new PartialUpdate("1", Person.class) // + PartialUpdate update = new PartialUpdate<>("1", Person.class) // .set("firstname", "mat"); adapter.update(update); @@ -383,7 +378,7 @@ public class RedisKeyValueAdapterTests { assertThat(template.hasKey("persons:address.country:andor"), is(true)); - PartialUpdate update = new PartialUpdate("1", Person.class); + PartialUpdate update = new PartialUpdate<>("1", Person.class); Address addressUpdate = new Address(); addressUpdate.country = "tear"; @@ -406,7 +401,7 @@ public class RedisKeyValueAdapterTests { assertThat(template.hasKey("persons:address.country:andor"), is(true)); - PartialUpdate update = new PartialUpdate("1", Person.class) // + PartialUpdate update = new PartialUpdate<>("1", Person.class) // .set("address.country", "tear"); adapter.update(update); @@ -425,7 +420,7 @@ public class RedisKeyValueAdapterTests { adapter.put("1", rand, "persons"); - PartialUpdate update = new PartialUpdate("1", Person.class) // + PartialUpdate update = new PartialUpdate<>("1", Person.class) // .del("address"); adapter.update(update); @@ -443,7 +438,7 @@ public class RedisKeyValueAdapterTests { adapter.put("1", rand, "persons"); - PartialUpdate update = new PartialUpdate("1", Person.class) // + PartialUpdate update = new PartialUpdate<>("1", Person.class) // .del("nicknames"); adapter.update(update); @@ -468,7 +463,7 @@ public class RedisKeyValueAdapterTests { adapter.put("1", rand, "persons"); - PartialUpdate update = new PartialUpdate("1", Person.class) // + PartialUpdate update = new PartialUpdate<>("1", Person.class) // .del("coworkers"); adapter.update(update); @@ -487,7 +482,7 @@ public class RedisKeyValueAdapterTests { adapter.put("1", rand, "persons"); - PartialUpdate update = new PartialUpdate("1", Person.class) // + PartialUpdate update = new PartialUpdate<>("1", Person.class) // .del("physicalAttributes"); adapter.update(update); @@ -506,7 +501,7 @@ public class RedisKeyValueAdapterTests { adapter.put("1", rand, "persons"); - PartialUpdate update = new PartialUpdate("1", Person.class) // + PartialUpdate update = new PartialUpdate<>("1", Person.class) // .del("relatives"); adapter.update(update); @@ -555,7 +550,7 @@ public class RedisKeyValueAdapterTests { adapter.put("1", tam, "persons"); - PartialUpdate update = new PartialUpdate("1", Person.class) // + PartialUpdate update = new PartialUpdate<>("1", Person.class) // .del("address.location"); adapter.update(update); @@ -574,7 +569,7 @@ public class RedisKeyValueAdapterTests { adapter.put("1", tam, "persons"); - PartialUpdate update = new PartialUpdate("1", Person.class) // + PartialUpdate update = new PartialUpdate<>("1", Person.class) // .set("address.location", new Point(17, 18)); adapter.update(update); diff --git a/src/test/java/org/springframework/data/redis/core/RedisKeyValueAdapterUnitTests.java b/src/test/java/org/springframework/data/redis/core/RedisKeyValueAdapterUnitTests.java index 2c4f800c0..e914aec44 100644 --- a/src/test/java/org/springframework/data/redis/core/RedisKeyValueAdapterUnitTests.java +++ b/src/test/java/org/springframework/data/redis/core/RedisKeyValueAdapterUnitTests.java @@ -66,7 +66,7 @@ public class RedisKeyValueAdapterUnitTests { @Before public void setUp() throws Exception { - template = new RedisTemplate(); + template = new RedisTemplate<>(); template.setConnectionFactory(jedisConnectionFactoryMock); template.afterPropertiesSet(); @@ -104,7 +104,7 @@ public class RedisKeyValueAdapterUnitTests { rd.addIndexedData(new SimpleIndexedPropertyValue("persons", "firstname", "rand")); when(redisConnectionMock.sMembers(Mockito.any(byte[].class))) - .thenReturn(new LinkedHashSet(Arrays.asList("persons:firstname:rand".getBytes()))); + .thenReturn(new LinkedHashSet<>(Arrays.asList("persons:firstname:rand".getBytes()))); when(redisConnectionMock.del((byte[][]) any())).thenReturn(1L); adapter.put("1", rd, "persons"); @@ -119,7 +119,7 @@ public class RedisKeyValueAdapterUnitTests { rd.addIndexedData(new SimpleIndexedPropertyValue("persons", "firstname", "rand")); when(redisConnectionMock.sMembers(Mockito.any(byte[].class))) - .thenReturn(new LinkedHashSet(Arrays.asList("persons:firstname:rand".getBytes()))); + .thenReturn(new LinkedHashSet<>(Arrays.asList("persons:firstname:rand".getBytes()))); when(redisConnectionMock.del((byte[][]) any())).thenReturn(0L); adapter.put("1", rd, "persons"); diff --git a/src/test/java/org/springframework/data/redis/core/RedisKeyValueTemplateTests.java b/src/test/java/org/springframework/data/redis/core/RedisKeyValueTemplateTests.java index fef718a95..475bf3d21 100644 --- a/src/test/java/org/springframework/data/redis/core/RedisKeyValueTemplateTests.java +++ b/src/test/java/org/springframework/data/redis/core/RedisKeyValueTemplateTests.java @@ -37,10 +37,8 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; -import org.springframework.dao.DataAccessException; import org.springframework.data.annotation.Id; import org.springframework.data.redis.ConnectionFactoryTracker; -import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; @@ -92,7 +90,7 @@ public class RedisKeyValueTemplateTests { @Before public void setUp() { - nativeTemplate = new RedisTemplate(); + nativeTemplate = new RedisTemplate<>(); nativeTemplate.setConnectionFactory(connectionFactory); nativeTemplate.afterPropertiesSet(); @@ -104,14 +102,10 @@ public class RedisKeyValueTemplateTests { @After public void tearDown() throws Exception { - nativeTemplate.execute(new RedisCallback() { + nativeTemplate.execute((RedisCallback) connection -> { - @Override - public Void doInRedis(RedisConnection connection) throws DataAccessException { - - connection.flushDb(); - return null; - } + connection.flushDb(); + return null; }); template.destroy(); @@ -126,14 +120,10 @@ public class RedisKeyValueTemplateTests { template.insert(rand); - nativeTemplate.execute(new RedisCallback() { + nativeTemplate.execute((RedisCallback) connection -> { - @Override - public Void doInRedis(RedisConnection connection) throws DataAccessException { - - assertThat(connection.exists(("template-test-person:" + rand.id).getBytes()), is(true)); - return null; - } + assertThat(connection.exists(("template-test-person:" + rand.id).getBytes()), is(true)); + return null; }); } @@ -149,13 +139,7 @@ public class RedisKeyValueTemplateTests { template.insert(rand); template.insert(mat); - List result = template.find(new RedisCallback() { - - @Override - public byte[] doInRedis(RedisConnection connection) throws DataAccessException { - return mat.id.getBytes(); - } - }, Person.class); + List result = template.find(connection -> mat.id.getBytes(), Person.class); assertThat(result.size(), is(1)); assertThat(result, hasItems(mat)); @@ -173,13 +157,8 @@ public class RedisKeyValueTemplateTests { template.insert(rand); template.insert(mat); - List result = template.find(new RedisCallback>() { - - @Override - public List doInRedis(RedisConnection connection) throws DataAccessException { - return Arrays.asList(rand.id.getBytes(), mat.id.getBytes()); - } - }, Person.class); + List result = template.find(connection -> Arrays.asList(rand.id.getBytes(), mat.id.getBytes()), + Person.class); assertThat(result.size(), is(2)); assertThat(result, hasItems(rand, mat)); @@ -197,13 +176,7 @@ public class RedisKeyValueTemplateTests { template.insert(rand); template.insert(mat); - List result = template.find(new RedisCallback>() { - - @Override - public List doInRedis(RedisConnection connection) throws DataAccessException { - return null; - } - }, Person.class); + List result = template.find(connection -> null, Person.class); assertThat(result.size(), is(0)); } @@ -220,84 +193,68 @@ public class RedisKeyValueTemplateTests { * Set the lastname and make sure we've an index on it afterwards */ Person update1 = new Person(rand.id, null, "al-thor"); - PartialUpdate update = new PartialUpdate(rand.id, update1); + PartialUpdate update = new PartialUpdate<>(rand.id, update1); template.insert(update); assertThat(template.findById(rand.id, Person.class), is(equalTo(Optional.of(new Person(rand.id, "rand", "al-thor"))))); - nativeTemplate.execute(new RedisCallback() { + nativeTemplate.execute((RedisCallback) connection -> { - @Override - public Void doInRedis(RedisConnection connection) throws DataAccessException { - - assertThat(connection.hGet(("template-test-person:" + rand.id).getBytes(), "firstname".getBytes()), - is(equalTo("rand".getBytes()))); - assertThat(connection.exists("template-test-person:lastname:al-thor".getBytes()), is(true)); - assertThat(connection.sIsMember("template-test-person:lastname:al-thor".getBytes(), rand.id.getBytes()), - is(true)); - return null; - } + assertThat(connection.hGet(("template-test-person:" + rand.id).getBytes(), "firstname".getBytes()), + is(equalTo("rand".getBytes()))); + assertThat(connection.exists("template-test-person:lastname:al-thor".getBytes()), is(true)); + assertThat(connection.sIsMember("template-test-person:lastname:al-thor".getBytes(), rand.id.getBytes()), + is(true)); + return null; }); /* * Set the firstname and make sure lastname index and value is not affected */ - update = new PartialUpdate(rand.id, Person.class).set("firstname", "frodo"); + update = new PartialUpdate<>(rand.id, Person.class).set("firstname", "frodo"); template.update(update); assertThat(template.findById(rand.id, Person.class), is(equalTo(Optional.of(new Person(rand.id, "frodo", "al-thor"))))); - nativeTemplate.execute(new RedisCallback() { + nativeTemplate.execute((RedisCallback) connection -> { - @Override - public Void doInRedis(RedisConnection connection) throws DataAccessException { - - assertThat(connection.exists("template-test-person:lastname:al-thor".getBytes()), is(true)); - assertThat(connection.sIsMember("template-test-person:lastname:al-thor".getBytes(), rand.id.getBytes()), - is(true)); - return null; - } + assertThat(connection.exists("template-test-person:lastname:al-thor".getBytes()), is(true)); + assertThat(connection.sIsMember("template-test-person:lastname:al-thor".getBytes(), rand.id.getBytes()), + is(true)); + return null; }); /* * Remote firstname and update lastname. Make sure lastname index is updated */ - update = new PartialUpdate(rand.id, Person.class) // + update = new PartialUpdate<>(rand.id, Person.class) // .del("firstname").set("lastname", "baggins"); template.doPartialUpdate(update); assertThat(template.findById(rand.id, Person.class), is(equalTo(Optional.of(new Person(rand.id, null, "baggins"))))); - nativeTemplate.execute(new RedisCallback() { + nativeTemplate.execute((RedisCallback) connection -> { - @Override - public Void doInRedis(RedisConnection connection) throws DataAccessException { - - assertThat(connection.exists("template-test-person:lastname:al-thor".getBytes()), is(false)); - assertThat(connection.exists("template-test-person:lastname:baggins".getBytes()), is(true)); - assertThat(connection.sIsMember("template-test-person:lastname:baggins".getBytes(), rand.id.getBytes()), - is(true)); - return null; - } + assertThat(connection.exists("template-test-person:lastname:al-thor".getBytes()), is(false)); + assertThat(connection.exists("template-test-person:lastname:baggins".getBytes()), is(true)); + assertThat(connection.sIsMember("template-test-person:lastname:baggins".getBytes(), rand.id.getBytes()), + is(true)); + return null; }); /* * Remove lastname and make sure the index vanishes */ - update = new PartialUpdate(rand.id, Person.class) // + update = new PartialUpdate<>(rand.id, Person.class) // .del("lastname"); template.doPartialUpdate(update); assertThat(template.findById(rand.id, Person.class), is(equalTo(Optional.of(new Person(rand.id, null, null))))); - nativeTemplate.execute(new RedisCallback() { + nativeTemplate.execute((RedisCallback) connection -> { - @Override - public Void doInRedis(RedisConnection connection) throws DataAccessException { - - assertThat(connection.keys("template-test-person:lastname:*".getBytes()).size(), is(0)); - return null; - } + assertThat(connection.keys("template-test-person:lastname:*".getBytes()).size(), is(0)); + return null; }); } @@ -309,22 +266,18 @@ public class RedisKeyValueTemplateTests { template.insert(source); - PartialUpdate update = new PartialUpdate(source.id, VariousTypes.class) // + PartialUpdate update = new PartialUpdate<>(source.id, VariousTypes.class) // .set("stringValue", "hooya!"); template.doPartialUpdate(update); - nativeTemplate.execute(new RedisCallback() { + nativeTemplate.execute((RedisCallback) connection -> { - @Override - public Void doInRedis(RedisConnection connection) throws DataAccessException { - - assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), "stringValue".getBytes()), - is("hooya!".getBytes())); - assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), - "simpleTypedMap._class".getBytes()), is(false)); - return null; - } + assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), "stringValue".getBytes()), + is("hooya!".getBytes())); + assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), + "simpleTypedMap._class".getBytes()), is(false)); + return null; }); } @@ -347,28 +300,24 @@ public class RedisKeyValueTemplateTests { portalStone.dimension.height = 350; portalStone.dimension.width = 70; - PartialUpdate update = new PartialUpdate(source.id, VariousTypes.class) // + PartialUpdate update = new PartialUpdate<>(source.id, VariousTypes.class) // .set("complexValue", portalStone); template.doPartialUpdate(update); - nativeTemplate.execute(new RedisCallback() { + nativeTemplate.execute((RedisCallback) connection -> { - @Override - public Void doInRedis(RedisConnection connection) throws DataAccessException { + assertThat( + connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), "complexValue.name".getBytes()), + is("Portal Stone".getBytes())); + assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), + "complexValue.dimension.height".getBytes()), is("350".getBytes())); + assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), + "complexValue.dimension.width".getBytes()), is("70".getBytes())); - assertThat( - connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), "complexValue.name".getBytes()), - is("Portal Stone".getBytes())); - assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), - "complexValue.dimension.height".getBytes()), is("350".getBytes())); - assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), - "complexValue.dimension.width".getBytes()), is("70".getBytes())); - - assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), - "complexValue.dimension.length".getBytes()), is(false)); - return null; - } + assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), + "complexValue.dimension.length".getBytes()), is(false)); + return null; }); } @@ -391,31 +340,26 @@ public class RedisKeyValueTemplateTests { portalStone.dimension.height = 350; portalStone.dimension.width = 70; - PartialUpdate update = new PartialUpdate(source.id, VariousTypes.class) // + PartialUpdate update = new PartialUpdate<>(source.id, VariousTypes.class) // .set("objectValue", portalStone); template.doPartialUpdate(update); - nativeTemplate.execute(new RedisCallback() { + nativeTemplate.execute((RedisCallback) connection -> { - @Override - public Void doInRedis(RedisConnection connection) throws DataAccessException { + assertThat( + connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), "objectValue._class".getBytes()), + is(Item.class.getName().getBytes())); + assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), "objectValue.name".getBytes()), + is("Portal Stone".getBytes())); + assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), + "objectValue.dimension.height".getBytes()), is("350".getBytes())); + assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), + "objectValue.dimension.width".getBytes()), is("70".getBytes())); - assertThat( - connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), "objectValue._class".getBytes()), - is(Item.class.getName().getBytes())); - assertThat( - connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), "objectValue.name".getBytes()), - is("Portal Stone".getBytes())); - assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), - "objectValue.dimension.height".getBytes()), is("350".getBytes())); - assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), - "objectValue.dimension.width".getBytes()), is("70".getBytes())); - - assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), "objectValue".getBytes()), - is(false)); - return null; - } + assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), "objectValue".getBytes()), + is(false)); + return null; }); } @@ -423,33 +367,30 @@ public class RedisKeyValueTemplateTests { public void partialUpdateSimpleTypedMap() { final VariousTypes source = new VariousTypes(); - source.simpleTypedMap = new LinkedHashMap(); + source.simpleTypedMap = new LinkedHashMap<>(); source.simpleTypedMap.put("key-1", "rand"); source.simpleTypedMap.put("key-2", "mat"); source.simpleTypedMap.put("key-3", "perrin"); template.insert(source); - PartialUpdate update = new PartialUpdate(source.id, VariousTypes.class) // + PartialUpdate update = new PartialUpdate<>(source.id, VariousTypes.class) // .set("simpleTypedMap", Collections.singletonMap("spring", "data")); template.doPartialUpdate(update); - nativeTemplate.execute(new RedisCallback() { + nativeTemplate.execute((RedisCallback) connection -> { - @Override - public Void doInRedis(RedisConnection connection) throws DataAccessException { - - assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), - "simpleTypedMap.[spring]".getBytes()), is("data".getBytes())); - assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), - "simpleTypedMap.[key-1]".getBytes()), is(false)); - assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), - "simpleTypedMap.[key-2]".getBytes()), is(false)); - assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), - "simpleTypedMap.[key-2]".getBytes()), is(false)); - return null; - } + assertThat( + connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), "simpleTypedMap.[spring]".getBytes()), + is("data".getBytes())); + assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), + "simpleTypedMap.[key-1]".getBytes()), is(false)); + assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), + "simpleTypedMap.[key-2]".getBytes()), is(false)); + assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), + "simpleTypedMap.[key-2]".getBytes()), is(false)); + return null; }); } @@ -457,7 +398,7 @@ public class RedisKeyValueTemplateTests { public void partialUpdateComplexTypedMap() { final VariousTypes source = new VariousTypes(); - source.complexTypedMap = new LinkedHashMap(); + source.complexTypedMap = new LinkedHashMap<>(); Item callandor = new Item(); callandor.name = "Callandor"; @@ -481,38 +422,34 @@ public class RedisKeyValueTemplateTests { hornOfValere.dimension.height = 70; hornOfValere.dimension.width = 25; - PartialUpdate update = new PartialUpdate(source.id, VariousTypes.class) // + PartialUpdate update = new PartialUpdate<>(source.id, VariousTypes.class) // .set("complexTypedMap", Collections.singletonMap("horn-of-valere", hornOfValere)); template.doPartialUpdate(update); - nativeTemplate.execute(new RedisCallback() { + nativeTemplate.execute((RedisCallback) connection -> { - @Override - public Void doInRedis(RedisConnection connection) throws DataAccessException { + assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), + "complexTypedMap.[horn-of-valere].name".getBytes()), is("Horn of Valere".getBytes())); + assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), + "complexTypedMap.[horn-of-valere].dimension.height".getBytes()), is("70".getBytes())); + assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), + "complexTypedMap.[horn-of-valere].dimension.width".getBytes()), is("25".getBytes())); - assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), - "complexTypedMap.[horn-of-valere].name".getBytes()), is("Horn of Valere".getBytes())); - assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), - "complexTypedMap.[horn-of-valere].dimension.height".getBytes()), is("70".getBytes())); - assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), - "complexTypedMap.[horn-of-valere].dimension.width".getBytes()), is("25".getBytes())); + assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), + "complexTypedMap.[callandor].name".getBytes()), is(false)); + assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), + "complexTypedMap.[callandor].dimension.height".getBytes()), is(false)); + assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), + "complexTypedMap.[callandor].dimension.width".getBytes()), is(false)); - assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), - "complexTypedMap.[callandor].name".getBytes()), is(false)); - assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), - "complexTypedMap.[callandor].dimension.height".getBytes()), is(false)); - assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), - "complexTypedMap.[callandor].dimension.width".getBytes()), is(false)); - - assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), - "complexTypedMap.[portal-stone].name".getBytes()), is(false)); - assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), - "complexTypedMap.[portal-stone].dimension.height".getBytes()), is(false)); - assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), - "complexTypedMap.[portal-stone].dimension.width".getBytes()), is(false)); - return null; - } + assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), + "complexTypedMap.[portal-stone].name".getBytes()), is(false)); + assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), + "complexTypedMap.[portal-stone].dimension.height".getBytes()), is(false)); + assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), + "complexTypedMap.[portal-stone].dimension.width".getBytes()), is(false)); + return null; }); } @@ -520,7 +457,7 @@ public class RedisKeyValueTemplateTests { public void partialUpdateObjectTypedMap() { final VariousTypes source = new VariousTypes(); - source.untypedMap = new LinkedHashMap(); + source.untypedMap = new LinkedHashMap<>(); Item callandor = new Item(); callandor.name = "Callandor"; @@ -545,54 +482,50 @@ public class RedisKeyValueTemplateTests { hornOfValere.dimension.height = 70; hornOfValere.dimension.width = 25; - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put("spring", "data"); map.put("horn-of-valere", hornOfValere); map.put("some-number", 100L); - PartialUpdate update = new PartialUpdate(source.id, VariousTypes.class) // + PartialUpdate update = new PartialUpdate<>(source.id, VariousTypes.class) // .set("untypedMap", map); template.doPartialUpdate(update); - nativeTemplate.execute(new RedisCallback() { + nativeTemplate.execute((RedisCallback) connection -> { - @Override - public Void doInRedis(RedisConnection connection) throws DataAccessException { + assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), + "untypedMap.[horn-of-valere].name".getBytes()), is("Horn of Valere".getBytes())); + assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), + "untypedMap.[horn-of-valere].dimension.height".getBytes()), is("70".getBytes())); + assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), + "untypedMap.[horn-of-valere].dimension.width".getBytes()), is("25".getBytes())); - assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), - "untypedMap.[horn-of-valere].name".getBytes()), is("Horn of Valere".getBytes())); - assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), - "untypedMap.[horn-of-valere].dimension.height".getBytes()), is("70".getBytes())); - assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), - "untypedMap.[horn-of-valere].dimension.width".getBytes()), is("25".getBytes())); + assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), + "untypedMap.[spring]._class".getBytes()), is("java.lang.String".getBytes())); + assertThat( + connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), "untypedMap.[spring]".getBytes()), + is("data".getBytes())); - assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), - "untypedMap.[spring]._class".getBytes()), is("java.lang.String".getBytes())); - assertThat( - connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), "untypedMap.[spring]".getBytes()), - is("data".getBytes())); + assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), + "untypedMap.[some-number]._class".getBytes()), is("java.lang.Long".getBytes())); + assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), + "untypedMap.[some-number]".getBytes()), is("100".getBytes())); - assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), - "untypedMap.[some-number]._class".getBytes()), is("java.lang.Long".getBytes())); - assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), - "untypedMap.[some-number]".getBytes()), is("100".getBytes())); + assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), + "untypedMap.[callandor].name".getBytes()), is(false)); + assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), + "untypedMap.[callandor].dimension.height".getBytes()), is(false)); + assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), + "untypedMap.[callandor].dimension.width".getBytes()), is(false)); - assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), - "untypedMap.[callandor].name".getBytes()), is(false)); - assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), - "untypedMap.[callandor].dimension.height".getBytes()), is(false)); - assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), - "untypedMap.[callandor].dimension.width".getBytes()), is(false)); - - assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), - "untypedMap.[portal-stone].name".getBytes()), is(false)); - assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), - "untypedMap.[portal-stone].dimension.height".getBytes()), is(false)); - assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), - "untypedMap.[portal-stone].dimension.width".getBytes()), is(false)); - return null; - } + assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), + "untypedMap.[portal-stone].name".getBytes()), is(false)); + assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), + "untypedMap.[portal-stone].dimension.height".getBytes()), is(false)); + assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), + "untypedMap.[portal-stone].dimension.width".getBytes()), is(false)); + return null; }); } @@ -600,34 +533,33 @@ public class RedisKeyValueTemplateTests { public void partialUpdateSimpleTypedList() { final VariousTypes source = new VariousTypes(); - source.simpleTypedList = new ArrayList(); + source.simpleTypedList = new ArrayList<>(); source.simpleTypedList.add("rand"); source.simpleTypedList.add("mat"); source.simpleTypedList.add("perrin"); template.insert(source); - PartialUpdate update = new PartialUpdate(source.id, VariousTypes.class) // + PartialUpdate update = new PartialUpdate<>(source.id, VariousTypes.class) // .set("simpleTypedList", Collections.singletonList("spring")); template.doPartialUpdate(update); - nativeTemplate.execute(new RedisCallback() { + nativeTemplate.execute((RedisCallback) connection -> { - @Override - public Void doInRedis(RedisConnection connection) throws DataAccessException { - - assertThat( - connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), "simpleTypedList.[0]".getBytes()), - is("spring".getBytes())); - assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), - "simpleTypedList.[1]".getBytes()), is(false)); - assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), - "simpleTypedList.[2]".getBytes()), is(false)); - assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), - "simpleTypedList.[3]".getBytes()), is(false)); - return null; - } + assertThat( + connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), "simpleTypedList.[0]".getBytes()), + is("spring".getBytes())); + assertThat( + connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), "simpleTypedList.[1]".getBytes()), + is(false)); + assertThat( + connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), "simpleTypedList.[2]".getBytes()), + is(false)); + assertThat( + connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), "simpleTypedList.[3]".getBytes()), + is(false)); + return null; }); } @@ -635,7 +567,7 @@ public class RedisKeyValueTemplateTests { public void partialUpdateComplexTypedList() { final VariousTypes source = new VariousTypes(); - source.complexTypedList = new ArrayList(); + source.complexTypedList = new ArrayList<>(); Item callandor = new Item(); callandor.name = "Callandor"; @@ -659,31 +591,27 @@ public class RedisKeyValueTemplateTests { hornOfValere.dimension.height = 70; hornOfValere.dimension.width = 25; - PartialUpdate update = new PartialUpdate(source.id, VariousTypes.class) // + PartialUpdate update = new PartialUpdate<>(source.id, VariousTypes.class) // .set("complexTypedList", Collections.singletonList(hornOfValere)); template.doPartialUpdate(update); - nativeTemplate.execute(new RedisCallback() { + nativeTemplate.execute((RedisCallback) connection -> { - @Override - public Void doInRedis(RedisConnection connection) throws DataAccessException { + assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), + "complexTypedList.[0].name".getBytes()), is("Horn of Valere".getBytes())); + assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), + "complexTypedList.[0].dimension.height".getBytes()), is("70".getBytes())); + assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), + "complexTypedList.[0].dimension.width".getBytes()), is("25".getBytes())); - assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), - "complexTypedList.[0].name".getBytes()), is("Horn of Valere".getBytes())); - assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), - "complexTypedList.[0].dimension.height".getBytes()), is("70".getBytes())); - assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), - "complexTypedList.[0].dimension.width".getBytes()), is("25".getBytes())); - - assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), - "complexTypedMap.[1].name".getBytes()), is(false)); - assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), - "complexTypedMap.[1].dimension.height".getBytes()), is(false)); - assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), - "complexTypedMap.[1].dimension.width".getBytes()), is(false)); - return null; - } + assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), + "complexTypedMap.[1].name".getBytes()), is(false)); + assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), + "complexTypedMap.[1].dimension.height".getBytes()), is(false)); + assertThat(connection.hExists(("template-test-type-mapping:" + source.id).getBytes(), + "complexTypedMap.[1].dimension.width".getBytes()), is(false)); + return null; }); } @@ -691,7 +619,7 @@ public class RedisKeyValueTemplateTests { public void partialUpdateObjectTypedList() { final VariousTypes source = new VariousTypes(); - source.untypedList = new ArrayList(); + source.untypedList = new ArrayList<>(); Item callandor = new Item(); callandor.name = "Callandor"; @@ -716,43 +644,39 @@ public class RedisKeyValueTemplateTests { hornOfValere.dimension.height = 70; hornOfValere.dimension.width = 25; - List list = new ArrayList(); + List list = new ArrayList<>(); list.add("spring"); list.add(hornOfValere); list.add(100L); - PartialUpdate update = new PartialUpdate(source.id, VariousTypes.class) // + PartialUpdate update = new PartialUpdate<>(source.id, VariousTypes.class) // .set("untypedList", list); template.doPartialUpdate(update); - nativeTemplate.execute(new RedisCallback() { + nativeTemplate.execute((RedisCallback) connection -> { - @Override - public Void doInRedis(RedisConnection connection) throws DataAccessException { + assertThat( + connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), "untypedList.[0]._class".getBytes()), + is("java.lang.String".getBytes())); + assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), "untypedList.[0]".getBytes()), + is("spring".getBytes())); - assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), - "untypedList.[0]._class".getBytes()), is("java.lang.String".getBytes())); - assertThat( - connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), "untypedList.[0]".getBytes()), - is("spring".getBytes())); + assertThat( + connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), "untypedList.[1].name".getBytes()), + is("Horn of Valere".getBytes())); + assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), + "untypedList.[1].dimension.height".getBytes()), is("70".getBytes())); + assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), + "untypedList.[1].dimension.width".getBytes()), is("25".getBytes())); - assertThat( - connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), "untypedList.[1].name".getBytes()), - is("Horn of Valere".getBytes())); - assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), - "untypedList.[1].dimension.height".getBytes()), is("70".getBytes())); - assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), - "untypedList.[1].dimension.width".getBytes()), is("25".getBytes())); + assertThat( + connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), "untypedList.[2]._class".getBytes()), + is("java.lang.Long".getBytes())); + assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), "untypedList.[2]".getBytes()), + is("100".getBytes())); - assertThat(connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), - "untypedList.[2]._class".getBytes()), is("java.lang.Long".getBytes())); - assertThat( - connection.hGet(("template-test-type-mapping:" + source.id).getBytes(), "untypedList.[2]".getBytes()), - is("100".getBytes())); - - return null; - } + return null; }); } @@ -773,18 +697,14 @@ public class RedisKeyValueTemplateTests { template.doPartialUpdate(update); - nativeTemplate.execute(new RedisCallback() { + nativeTemplate.execute((RedisCallback) connection -> { - @Override - public Void doInRedis(RedisConnection connection) throws DataAccessException { - - assertThat(connection.hGet(("template-test-person:" + rand.id).getBytes(), "lastname".getBytes()), - is(equalTo("doe".getBytes()))); - assertThat(connection.exists("template-test-person:email:rand@twof.com".getBytes()), is(true)); - assertThat(connection.exists("template-test-person:lastname:al-thor".getBytes()), is(false)); - assertThat(connection.sIsMember("template-test-person:lastname:doe".getBytes(), rand.id.getBytes()), is(true)); - return null; - } + assertThat(connection.hGet(("template-test-person:" + rand.id).getBytes(), "lastname".getBytes()), + is(equalTo("doe".getBytes()))); + assertThat(connection.exists("template-test-person:email:rand@twof.com".getBytes()), is(true)); + assertThat(connection.exists("template-test-person:lastname:al-thor".getBytes()), is(false)); + assertThat(connection.sIsMember("template-test-person:lastname:doe".getBytes(), rand.id.getBytes()), is(true)); + return null; }); } @@ -798,30 +718,22 @@ public class RedisKeyValueTemplateTests { template.insert(rand); - nativeTemplate.execute(new RedisCallback() { + nativeTemplate.execute((RedisCallback) connection -> { - @Override - public Void doInRedis(RedisConnection connection) throws DataAccessException { - - assertThat(connection.exists("template-test-person:email:rand@twof.com".getBytes()), is(true)); - assertThat(connection.exists("template-test-person:lastname:al-thor".getBytes()), is(true)); - return null; - } + assertThat(connection.exists("template-test-person:email:rand@twof.com".getBytes()), is(true)); + assertThat(connection.exists("template-test-person:lastname:al-thor".getBytes()), is(true)); + return null; }); rand.lastname = null; template.update(rand); - nativeTemplate.execute(new RedisCallback() { + nativeTemplate.execute((RedisCallback) connection -> { - @Override - public Void doInRedis(RedisConnection connection) throws DataAccessException { - - assertThat(connection.exists("template-test-person:email:rand@twof.com".getBytes()), is(true)); - assertThat(connection.exists("template-test-person:lastname:al-thor".getBytes()), is(false)); - return null; - } + assertThat(connection.exists("template-test-person:email:rand@twof.com".getBytes()), is(true)); + assertThat(connection.exists("template-test-person:lastname:al-thor".getBytes()), is(false)); + return null; }); } @@ -886,13 +798,8 @@ public class RedisKeyValueTemplateTests { template.insert(source); - nativeTemplate.execute(new RedisCallback() { - - @Override - public Boolean doInRedis(RedisConnection connection) throws DataAccessException { - return connection.persist((WithTtl.class.getName() + ":ttl-1").getBytes()); - } - }); + nativeTemplate.execute( + (RedisCallback) connection -> connection.persist((WithTtl.class.getName() + ":ttl-1").getBytes())); Optional target = template.findById(source.id, WithTtl.class); assertThat(target.get().ttl, is(-1L)); diff --git a/src/test/java/org/springframework/data/redis/core/RedisTemplateTests.java b/src/test/java/org/springframework/data/redis/core/RedisTemplateTests.java index 4ffb3f74e..b6e9ff037 100644 --- a/src/test/java/org/springframework/data/redis/core/RedisTemplateTests.java +++ b/src/test/java/org/springframework/data/redis/core/RedisTemplateTests.java @@ -39,9 +39,7 @@ import org.springframework.data.redis.ObjectFactory; import org.springframework.data.redis.Person; import org.springframework.data.redis.RedisTestProfileValueSource; import org.springframework.data.redis.SettingsUtils; -import org.springframework.data.redis.TestCondition; import org.springframework.data.redis.connection.DataType; -import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.StringRedisConnection; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; @@ -83,11 +81,9 @@ public class RedisTemplateTests { @After public void tearDown() { - redisTemplate.execute(new RedisCallback() { - public Object doInRedis(RedisConnection connection) { - connection.flushDb(); - return null; - } + redisTemplate.execute((RedisCallback) connection -> { + connection.flushDb(); + return null; }); } @@ -125,11 +121,7 @@ public class RedisTemplateTests { redisTemplate.delete(key1); redisTemplate.restore(key1, serializedValue, 200, TimeUnit.MILLISECONDS); assertThat(redisTemplate.boundValueOps(key1).get(), isEqual(value1)); - waitFor(new TestCondition() { - public boolean passes() { - return (!redisTemplate.hasKey(key1)); - } - }, 400); + waitFor(() -> (!redisTemplate.hasKey(key1)), 400); } @SuppressWarnings("unchecked") @@ -154,12 +146,10 @@ public class RedisTemplateTests { @Test public void testStringTemplateExecutesWithStringConn() { assumeTrue(redisTemplate instanceof StringRedisTemplate); - String value = redisTemplate.execute(new RedisCallback() { - public String doInRedis(RedisConnection connection) { - StringRedisConnection stringConn = (StringRedisConnection) connection; - stringConn.set("test", "it"); - return stringConn.get("test"); - } + String value = redisTemplate.execute((RedisCallback) connection -> { + StringRedisConnection stringConn = (StringRedisConnection) connection; + stringConn.set("test", "it"); + return stringConn.get("test"); }); assertEquals(value, "it"); } @@ -190,9 +180,9 @@ public class RedisTemplateTests { } }); List list = Collections.singletonList(listValue); - Set set = new HashSet(Collections.singletonList(setValue)); - Set> tupleSet = new LinkedHashSet>( - Collections.singletonList(new DefaultTypedTuple(zsetValue, 1d))); + Set set = new HashSet<>(Collections.singletonList(setValue)); + Set> tupleSet = new LinkedHashSet<>( + Collections.singletonList(new DefaultTypedTuple<>(zsetValue, 1d))); assertThat(results, isEqual(Arrays.asList(new Object[] { value1, 1l, list, 1l, set, true, tupleSet }))); } @@ -233,16 +223,15 @@ public class RedisTemplateTests { operations.opsForZSet().range("foozset", 0, -1); operations.opsForHash().put("foomap", "10", "11"); operations.opsForHash().entries("foomap"); - return operations.exec(new GenericToStringSerializer(Long.class)); + return operations.exec(new GenericToStringSerializer<>(Long.class)); } }); // Everything should be converted to Longs List list = Collections.singletonList(6l); - Set longSet = new HashSet(Collections.singletonList(7l)); - Set> tupleSet = new LinkedHashSet>( - Collections.singletonList(new DefaultTypedTuple(9l, 1d))); - Set zSet = new LinkedHashSet(Collections.singletonList(9l)); - Map map = new LinkedHashMap(); + Set longSet = new HashSet<>(Collections.singletonList(7l)); + Set> tupleSet = new LinkedHashSet<>(Collections.singletonList(new DefaultTypedTuple<>(9l, 1d))); + Set zSet = new LinkedHashSet<>(Collections.singletonList(9l)); + Map map = new LinkedHashMap<>(); map.put(10l, 11l); assertThat(results, isEqual(Arrays.asList(new Object[] { 5l, 1L, 1l, list, 1l, longSet, true, tupleSet, zSet, true, map }))); @@ -281,17 +270,15 @@ public class RedisTemplateTests { final K listKey = keyFactory.instance(); final V listValue = valueFactory.instance(); final V listValue2 = valueFactory.instance(); - List results = redisTemplate.executePipelined(new RedisCallback() { - public Object doInRedis(RedisConnection connection) throws DataAccessException { - byte[] rawKey = serialize(key1, redisTemplate.getKeySerializer()); - byte[] rawListKey = serialize(listKey, redisTemplate.getKeySerializer()); - connection.set(rawKey, serialize(value1, redisTemplate.getValueSerializer())); - connection.get(rawKey); - connection.rPush(rawListKey, serialize(listValue, redisTemplate.getValueSerializer())); - connection.rPush(rawListKey, serialize(listValue2, redisTemplate.getValueSerializer())); - connection.lRange(rawListKey, 0, -1); - return null; - } + List results = redisTemplate.executePipelined((RedisCallback) connection -> { + byte[] rawKey = serialize(key1, redisTemplate.getKeySerializer()); + byte[] rawListKey = serialize(listKey, redisTemplate.getKeySerializer()); + connection.set(rawKey, serialize(value1, redisTemplate.getValueSerializer())); + connection.get(rawKey); + connection.rPush(rawListKey, serialize(listValue, redisTemplate.getValueSerializer())); + connection.rPush(rawListKey, serialize(listValue2, redisTemplate.getValueSerializer())); + connection.lRange(rawListKey, 0, -1); + return null; }); assertThat(results, isEqual(Arrays.asList(new Object[] { value1, 1l, 2l, Arrays.asList(new Object[] { listValue, listValue2 }) }))); @@ -303,17 +290,15 @@ public class RedisTemplateTests { assumeTrue(redisTemplate instanceof StringRedisTemplate); - List results = redisTemplate.executePipelined(new RedisCallback() { - public Object doInRedis(RedisConnection connection) throws DataAccessException { - StringRedisConnection stringRedisConn = (StringRedisConnection) connection; - stringRedisConn.set("foo", "5"); - stringRedisConn.get("foo"); - stringRedisConn.rPush("foolist", "10"); - stringRedisConn.rPush("foolist", "11"); - stringRedisConn.lRange("foolist", 0, -1); - return null; - } - }, new GenericToStringSerializer(Long.class)); + List results = redisTemplate.executePipelined((RedisCallback) connection -> { + StringRedisConnection stringRedisConn = (StringRedisConnection) connection; + stringRedisConn.set("foo", "5"); + stringRedisConn.get("foo"); + stringRedisConn.rPush("foolist", "10"); + stringRedisConn.rPush("foolist", "11"); + stringRedisConn.lRange("foolist", 0, -1); + return null; + }, new GenericToStringSerializer<>(Long.class)); assertEquals(Arrays.asList(new Object[] { 5l, 1l, 2l, Arrays.asList(new Long[] { 10l, 11l }) }), results); } @@ -324,18 +309,16 @@ public class RedisTemplateTests { assumeTrue(redisTemplate instanceof StringRedisTemplate); redisTemplate.setKeySerializer(new StringRedisSerializer()); - redisTemplate.setHashKeySerializer(new GenericToStringSerializer(Long.class)); - redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer(Person.class)); + redisTemplate.setHashKeySerializer(new GenericToStringSerializer<>(Long.class)); + redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<>(Person.class)); Person person = new Person("Homer", "Simpson", 38); redisTemplate.opsForHash().put((K) "foo", 1L, person); - List results = redisTemplate.executePipelined(new RedisCallback() { - public Object doInRedis(RedisConnection connection) throws DataAccessException { - connection.hGetAll(((StringRedisSerializer) redisTemplate.getKeySerializer()).serialize("foo")); - return null; - } + List results = redisTemplate.executePipelined((RedisCallback) connection -> { + connection.hGetAll(((StringRedisSerializer) redisTemplate.getKeySerializer()).serialize("foo")); + return null; }); assertEquals(((Map) results.get(0)).get(1L), person); @@ -343,11 +326,7 @@ public class RedisTemplateTests { @Test(expected = InvalidDataAccessApiUsageException.class) public void testExecutePipelinedNonNullRedisCallback() { - redisTemplate.executePipelined(new RedisCallback() { - public String doInRedis(RedisConnection connection) throws DataAccessException { - return "Hey There"; - } - }); + redisTemplate.executePipelined((RedisCallback) connection -> "Hey There"); } @SuppressWarnings({ "rawtypes", "unchecked" }) @@ -387,7 +366,7 @@ public class RedisTemplateTests { operations.opsForValue().get("foo"); return null; } - }, new GenericToStringSerializer(Long.class)); + }, new GenericToStringSerializer<>(Long.class)); // Should contain the List of deserialized exec results and the result of the last call to get() assertEquals(Arrays.asList(new Object[] { Arrays.asList(new Object[] { 1l, 5l, 0l }), 2l }), pipelinedResults); } @@ -420,7 +399,7 @@ public class RedisTemplateTests { V value2 = valueFactory.instance(); redisTemplate.opsForValue().set(key1, value1); redisTemplate.opsForValue().set(key2, value2); - List keys = new ArrayList(); + List keys = new ArrayList<>(); keys.add(key1); keys.add(key2); redisTemplate.delete(keys); @@ -456,11 +435,7 @@ public class RedisTemplateTests { assumeTrue(value1 instanceof Number); redisTemplate.opsForList().rightPush(key1, value1); List results = redisTemplate.sort(SortQueryBuilder.sort(key1).get("#").build(), - new BulkMapper() { - public String mapBulk(List tuple) { - return "FOO"; - } - }); + tuple -> "FOO"); assertEquals(Collections.singletonList("FOO"), results); } @@ -474,11 +449,7 @@ public class RedisTemplateTests { assertTrue(redisTemplate.getExpire(key1, TimeUnit.MILLISECONDS) > 0l); // Timeout is longer because expire will be 1 sec if pExpire not supported - waitFor(new TestCondition() { - public boolean passes() { - return (!redisTemplate.hasKey(key1)); - } - }, 1500l); + waitFor(() -> (!redisTemplate.hasKey(key1)), 1500l); } @Test @@ -629,11 +600,7 @@ public class RedisTemplateTests { V value1 = valueFactory.instance(); redisTemplate.boundValueOps(key1).set(value1); redisTemplate.expireAt(key1, new Date(System.currentTimeMillis() + 5l)); - waitFor(new TestCondition() { - public boolean passes() { - return (!redisTemplate.hasKey(key1)); - } - }, 5l); + waitFor(() -> (!redisTemplate.hasKey(key1)), 5l); } @Test @@ -651,11 +618,7 @@ public class RedisTemplateTests { template2.boundValueOps((String) key1).set((String) value1); template2.expireAt((String) key1, new Date(System.currentTimeMillis() + 5l)); // Just ensure this works as expected, pExpireAt just adds some precision over expireAt - waitFor(new TestCondition() { - public boolean passes() { - return (!template2.hasKey((String) key1)); - } - }, 5l); + waitFor(() -> (!template2.hasKey((String) key1)), 5l); } @Test @@ -715,11 +678,7 @@ public class RedisTemplateTests { final V value3 = valueFactory.instance(); redisTemplate.opsForValue().set(key1, value1); - final Thread th = new Thread(new Runnable() { - public void run() { - redisTemplate.opsForValue().set(key1, value2); - } - }); + final Thread th = new Thread(() -> redisTemplate.opsForValue().set(key1, value2)); List results = redisTemplate.execute(new SessionCallback>() { @SuppressWarnings({ "unchecked", "rawtypes" }) @@ -755,11 +714,7 @@ public class RedisTemplateTests { final V value2 = valueFactory.instance(); final V value3 = valueFactory.instance(); redisTemplate.opsForValue().set(key1, value1); - final Thread th = new Thread(new Runnable() { - public void run() { - redisTemplate.opsForValue().set(key1, value2); - } - }); + final Thread th = new Thread(() -> redisTemplate.opsForValue().set(key1, value2)); List results = redisTemplate.execute(new SessionCallback>() { @SuppressWarnings({ "unchecked", "rawtypes" }) @@ -793,17 +748,13 @@ public class RedisTemplateTests { final V value3 = valueFactory.instance(); redisTemplate.opsForValue().set(key1, value1); - final Thread th = new Thread(new Runnable() { - public void run() { - redisTemplate.opsForValue().set(key1, value2); - } - }); + final Thread th = new Thread(() -> redisTemplate.opsForValue().set(key1, value2)); List results = redisTemplate.execute(new SessionCallback>() { @SuppressWarnings({ "unchecked", "rawtypes" }) public List execute(RedisOperations operations) throws DataAccessException { - List keys = new ArrayList(); + List keys = new ArrayList<>(); keys.add(key1); keys.add(key2); operations.watch(keys); @@ -839,7 +790,7 @@ public class RedisTemplateTests { public void testExecuteScriptCustomSerializers() { assumeTrue(RedisTestProfileValueSource.matches("redisVersion", "2.6")); K key1 = keyFactory.instance(); - final DefaultRedisScript script = new DefaultRedisScript(); + final DefaultRedisScript script = new DefaultRedisScript<>(); script.setScriptText("return 'Hey'"); script.setResultType(String.class); assertEquals("Hey", redisTemplate.execute(script, redisTemplate.getValueSerializer(), new StringRedisSerializer(), diff --git a/src/test/java/org/springframework/data/redis/core/RedisTemplateUnitTests.java b/src/test/java/org/springframework/data/redis/core/RedisTemplateUnitTests.java index 77b16e5c4..c7199767e 100644 --- a/src/test/java/org/springframework/data/redis/core/RedisTemplateUnitTests.java +++ b/src/test/java/org/springframework/data/redis/core/RedisTemplateUnitTests.java @@ -47,7 +47,7 @@ public class RedisTemplateUnitTests { @Before public void setUp() { - template = new RedisTemplate(); + template = new RedisTemplate<>(); template.setConnectionFactory(connectionFactoryMock); when(connectionFactoryMock.getConnection()).thenReturn(redisConnectionMock); @@ -73,7 +73,7 @@ public class RedisTemplateUnitTests { ShadowingClassLoader scl = new ShadowingClassLoader(ClassLoader.getSystemClassLoader()); - template = new RedisTemplate(); + template = new RedisTemplate<>(); template.setConnectionFactory(connectionFactoryMock); template.setBeanClassLoader(scl); template.afterPropertiesSet(); diff --git a/src/test/java/org/springframework/data/redis/core/ScanCursorUnitTests.java b/src/test/java/org/springframework/data/redis/core/ScanCursorUnitTests.java index f6051307c..2df9dc431 100644 --- a/src/test/java/org/springframework/data/redis/core/ScanCursorUnitTests.java +++ b/src/test/java/org/springframework/data/redis/core/ScanCursorUnitTests.java @@ -44,19 +44,19 @@ public class ScanCursorUnitTests { @Test // DATAREDIS-290 public void cursorShouldNotLoopWhenNoValuesFound() { - CapturingCursorDummy cursor = initCursor(new LinkedList>()); + CapturingCursorDummy cursor = initCursor(new LinkedList<>()); assertThat(cursor.hasNext(), is(false)); } @Test(expected = NoSuchElementException.class) // DATAREDIS-290 public void cursorShouldReturnNullWhenNoNextElementAvailable() { - initCursor(new LinkedList>()).next(); + initCursor(new LinkedList<>()).next(); } @Test // DATAREDIS-290 public void cursorShouldNotLoopWhenReachingStartingPointInFistLoop() { - LinkedList> values = new LinkedList>(); + LinkedList> values = new LinkedList<>(); values.add(createIteration(0, "spring", "data", "redis")); CapturingCursorDummy cursor = initCursor(values); @@ -76,7 +76,7 @@ public class ScanCursorUnitTests { @Test // DATAREDIS-290 public void cursorShouldStopLoopWhenReachingStartingPoint() { - LinkedList> values = new LinkedList>(); + LinkedList> values = new LinkedList<>(); values.add(createIteration(1, "spring")); values.add(createIteration(2, "data")); values.add(createIteration(0, "redis")); @@ -111,7 +111,7 @@ public class ScanCursorUnitTests { @Test(expected = InvalidDataAccessApiUsageException.class) // DATAREDIS-290 public void repoeningCursorShouldHappenAtLastPosition() throws IOException { - LinkedList> values = new LinkedList>(); + LinkedList> values = new LinkedList<>(); values.add(createIteration(1, "spring")); values.add(createIteration(2, "data")); values.add(createIteration(0, "redis")); @@ -131,7 +131,7 @@ public class ScanCursorUnitTests { @Test // DATAREDIS-290 public void positionShouldBeIncrementedCorrectly() throws IOException { - LinkedList> values = new LinkedList>(); + LinkedList> values = new LinkedList<>(); values.add(createIteration(1, "spring")); values.add(createIteration(2, "data")); values.add(createIteration(0, "redis")); @@ -149,7 +149,7 @@ public class ScanCursorUnitTests { @Test // DATAREDIS-417 public void hasNextShouldCallScanUntilFinishedWhenScanResultIsAnEmptyCollection() { - LinkedList> values = new LinkedList>(); + LinkedList> values = new LinkedList<>(); values.add(createIteration(1, "spring")); values.add(createIteration(2)); values.add(createIteration(3)); @@ -158,7 +158,7 @@ public class ScanCursorUnitTests { values.add(createIteration(0, "redis")); Cursor cursor = initCursor(values); - List result = new ArrayList(); + List result = new ArrayList<>(); while (cursor.hasNext()) { result.add(cursor.next()); } @@ -170,7 +170,7 @@ public class ScanCursorUnitTests { @Test // DATAREDIS-417 public void hasNextShouldStopWhenScanResultIsAnEmptyCollectionAndStateIsFinished() { - LinkedList> values = new LinkedList>(); + LinkedList> values = new LinkedList<>(); values.add(createIteration(1, "spring")); values.add(createIteration(2)); values.add(createIteration(3)); @@ -181,7 +181,7 @@ public class ScanCursorUnitTests { values.add(createIteration(0)); Cursor cursor = initCursor(values); - List result = new ArrayList(); + List result = new ArrayList<>(); while (cursor.hasNext()) { result.add(cursor.next()); } @@ -193,7 +193,7 @@ public class ScanCursorUnitTests { @Test // DATAREDIS-417 public void hasNextShouldStopCorrectlyWhenWholeScanIterationDoesNotReturnResultsAndStateIsFinished() { - LinkedList> values = new LinkedList>(); + LinkedList> values = new LinkedList<>(); values.add(createIteration(1)); values.add(createIteration(2)); values.add(createIteration(3)); @@ -221,8 +221,7 @@ public class ScanCursorUnitTests { } private ScanIteration createIteration(long cursorId, String... values) { - return new ScanIteration(cursorId, values.length > 0 ? Arrays.asList(values) - : Collections. emptyList()); + return new ScanIteration<>(cursorId, values.length > 0 ? Arrays.asList(values) : Collections. emptyList()); } private class CapturingCursorDummy extends ScanCursor { @@ -239,7 +238,7 @@ public class ScanCursorUnitTests { protected ScanIteration doScan(long cursorId, ScanOptions options) { if (cursors == null) { - cursors = new Stack(); + cursors = new Stack<>(); } this.cursors.push(cursorId); return this.values.poll(); diff --git a/src/test/java/org/springframework/data/redis/core/SessionTest.java b/src/test/java/org/springframework/data/redis/core/SessionTest.java index 0e699480f..8c9b357ef 100644 --- a/src/test/java/org/springframework/data/redis/core/SessionTest.java +++ b/src/test/java/org/springframework/data/redis/core/SessionTest.java @@ -1,12 +1,12 @@ /* * Copyright 2011-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. @@ -19,15 +19,9 @@ import static org.junit.Assert.*; import static org.mockito.Mockito.*; import org.junit.Test; -import org.springframework.dao.DataAccessException; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.StringRedisConnection; -import org.springframework.data.redis.core.RedisCallback; -import org.springframework.data.redis.core.RedisOperations; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.core.SessionCallback; -import org.springframework.data.redis.core.StringRedisTemplate; /** * @author Costin Leau @@ -56,11 +50,9 @@ public class SessionTest { } private void checkConnection(RedisTemplate template, final RedisConnection expectedConnection) { - template.execute(new RedisCallback() { - public Object doInRedis(RedisConnection connection) throws DataAccessException { - assertSame(expectedConnection, connection); - return null; - } + template.execute(connection -> { + assertSame(expectedConnection, connection); + return null; }, true); } } diff --git a/src/test/java/org/springframework/data/redis/core/convert/ConversionTestEntities.java b/src/test/java/org/springframework/data/redis/core/convert/ConversionTestEntities.java index 1f75a321a..892c8e2a6 100644 --- a/src/test/java/org/springframework/data/redis/core/convert/ConversionTestEntities.java +++ b/src/test/java/org/springframework/data/redis/core/convert/ConversionTestEntities.java @@ -179,7 +179,7 @@ public class ConversionTestEntities { static class TypeWithObjectValueTypes { Object object; - Map map = new HashMap(); - List list = new ArrayList(); + Map map = new HashMap<>(); + List list = new ArrayList<>(); } } diff --git a/src/test/java/org/springframework/data/redis/core/convert/MappingRedisConverterUnitTests.java b/src/test/java/org/springframework/data/redis/core/convert/MappingRedisConverterUnitTests.java index 887f94266..688f29cef 100644 --- a/src/test/java/org/springframework/data/redis/core/convert/MappingRedisConverterUnitTests.java +++ b/src/test/java/org/springframework/data/redis/core/convert/MappingRedisConverterUnitTests.java @@ -32,7 +32,16 @@ import java.time.LocalTime; import java.time.Period; import java.time.ZoneId; import java.time.ZonedDateTime; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; import org.hamcrest.core.IsEqual; import org.junit.Before; @@ -213,7 +222,7 @@ public class MappingRedisConverterUnitTests { @Test // DATAREDIS-425 public void readConsidersClassTypeInformationCorrectlyForNonMatchingTypes() { - Map map = new HashMap(); + Map map = new HashMap<>(); map.put("address._class", AddressWithPostcode.class.getName()); map.put("address.postcode", "1234"); @@ -246,7 +255,7 @@ public class MappingRedisConverterUnitTests { @Test // DATAREDIS-425 public void readConvertsListOfSimplePropertiesCorrectly() { - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put("nicknames.[0]", "dragon reborn"); map.put("nicknames.[1]", "lews therin"); RedisData rdo = new RedisData(Bucket.newBucketFromStringMap(map)); @@ -257,7 +266,7 @@ public class MappingRedisConverterUnitTests { @Test // DATAREDIS-425 public void readConvertsUnorderedListOfSimplePropertiesCorrectly() { - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put("nicknames.[9]", "car'a'carn"); map.put("nicknames.[10]", "lews therin"); map.put("nicknames.[1]", "dragon reborn"); @@ -269,7 +278,7 @@ public class MappingRedisConverterUnitTests { @Test // DATAREDIS-425 public void readComplexPropertyCorrectly() { - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put("address.city", "two rivers"); map.put("address.country", "andor"); RedisData rdo = new RedisData(Bucket.newBucketFromStringMap(map)); @@ -284,7 +293,7 @@ public class MappingRedisConverterUnitTests { @Test // DATAREDIS-425 public void readListComplexPropertyCorrectly() { - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put("coworkers.[0].firstname", "mat"); map.put("coworkers.[0].nicknames.[0]", "prince of the ravens"); map.put("coworkers.[0].nicknames.[1]", "gambler"); @@ -307,7 +316,7 @@ public class MappingRedisConverterUnitTests { @Test // DATAREDIS-425 public void readUnorderedListOfComplexPropertyCorrectly() { - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put("coworkers.[10].firstname", "perrin"); map.put("coworkers.[10].address.city", "two rivers"); map.put("coworkers.[1].firstname", "mat"); @@ -331,7 +340,7 @@ public class MappingRedisConverterUnitTests { @Test // DATAREDIS-425 public void readListComplexPropertyCorrectlyAndConsidersClassTypeInformation() { - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put("coworkers.[0]._class", TaVeren.class.getName()); map.put("coworkers.[0].firstname", "mat"); @@ -347,7 +356,7 @@ public class MappingRedisConverterUnitTests { @Test // DATAREDIS-425 public void writeAppendsMapWithSimpleKeyCorrectly() { - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put("hair-color", "red"); map.put("eye-color", "grey"); @@ -362,11 +371,11 @@ public class MappingRedisConverterUnitTests { @Test // DATAREDIS-425 public void writeAppendsMapWithSimpleKeyOnNestedObjectCorrectly() { - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put("hair-color", "red"); map.put("eye-color", "grey"); - rand.coworkers = new ArrayList(); + rand.coworkers = new ArrayList<>(); rand.coworkers.add(new Person()); rand.coworkers.get(0).physicalAttributes = map; @@ -380,7 +389,7 @@ public class MappingRedisConverterUnitTests { @Test // DATAREDIS-425 public void readSimpleMapValuesCorrectly() { - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put("physicalAttributes.[hair-color]", "red"); map.put("physicalAttributes.[eye-color]", "grey"); @@ -396,7 +405,7 @@ public class MappingRedisConverterUnitTests { @Test // DATAREDIS-425 public void writeAppendsMapWithComplexObjectsCorrectly() { - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); Person janduin = new Person(); janduin.firstname = "janduin"; map.put("father", janduin); @@ -415,7 +424,7 @@ public class MappingRedisConverterUnitTests { @Test // DATAREDIS-425 public void readMapWithComplexObjectsCorrectly() { - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put("relatives.[father].firstname", "janduin"); map.put("relatives.[step-father].firstname", "tam"); @@ -431,7 +440,7 @@ public class MappingRedisConverterUnitTests { @Test // DATAREDIS-425 public void writeAppendsClassTypeInformationCorrectlyForMapWithComplexObjects() { - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); Person lews = new TaVeren(); lews.firstname = "lews"; map.put("previous-incarnation", lews); @@ -447,7 +456,7 @@ public class MappingRedisConverterUnitTests { @Test // DATAREDIS-425 public void readConsidersClassTypeInformationCorrectlyForMapWithComplexObjects() { - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put("relatives.[previous-incarnation]._class", TaVeren.class.getName()); map.put("relatives.[previous-incarnation].firstname", "lews"); @@ -695,14 +704,14 @@ public class MappingRedisConverterUnitTests { location.id = "1"; location.name = "tar valon"; - Map locationMap = new LinkedHashMap(); + Map locationMap = new LinkedHashMap<>(); locationMap.put("id", location.id); locationMap.put("name", location.name); when(resolverMock.resolveReference(eq("1"), eq("locations"))) .thenReturn(Bucket.newBucketFromStringMap(locationMap).rawMap()); - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put("location", "locations:1"); Person target = converter.read(Person.class, new RedisData(Bucket.newBucketFromStringMap(map))); @@ -737,14 +746,14 @@ public class MappingRedisConverterUnitTests { location.id = "1"; location.name = "tar valon"; - Map locationMap = new LinkedHashMap(); + Map locationMap = new LinkedHashMap<>(); locationMap.put("id", location.id); locationMap.put("name", location.name); when(resolverMock.resolveReference(eq("1"), eq("locations"))) .thenReturn(Bucket.newBucketFromStringMap(locationMap).rawMap()); - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put("coworkers.[0].location", "locations:1"); Person target = converter.read(Person.class, new RedisData(Bucket.newBucketFromStringMap(map))); @@ -792,15 +801,15 @@ public class MappingRedisConverterUnitTests { tear.id = "3"; tear.name = "city of tear"; - Map tarValonMap = new LinkedHashMap(); + Map tarValonMap = new LinkedHashMap<>(); tarValonMap.put("id", tarValon.id); tarValonMap.put("name", tarValon.name); - Map falmeMap = new LinkedHashMap(); + Map falmeMap = new LinkedHashMap<>(); falmeMap.put("id", falme.id); falmeMap.put("name", falme.name); - Map tearMap = new LinkedHashMap(); + Map tearMap = new LinkedHashMap<>(); tearMap.put("id", tear.id); tearMap.put("name", tear.name); @@ -813,7 +822,7 @@ public class MappingRedisConverterUnitTests { when(resolverMock.resolveReference(eq("3"), eq("locations"))) .thenReturn(Bucket.newBucketFromStringMap(tearMap).rawMap()); - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put("visited.[0]", "locations:1"); map.put("visited.[1]", "locations:2"); map.put("visited.[2]", "locations:3"); @@ -955,7 +964,7 @@ public class MappingRedisConverterUnitTests { .setCustomConversions(new RedisCustomConversions(Collections.singletonList(new BytesToAddressConverter()))); this.converter.afterPropertiesSet(); - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put("_raw", "{\"city\":\"unknown\",\"country\":\"Tel'aran'rhiod\"}"); Address target = converter.read(Address.class, new RedisData(Bucket.newBucketFromStringMap(map))); @@ -972,7 +981,7 @@ public class MappingRedisConverterUnitTests { .setCustomConversions(new RedisCustomConversions(Collections.singletonList(new BytesToAddressConverter()))); this.converter.afterPropertiesSet(); - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put("address", "{\"city\":\"unknown\",\"country\":\"Tel'aran'rhiod\"}"); Person target = converter.read(Person.class, new RedisData(Bucket.newBucketFromStringMap(map))); @@ -1038,7 +1047,7 @@ public class MappingRedisConverterUnitTests { this.converter .setCustomConversions(new RedisCustomConversions(Collections.singletonList(new MapToSpeciesConverter()))); this.converter.afterPropertiesSet(); - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put("species-name", "trolloc"); Species target = converter.read(Species.class, new RedisData(Bucket.newBucketFromStringMap(map))); @@ -1055,7 +1064,7 @@ public class MappingRedisConverterUnitTests { .setCustomConversions(new RedisCustomConversions(Collections.singletonList(new MapToSpeciesConverter()))); this.converter.afterPropertiesSet(); - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put("species.species-name", "trolloc"); Person target = converter.read(Person.class, new RedisData(Bucket.newBucketFromStringMap(map))); @@ -1073,7 +1082,7 @@ public class MappingRedisConverterUnitTests { this.converter.afterPropertiesSet(); TheWheelOfTime twot = new TheWheelOfTime(); - twot.species = new ArrayList(); + twot.species = new ArrayList<>(); Species myrddraal = new Species(); myrddraal.name = "myrddraal"; @@ -1092,7 +1101,7 @@ public class MappingRedisConverterUnitTests { .setCustomConversions(new RedisCustomConversions(Collections.singletonList(new MapToSpeciesConverter()))); this.converter.afterPropertiesSet(); - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put("species.[0].species-name", "trolloc"); TheWheelOfTime target = converter.read(TheWheelOfTime.class, new RedisData(Bucket.newBucketFromStringMap(map))); @@ -1111,11 +1120,11 @@ public class MappingRedisConverterUnitTests { .setCustomConversions(new RedisCustomConversions(Collections.singletonList(new ListToByteConverter()))); this.converter.afterPropertiesSet(); - Map innerMap = new LinkedHashMap(); + Map innerMap = new LinkedHashMap<>(); innerMap.put("address", "tyrionl@netflix.com"); innerMap.put("when", new String[] { "pipeline.failed" }); - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); map.put("email", Collections.singletonList(innerMap)); RedisData target = write(map); @@ -1136,7 +1145,7 @@ public class MappingRedisConverterUnitTests { @Test // DATAREDIS-492 public void readHandlesArraysOfSimpleTypeProperly() { - Map source = new LinkedHashMap(); + Map source = new LinkedHashMap<>(); source.put("arrayOfSimpleTypes.[0]", "rand"); source.put("arrayOfSimpleTypes.[1]", "mat"); source.put("arrayOfSimpleTypes.[2]", "perrin"); @@ -1171,7 +1180,7 @@ public class MappingRedisConverterUnitTests { @Test // DATAREDIS-492 public void readHandlesArraysOfComplexTypeProperly() { - Map source = new LinkedHashMap(); + Map source = new LinkedHashMap<>(); source.put("arrayOfCompexTypes.[0].name", "trolloc"); source.put("arrayOfCompexTypes.[1].name", "myrddraal"); source.put("arrayOfCompexTypes.[1].alsoKnownAs.[0]", "halfmen"); @@ -1208,7 +1217,7 @@ public class MappingRedisConverterUnitTests { @Test // DATAREDIS-489 public void readHandlesArraysOfObjectTypeProperly() { - Map source = new LinkedHashMap(); + Map source = new LinkedHashMap<>(); source.put("arrayOfObject.[0]", "rand"); source.put("arrayOfObject.[0]._class", "java.lang.String"); source.put("arrayOfObject.[1]._class", Species.class.getName()); @@ -1320,7 +1329,7 @@ public class MappingRedisConverterUnitTests { @Test // DATAREDIS-509 public void writeHandlesArraysOfPrimitivesProperly() { - Map source = new LinkedHashMap(); + Map source = new LinkedHashMap<>(); source.put("arrayOfPrimitives.[0]", "1"); source.put("arrayOfPrimitives.[1]", "2"); source.put("arrayOfPrimitives.[2]", "3"); @@ -1348,7 +1357,7 @@ public class MappingRedisConverterUnitTests { value.firstname = "rand"; value.age = 24; - PartialUpdate update = new PartialUpdate("123", value); + PartialUpdate update = new PartialUpdate<>("123", value); assertThat(write(update).getBucket().get("_class"), is(nullValue())); } @@ -1360,7 +1369,7 @@ public class MappingRedisConverterUnitTests { value.firstname = "rand"; value.age = 24; - PartialUpdate update = new PartialUpdate("123", value); + PartialUpdate update = new PartialUpdate<>("123", value); assertThat(write(update).getBucket(), isBucket().containingUtf8String("firstname", "rand").containingUtf8String("age", "24")); @@ -1369,7 +1378,7 @@ public class MappingRedisConverterUnitTests { @Test // DATAREDIS-471 public void writeShouldWritePartialUpdatePathWithSimpleValueCorrectly() { - PartialUpdate update = new PartialUpdate("123", Person.class).set("firstname", "rand").set("age", + PartialUpdate update = new PartialUpdate<>("123", Person.class).set("firstname", "rand").set("age", 24); assertThat(write(update).getBucket(), @@ -1379,7 +1388,7 @@ public class MappingRedisConverterUnitTests { @Test // DATAREDIS-471 public void writeShouldWritePartialUpdateNestedPathWithSimpleValueCorrectly() { - PartialUpdate update = new PartialUpdate("123", Person.class).set("address.city", "two rivers"); + PartialUpdate update = new PartialUpdate<>("123", Person.class).set("address.city", "two rivers"); assertThat(write(update).getBucket(), isBucket().containingUtf8String("address.city", "two rivers")); } @@ -1391,7 +1400,7 @@ public class MappingRedisConverterUnitTests { address.city = "two rivers"; address.country = "andor"; - PartialUpdate update = new PartialUpdate("123", Person.class).set("address", address); + PartialUpdate update = new PartialUpdate<>("123", Person.class).set("address", address); assertThat(write(update).getBucket(), isBucket().containingUtf8String("address.city", "two rivers").containingUtf8String("address.country", "andor")); @@ -1400,7 +1409,7 @@ public class MappingRedisConverterUnitTests { @Test // DATAREDIS-471 public void writeShouldWritePartialUpdatePathWithSimpleListValueCorrectly() { - PartialUpdate update = new PartialUpdate("123", Person.class).set("nicknames", + PartialUpdate update = new PartialUpdate<>("123", Person.class).set("nicknames", Arrays.asList("dragon", "lews")); assertThat(write(update).getBucket(), @@ -1417,7 +1426,7 @@ public class MappingRedisConverterUnitTests { Person perrin = new Person(); perrin.firstname = "perrin"; - PartialUpdate update = new PartialUpdate("123", Person.class).set("coworkers", + PartialUpdate update = new PartialUpdate<>("123", Person.class).set("coworkers", Arrays.asList(mat, perrin)); assertThat(write(update).getBucket(), isBucket().containingUtf8String("coworkers.[0].firstname", "mat") @@ -1427,7 +1436,7 @@ public class MappingRedisConverterUnitTests { @Test // DATAREDIS-471 public void writeShouldWritePartialUpdatePathWithSimpleListValueWhenNotPassedInAsCollectionCorrectly() { - PartialUpdate update = new PartialUpdate("123", Person.class).set("nicknames", "dragon"); + PartialUpdate update = new PartialUpdate<>("123", Person.class).set("nicknames", "dragon"); assertThat(write(update).getBucket(), isBucket().containingUtf8String("nicknames.[0]", "dragon")); } @@ -1439,7 +1448,7 @@ public class MappingRedisConverterUnitTests { mat.firstname = "mat"; mat.age = 24; - PartialUpdate update = new PartialUpdate("123", Person.class).set("coworkers", mat); + PartialUpdate update = new PartialUpdate<>("123", Person.class).set("coworkers", mat); assertThat(write(update).getBucket(), isBucket().containingUtf8String("coworkers.[0].firstname", "mat") .containingUtf8String("coworkers.[0].age", "24")); @@ -1448,7 +1457,7 @@ public class MappingRedisConverterUnitTests { @Test // DATAREDIS-471 public void writeShouldWritePartialUpdatePathWithSimpleListValueWhenNotPassedInAsCollectionWithPositionalParameterCorrectly() { - PartialUpdate update = new PartialUpdate("123", Person.class).set("nicknames.[5]", "dragon"); + PartialUpdate update = new PartialUpdate<>("123", Person.class).set("nicknames.[5]", "dragon"); assertThat(write(update).getBucket(), isBucket().containingUtf8String("nicknames.[5]", "dragon")); } @@ -1460,7 +1469,7 @@ public class MappingRedisConverterUnitTests { mat.firstname = "mat"; mat.age = 24; - PartialUpdate update = new PartialUpdate("123", Person.class).set("coworkers.[5]", mat); + PartialUpdate update = new PartialUpdate<>("123", Person.class).set("coworkers.[5]", mat); assertThat(write(update).getBucket(), isBucket().containingUtf8String("coworkers.[5].firstname", "mat") .containingUtf8String("coworkers.[5].age", "24")); @@ -1469,7 +1478,7 @@ public class MappingRedisConverterUnitTests { @Test // DATAREDIS-471 public void writeShouldWritePartialUpdatePathWithSimpleMapValueCorrectly() { - PartialUpdate update = new PartialUpdate("123", Person.class).set("physicalAttributes", + PartialUpdate update = new PartialUpdate<>("123", Person.class).set("physicalAttributes", Collections.singletonMap("eye-color", "grey")); assertThat(write(update).getBucket(), isBucket().containingUtf8String("physicalAttributes.[eye-color]", "grey")); @@ -1482,7 +1491,7 @@ public class MappingRedisConverterUnitTests { tam.firstname = "tam"; tam.alive = false; - PartialUpdate update = new PartialUpdate("123", Person.class).set("relatives", + PartialUpdate update = new PartialUpdate<>("123", Person.class).set("relatives", Collections.singletonMap("father", tam)); assertThat(write(update).getBucket(), isBucket().containingUtf8String("relatives.[father].firstname", "tam") @@ -1492,7 +1501,7 @@ public class MappingRedisConverterUnitTests { @Test // DATAREDIS-471 public void writeShouldWritePartialUpdatePathWithSimpleMapValueWhenNotPassedInAsCollectionCorrectly() { - PartialUpdate update = new PartialUpdate("123", Person.class).set("physicalAttributes", + PartialUpdate update = new PartialUpdate<>("123", Person.class).set("physicalAttributes", Collections.singletonMap("eye-color", "grey").entrySet().iterator().next()); assertThat(write(update).getBucket(), isBucket().containingUtf8String("physicalAttributes.[eye-color]", "grey")); @@ -1505,7 +1514,7 @@ public class MappingRedisConverterUnitTests { tam.firstname = "tam"; tam.alive = false; - PartialUpdate update = new PartialUpdate("123", Person.class).set("relatives", + PartialUpdate update = new PartialUpdate<>("123", Person.class).set("relatives", Collections.singletonMap("father", tam).entrySet().iterator().next()); assertThat(write(update).getBucket(), isBucket().containingUtf8String("relatives.[father].firstname", "tam") @@ -1515,7 +1524,7 @@ public class MappingRedisConverterUnitTests { @Test // DATAREDIS-471 public void writeShouldWritePartialUpdatePathWithSimpleMapValueWhenNotPassedInAsCollectionWithPositionalParameterCorrectly() { - PartialUpdate update = new PartialUpdate("123", Person.class).set("physicalAttributes.[eye-color]", + PartialUpdate update = new PartialUpdate<>("123", Person.class).set("physicalAttributes.[eye-color]", "grey"); assertThat(write(update).getBucket(), isBucket().containingUtf8String("physicalAttributes.[eye-color]", "grey")); @@ -1524,7 +1533,7 @@ public class MappingRedisConverterUnitTests { @Test // DATAREDIS-471 public void writeShouldWritePartialUpdatePathWithSimpleMapValueOnNestedElementCorrectly() { - PartialUpdate update = new PartialUpdate("123", Person.class).set("relatives.[father].firstname", + PartialUpdate update = new PartialUpdate<>("123", Person.class).set("relatives.[father].firstname", "tam"); assertThat(write(update).getBucket(), isBucket().containingUtf8String("relatives.[father].firstname", "tam")); @@ -1533,7 +1542,7 @@ public class MappingRedisConverterUnitTests { @Test(expected = MappingException.class) // DATAREDIS-471 public void writeShouldThrowExceptionOnPartialUpdatePathWithSimpleMapValueWhenItsASingleValueWithoutPath() { - PartialUpdate update = new PartialUpdate("123", Person.class).set("physicalAttributes", "grey"); + PartialUpdate update = new PartialUpdate<>("123", Person.class).set("physicalAttributes", "grey"); write(update); } @@ -1550,7 +1559,7 @@ public class MappingRedisConverterUnitTests { address.country = "Tel'aran'rhiod"; address.city = "unknown"; - PartialUpdate update = new PartialUpdate("123", Person.class).set("address", address); + PartialUpdate update = new PartialUpdate<>("123", Person.class).set("address", address); assertThat(write(update).getBucket(), isBucket().containingUtf8String("address", "{\"city\":\"unknown\",\"country\":\"Tel'aran'rhiod\"}")); @@ -1567,7 +1576,7 @@ public class MappingRedisConverterUnitTests { tear.id = "2"; tear.name = "city of tear"; - PartialUpdate update = new PartialUpdate("123", Person.class).set("visited", + PartialUpdate update = new PartialUpdate<>("123", Person.class).set("visited", Arrays.asList(tar, tear)); assertThat(write(update).getBucket(), @@ -1583,7 +1592,7 @@ public class MappingRedisConverterUnitTests { location.id = "1"; location.name = "tar valon"; - PartialUpdate update = new PartialUpdate("123", Person.class) // + PartialUpdate update = new PartialUpdate<>("123", Person.class) // .set("location", location); assertThat(write(update).getBucket(), @@ -1600,7 +1609,7 @@ public class MappingRedisConverterUnitTests { exception.expectMessage("java.lang.Integer"); exception.expectMessage("age"); - PartialUpdate update = new PartialUpdate("123", Person.class) // + PartialUpdate update = new PartialUpdate<>("123", Person.class) // .set("age", "twenty-four"); assertThat(write(update).getBucket().get("_class"), is(nullValue())); @@ -1614,7 +1623,7 @@ public class MappingRedisConverterUnitTests { exception.expectMessage(Person.class.getName()); exception.expectMessage("coworkers.[0]"); - PartialUpdate update = new PartialUpdate("123", Person.class) // + PartialUpdate update = new PartialUpdate<>("123", Person.class) // .set("coworkers.[0]", "buh buh the bear"); assertThat(write(update).getBucket().get("_class"), is(nullValue())); @@ -1628,7 +1637,7 @@ public class MappingRedisConverterUnitTests { exception.expectMessage(Person.class.getName()); exception.expectMessage("coworkers"); - PartialUpdate update = new PartialUpdate("123", Person.class) // + PartialUpdate update = new PartialUpdate<>("123", Person.class) // .set("coworkers", Collections.singletonList("foo")); assertThat(write(update).getBucket().get("_class"), is(nullValue())); @@ -1642,7 +1651,7 @@ public class MappingRedisConverterUnitTests { exception.expectMessage(Person.class.getName()); exception.expectMessage("relatives.[father]"); - PartialUpdate update = new PartialUpdate("123", Person.class) // + PartialUpdate update = new PartialUpdate<>("123", Person.class) // .set("relatives.[father]", "buh buh the bear"); assertThat(write(update).getBucket().get("_class"), is(nullValue())); @@ -1656,7 +1665,7 @@ public class MappingRedisConverterUnitTests { exception.expectMessage(Person.class.getName()); exception.expectMessage("relatives.[father]"); - PartialUpdate update = new PartialUpdate("123", Person.class) // + PartialUpdate update = new PartialUpdate<>("123", Person.class) // .set("relatives", Collections.singletonMap("father", "buh buh the bear")); assertThat(write(update).getBucket().get("_class"), is(nullValue())); @@ -1686,7 +1695,7 @@ public class MappingRedisConverterUnitTests { .withFieldVisibility(Visibility.ANY).withGetterVisibility(Visibility.NONE) .withSetterVisibility(Visibility.NONE).withCreatorVisibility(Visibility.NONE)); - serializer = new Jackson2JsonRedisSerializer
(Address.class); + serializer = new Jackson2JsonRedisSerializer<>(Address.class); serializer.setObjectMapper(mapper); } @@ -1706,7 +1715,7 @@ public class MappingRedisConverterUnitTests { return null; } - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); if (source.name != null) { map.put("species-name", source.name.getBytes(Charset.forName("UTF-8"))); } @@ -1729,7 +1738,7 @@ public class MappingRedisConverterUnitTests { .withFieldVisibility(Visibility.ANY).withGetterVisibility(Visibility.NONE) .withSetterVisibility(Visibility.NONE).withCreatorVisibility(Visibility.NONE)); - serializer = new Jackson2JsonRedisSerializer(List.class); + serializer = new Jackson2JsonRedisSerializer<>(List.class); serializer.setObjectMapper(mapper); } @@ -1780,7 +1789,7 @@ public class MappingRedisConverterUnitTests { .withFieldVisibility(Visibility.ANY).withGetterVisibility(Visibility.NONE) .withSetterVisibility(Visibility.NONE).withCreatorVisibility(Visibility.NONE)); - serializer = new Jackson2JsonRedisSerializer
(Address.class); + serializer = new Jackson2JsonRedisSerializer<>(Address.class); serializer.setObjectMapper(mapper); } diff --git a/src/test/java/org/springframework/data/redis/core/convert/PathIndexResolverUnitTests.java b/src/test/java/org/springframework/data/redis/core/convert/PathIndexResolverUnitTests.java index f079a8e06..4ce4db4ac 100644 --- a/src/test/java/org/springframework/data/redis/core/convert/PathIndexResolverUnitTests.java +++ b/src/test/java/org/springframework/data/redis/core/convert/PathIndexResolverUnitTests.java @@ -116,7 +116,7 @@ public class PathIndexResolverUnitTests { public void shouldResolveMultipleAnnotatedIndexesInLists() { TheWheelOfTime twot = new TheWheelOfTime(); - twot.mainCharacters = new ArrayList(); + twot.mainCharacters = new ArrayList<>(); Person rand = new Person(); rand.address = new Address(); @@ -142,7 +142,7 @@ public class PathIndexResolverUnitTests { public void shouldResolveAnnotatedIndexesInMap() { TheWheelOfTime twot = new TheWheelOfTime(); - twot.places = new LinkedHashMap(); + twot.places = new LinkedHashMap<>(); Location stoneOfTear = new Location(); stoneOfTear.name = "Stone of Tear"; @@ -165,7 +165,7 @@ public class PathIndexResolverUnitTests { indexConfig.addIndexDefinition(new SimpleIndexDefinition(KEYSPACE_PERSON, "physicalAttributes.eye-color")); Person rand = new Person(); - rand.physicalAttributes = new LinkedHashMap(); + rand.physicalAttributes = new LinkedHashMap<>(); rand.physicalAttributes.put("eye-color", "grey"); Set indexes = indexResolver.resolveIndexesFor(ClassTypeInformation.from(Person.class), rand); @@ -181,7 +181,7 @@ public class PathIndexResolverUnitTests { indexConfig.addIndexDefinition(new SimpleIndexDefinition(KEYSPACE_PERSON, "relatives.father.firstname")); Person rand = new Person(); - rand.relatives = new LinkedHashMap(); + rand.relatives = new LinkedHashMap<>(); Person janduin = new Person(); janduin.firstname = "janduin"; @@ -201,7 +201,7 @@ public class PathIndexResolverUnitTests { indexConfig.addIndexDefinition(new SimpleIndexDefinition(KEYSPACE_PERSON, "physicalAttributes.eye-color")); Person rand = new Person(); - rand.physicalAttributes = new LinkedHashMap(); + rand.physicalAttributes = new LinkedHashMap<>(); rand.physicalAttributes.put("eye-color", null); Set indexes = indexResolver.resolveIndexesFor(ClassTypeInformation.from(Person.class), rand); @@ -321,7 +321,7 @@ public class PathIndexResolverUnitTests { hat.type = "hat"; TaVeren mat = new TaVeren(); - mat.characteristics = new LinkedHashMap(2); + mat.characteristics = new LinkedHashMap<>(2); mat.characteristics.put("clothing", hat); mat.characteristics.put("gambling", "owns the dark one's luck"); @@ -339,7 +339,7 @@ public class PathIndexResolverUnitTests { hat.type = "hat"; TaVeren mat = new TaVeren(); - mat.items = new ArrayList(2); + mat.items = new ArrayList<>(2); mat.items.add(hat); mat.items.add("foxhead medallion"); @@ -358,7 +358,7 @@ public class PathIndexResolverUnitTests { hat.type = "hat"; TaVeren mat = new TaVeren(); - mat.items = new ArrayList(2); + mat.items = new ArrayList<>(2); mat.items.add(hat); mat.items.add("foxhead medallion"); @@ -384,7 +384,7 @@ public class PathIndexResolverUnitTests { public void resolveIndexOnMapField() { IndexedOnMapField source = new IndexedOnMapField(); - source.values = new LinkedHashMap(); + source.values = new LinkedHashMap<>(); source.values.put("jon", "snow"); source.values.put("arya", "stark"); @@ -403,7 +403,7 @@ public class PathIndexResolverUnitTests { public void resolveIndexOnListField() { IndexedOnListField source = new IndexedOnListField(); - source.values = new ArrayList(); + source.values = new ArrayList<>(); source.values.add("jon"); source.values.add("arya"); diff --git a/src/test/java/org/springframework/data/redis/core/convert/SpelIndexResolverUnitTests.java b/src/test/java/org/springframework/data/redis/core/convert/SpelIndexResolverUnitTests.java index ee298132e..7c7ed1bcd 100644 --- a/src/test/java/org/springframework/data/redis/core/convert/SpelIndexResolverUnitTests.java +++ b/src/test/java/org/springframework/data/redis/core/convert/SpelIndexResolverUnitTests.java @@ -30,9 +30,6 @@ import org.springframework.data.redis.core.index.SpelIndexDefinition; import org.springframework.data.redis.core.mapping.RedisMappingContext; import org.springframework.data.redis.core.mapping.RedisPersistentEntity; import org.springframework.data.util.ClassTypeInformation; -import org.springframework.expression.AccessException; -import org.springframework.expression.BeanResolver; -import org.springframework.expression.EvaluationContext; import org.springframework.expression.spel.SpelEvaluationException; /** @@ -131,15 +128,10 @@ public class SpelIndexResolverUnitTests { public void withBeanAndThis() { this.resolver = createWithExpression("@bean.run(#this)"); - this.resolver.setBeanResolver(new BeanResolver() { - @Override - public Object resolve(EvaluationContext context, String beanName) throws AccessException { - return new Object() { - @SuppressWarnings("unused") - public Object run(Object arg) { - return arg; - } - }; + this.resolver.setBeanResolver((context, beanName) -> new Object() { + @SuppressWarnings("unused") + public Object run(Object arg) { + return arg; } }); @@ -174,7 +166,7 @@ public class SpelIndexResolverUnitTests { static class Session { - private Map sessionAttrs = new HashMap(); + private Map sessionAttrs = new HashMap<>(); public void setAttribute(String attrName, Object attrValue) { this.sessionAttrs.put(attrName, attrValue); diff --git a/src/test/java/org/springframework/data/redis/core/mapping/BasicRedisPersistentEntityUnitTests.java b/src/test/java/org/springframework/data/redis/core/mapping/BasicRedisPersistentEntityUnitTests.java index 2ab795ada..b7386192c 100644 --- a/src/test/java/org/springframework/data/redis/core/mapping/BasicRedisPersistentEntityUnitTests.java +++ b/src/test/java/org/springframework/data/redis/core/mapping/BasicRedisPersistentEntityUnitTests.java @@ -20,8 +20,6 @@ import static org.hamcrest.core.IsEqual.*; import static org.junit.Assert.*; import static org.mockito.Mockito.*; -import java.io.Serializable; - import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -57,7 +55,7 @@ public class BasicRedisPersistentEntityUnitTests { public void setUp() { when(entityInformation.getType()).thenReturn((Class) ConversionTestEntities.Person.class); - entity = new BasicRedisPersistentEntity(entityInformation, keySpaceResolver, ttlAccessor); + entity = new BasicRedisPersistentEntity<>(entityInformation, keySpaceResolver, ttlAccessor); } @Test // DATAREDIS-425 diff --git a/src/test/java/org/springframework/data/redis/core/mapping/ConfigAwareTimeToLiveAccessorUnitTests.java b/src/test/java/org/springframework/data/redis/core/mapping/ConfigAwareTimeToLiveAccessorUnitTests.java index 24d83c344..8d4abfe63 100644 --- a/src/test/java/org/springframework/data/redis/core/mapping/ConfigAwareTimeToLiveAccessorUnitTests.java +++ b/src/test/java/org/springframework/data/redis/core/mapping/ConfigAwareTimeToLiveAccessorUnitTests.java @@ -141,7 +141,7 @@ public class ConfigAwareTimeToLiveAccessorUnitTests { public void getTimeToLiveShouldReturnDefaultValue() { Long ttl = accessor - .getTimeToLive(new PartialUpdate("123", new TypeWithRedisHashAnnotation())); + .getTimeToLive(new PartialUpdate<>("123", new TypeWithRedisHashAnnotation())); assertThat(ttl, is(5L)); } @@ -150,7 +150,7 @@ public class ConfigAwareTimeToLiveAccessorUnitTests { public void getTimeToLiveShouldReturnValueWhenUpdateModifiesTtlProperty() { Long ttl = accessor - .getTimeToLive(new PartialUpdate("123", new SimpleTypeWithTTLProperty()) + .getTimeToLive(new PartialUpdate<>("123", new SimpleTypeWithTTLProperty()) .set("ttl", 100).refreshTtl(true)); assertThat(ttl, is(100L)); @@ -159,7 +159,8 @@ public class ConfigAwareTimeToLiveAccessorUnitTests { @Test // DATAREDIS-471 public void getTimeToLiveShouldReturnPropertyValueWhenUpdateModifiesTtlProperty() { - Long ttl = accessor.getTimeToLive(new PartialUpdate("123", + Long ttl = accessor.getTimeToLive( + new PartialUpdate<>("123", new TypeWithRedisHashAnnotationAndTTLProperty()).set("ttl", 100).refreshTtl(true)); assertThat(ttl, is(100L)); @@ -168,7 +169,8 @@ public class ConfigAwareTimeToLiveAccessorUnitTests { @Test // DATAREDIS-471 public void getTimeToLiveShouldReturnDefaultValueWhenUpdateDoesNotModifyTtlProperty() { - Long ttl = accessor.getTimeToLive(new PartialUpdate("123", + Long ttl = accessor + .getTimeToLive(new PartialUpdate<>("123", new TypeWithRedisHashAnnotationAndTTLProperty()).refreshTtl(true)); assertThat(ttl, is(10L)); diff --git a/src/test/java/org/springframework/data/redis/core/script/AbstractDefaultScriptExecutorTests.java b/src/test/java/org/springframework/data/redis/core/script/AbstractDefaultScriptExecutorTests.java index 06cd52c4f..ce22e1b1c 100644 --- a/src/test/java/org/springframework/data/redis/core/script/AbstractDefaultScriptExecutorTests.java +++ b/src/test/java/org/springframework/data/redis/core/script/AbstractDefaultScriptExecutorTests.java @@ -26,7 +26,6 @@ import org.junit.Test; import org.springframework.core.io.ClassPathResource; import org.springframework.dao.DataAccessException; import org.springframework.data.redis.Person; -import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisOperations; @@ -42,7 +41,7 @@ import org.springframework.test.annotation.IfProfileValue; /** * Integration test of {@link DefaultScriptExecutor} - * + * * @author Jennifer Hickey * @author Thomas Darimont * @author Christoph Strobl @@ -64,12 +63,10 @@ public abstract class AbstractDefaultScriptExecutorTests { return; } - template.execute(new RedisCallback() { - public Object doInRedis(RedisConnection connection) { - connection.flushDb(); - connection.scriptFlush(); - return null; - } + template.execute((RedisCallback) connection -> { + connection.flushDb(); + connection.scriptFlush(); + return null; }); } @@ -79,7 +76,7 @@ public abstract class AbstractDefaultScriptExecutorTests { this.template = new StringRedisTemplate(); template.setConnectionFactory(getConnectionFactory()); template.afterPropertiesSet(); - DefaultRedisScript script = new DefaultRedisScript(); + DefaultRedisScript script = new DefaultRedisScript<>(); script.setLocation(new ClassPathResource("org/springframework/data/redis/core/script/increment.lua")); script.setResultType(Long.class); ScriptExecutor scriptExecutor = new DefaultScriptExecutor(template); @@ -94,10 +91,10 @@ public abstract class AbstractDefaultScriptExecutorTests { public void testExecuteBooleanResult() { this.template = new RedisTemplate(); template.setKeySerializer(new StringRedisSerializer()); - template.setValueSerializer(new GenericToStringSerializer(Long.class)); + template.setValueSerializer(new GenericToStringSerializer<>(Long.class)); template.setConnectionFactory(getConnectionFactory()); template.afterPropertiesSet(); - DefaultRedisScript script = new DefaultRedisScript(); + DefaultRedisScript script = new DefaultRedisScript<>(); script.setLocation(new ClassPathResource("org/springframework/data/redis/core/script/cas.lua")); script.setResultType(Boolean.class); ScriptExecutor scriptExecutor = new DefaultScriptExecutor(template); @@ -114,11 +111,11 @@ public abstract class AbstractDefaultScriptExecutorTests { template.setConnectionFactory(getConnectionFactory()); template.afterPropertiesSet(); template.boundListOps("mylist").leftPushAll("a", "b", "c", "d"); - DefaultRedisScript script = new DefaultRedisScript(); + DefaultRedisScript script = new DefaultRedisScript<>(); script.setLocation(new ClassPathResource("org/springframework/data/redis/core/script/bulkpop.lua")); script.setResultType(List.class); ScriptExecutor scriptExecutor = new DefaultScriptExecutor(template); - List result = scriptExecutor.execute(script, new GenericToStringSerializer(Long.class), + List result = scriptExecutor.execute(script, new GenericToStringSerializer<>(Long.class), template.getValueSerializer(), Collections.singletonList("mylist"), 1l); assertEquals(Collections.singletonList("a"), result); } @@ -129,7 +126,7 @@ public abstract class AbstractDefaultScriptExecutorTests { this.template = new StringRedisTemplate(); template.setConnectionFactory(getConnectionFactory()); template.afterPropertiesSet(); - DefaultRedisScript script = new DefaultRedisScript(); + DefaultRedisScript script = new DefaultRedisScript<>(); script.setLocation(new ClassPathResource("org/springframework/data/redis/core/script/popandlength.lua")); script.setResultType(List.class); ScriptExecutor scriptExecutor = new DefaultScriptExecutor(template); @@ -146,7 +143,7 @@ public abstract class AbstractDefaultScriptExecutorTests { this.template = new StringRedisTemplate(); template.setConnectionFactory(getConnectionFactory()); template.afterPropertiesSet(); - DefaultRedisScript script = new DefaultRedisScript(); + DefaultRedisScript script = new DefaultRedisScript<>(); script.setScriptText("return redis.call('GET',KEYS[1])"); script.setResultType(String.class); template.opsForValue().set("foo", "bar"); @@ -159,7 +156,7 @@ public abstract class AbstractDefaultScriptExecutorTests { public void testExecuteStatusResult() { this.template = new RedisTemplate(); template.setKeySerializer(new StringRedisSerializer()); - template.setValueSerializer(new GenericToStringSerializer(Long.class)); + template.setValueSerializer(new GenericToStringSerializer<>(Long.class)); template.setConnectionFactory(getConnectionFactory()); template.afterPropertiesSet(); DefaultRedisScript script = new DefaultRedisScript(); @@ -172,13 +169,13 @@ public abstract class AbstractDefaultScriptExecutorTests { @SuppressWarnings("unchecked") @Test public void testExecuteCustomResultSerializer() { - Jackson2JsonRedisSerializer personSerializer = new Jackson2JsonRedisSerializer(Person.class); + Jackson2JsonRedisSerializer personSerializer = new Jackson2JsonRedisSerializer<>(Person.class); this.template = new RedisTemplate(); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(personSerializer); template.setConnectionFactory(getConnectionFactory()); template.afterPropertiesSet(); - DefaultRedisScript script = new DefaultRedisScript(); + DefaultRedisScript script = new DefaultRedisScript<>(); script.setScriptSource(new StaticScriptSource("redis.call('SET',KEYS[1], ARGV[1])\nreturn 'FOO'")); script.setResultType(String.class); ScriptExecutor scriptExecutor = new DefaultScriptExecutor(template); @@ -195,7 +192,7 @@ public abstract class AbstractDefaultScriptExecutorTests { this.template = new StringRedisTemplate(); template.setConnectionFactory(getConnectionFactory()); template.afterPropertiesSet(); - final DefaultRedisScript script = new DefaultRedisScript(); + final DefaultRedisScript script = new DefaultRedisScript<>(); script.setScriptText("return KEYS[1]"); script.setResultType(String.class); List results = template.executePipelined(new SessionCallback() { @@ -215,7 +212,7 @@ public abstract class AbstractDefaultScriptExecutorTests { this.template = new StringRedisTemplate(); template.setConnectionFactory(getConnectionFactory()); template.afterPropertiesSet(); - final DefaultRedisScript script = new DefaultRedisScript(); + final DefaultRedisScript script = new DefaultRedisScript<>(); script.setScriptText("return 'bar'..KEYS[1]"); script.setResultType(String.class); List results = (List) template.execute(new SessionCallback>() { @@ -237,7 +234,7 @@ public abstract class AbstractDefaultScriptExecutorTests { this.template = new StringRedisTemplate(); template.setConnectionFactory(getConnectionFactory()); template.afterPropertiesSet(); - DefaultRedisScript script = new DefaultRedisScript(); + DefaultRedisScript script = new DefaultRedisScript<>(); script.setScriptText("return 'HELLO'"); script.setResultType(String.class); ScriptExecutor scriptExecutor = new DefaultScriptExecutor(template); @@ -253,7 +250,7 @@ public abstract class AbstractDefaultScriptExecutorTests { template.setConnectionFactory(getConnectionFactory()); template.afterPropertiesSet(); - DefaultRedisScript script = new DefaultRedisScript(); + DefaultRedisScript script = new DefaultRedisScript<>(); script.setScriptText("return 'BUBU" + System.currentTimeMillis() + "'"); script.setResultType(String.class); diff --git a/src/test/java/org/springframework/data/redis/core/script/DefaultRedisScriptTests.java b/src/test/java/org/springframework/data/redis/core/script/DefaultRedisScriptTests.java index e40dc9c8d..1293fc504 100644 --- a/src/test/java/org/springframework/data/redis/core/script/DefaultRedisScriptTests.java +++ b/src/test/java/org/springframework/data/redis/core/script/DefaultRedisScriptTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.redis.core.script; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.Assert.*; import org.junit.Test; import org.springframework.core.io.ClassPathResource; @@ -25,7 +24,7 @@ import org.springframework.scripting.support.StaticScriptSource; /** * Test of {@link DefaultRedisScript} - * + * * @author Jennifer Hickey */ public class DefaultRedisScriptTests { @@ -33,7 +32,7 @@ public class DefaultRedisScriptTests { @Test public void testGetSha1() { StaticScriptSource script = new StaticScriptSource("return KEYS[1]"); - DefaultRedisScript redisScript = new DefaultRedisScript(); + DefaultRedisScript redisScript = new DefaultRedisScript<>(); redisScript.setScriptSource(script); redisScript.setResultType(String.class); String sha1 = redisScript.getSha1(); @@ -46,7 +45,7 @@ public class DefaultRedisScriptTests { @Test public void testGetScriptAsString() { - DefaultRedisScript redisScript = new DefaultRedisScript(); + DefaultRedisScript redisScript = new DefaultRedisScript<>(); redisScript.setScriptText("return ARGS[1]"); redisScript.setResultType(String.class); assertEquals("return ARGS[1]", redisScript.getScriptAsString()); @@ -54,7 +53,7 @@ public class DefaultRedisScriptTests { @Test(expected = ScriptingException.class) public void testGetScriptAsStringError() { - DefaultRedisScript redisScript = new DefaultRedisScript(); + DefaultRedisScript redisScript = new DefaultRedisScript<>(); redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("nonexistent"))); redisScript.setResultType(Long.class); redisScript.getScriptAsString(); @@ -62,7 +61,7 @@ public class DefaultRedisScriptTests { @Test(expected = IllegalArgumentException.class) public void initializeWithNoScript() throws Exception { - DefaultRedisScript redisScript = new DefaultRedisScript(); + DefaultRedisScript redisScript = new DefaultRedisScript<>(); redisScript.afterPropertiesSet(); } } diff --git a/src/test/java/org/springframework/data/redis/core/script/DefaultScriptExecutorUnitTests.java b/src/test/java/org/springframework/data/redis/core/script/DefaultScriptExecutorUnitTests.java index bf2b233bc..ae6d3b031 100644 --- a/src/test/java/org/springframework/data/redis/core/script/DefaultScriptExecutorUnitTests.java +++ b/src/test/java/org/springframework/data/redis/core/script/DefaultScriptExecutorUnitTests.java @@ -34,7 +34,7 @@ import org.springframework.data.redis.core.StringRedisTemplate; @RunWith(MockitoJUnitRunner.class) public class DefaultScriptExecutorUnitTests { - private final DefaultRedisScript SCRIPT = new DefaultRedisScript("return KEYS[0]", String.class); + private final DefaultRedisScript SCRIPT = new DefaultRedisScript<>("return KEYS[0]", String.class); private StringRedisTemplate template; private @Mock RedisConnection redisConnectionMock; @@ -49,7 +49,7 @@ public class DefaultScriptExecutorUnitTests { template = spy(new StringRedisTemplate(connectionFactoryMock)); template.afterPropertiesSet(); - executor = new DefaultScriptExecutor(template); + executor = new DefaultScriptExecutor<>(template); } @Test // DATAREDIS-347 diff --git a/src/test/java/org/springframework/data/redis/listener/PubSubResubscribeTests.java b/src/test/java/org/springframework/data/redis/listener/PubSubResubscribeTests.java index b52f2cd22..078780cd0 100644 --- a/src/test/java/org/springframework/data/redis/listener/PubSubResubscribeTests.java +++ b/src/test/java/org/springframework/data/redis/listener/PubSubResubscribeTests.java @@ -45,7 +45,6 @@ import org.springframework.core.task.SyncTaskExecutor; import org.springframework.data.redis.ConnectionFactoryTracker; import org.springframework.data.redis.RedisTestProfileValueSource; import org.springframework.data.redis.SettingsUtils; -import org.springframework.data.redis.TestCondition; import org.springframework.data.redis.connection.ClusterTestVariables; import org.springframework.data.redis.connection.RedisClusterConfiguration; import org.springframework.data.redis.connection.RedisConnectionFactory; @@ -68,7 +67,7 @@ public class PubSubResubscribeTests { private static final String CHANNEL = "pubsub::test"; - private final BlockingDeque bag = new LinkedBlockingDeque(99); + private final BlockingDeque bag = new LinkedBlockingDeque<>(99); private final Object handler = new MessageHandler("handler1", bag); private final MessageListenerAdapter adapter = new MessageListenerAdapter(handler); @@ -156,12 +155,7 @@ public class PubSubResubscribeTests { container.afterPropertiesSet(); container.start(); - waitFor(new TestCondition() { - @Override - public boolean passes() { - return container.getConnectionFactory().getConnection().isSubscribed(); - } - }, 1000); + waitFor(container.getConnectionFactory().getConnection()::isSubscribed, 1000); } @After @@ -178,7 +172,7 @@ public class PubSubResubscribeTests { final String PATTERN = "p*"; final String ANOTHER_CHANNEL = "pubsub::test::extra"; - BlockingDeque bag2 = new LinkedBlockingDeque(99); + BlockingDeque bag2 = new LinkedBlockingDeque<>(99); MessageListenerAdapter anotherListener = new MessageListenerAdapter(new MessageHandler("handler2", bag2)); anotherListener.setSerializer(template.getValueSerializer()); anotherListener.afterPropertiesSet(); @@ -195,7 +189,7 @@ public class PubSubResubscribeTests { template.convertAndSend(ANOTHER_CHANNEL, payload2); // anotherListener receives both messages - List msgs = new ArrayList(); + List msgs = new ArrayList<>(); msgs.add(bag2.poll(500, TimeUnit.MILLISECONDS)); msgs.add(bag2.poll(500, TimeUnit.MILLISECONDS)); @@ -260,7 +254,7 @@ public class PubSubResubscribeTests { template.convertAndSend(ANOTHER_CHANNEL, anotherPayload1); template.convertAndSend(ANOTHER_CHANNEL, anotherPayload2); - Set set = new LinkedHashSet(); + Set set = new LinkedHashSet<>(); set.add(bag.poll(500, TimeUnit.MILLISECONDS)); set.add(bag.poll(500, TimeUnit.MILLISECONDS)); @@ -293,11 +287,11 @@ public class PubSubResubscribeTests { template.convertAndSend("somechannel", "HELLO"); template.convertAndSend(CHANNEL, "WORLD"); - Set set = new LinkedHashSet(); + Set set = new LinkedHashSet<>(); set.add(bag.poll(500, TimeUnit.MILLISECONDS)); set.add(bag.poll(500, TimeUnit.MILLISECONDS)); - assertEquals(new HashSet(Arrays.asList(new String[] { "HELLO", "WORLD" })), set); + assertEquals(new HashSet<>(Arrays.asList(new String[] { "HELLO", "WORLD" })), set); } private class MessageHandler { diff --git a/src/test/java/org/springframework/data/redis/listener/PubSubTestParams.java b/src/test/java/org/springframework/data/redis/listener/PubSubTestParams.java index 5a6c29471..b5d42a947 100644 --- a/src/test/java/org/springframework/data/redis/listener/PubSubTestParams.java +++ b/src/test/java/org/springframework/data/redis/listener/PubSubTestParams.java @@ -1,12 +1,12 @@ /* * Copyright 2011-2016 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. @@ -52,10 +52,10 @@ public class PubSubTestParams { jedisConnFactory.afterPropertiesSet(); RedisTemplate stringTemplate = new StringRedisTemplate(jedisConnFactory); - RedisTemplate personTemplate = new RedisTemplate(); + RedisTemplate personTemplate = new RedisTemplate<>(); personTemplate.setConnectionFactory(jedisConnFactory); personTemplate.afterPropertiesSet(); - RedisTemplate rawTemplate = new RedisTemplate(); + RedisTemplate rawTemplate = new RedisTemplate<>(); rawTemplate.setEnableDefaultSerializer(false); rawTemplate.setConnectionFactory(jedisConnFactory); rawTemplate.afterPropertiesSet(); @@ -68,10 +68,10 @@ public class PubSubTestParams { lettuceConnFactory.afterPropertiesSet(); RedisTemplate stringTemplateLtc = new StringRedisTemplate(lettuceConnFactory); - RedisTemplate personTemplateLtc = new RedisTemplate(); + RedisTemplate personTemplateLtc = new RedisTemplate<>(); personTemplateLtc.setConnectionFactory(lettuceConnFactory); personTemplateLtc.afterPropertiesSet(); - RedisTemplate rawTemplateLtc = new RedisTemplate(); + RedisTemplate rawTemplateLtc = new RedisTemplate<>(); rawTemplateLtc.setEnableDefaultSerializer(false); rawTemplateLtc.setConnectionFactory(lettuceConnFactory); rawTemplateLtc.afterPropertiesSet(); diff --git a/src/test/java/org/springframework/data/redis/listener/PubSubTests.java b/src/test/java/org/springframework/data/redis/listener/PubSubTests.java index be0826dbe..c226a3c02 100644 --- a/src/test/java/org/springframework/data/redis/listener/PubSubTests.java +++ b/src/test/java/org/springframework/data/redis/listener/PubSubTests.java @@ -1,12 +1,12 @@ /* * Copyright 2011-2017 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. @@ -47,7 +47,7 @@ import org.springframework.data.redis.test.util.RedisSentinelRule; /** * Base test class for PubSub integration tests - * + * * @author Costin Leau * @author Jennifer Hickey */ @@ -62,7 +62,7 @@ public class PubSubTests { protected ObjectFactory factory; @SuppressWarnings("rawtypes") protected RedisTemplate template; - private final BlockingDeque bag = new LinkedBlockingDeque(99); + private final BlockingDeque bag = new LinkedBlockingDeque<>(99); private final Object handler = new Object() { @SuppressWarnings("unused") @@ -121,7 +121,7 @@ public class PubSubTests { /** * Return a new instance of T - * + * * @return */ protected T getT() { @@ -137,7 +137,7 @@ public class PubSubTests { template.convertAndSend(CHANNEL, payload1); template.convertAndSend(CHANNEL, payload2); - Set set = new LinkedHashSet(); + Set set = new LinkedHashSet<>(); set.add((T) bag.poll(1, TimeUnit.SECONDS)); set.add((T) bag.poll(1, TimeUnit.SECONDS)); @@ -188,7 +188,7 @@ public class PubSubTests { template.convertAndSend(CHANNEL, payload); - Set set = new LinkedHashSet(); + Set set = new LinkedHashSet<>(); set.add((T) bag.poll(3, TimeUnit.SECONDS)); assertThat(set, hasItems(payload)); diff --git a/src/test/java/org/springframework/data/redis/listener/RedisMessageListenerContainerTests.java b/src/test/java/org/springframework/data/redis/listener/RedisMessageListenerContainerTests.java index 6ac6dc4c3..cae49f5ff 100644 --- a/src/test/java/org/springframework/data/redis/listener/RedisMessageListenerContainerTests.java +++ b/src/test/java/org/springframework/data/redis/listener/RedisMessageListenerContainerTests.java @@ -25,8 +25,6 @@ import java.util.concurrent.Executor; import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.springframework.core.task.SyncTaskExecutor; import org.springframework.data.redis.SettingsUtils; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; @@ -84,14 +82,10 @@ public class RedisMessageListenerContainerTests { final Thread main = Thread.currentThread(); // interrupt thread once Executor.execute is called - doAnswer(new Answer() { + doAnswer(invocationOnMock -> { - @Override - public Object answer(final InvocationOnMock invocationOnMock) throws Throwable { - - main.interrupt(); - return null; - } + main.interrupt(); + return null; }).when(executorMock).execute(any(Runnable.class)); container.addMessageListener(adapter, new ChannelTopic("a")); diff --git a/src/test/java/org/springframework/data/redis/listener/SubscriptionConnectionTests.java b/src/test/java/org/springframework/data/redis/listener/SubscriptionConnectionTests.java index ca9996d93..94a321b22 100644 --- a/src/test/java/org/springframework/data/redis/listener/SubscriptionConnectionTests.java +++ b/src/test/java/org/springframework/data/redis/listener/SubscriptionConnectionTests.java @@ -42,7 +42,7 @@ import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; /** * Integration tests confirming that {@link RedisMessageListenerContainer} closes connections after unsubscribing - * + * * @author Jennifer Hickey * @author Thomas Darimont * @author Christoph Strobl @@ -56,7 +56,7 @@ public class SubscriptionConnectionTests { private RedisConnectionFactory connectionFactory; - private List containers = new ArrayList(); + private List containers = new ArrayList<>(); private final Object handler = new Object() { @SuppressWarnings("unused") diff --git a/src/test/java/org/springframework/data/redis/mapping/BeanUtilsHashMapperTest.java b/src/test/java/org/springframework/data/redis/mapping/BeanUtilsHashMapperTest.java index 235a56c7b..f344b4a28 100644 --- a/src/test/java/org/springframework/data/redis/mapping/BeanUtilsHashMapperTest.java +++ b/src/test/java/org/springframework/data/redis/mapping/BeanUtilsHashMapperTest.java @@ -1,12 +1,12 @@ /* - * Copyright 2011-2013 the original author or authors. - * + * Copyright 2011-2017 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. @@ -25,7 +25,7 @@ import org.springframework.data.redis.hash.BeanUtilsHashMapper; public class BeanUtilsHashMapperTest extends AbstractHashMapperTest { protected BeanUtilsHashMapper mapperFor(Class t) { - return new BeanUtilsHashMapper(t); + return new BeanUtilsHashMapper<>(t); } @Test(expected = Exception.class) diff --git a/src/test/java/org/springframework/data/redis/mapping/Jackson2HashMapperTests.java b/src/test/java/org/springframework/data/redis/mapping/Jackson2HashMapperTests.java index a9b5f94c8..34d5e55b8 100644 --- a/src/test/java/org/springframework/data/redis/mapping/Jackson2HashMapperTests.java +++ b/src/test/java/org/springframework/data/redis/mapping/Jackson2HashMapperTests.java @@ -76,7 +76,7 @@ public class Jackson2HashMapperTests { @Before public void setUp() { - this.template = new RedisTemplate(); + this.template = new RedisTemplate<>(); this.template.setConnectionFactory(factory); template.afterPropertiesSet(); diff --git a/src/test/java/org/springframework/data/redis/mapping/Jackson2HashMapperUnitTests.java b/src/test/java/org/springframework/data/redis/mapping/Jackson2HashMapperUnitTests.java index ba9630b95..81d62527c 100644 --- a/src/test/java/org/springframework/data/redis/mapping/Jackson2HashMapperUnitTests.java +++ b/src/test/java/org/springframework/data/redis/mapping/Jackson2HashMapperUnitTests.java @@ -15,6 +15,8 @@ */ package org.springframework.data.redis.mapping; +import lombok.Data; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -31,8 +33,6 @@ import org.springframework.data.redis.Person; import org.springframework.data.redis.hash.HashMapper; import org.springframework.data.redis.hash.Jackson2HashMapper; -import lombok.Data; - /** * Unit tests for {@link Jackson2HashMapper}. * @@ -114,7 +114,7 @@ public class Jackson2HashMapperUnitTests extends AbstractHashMapperTest { public void shouldMapTypedMapOfSimpleTypes() { WithMap source = new WithMap(); - source.strings = new LinkedHashMap(); + source.strings = new LinkedHashMap<>(); source.strings.put("1", "spring"); source.strings.put("2", "data"); source.strings.put("3", "redis"); @@ -125,7 +125,7 @@ public class Jackson2HashMapperUnitTests extends AbstractHashMapperTest { public void shouldMapTypedMapOfComplexTypes() { WithMap source = new WithMap(); - source.persons = new LinkedHashMap(); + source.persons = new LinkedHashMap<>(); source.persons.put("1", new Person("jon", "snow", 19)); source.persons.put("2", new Person("tyrion", "lannister", 19)); assertBackAndForwardMapping(source); @@ -135,7 +135,7 @@ public class Jackson2HashMapperUnitTests extends AbstractHashMapperTest { public void shouldMapUntypedMap() { WithMap source = new WithMap(); - source.objects = new LinkedHashMap(); + source.objects = new LinkedHashMap<>(); source.objects.put("1", "spring"); source.objects.put("2", Integer.valueOf(100)); source.objects.put("3", "redis"); @@ -146,16 +146,16 @@ public class Jackson2HashMapperUnitTests extends AbstractHashMapperTest { public void nestedStuff() { WithList nestedList = new WithList(); - nestedList.objects = new ArrayList(); + nestedList.objects = new ArrayList<>(); WithMap deepNestedMap = new WithMap(); - deepNestedMap.persons = new LinkedHashMap(); + deepNestedMap.persons = new LinkedHashMap<>(); deepNestedMap.persons.put("jon", new Person("jon", "snow", 24)); nestedList.objects.add(deepNestedMap); WithMap outer = new WithMap(); - outer.objects = new LinkedHashMap(); + outer.objects = new LinkedHashMap<>(); outer.objects.put("1", nestedList); assertBackAndForwardMapping(outer); diff --git a/src/test/java/org/springframework/data/redis/repository/RedisRepositoryClusterIntegrationTests.java b/src/test/java/org/springframework/data/redis/repository/RedisRepositoryClusterIntegrationTests.java index 556ed5267..42b37dc7c 100644 --- a/src/test/java/org/springframework/data/redis/repository/RedisRepositoryClusterIntegrationTests.java +++ b/src/test/java/org/springframework/data/redis/repository/RedisRepositoryClusterIntegrationTests.java @@ -63,7 +63,7 @@ public class RedisRepositoryClusterIntegrationTests extends RedisRepositoryInteg connectionFactory.afterPropertiesSet(); - RedisTemplate template = new RedisTemplate(); + RedisTemplate template = new RedisTemplate<>(); template.setConnectionFactory(connectionFactory); return template; diff --git a/src/test/java/org/springframework/data/redis/repository/RedisRepositoryIntegrationTests.java b/src/test/java/org/springframework/data/redis/repository/RedisRepositoryIntegrationTests.java index 06fb56fb4..51d1f5394 100644 --- a/src/test/java/org/springframework/data/redis/repository/RedisRepositoryIntegrationTests.java +++ b/src/test/java/org/springframework/data/redis/repository/RedisRepositoryIntegrationTests.java @@ -45,7 +45,7 @@ public class RedisRepositoryIntegrationTests extends RedisRepositoryIntegrationT JedisConnectionFactory connectionFactory = new JedisConnectionFactory(); connectionFactory.afterPropertiesSet(); - RedisTemplate template = new RedisTemplate(); + RedisTemplate template = new RedisTemplate<>(); template.setConnectionFactory(connectionFactory); return template; diff --git a/src/test/java/org/springframework/data/redis/repository/cdi/RedisCdiDependenciesProducer.java b/src/test/java/org/springframework/data/redis/repository/cdi/RedisCdiDependenciesProducer.java index 64f26ad8b..a26e2bee6 100644 --- a/src/test/java/org/springframework/data/redis/repository/cdi/RedisCdiDependenciesProducer.java +++ b/src/test/java/org/springframework/data/redis/repository/cdi/RedisCdiDependenciesProducer.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2016-2017 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. @@ -60,7 +60,7 @@ public class RedisCdiDependenciesProducer { @Produces public RedisOperations redisOperationsProducer(RedisConnectionFactory redisConnectionFactory) { - RedisTemplate template = new RedisTemplate(); + RedisTemplate template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); template.afterPropertiesSet(); return template; diff --git a/src/test/java/org/springframework/data/redis/serializer/Jackson2JsonRedisSerializerTests.java b/src/test/java/org/springframework/data/redis/serializer/Jackson2JsonRedisSerializerTests.java index 14e93fa7d..aef671282 100644 --- a/src/test/java/org/springframework/data/redis/serializer/Jackson2JsonRedisSerializerTests.java +++ b/src/test/java/org/springframework/data/redis/serializer/Jackson2JsonRedisSerializerTests.java @@ -36,7 +36,7 @@ public class Jackson2JsonRedisSerializerTests { @Before public void setUp() { - this.serializer = new Jackson2JsonRedisSerializer(Person.class); + this.serializer = new Jackson2JsonRedisSerializer<>(Person.class); } @Test // DATAREDIS-241 diff --git a/src/test/java/org/springframework/data/redis/serializer/SimpleRedisSerializerTests.java b/src/test/java/org/springframework/data/redis/serializer/SimpleRedisSerializerTests.java index 028502878..ebd4bdd7c 100644 --- a/src/test/java/org/springframework/data/redis/serializer/SimpleRedisSerializerTests.java +++ b/src/test/java/org/springframework/data/redis/serializer/SimpleRedisSerializerTests.java @@ -1,12 +1,12 @@ /* * Copyright 2011-2017 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. @@ -170,7 +170,7 @@ public class SimpleRedisSerializerTests { @Test public void testJsonSerializer() throws Exception { - Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Person.class); + Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer<>(Person.class); String value = UUID.randomUUID().toString(); Person p1 = new Person(value, value, 1, new Address(value, 2)); assertEquals(p1, serializer.deserialize(serializer.serialize(p1))); diff --git a/src/test/java/org/springframework/data/redis/support/BoundKeyOperationsTest.java b/src/test/java/org/springframework/data/redis/support/BoundKeyOperationsTest.java index 9c8c1c468..d68b1ef17 100644 --- a/src/test/java/org/springframework/data/redis/support/BoundKeyOperationsTest.java +++ b/src/test/java/org/springframework/data/redis/support/BoundKeyOperationsTest.java @@ -1,12 +1,12 @@ /* * Copyright 2011-2017 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. @@ -28,10 +28,8 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; -import org.springframework.dao.DataAccessException; import org.springframework.data.redis.ConnectionFactoryTracker; import org.springframework.data.redis.ObjectFactory; -import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.core.BoundKeyOperations; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate; @@ -72,13 +70,9 @@ public class BoundKeyOperationsTest { @SuppressWarnings("unchecked") @After public void tearDown() { - template.execute(new RedisCallback() { - - @Override - public Object doInRedis(RedisConnection connection) throws DataAccessException { - connection.flushDb(); - return null; - } + template.execute((RedisCallback) connection -> { + connection.flushDb(); + return null; }); } diff --git a/src/test/java/org/springframework/data/redis/support/atomic/RedisAtomicDoubleTests.java b/src/test/java/org/springframework/data/redis/support/atomic/RedisAtomicDoubleTests.java index f7fd10264..736314083 100644 --- a/src/test/java/org/springframework/data/redis/support/atomic/RedisAtomicDoubleTests.java +++ b/src/test/java/org/springframework/data/redis/support/atomic/RedisAtomicDoubleTests.java @@ -60,10 +60,10 @@ public class RedisAtomicDoubleTests extends AbstractRedisAtomicsTests { this.doubleCounter = new RedisAtomicDouble(getClass().getSimpleName() + ":double", factory); this.factory = factory; - this.template = new RedisTemplate(); + this.template = new RedisTemplate<>(); this.template.setConnectionFactory(factory); this.template.setKeySerializer(new StringRedisSerializer()); - this.template.setValueSerializer(new GenericToStringSerializer(Double.class)); + this.template.setValueSerializer(new GenericToStringSerializer<>(Double.class)); this.template.afterPropertiesSet(); ConnectionFactoryTracker.add(factory); @@ -182,7 +182,7 @@ public class RedisAtomicDoubleTests extends AbstractRedisAtomicsTests { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("a valid key serializer in template is required"); - new RedisAtomicDouble("foo", new RedisTemplate()); + new RedisAtomicDouble("foo", new RedisTemplate<>()); } @Test // DATAREDIS-317 @@ -191,7 +191,7 @@ public class RedisAtomicDoubleTests extends AbstractRedisAtomicsTests { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("a valid value serializer in template is required"); - RedisTemplate template = new RedisTemplate(); + RedisTemplate template = new RedisTemplate<>(); template.setKeySerializer(new StringRedisSerializer()); new RedisAtomicDouble("foo", template); } diff --git a/src/test/java/org/springframework/data/redis/support/atomic/RedisAtomicIntegerTests.java b/src/test/java/org/springframework/data/redis/support/atomic/RedisAtomicIntegerTests.java index 8c442c710..57a947a0f 100644 --- a/src/test/java/org/springframework/data/redis/support/atomic/RedisAtomicIntegerTests.java +++ b/src/test/java/org/springframework/data/redis/support/atomic/RedisAtomicIntegerTests.java @@ -58,10 +58,10 @@ public class RedisAtomicIntegerTests extends AbstractRedisAtomicsTests { this.intCounter = new RedisAtomicInteger(getClass().getSimpleName() + ":int", factory); this.factory = factory; - this.template = new RedisTemplate(); + this.template = new RedisTemplate<>(); this.template.setConnectionFactory(factory); this.template.setKeySerializer(new StringRedisSerializer()); - this.template.setValueSerializer(new GenericToStringSerializer(Integer.class)); + this.template.setValueSerializer(new GenericToStringSerializer<>(Integer.class)); this.template.afterPropertiesSet(); ConnectionFactoryTracker.add(factory); @@ -155,20 +155,18 @@ public class RedisAtomicIntegerTests extends AbstractRedisAtomicsTests { final AtomicBoolean failed = new AtomicBoolean(false); for (int i = 0; i < NUM; i++) { - new Thread(new Runnable() { - public void run() { - RedisAtomicInteger atomicInteger = new RedisAtomicInteger(KEY, factory); - try { - if (atomicInteger.compareAndSet(0, 1)) { - System.out.println(atomicInteger.get()); - if (alreadySet.get()) { - failed.set(true); - } - alreadySet.set(true); + new Thread(() -> { + RedisAtomicInteger atomicInteger = new RedisAtomicInteger(KEY, factory); + try { + if (atomicInteger.compareAndSet(0, 1)) { + System.out.println(atomicInteger.get()); + if (alreadySet.get()) { + failed.set(true); } - } finally { - latch.countDown(); + alreadySet.set(true); } + } finally { + latch.countDown(); } }).start(); } @@ -183,7 +181,7 @@ public class RedisAtomicIntegerTests extends AbstractRedisAtomicsTests { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("a valid key serializer in template is required"); - new RedisAtomicInteger("foo", new RedisTemplate()); + new RedisAtomicInteger("foo", new RedisTemplate<>()); } @Test // DATAREDIS-317 @@ -192,7 +190,7 @@ public class RedisAtomicIntegerTests extends AbstractRedisAtomicsTests { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("a valid value serializer in template is required"); - RedisTemplate template = new RedisTemplate(); + RedisTemplate template = new RedisTemplate<>(); template.setKeySerializer(new StringRedisSerializer()); new RedisAtomicInteger("foo", template); } diff --git a/src/test/java/org/springframework/data/redis/support/atomic/RedisAtomicLongTests.java b/src/test/java/org/springframework/data/redis/support/atomic/RedisAtomicLongTests.java index 18684b51b..11a62f987 100644 --- a/src/test/java/org/springframework/data/redis/support/atomic/RedisAtomicLongTests.java +++ b/src/test/java/org/springframework/data/redis/support/atomic/RedisAtomicLongTests.java @@ -54,10 +54,10 @@ public class RedisAtomicLongTests extends AbstractRedisAtomicsTests { this.longCounter = new RedisAtomicLong(getClass().getSimpleName() + ":long", factory); this.factory = factory; - this.template = new RedisTemplate(); + this.template = new RedisTemplate<>(); this.template.setConnectionFactory(factory); this.template.setKeySerializer(new StringRedisSerializer()); - this.template.setValueSerializer(new GenericToStringSerializer(Long.class)); + this.template.setValueSerializer(new GenericToStringSerializer<>(Long.class)); this.template.afterPropertiesSet(); ConnectionFactoryTracker.add(factory); @@ -154,7 +154,7 @@ public class RedisAtomicLongTests extends AbstractRedisAtomicsTests { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("a valid key serializer in template is required"); - RedisTemplate template = new RedisTemplate(); + RedisTemplate template = new RedisTemplate<>(); new RedisAtomicLong("foo", template); } @@ -164,7 +164,7 @@ public class RedisAtomicLongTests extends AbstractRedisAtomicsTests { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("a valid value serializer in template is required"); - RedisTemplate template = new RedisTemplate(); + RedisTemplate template = new RedisTemplate<>(); template.setKeySerializer(new StringRedisSerializer()); new RedisAtomicLong("foo", template); } @@ -172,10 +172,10 @@ public class RedisAtomicLongTests extends AbstractRedisAtomicsTests { @Test // DATAREDIS-317 public void testShouldBeAbleToUseRedisAtomicLongWithProperlyConfiguredRedisTemplate() { - RedisTemplate template = new RedisTemplate(); + RedisTemplate template = new RedisTemplate<>(); template.setConnectionFactory(factory); template.setKeySerializer(new StringRedisSerializer()); - template.setValueSerializer(new GenericToStringSerializer(Long.class)); + template.setValueSerializer(new GenericToStringSerializer<>(Long.class)); template.afterPropertiesSet(); RedisAtomicLong ral = new RedisAtomicLong("DATAREDIS-317.atomicLong", template); diff --git a/src/test/java/org/springframework/data/redis/support/collections/AbstractRedisCollectionTests.java b/src/test/java/org/springframework/data/redis/support/collections/AbstractRedisCollectionTests.java index 34c671829..4109f6b76 100644 --- a/src/test/java/org/springframework/data/redis/support/collections/AbstractRedisCollectionTests.java +++ b/src/test/java/org/springframework/data/redis/support/collections/AbstractRedisCollectionTests.java @@ -1,12 +1,12 @@ /* - * Copyright 2011-2013 the original author or authors. - * + * Copyright 2011-2017 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. @@ -15,18 +15,9 @@ */ package org.springframework.data.redis.support.collections; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.hasItem; -import static org.hamcrest.CoreMatchers.hasItems; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.junit.Assert.assertArrayEquals; -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.springframework.data.redis.matcher.RedisTestMatchers.isEqual; +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.*; +import static org.springframework.data.redis.matcher.RedisTestMatchers.*; import java.util.Arrays; import java.util.Collection; @@ -43,14 +34,14 @@ import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.springframework.data.redis.ConnectionFactoryTracker; import org.springframework.data.redis.ObjectFactory; -import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate; /** * Base test for Redis collections. - * + * * @author Costin Leau + * @author Mark Paluch */ @RunWith(Parameterized.class) public abstract class AbstractRedisCollectionTests { @@ -87,7 +78,7 @@ public abstract class AbstractRedisCollectionTests { /** * Return a new instance of T - * + * * @return */ protected T getT() { @@ -99,12 +90,9 @@ public abstract class AbstractRedisCollectionTests { public void tearDown() throws Exception { // remove the collection entirely since clear() doesn't always work collection.getOperations().delete(Collections.singleton(collection.getKey())); - template.execute(new RedisCallback() { - - public Object doInRedis(RedisConnection connection) { - connection.flushDb(); - return null; - } + template.execute((RedisCallback) connection -> { + connection.flushDb(); + return null; }); } diff --git a/src/test/java/org/springframework/data/redis/support/collections/AbstractRedisCollectionUnitTests.java b/src/test/java/org/springframework/data/redis/support/collections/AbstractRedisCollectionUnitTests.java index 9303620de..0e72a46d3 100644 --- a/src/test/java/org/springframework/data/redis/support/collections/AbstractRedisCollectionUnitTests.java +++ b/src/test/java/org/springframework/data/redis/support/collections/AbstractRedisCollectionUnitTests.java @@ -59,7 +59,7 @@ public class AbstractRedisCollectionUnitTests { collection = new AbstractRedisCollection("key", redisTemplateSpy) { - private List delegate = new ArrayList(); + private List delegate = new ArrayList<>(); @Override public boolean add(String value) { diff --git a/src/test/java/org/springframework/data/redis/support/collections/AbstractRedisListTests.java b/src/test/java/org/springframework/data/redis/support/collections/AbstractRedisListTests.java index b065c8c95..8abd84554 100644 --- a/src/test/java/org/springframework/data/redis/support/collections/AbstractRedisListTests.java +++ b/src/test/java/org/springframework/data/redis/support/collections/AbstractRedisListTests.java @@ -1,12 +1,12 @@ /* - * Copyright 2011-2013 the original author or authors. - * + * Copyright 2011-2017 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. @@ -33,7 +33,7 @@ import org.springframework.data.redis.core.RedisTemplate; /** * Integration test for RedisList - * + * * @author Costin Leau * @author Jennifer Hickey */ @@ -43,7 +43,7 @@ public abstract class AbstractRedisListTests extends AbstractRedisCollectionT /** * Constructs a new AbstractRedisListTests instance. - * + * * @param factory * @param template */ @@ -367,7 +367,7 @@ public abstract class AbstractRedisListTests extends AbstractRedisCollectionT list.add(t2); list.add(t3); - List c = new ArrayList(); + List c = new ArrayList<>(); list.drainTo(c, 2); assertEquals(1, list.size()); @@ -387,7 +387,7 @@ public abstract class AbstractRedisListTests extends AbstractRedisCollectionT list.add(t2); list.add(t3); - List c = new ArrayList(); + List c = new ArrayList<>(); list.drainTo(c); assertTrue(list.isEmpty()); diff --git a/src/test/java/org/springframework/data/redis/support/collections/AbstractRedisMapTests.java b/src/test/java/org/springframework/data/redis/support/collections/AbstractRedisMapTests.java index 0d7c1f7ce..52945c055 100644 --- a/src/test/java/org/springframework/data/redis/support/collections/AbstractRedisMapTests.java +++ b/src/test/java/org/springframework/data/redis/support/collections/AbstractRedisMapTests.java @@ -1,12 +1,12 @@ /* * Copyright 2011-2017 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. @@ -44,7 +44,6 @@ import org.springframework.data.redis.DoubleAsStringObjectFactory; import org.springframework.data.redis.LongAsStringObjectFactory; import org.springframework.data.redis.ObjectFactory; import org.springframework.data.redis.RedisSystemException; -import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.Cursor; import org.springframework.data.redis.core.RedisCallback; @@ -58,11 +57,11 @@ import org.springframework.test.annotation.IfProfileValue; /** * Integration test for Redis Map. - * + * * @author Costin Leau * @author Jennifer Hickey * @author Christoph Strobl - * @auhtor Thomas Darimont + * @author Thomas Darimont */ @RunWith(Parameterized.class) public abstract class AbstractRedisMapTests { @@ -118,12 +117,9 @@ public abstract class AbstractRedisMapTests { public void tearDown() throws Exception { // remove the collection entirely since clear() doesn't always work map.getOperations().delete(Collections.singleton(map.getKey())); - template.execute(new RedisCallback() { - - public Object doInRedis(RedisConnection connection) { - connection.flushDb(); - return null; - } + template.execute((RedisCallback) connection -> { + connection.flushDb(); + return null; }); } @@ -178,7 +174,7 @@ public abstract class AbstractRedisMapTests { @Test public void testNotEquals() { RedisOperations ops = map.getOperations(); - RedisStore newInstance = new DefaultRedisMap(ops. boundHashOps(map.getKey() + ":new")); + RedisStore newInstance = new DefaultRedisMap<>(ops. boundHashOps(map.getKey() + ":new")); assertFalse(map.equals(newInstance)); assertFalse(newInstance.equals(map)); } @@ -290,7 +286,7 @@ public abstract class AbstractRedisMapTests { @Test public void testPutAll() { - Map m = new LinkedHashMap(); + Map m = new LinkedHashMap<>(); K k1 = getKey(); K k2 = getKey(); @@ -385,8 +381,8 @@ public abstract class AbstractRedisMapTests { entries = map.entrySet(); - Set keys = new LinkedHashSet(); - Collection values = new ArrayList(); + Set keys = new LinkedHashSet<>(); + Collection values = new ArrayList<>(); for (Entry entry : entries) { keys.add(entry.getKey()); diff --git a/src/test/java/org/springframework/data/redis/support/collections/AbstractRedisSetTests.java b/src/test/java/org/springframework/data/redis/support/collections/AbstractRedisSetTests.java index 9dfac9826..8f5c19e82 100644 --- a/src/test/java/org/springframework/data/redis/support/collections/AbstractRedisSetTests.java +++ b/src/test/java/org/springframework/data/redis/support/collections/AbstractRedisSetTests.java @@ -1,12 +1,12 @@ /* * Copyright 2011-2017 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. @@ -42,7 +42,7 @@ import org.springframework.test.annotation.IfProfileValue; /** * Integration test for Redis set. - * + * * @author Costin Leau * @author Christoph Strobl * @author Thomas Darimont @@ -61,7 +61,7 @@ public abstract class AbstractRedisSetTests extends AbstractRedisCollectionTe /** * Constructs a new AbstractRedisSetTests instance. - * + * * @param factory * @param template */ @@ -79,7 +79,7 @@ public abstract class AbstractRedisSetTests extends AbstractRedisCollectionTe @SuppressWarnings("unchecked") private RedisSet createSetFor(String key) { - return new DefaultRedisSet((BoundSetOperations) set.getOperations().boundSetOps(key)); + return new DefaultRedisSet<>((BoundSetOperations) set.getOperations().boundSetOps(key)); } @Test @@ -238,7 +238,7 @@ public abstract class AbstractRedisSetTests extends AbstractRedisCollectionTe assertThat(collection.addAll(list), is(true)); Iterator iterator = collection.iterator(); - List result = new ArrayList(list); + List result = new ArrayList<>(list); while (iterator.hasNext()) { T expected = iterator.next(); @@ -264,7 +264,7 @@ public abstract class AbstractRedisSetTests extends AbstractRedisCollectionTe Object[] array = collection.toArray(); - List result = new ArrayList(list); + List result = new ArrayList<>(list); for (int i = 0; i < array.length; i++) { Iterator resultItr = result.iterator(); @@ -288,7 +288,7 @@ public abstract class AbstractRedisSetTests extends AbstractRedisCollectionTe assertThat(collection.addAll(list), is(true)); Object[] array = collection.toArray(new Object[expectedArray.length]); - List result = new ArrayList(list); + List result = new ArrayList<>(list); for (int i = 0; i < array.length; i++) { Iterator resultItr = result.iterator(); diff --git a/src/test/java/org/springframework/data/redis/support/collections/AbstractRedisZSetTest.java b/src/test/java/org/springframework/data/redis/support/collections/AbstractRedisZSetTest.java index 8fef2f803..e59e95e6e 100644 --- a/src/test/java/org/springframework/data/redis/support/collections/AbstractRedisZSetTest.java +++ b/src/test/java/org/springframework/data/redis/support/collections/AbstractRedisZSetTest.java @@ -1,12 +1,12 @@ /* * Copyright 2011-2017 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. @@ -48,7 +48,7 @@ import org.springframework.test.annotation.IfProfileValue; /** * Integration test for Redis ZSet. - * + * * @author Costin Leau * @author Jennifer Hickey * @author Thomas Darimont @@ -68,7 +68,7 @@ public abstract class AbstractRedisZSetTest extends AbstractRedisCollectionTe /** * Constructs a new AbstractRedisZSetTest instance. - * + * * @param factory * @param template */ @@ -212,7 +212,7 @@ public abstract class AbstractRedisZSetTest extends AbstractRedisCollectionTe @SuppressWarnings("unchecked") private RedisZSet createZSetFor(String key) { - return new DefaultRedisZSet((BoundZSetOperations) zSet.getOperations().boundZSetOps(key)); + return new DefaultRedisZSet<>((BoundZSetOperations) zSet.getOperations().boundZSetOps(key)); } @SuppressWarnings("unchecked") diff --git a/src/test/java/org/springframework/data/redis/support/collections/CollectionTestParams.java b/src/test/java/org/springframework/data/redis/support/collections/CollectionTestParams.java index d0303b758..a70ebe67f 100644 --- a/src/test/java/org/springframework/data/redis/support/collections/CollectionTestParams.java +++ b/src/test/java/org/springframework/data/redis/support/collections/CollectionTestParams.java @@ -53,7 +53,7 @@ public abstract class CollectionTestParams { throw new RuntimeException("Cannot init XStream", ex); } OxmSerializer serializer = new OxmSerializer(xstream, xstream); - Jackson2JsonRedisSerializer jackson2JsonSerializer = new Jackson2JsonRedisSerializer(Person.class); + Jackson2JsonRedisSerializer jackson2JsonSerializer = new Jackson2JsonRedisSerializer<>(Person.class); StringRedisSerializer stringSerializer = new StringRedisSerializer(); // create Jedis Factory @@ -71,27 +71,27 @@ public abstract class CollectionTestParams { jedisConnFactory.afterPropertiesSet(); RedisTemplate stringTemplate = new StringRedisTemplate(jedisConnFactory); - RedisTemplate personTemplate = new RedisTemplate(); + RedisTemplate personTemplate = new RedisTemplate<>(); personTemplate.setConnectionFactory(jedisConnFactory); personTemplate.afterPropertiesSet(); - RedisTemplate xstreamStringTemplate = new RedisTemplate(); + RedisTemplate xstreamStringTemplate = new RedisTemplate<>(); xstreamStringTemplate.setConnectionFactory(jedisConnFactory); xstreamStringTemplate.setDefaultSerializer(serializer); xstreamStringTemplate.afterPropertiesSet(); - RedisTemplate xstreamPersonTemplate = new RedisTemplate(); + RedisTemplate xstreamPersonTemplate = new RedisTemplate<>(); xstreamPersonTemplate.setConnectionFactory(jedisConnFactory); xstreamPersonTemplate.setValueSerializer(serializer); xstreamPersonTemplate.afterPropertiesSet(); // jackson2 - RedisTemplate jackson2JsonPersonTemplate = new RedisTemplate(); + RedisTemplate jackson2JsonPersonTemplate = new RedisTemplate<>(); jackson2JsonPersonTemplate.setConnectionFactory(jedisConnFactory); jackson2JsonPersonTemplate.setValueSerializer(jackson2JsonSerializer); jackson2JsonPersonTemplate.afterPropertiesSet(); - RedisTemplate rawTemplate = new RedisTemplate(); + RedisTemplate rawTemplate = new RedisTemplate<>(); rawTemplate.setConnectionFactory(jedisConnFactory); rawTemplate.setEnableDefaultSerializer(false); rawTemplate.setKeySerializer(stringSerializer); @@ -105,26 +105,26 @@ public abstract class CollectionTestParams { lettuceConnFactory.afterPropertiesSet(); RedisTemplate stringTemplateLtc = new StringRedisTemplate(lettuceConnFactory); - RedisTemplate personTemplateLtc = new RedisTemplate(); + RedisTemplate personTemplateLtc = new RedisTemplate<>(); personTemplateLtc.setConnectionFactory(lettuceConnFactory); personTemplateLtc.afterPropertiesSet(); - RedisTemplate xstreamStringTemplateLtc = new RedisTemplate(); + RedisTemplate xstreamStringTemplateLtc = new RedisTemplate<>(); xstreamStringTemplateLtc.setConnectionFactory(lettuceConnFactory); xstreamStringTemplateLtc.setDefaultSerializer(serializer); xstreamStringTemplateLtc.afterPropertiesSet(); - RedisTemplate xstreamPersonTemplateLtc = new RedisTemplate(); + RedisTemplate xstreamPersonTemplateLtc = new RedisTemplate<>(); xstreamPersonTemplateLtc.setValueSerializer(serializer); xstreamPersonTemplateLtc.setConnectionFactory(lettuceConnFactory); xstreamPersonTemplateLtc.afterPropertiesSet(); - RedisTemplate jackson2JsonPersonTemplateLtc = new RedisTemplate(); + RedisTemplate jackson2JsonPersonTemplateLtc = new RedisTemplate<>(); jackson2JsonPersonTemplateLtc.setValueSerializer(jackson2JsonSerializer); jackson2JsonPersonTemplateLtc.setConnectionFactory(lettuceConnFactory); jackson2JsonPersonTemplateLtc.afterPropertiesSet(); - RedisTemplate rawTemplateLtc = new RedisTemplate(); + RedisTemplate rawTemplateLtc = new RedisTemplate<>(); rawTemplateLtc.setConnectionFactory(lettuceConnFactory); rawTemplateLtc.setEnableDefaultSerializer(false); rawTemplateLtc.setKeySerializer(stringSerializer); diff --git a/src/test/java/org/springframework/data/redis/support/collections/RedisCollectionFactoryBeanTests.java b/src/test/java/org/springframework/data/redis/support/collections/RedisCollectionFactoryBeanTests.java index 002cae4b4..6394f6ac6 100644 --- a/src/test/java/org/springframework/data/redis/support/collections/RedisCollectionFactoryBeanTests.java +++ b/src/test/java/org/springframework/data/redis/support/collections/RedisCollectionFactoryBeanTests.java @@ -1,12 +1,12 @@ /* * Copyright 2011-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. @@ -25,16 +25,9 @@ import org.springframework.data.redis.ConnectionFactoryTracker; import org.springframework.data.redis.ObjectFactory; import org.springframework.data.redis.SettingsUtils; import org.springframework.data.redis.StringObjectFactory; -import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.data.redis.support.collections.DefaultRedisList; -import org.springframework.data.redis.support.collections.DefaultRedisMap; -import org.springframework.data.redis.support.collections.DefaultRedisSet; -import org.springframework.data.redis.support.collections.RedisCollectionFactoryBean; -import org.springframework.data.redis.support.collections.RedisProperties; -import org.springframework.data.redis.support.collections.RedisStore; import org.springframework.data.redis.support.collections.RedisCollectionFactoryBean.CollectionType; /** @@ -67,12 +60,9 @@ public class RedisCollectionFactoryBeanTests { @After public void tearDown() throws Exception { // clean up the whole db - template.execute(new RedisCallback() { - - public Object doInRedis(RedisConnection connection) { - connection.flushDb(); - return null; - } + template.execute((RedisCallback) connection -> { + connection.flushDb(); + return null; }); } diff --git a/src/test/java/org/springframework/data/redis/support/collections/RedisMapTests.java b/src/test/java/org/springframework/data/redis/support/collections/RedisMapTests.java index ea7598522..f3fb03704 100644 --- a/src/test/java/org/springframework/data/redis/support/collections/RedisMapTests.java +++ b/src/test/java/org/springframework/data/redis/support/collections/RedisMapTests.java @@ -72,8 +72,8 @@ public class RedisMapTests extends AbstractRedisMapTests { throw new RuntimeException("Cannot init XStream", ex); } OxmSerializer serializer = new OxmSerializer(xstream, xstream); - Jackson2JsonRedisSerializer jackson2JsonSerializer = new Jackson2JsonRedisSerializer(Person.class); - Jackson2JsonRedisSerializer jackson2JsonStringSerializer = new Jackson2JsonRedisSerializer( + Jackson2JsonRedisSerializer jackson2JsonSerializer = new Jackson2JsonRedisSerializer<>(Person.class); + Jackson2JsonRedisSerializer jackson2JsonStringSerializer = new Jackson2JsonRedisSerializer<>( String.class); StringRedisSerializer stringSerializer = new StringRedisSerializer(); @@ -98,19 +98,19 @@ public class RedisMapTests extends AbstractRedisMapTests { genericTemplate.setConnectionFactory(jedisConnFactory); genericTemplate.afterPropertiesSet(); - RedisTemplate xstreamGenericTemplate = new RedisTemplate(); + RedisTemplate xstreamGenericTemplate = new RedisTemplate<>(); xstreamGenericTemplate.setConnectionFactory(jedisConnFactory); xstreamGenericTemplate.setDefaultSerializer(serializer); xstreamGenericTemplate.afterPropertiesSet(); - RedisTemplate jackson2JsonPersonTemplate = new RedisTemplate(); + RedisTemplate jackson2JsonPersonTemplate = new RedisTemplate<>(); jackson2JsonPersonTemplate.setConnectionFactory(jedisConnFactory); jackson2JsonPersonTemplate.setDefaultSerializer(jackson2JsonSerializer); jackson2JsonPersonTemplate.setHashKeySerializer(jackson2JsonSerializer); jackson2JsonPersonTemplate.setHashValueSerializer(jackson2JsonStringSerializer); jackson2JsonPersonTemplate.afterPropertiesSet(); - RedisTemplate rawTemplate = new RedisTemplate(); + RedisTemplate rawTemplate = new RedisTemplate<>(); rawTemplate.setEnableDefaultSerializer(false); rawTemplate.setConnectionFactory(jedisConnFactory); rawTemplate.setKeySerializer(stringSerializer); @@ -127,12 +127,12 @@ public class RedisMapTests extends AbstractRedisMapTests { genericTemplateLettuce.setConnectionFactory(lettuceConnFactory); genericTemplateLettuce.afterPropertiesSet(); - RedisTemplate xGenericTemplateLettuce = new RedisTemplate(); + RedisTemplate xGenericTemplateLettuce = new RedisTemplate<>(); xGenericTemplateLettuce.setConnectionFactory(lettuceConnFactory); xGenericTemplateLettuce.setDefaultSerializer(serializer); xGenericTemplateLettuce.afterPropertiesSet(); - RedisTemplate jackson2JsonPersonTemplateLettuce = new RedisTemplate(); + RedisTemplate jackson2JsonPersonTemplateLettuce = new RedisTemplate<>(); jackson2JsonPersonTemplateLettuce.setConnectionFactory(lettuceConnFactory); jackson2JsonPersonTemplateLettuce.setDefaultSerializer(jackson2JsonSerializer); jackson2JsonPersonTemplateLettuce.setHashKeySerializer(jackson2JsonSerializer); @@ -143,7 +143,7 @@ public class RedisMapTests extends AbstractRedisMapTests { stringTemplateLtc.setConnectionFactory(lettuceConnFactory); stringTemplateLtc.afterPropertiesSet(); - RedisTemplate rawTemplateLtc = new RedisTemplate(); + RedisTemplate rawTemplateLtc = new RedisTemplate<>(); rawTemplateLtc.setEnableDefaultSerializer(false); rawTemplateLtc.setConnectionFactory(lettuceConnFactory); rawTemplateLtc.setKeySerializer(stringSerializer); diff --git a/src/test/java/org/springframework/data/redis/support/collections/RedisPropertiesTests.java b/src/test/java/org/springframework/data/redis/support/collections/RedisPropertiesTests.java index 10cf0613a..b95db2871 100644 --- a/src/test/java/org/springframework/data/redis/support/collections/RedisPropertiesTests.java +++ b/src/test/java/org/springframework/data/redis/support/collections/RedisPropertiesTests.java @@ -188,7 +188,7 @@ public class RedisPropertiesTests extends RedisMapTests { props.setProperty(key2, val); Enumeration names = props.propertyNames(); - Set keys = new LinkedHashSet(); + Set keys = new LinkedHashSet<>(); keys.add(names.nextElement()); keys.add(names.nextElement()); keys.add(names.nextElement()); @@ -238,8 +238,8 @@ public class RedisPropertiesTests extends RedisMapTests { throw new RuntimeException("Cannot init XStream", ex); } OxmSerializer serializer = new OxmSerializer(xstream, xstream); - Jackson2JsonRedisSerializer jackson2JsonSerializer = new Jackson2JsonRedisSerializer(Person.class); - Jackson2JsonRedisSerializer jackson2JsonStringSerializer = new Jackson2JsonRedisSerializer( + Jackson2JsonRedisSerializer jackson2JsonSerializer = new Jackson2JsonRedisSerializer<>(Person.class); + Jackson2JsonRedisSerializer jackson2JsonStringSerializer = new Jackson2JsonRedisSerializer<>( String.class); // create Jedis Factory @@ -257,12 +257,12 @@ public class RedisPropertiesTests extends RedisMapTests { RedisTemplate genericTemplate = new StringRedisTemplate(jedisConnFactory); - RedisTemplate xstreamGenericTemplate = new RedisTemplate(); + RedisTemplate xstreamGenericTemplate = new RedisTemplate<>(); xstreamGenericTemplate.setConnectionFactory(jedisConnFactory); xstreamGenericTemplate.setDefaultSerializer(serializer); xstreamGenericTemplate.afterPropertiesSet(); - RedisTemplate jackson2JsonPersonTemplate = new RedisTemplate(); + RedisTemplate jackson2JsonPersonTemplate = new RedisTemplate<>(); jackson2JsonPersonTemplate.setConnectionFactory(jedisConnFactory); jackson2JsonPersonTemplate.setDefaultSerializer(jackson2JsonSerializer); jackson2JsonPersonTemplate.setHashKeySerializer(jackson2JsonSerializer); @@ -277,12 +277,12 @@ public class RedisPropertiesTests extends RedisMapTests { lettuceConnFactory.afterPropertiesSet(); RedisTemplate genericTemplateLtc = new StringRedisTemplate(lettuceConnFactory); - RedisTemplate xGenericTemplateLtc = new RedisTemplate(); + RedisTemplate xGenericTemplateLtc = new RedisTemplate<>(); xGenericTemplateLtc.setConnectionFactory(lettuceConnFactory); xGenericTemplateLtc.setDefaultSerializer(serializer); xGenericTemplateLtc.afterPropertiesSet(); - RedisTemplate jackson2JsonPersonTemplateLtc = new RedisTemplate(); + RedisTemplate jackson2JsonPersonTemplateLtc = new RedisTemplate<>(); jackson2JsonPersonTemplateLtc.setConnectionFactory(lettuceConnFactory); jackson2JsonPersonTemplateLtc.setDefaultSerializer(jackson2JsonSerializer); jackson2JsonPersonTemplateLtc.setHashKeySerializer(jackson2JsonSerializer); diff --git a/src/test/java/org/springframework/data/redis/test/util/IsBucketMatcher.java b/src/test/java/org/springframework/data/redis/test/util/IsBucketMatcher.java index 1598b196c..79434e098 100644 --- a/src/test/java/org/springframework/data/redis/test/util/IsBucketMatcher.java +++ b/src/test/java/org/springframework/data/redis/test/util/IsBucketMatcher.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2017 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. @@ -29,14 +29,14 @@ import org.springframework.data.redis.core.convert.Bucket; /** * {@link TypeSafeMatcher} implementation for checking contents of {@link Bucket}. - * + * * @author Christoph Strobl * @since 1.7 */ public class IsBucketMatcher extends TypeSafeMatcher { - Map expected = new LinkedHashMap(); - Set without = new LinkedHashSet(); + Map expected = new LinkedHashMap<>(); + Set without = new LinkedHashSet<>(); /* * (non-Javadoc) @@ -122,7 +122,7 @@ public class IsBucketMatcher extends TypeSafeMatcher { /** * Creates new {@link IsBucketMatcher}. - * + * * @return */ public static IsBucketMatcher isBucket() { @@ -131,7 +131,7 @@ public class IsBucketMatcher extends TypeSafeMatcher { /** * Checks for presence of type hint at given path. - * + * * @param path * @param type * @return @@ -144,7 +144,7 @@ public class IsBucketMatcher extends TypeSafeMatcher { /** * Checks for presence of equivalent String value at path. - * + * * @param path * @param value * @return @@ -157,7 +157,7 @@ public class IsBucketMatcher extends TypeSafeMatcher { /** * Checks for presence of given value at path. - * + * * @param path * @param value * @return @@ -176,7 +176,7 @@ public class IsBucketMatcher extends TypeSafeMatcher { /** * Checks for presence of equivalent time in msec value at path. - * + * * @param path * @param date * @return @@ -189,7 +189,7 @@ public class IsBucketMatcher extends TypeSafeMatcher { /** * Checks given path is not present. - * + * * @param path * @return */ diff --git a/src/test/java/org/springframework/data/redis/test/util/MockitoUtils.java b/src/test/java/org/springframework/data/redis/test/util/MockitoUtils.java index 0b598a638..fc801e7b2 100644 --- a/src/test/java/org/springframework/data/redis/test/util/MockitoUtils.java +++ b/src/test/java/org/springframework/data/redis/test/util/MockitoUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2017 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. @@ -36,7 +36,7 @@ public class MockitoUtils { /** * Verifies a given method is called a total number of times across all given mocks. - * + * * @param method * @param mode * @param mocks @@ -62,7 +62,7 @@ public class MockitoUtils { private static List getInvocations(String method, Object... mocks) { - List invocations = new ArrayList(); + List invocations = new ArrayList<>(); for (Object mock : mocks) { if (StringUtils.hasText(method)) { diff --git a/src/test/java/org/springframework/data/redis/test/util/RedisSentinelRule.java b/src/test/java/org/springframework/data/redis/test/util/RedisSentinelRule.java index dda3b7e15..e72a4d895 100644 --- a/src/test/java/org/springframework/data/redis/test/util/RedisSentinelRule.java +++ b/src/test/java/org/springframework/data/redis/test/util/RedisSentinelRule.java @@ -1,5 +1,5 @@ /* - * Copyright 2014 the original author or authors. + * Copyright 2014-2017 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. @@ -15,6 +15,8 @@ */ package org.springframework.data.redis.test.util; +import redis.clients.jedis.Jedis; + import java.util.HashMap; import java.util.Map; @@ -25,8 +27,6 @@ import org.junit.runners.model.Statement; import org.springframework.data.redis.connection.RedisNode; import org.springframework.data.redis.connection.RedisSentinelConfiguration; -import redis.clients.jedis.Jedis; - /** * @author Christoph Strobl */ @@ -42,7 +42,7 @@ public class RedisSentinelRule implements TestRule { private RedisSentinelConfiguration sentinelConfig; private SentinelsAvailable requiredSentinels; - private Map cache = new HashMap(); + private Map cache = new HashMap<>(); protected RedisSentinelRule(RedisSentinelConfiguration config) { this.sentinelConfig = config; @@ -50,7 +50,7 @@ public class RedisSentinelRule implements TestRule { /** * Create new {@link RedisSentinelRule} for given {@link RedisSentinelConfiguration}. - * + * * @param config * @return */ @@ -60,7 +60,7 @@ public class RedisSentinelRule implements TestRule { /** * Create new {@link RedisSentinelRule} using default configuration. - * + * * @return */ public static RedisSentinelRule withDefaultConfig() { @@ -75,7 +75,7 @@ public class RedisSentinelRule implements TestRule { /** * Verifies all {@literal Sentinel} nodes are available. - * + * * @return */ public RedisSentinelRule allActive() { @@ -86,7 +86,7 @@ public class RedisSentinelRule implements TestRule { /** * Verifies at least one {@literal Sentinel} node is available. - * + * * @return */ public RedisSentinelRule oneActive() { @@ -98,7 +98,7 @@ public class RedisSentinelRule implements TestRule { /** * Will only check {@link RedisSentinelConfiguration} configuration in case {@link RequiresRedisSentinel} is detected * on test method. - * + * * @return */ public RedisSentinelRule dynamicModeSelection() {