From de6bb81ea4f82f73b379ac3ee39cb5cdd227b35d Mon Sep 17 00:00:00 2001 From: John Blum Date: Wed, 18 Oct 2023 18:44:26 -0700 Subject: [PATCH 1/2] Prepare issue branch for 2748 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index c3b30527e5..3213d4d7e2 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.springframework.data spring-data-redis - 3.2.0-SNAPSHOT + 3.2.0-GH-2748-SNAPSHOT Spring Data Redis Spring Data module for Redis From 6c6d238d400dec1d11db5ce9cecbb81f8137035a Mon Sep 17 00:00:00 2001 From: John Blum Date: Wed, 18 Oct 2023 18:50:40 -0700 Subject: [PATCH 2/2] Apply consistent Exception variable names to all catch blocks. We now consistently align with the core Spring Framework's use of 'ex' as the variable name for Exceptions handled in catch blocks, and 'ignore' for all Exceptions thrown, but ignored by framework code. Both 'ex' and 'ignore' were appropriately used based on the context and nautre of the Exception handler in the catch block. Additionally, we use the 'expected' variable name for Exception thrown in tests where the thrown Exception is the expected outcome of the test case. Only 1 exception exists to these name conventions, and that is 'nested', which was necessarily used in ScanCursor due to the nested try-catch blocks. Applied consistent use of String.format(..) to Exception messages requiring formatting. Formatted catch block according to source code formatting style. Closes #2748 --- .../redis/cache/DefaultRedisCacheWriter.java | 7 +- .../data/redis/cache/RedisCache.java | 8 +-- .../connection/AbstractRedisConnection.java | 4 +- .../connection/ClusterCommandExecutor.java | 45 ++++++------ .../data/redis/connection/RedisNode.java | 2 +- .../redis/connection/convert/Converters.java | 4 +- .../jedis/JedisClusterConnection.java | 20 +++--- .../connection/jedis/JedisConnection.java | 32 ++++----- .../jedis/JedisConnectionFactory.java | 12 ++-- .../lettuce/LettuceClusterConnection.java | 8 +-- .../connection/lettuce/LettuceConnection.java | 72 +++++++++---------- .../lettuce/LettuceConnectionFactory.java | 24 +++---- .../lettuce/LettuceFutureUtils.java | 10 +-- .../LettucePoolingConnectionProvider.java | 4 +- .../lettuce/LettuceSentinelConnection.java | 8 +-- .../connection/lettuce/StreamConverters.java | 2 +- .../core/BoundOperationsProxyFactory.java | 6 +- .../CloseSuppressingInvocationHandler.java | 4 +- .../core/DefaultReactiveStreamOperations.java | 7 +- .../redis/core/DefaultValueOperations.java | 2 +- .../data/redis/core/RedisConnectionUtils.java | 4 +- .../data/redis/core/RedisTemplate.java | 6 +- .../data/redis/core/ScanCursor.java | 6 +- .../redis/core/convert/BinaryConverters.java | 6 +- .../data/redis/core/convert/Bucket.java | 4 +- .../core/convert/MappingRedisConverter.java | 3 +- .../redis/core/convert/PathIndexResolver.java | 6 +- .../core/mapping/RedisMappingContext.java | 21 +++--- .../redis/core/script/DefaultRedisScript.java | 4 +- .../core/script/DefaultScriptExecutor.java | 7 +- .../data/redis/core/script/DigestUtils.java | 3 +- .../redis/core/types/RedisClientInfo.java | 6 +- .../data/redis/hash/BeanUtilsHashMapper.java | 2 +- .../data/redis/hash/Jackson2HashMapper.java | 10 +-- .../RedisMessageListenerContainer.java | 45 ++++++------ .../adapter/MessageListenerAdapter.java | 15 ++-- .../cdi/RedisKeyValueAdapterBean.java | 4 +- .../cdi/RedisKeyValueTemplateBean.java | 4 +- .../GenericJackson2JsonRedisSerializer.java | 12 ++-- .../JdkSerializationRedisSerializer.java | 8 +-- .../redis/stream/DefaultStreamReceiver.java | 4 +- .../data/redis/stream/StreamPollTask.java | 20 +++--- .../support/collections/DefaultRedisList.java | 10 +-- .../data/redis/SettingsUtils.java | 2 +- .../cache/DefaultRedisCacheWriterTests.java | 4 +- .../redis/cache/LegacyRedisCacheTests.java | 5 +- .../data/redis/cache/RedisCacheTests.java | 4 +- .../AbstractConnectionIntegrationTests.java | 23 +++--- ...actConnectionPipelineIntegrationTests.java | 4 +- .../ClusterCommandExecutorUnitTests.java | 6 +- .../jedis/JedisClusterConnectionTests.java | 8 +-- .../JedisConnectionIntegrationTests.java | 30 ++++---- ...disConnectionPipelineIntegrationTests.java | 8 +-- ...ConnectionTransactionIntegrationTests.java | 8 +-- .../jedis/JedisConnectionUnitTests.java | 3 +- .../redis/connection/jedis/ScanTests.java | 4 +- .../JedisConnectionFactoryExtension.java | 4 +- .../LettuceConnectionFactoryTests.java | 13 ++-- .../LettuceConnectionIntegrationTests.java | 9 +-- .../LettuceReactiveCommandsTestSupport.java | 4 +- .../LettuceSentinelIntegrationTests.java | 5 +- ...nnectionSplittingInterceptorUnitTests.java | 4 +- .../DefaultSetOperationsIntegrationTests.java | 6 +- ...ReactiveRedisTemplateIntegrationTests.java | 26 +++---- .../redis/core/RedisKeyValueAdapterTests.java | 3 +- .../core/RedisTemplateIntegrationTests.java | 15 ++-- .../EnabledOnRedisAvailableCondition.java | 11 +-- .../redis/test/condition/RedisConditions.java | 4 +- .../redis/test/condition/RedisDetector.java | 5 +- .../ParameterizedRedisTestExtension.java | 4 +- .../data/redis/util/ConnectionVerifier.java | 12 ++-- 71 files changed, 363 insertions(+), 362 deletions(-) diff --git a/src/main/java/org/springframework/data/redis/cache/DefaultRedisCacheWriter.java b/src/main/java/org/springframework/data/redis/cache/DefaultRedisCacheWriter.java index d80fd6335f..5d997bee42 100644 --- a/src/main/java/org/springframework/data/redis/cache/DefaultRedisCacheWriter.java +++ b/src/main/java/org/springframework/data/redis/cache/DefaultRedisCacheWriter.java @@ -377,13 +377,14 @@ private void checkAndPotentiallyWaitUntilUnlocked(String name, RedisConnection c while (doCheckLock(name, connection)) { Thread.sleep(this.sleepTime.toMillis()); } - } catch (InterruptedException cause) { + } catch (InterruptedException ex) { // Re-interrupt current Thread to allow other participants to react. Thread.currentThread().interrupt(); - throw new PessimisticLockingFailureException(String.format("Interrupted while waiting to unlock cache %s", name), - cause); + String message = String.format("Interrupted while waiting to unlock cache %s", name); + + throw new PessimisticLockingFailureException(message, ex); } finally { this.statistics.incLockTime(name, System.nanoTime() - lockWaitTimeNs); } diff --git a/src/main/java/org/springframework/data/redis/cache/RedisCache.java b/src/main/java/org/springframework/data/redis/cache/RedisCache.java index 2df721c0a4..11debd8710 100644 --- a/src/main/java/org/springframework/data/redis/cache/RedisCache.java +++ b/src/main/java/org/springframework/data/redis/cache/RedisCache.java @@ -189,8 +189,8 @@ protected T loadCacheValue(Object key, Callable valueLoader) { try { value = valueLoader.call(); - } catch (Exception cause) { - throw new ValueRetrievalException(key, valueLoader, cause); + } catch (Exception ex) { + throw new ValueRetrievalException(key, valueLoader, ex); } put(key, value); @@ -425,14 +425,14 @@ protected String convertKey(Object key) { if (conversionService.canConvert(source, TypeDescriptor.valueOf(String.class))) { try { return conversionService.convert(key, String.class); - } catch (ConversionFailedException cause) { + } catch (ConversionFailedException ex) { // May fail if the given key is a collection if (isCollectionLikeOrMap(source)) { return convertCollectionLikeOrMapKey(key, source); } - throw cause; + throw ex; } } 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 71c2e0050a..fcdffc4a38 100644 --- a/src/main/java/org/springframework/data/redis/connection/AbstractRedisConnection.java +++ b/src/main/java/org/springframework/data/redis/connection/AbstractRedisConnection.java @@ -114,8 +114,8 @@ public void close() throws DataAccessException { try { connection.close(); - } catch (IOException e) { - LOGGER.info("Failed to close sentinel connection", e); + } catch (IOException ex) { + LOGGER.info("Failed to close sentinel connection", ex); } } } 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 849f9e14b0..0b28fbd05c 100644 --- a/src/main/java/org/springframework/data/redis/connection/ClusterCommandExecutor.java +++ b/src/main/java/org/springframework/data/redis/connection/ClusterCommandExecutor.java @@ -131,10 +131,11 @@ private NodeResult executeCommandOnSingleNode(ClusterCommandCallback this.maxRedirects) { - throw new TooManyClusterRedirectionsException(String.format( - "Cannot follow Cluster Redirects over more than %s legs; " - + "Consider increasing the number of redirects to follow; Current value is: %s.", - redirectCount, this.maxRedirects)); + String message = String.format("Cannot follow Cluster Redirects over more than %s legs; " + + "Consider increasing the number of redirects to follow; Current value is: %s.", + redirectCount, this.maxRedirects); + + throw new TooManyClusterRedirectionsException(message); } RedisClusterNode nodeToUse = lookupNode(node); @@ -145,15 +146,19 @@ private NodeResult executeCommandOnSingleNode(ClusterCommandCallback(node, commandCallback.doInCluster(client)); - } catch (RuntimeException cause) { + } catch (RuntimeException ex) { - RuntimeException translatedException = convertToDataAccessException(cause); + RuntimeException translatedException = convertToDataAccessException(ex); if (translatedException instanceof ClusterRedirectException clusterRedirectException) { - return executeCommandOnSingleNode(commandCallback, topologyProvider.getTopology().lookup( - clusterRedirectException.getTargetHost(), clusterRedirectException.getTargetPort()), redirectCount + 1); + + String targetHost = clusterRedirectException.getTargetHost(); + int targetPort = clusterRedirectException.getTargetPort(); + RedisClusterNode clusterNode = topologyProvider.getTopology().lookup(targetHost, targetPort); + + return executeCommandOnSingleNode(commandCallback, clusterNode, redirectCount + 1); } else { - throw translatedException != null ? translatedException : cause; + throw translatedException != null ? translatedException : ex; } } finally { this.resourceProvider.returnResourceForSpecificNode(nodeToUse, client); @@ -172,8 +177,8 @@ private RedisClusterNode lookupNode(RedisClusterNode node) { try { return topologyProvider.getTopology().lookup(node); - } catch (ClusterStateFailureException cause) { - throw new IllegalArgumentException(String.format("Node %s is unknown to cluster", node), cause); + } catch (ClusterStateFailureException ex) { + throw new IllegalArgumentException(String.format("Node %s is unknown to cluster", node), ex); } } @@ -209,8 +214,8 @@ public MultiNodeResult executeCommandAsyncOnNodes(ClusterCommandCallba for (RedisClusterNode node : nodes) { try { resolvedRedisClusterNodes.add(topology.lookup(node)); - } catch (ClusterStateFailureException cause) { - throw new IllegalArgumentException(String.format("Node %s is unknown to cluster", node), cause); + } catch (ClusterStateFailureException ex) { + throw new IllegalArgumentException(String.format("Node %s is unknown to cluster", node), ex); } } @@ -249,13 +254,13 @@ MultiNodeResult collectResults(Map>> } entryIterator.remove(); - } catch (ExecutionException exception) { + } catch (ExecutionException ex) { entryIterator.remove(); - exceptionCollector.addException(nodeExecution, exception.getCause()); + exceptionCollector.addException(nodeExecution, ex.getCause()); } catch (TimeoutException ignore) { - } catch (InterruptedException exception) { + } catch (InterruptedException ex) { Thread.currentThread().interrupt(); - exceptionCollector.addException(nodeExecution, exception); + exceptionCollector.addException(nodeExecution, ex); break OUT; } } @@ -316,11 +321,11 @@ private NodeResult executeMultiKeyCommandOnSingleNode(MultiKeyClusterC try { return new NodeResult<>(node, commandCallback.doInCluster(client, key), key); - } catch (RuntimeException cause) { + } catch (RuntimeException ex) { - RuntimeException translatedException = convertToDataAccessException(cause); + RuntimeException translatedException = convertToDataAccessException(ex); - throw translatedException != null ? translatedException : cause; + throw translatedException != null ? translatedException : ex; } finally { this.resourceProvider.returnResourceForSpecificNode(node, client); } diff --git a/src/main/java/org/springframework/data/redis/connection/RedisNode.java b/src/main/java/org/springframework/data/redis/connection/RedisNode.java index 490e58eaaf..7c66f5a1e9 100644 --- a/src/main/java/org/springframework/data/redis/connection/RedisNode.java +++ b/src/main/java/org/springframework/data/redis/connection/RedisNode.java @@ -101,7 +101,7 @@ public static RedisNode fromString(String hostPortString) { int port = -1; try { port = Integer.parseInt(portString); - } catch (RuntimeException e) { + } catch (RuntimeException ignore) { throw new IllegalArgumentException(String.format("Unparseable port number: %s", hostPortString)); } 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 7956f03bb7..94dbc9087d 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 @@ -109,8 +109,8 @@ public static Properties toProperties(String source) { try (StringReader stringReader = new StringReader(source)) { info.load(stringReader); - } catch (Exception cause) { - throw new RedisSystemException("Cannot read Redis info", cause); + } catch (Exception ex) { + throw new RedisSystemException("Cannot read Redis info", ex); } return info; diff --git a/src/main/java/org/springframework/data/redis/connection/jedis/JedisClusterConnection.java b/src/main/java/org/springframework/data/redis/connection/jedis/JedisClusterConnection.java index d02bea66a5..16cec8f85a 100644 --- a/src/main/java/org/springframework/data/redis/connection/jedis/JedisClusterConnection.java +++ b/src/main/java/org/springframework/data/redis/connection/jedis/JedisClusterConnection.java @@ -123,8 +123,8 @@ public JedisClusterConnection(JedisCluster cluster) { Object custerCommandExecutor = executorDfa.getPropertyValue("executor"); DirectFieldAccessor dfa = new DirectFieldAccessor(custerCommandExecutor); clusterCommandExecutor.setMaxRedirects((Integer) dfa.getPropertyValue("maxRedirects")); - } catch (Exception e) { - // ignore it and work with the executor default + } catch (Exception ignore) { + // ignore and work with the executor default } } @@ -381,8 +381,8 @@ public void subscribe(MessageListener listener, byte[]... channels) { JedisMessageListener jedisPubSub = new JedisMessageListener(listener); subscription = new JedisSubscription(listener, jedisPubSub, channels, null); cluster.subscribe(jedisPubSub, channels); - } catch (Exception cause) { - throw convertJedisAccessException(cause); + } catch (Exception ex) { + throw convertJedisAccessException(ex); } } @@ -398,8 +398,8 @@ public void pSubscribe(MessageListener listener, byte[]... patterns) { JedisMessageListener jedisPubSub = new JedisMessageListener(listener); subscription = new JedisSubscription(listener, jedisPubSub, null, patterns); cluster.psubscribe(jedisPubSub, patterns); - } catch (Exception cause) { - throw convertJedisAccessException(cause); + } catch (Exception ex) { + throw convertJedisAccessException(ex); } } @@ -643,8 +643,8 @@ public void close() throws DataAccessException { if (!closed && disposeClusterCommandExecutorOnClose) { try { clusterCommandExecutor.destroy(); - } catch (Exception cause) { - log.warn("Cannot properly close cluster command executor", cause); + } catch (Exception ex) { + log.warn("Cannot properly close cluster command executor", ex); } } @@ -864,8 +864,8 @@ public ClusterTopology getTopology() { return cached; - } catch (Exception cause) { - errors.put(entry.getKey(), cause); + } catch (Exception ex) { + errors.put(entry.getKey(), ex); } } diff --git a/src/main/java/org/springframework/data/redis/connection/jedis/JedisConnection.java b/src/main/java/org/springframework/data/redis/connection/jedis/JedisConnection.java index a474bbb8fe..83acd8d07a 100644 --- a/src/main/java/org/springframework/data/redis/connection/jedis/JedisConnection.java +++ b/src/main/java/org/springframework/data/redis/connection/jedis/JedisConnection.java @@ -193,9 +193,9 @@ protected JedisConnection(Jedis jedis, @Nullable Pool pool, JedisClientCo if (nodeConfig.getDatabase() != jedis.getDB()) { try { select(nodeConfig.getDatabase()); - } catch (DataAccessException cause) { + } catch (DataAccessException ex) { close(); - throw cause; + throw ex; } } } @@ -413,17 +413,17 @@ private List convertPipelineResults() { if (!result.isStatus()) { results.add(result.conversionRequired() ? result.convert(data) : data); } - } catch (JedisDataException e) { - DataAccessException dataAccessException = convertJedisAccessException(e); + } catch (JedisDataException ex) { + DataAccessException dataAccessException = convertJedisAccessException(ex); if (cause == null) { cause = dataAccessException; } results.add(dataAccessException); - } catch (DataAccessException e) { + } catch (DataAccessException ex) { if (cause == null) { - cause = e; + cause = ex; } - results.add(e); + results.add(ex); } } @@ -488,8 +488,8 @@ public List exec() { ? new TransactionResultConverter<>(txResults, JedisExceptionConverter.INSTANCE).convert(results) : results; - } catch (Exception cause) { - throw convertJedisAccessException(cause); + } catch (Exception ex) { + throw convertJedisAccessException(ex); } finally { txResults.clear(); transaction = null; @@ -684,7 +684,7 @@ protected boolean isActive(RedisNode node) { verification = getJedis(node); verification.connect(); return verification.ping().equalsIgnoreCase("pong"); - } catch (Exception cause) { + } catch (Exception ignore) { return false; } finally { if (verification != null) { @@ -708,8 +708,8 @@ private T doWithJedis(Function callback) { try { return callback.apply(getJedis()); - } catch (Exception cause) { - throw convertJedisAccessException(cause); + } catch (Exception ex) { + throw convertJedisAccessException(ex); } } @@ -717,8 +717,8 @@ private void doWithJedis(Consumer callback) { try { callback.accept(getJedis()); - } catch (Exception cause) { - throw convertJedisAccessException(cause); + } catch (Exception ex) { + throw convertJedisAccessException(ex); } } @@ -727,9 +727,9 @@ private void doExceptionThrowingOperationSafely(ExceptionThrowingOperation opera try { operation.run(); } - catch (Exception cause) { + catch (Exception ex) { if (LOGGER.isDebugEnabled()) { - LOGGER.debug(logMessage, cause); + LOGGER.debug(logMessage, ex); } } } diff --git a/src/main/java/org/springframework/data/redis/connection/jedis/JedisConnectionFactory.java b/src/main/java/org/springframework/data/redis/connection/jedis/JedisConnectionFactory.java index b231900022..ba3575536a 100644 --- a/src/main/java/org/springframework/data/redis/connection/jedis/JedisConnectionFactory.java +++ b/src/main/java/org/springframework/data/redis/connection/jedis/JedisConnectionFactory.java @@ -703,8 +703,8 @@ public void stop() { try { clusterCommandExecutor.destroy(); this.clusterCommandExecutor = null; - } catch (Exception cause) { - throw new RuntimeException(cause); + } catch (Exception ex) { + throw new RuntimeException(ex); } } @@ -715,8 +715,8 @@ public void stop() { try { this.cluster.close(); this.cluster = null; - } catch (Exception cause) { - log.warn("Cannot properly close Jedis cluster", cause); + } catch (Exception ex) { + log.warn("Cannot properly close Jedis cluster", ex); } } @@ -869,8 +869,8 @@ protected Jedis fetchJedisConnector() { jedis.connect(); return jedis; - } catch (Exception cause) { - throw new RedisConnectionFailureException("Cannot get Jedis connection", cause); + } catch (Exception ex) { + throw new RedisConnectionFailureException("Cannot get Jedis connection", ex); } } diff --git a/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceClusterConnection.java b/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceClusterConnection.java index cfca71fba9..5d2f53618f 100644 --- a/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceClusterConnection.java +++ b/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceClusterConnection.java @@ -382,8 +382,8 @@ public Long clusterCountKeysInSlot(int slot) { try { return getConnection().clusterCountKeysInSlot(slot); - } catch (Exception cause) { - throw this.exceptionConverter.translate(cause); + } catch (Exception ex) { + throw this.exceptionConverter.translate(ex); } } @@ -453,8 +453,8 @@ public List clusterGetKeysInSlot(int slot, Integer count) { try { return getConnection().clusterGetKeysInSlot(slot, count); - } catch (Exception cause) { - throw this.exceptionConverter.translate(cause); + } catch (Exception ex) { + throw this.exceptionConverter.translate(ex); } } 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 30f1761807..01ba6a780c 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 @@ -410,8 +410,8 @@ private LettuceInvoker doInvoke(RedisClusterAsyncCommands connec } else { pipeline(newLettuceResult(future.get(), converter, nullDefault)); } - } catch (Exception cause) { - throw convertLettuceAccessException(cause); + } catch (Exception ex) { + throw convertLettuceAccessException(ex); } return null; @@ -428,8 +428,8 @@ private LettuceInvoker doInvoke(RedisClusterAsyncCommands connec } else { transaction(newLettuceResult(future.get(), converter, nullDefault)); } - } catch (Exception cause) { - throw convertLettuceAccessException(cause); + } catch (Exception ex) { + throw convertLettuceAccessException(ex); } return null; @@ -443,8 +443,8 @@ private LettuceInvoker doInvoke(RedisClusterAsyncCommands connec Object result = await(future.get()); return result != null ? converter.convert(result) : nullDefault.get(); - } catch (Exception cause) { - throw convertLettuceAccessException(cause); + } catch (Exception ex) { + throw convertLettuceAccessException(ex); } }); } @@ -503,8 +503,8 @@ public void close() { try { reset(); - } catch (RuntimeException cause) { - LOGGER.debug("Failed to reset connection during close", cause); + } catch (RuntimeException ex) { + LOGGER.debug("Failed to reset connection during close", ex); } } @@ -517,8 +517,8 @@ private void reset() { } this.connectionProvider.release(this.asyncDedicatedConnection); this.asyncDedicatedConnection = null; - } catch (RuntimeException cause) { - throw convertLettuceAccessException(cause); + } catch (RuntimeException ex) { + throw convertLettuceAccessException(ex); } } @@ -613,11 +613,11 @@ public List closePipeline() { try { results.add(result.conversionRequired() ? result.convert(result.get()) : result.get()); - } catch (DataAccessException cause) { + } catch (DataAccessException ex) { if (problem == null) { - problem = cause; + problem = ex; } - results.add(cause); + results.add(ex); } } } @@ -634,8 +634,8 @@ public List closePipeline() { } throw new RedisPipelineException(new QueryTimeoutException("Redis command timed out")); - } catch (Exception cause) { - throw new RedisPipelineException(cause); + } catch (Exception ex) { + throw new RedisPipelineException(ex); } } @@ -660,8 +660,8 @@ public void discard() { return; } getDedicatedRedisCommands().discard(); - } catch (Exception cause) { - throw convertLettuceAccessException(cause); + } catch (Exception ex) { + throw convertLettuceAccessException(ex); } finally { txResults.clear(); } @@ -695,8 +695,8 @@ public List exec() { return convertPipelineAndTxResults ? new LettuceTransactionResultConverter(txResults, exceptionConverter).convert(results) : results; - } catch (Exception cause) { - throw convertLettuceAccessException(cause); + } catch (Exception ex) { + throw convertLettuceAccessException(ex); } finally { txResults.clear(); } @@ -717,8 +717,8 @@ public void multi() { return; } getDedicatedRedisCommands().multi(); - } catch (Exception cause) { - throw convertLettuceAccessException(cause); + } catch (Exception ex) { + throw convertLettuceAccessException(ex); } } @@ -727,7 +727,7 @@ public void select(int dbIndex) { if (asyncSharedConnection != null) { throw new InvalidDataAccessApiUsageException("Selecting a new database not supported due to shared connection;" - + " Use separate ConnectionFactorys to work with multiple databases"); + + " Use separate ConnectionFactory instances to work with multiple databases"); } this.dbIndex = dbIndex; @@ -749,8 +749,8 @@ public void unwatch() { return; } getDedicatedRedisCommands().unwatch(); - } catch (Exception cause) { - throw convertLettuceAccessException(cause); + } catch (Exception ex) { + throw convertLettuceAccessException(ex); } } @@ -771,8 +771,8 @@ public void watch(byte[]... keys) { return; } getDedicatedRedisCommands().watch(keys); - } catch (Exception cause) { - throw convertLettuceAccessException(cause); + } catch (Exception ex) { + throw convertLettuceAccessException(ex); } } @@ -808,8 +808,8 @@ public void pSubscribe(MessageListener listener, byte[]... patterns) { try { this.subscription = initSubscription(listener); this.subscription.pSubscribe(patterns); - } catch (Exception cause) { - throw convertLettuceAccessException(cause); + } catch (Exception ex) { + throw convertLettuceAccessException(ex); } } @@ -825,8 +825,8 @@ public void subscribe(MessageListener listener, byte[]... channels) { try { this.subscription = initSubscription(listener); this.subscription.subscribe(channels); - } catch (Exception cause) { - throw convertLettuceAccessException(cause); + } catch (Exception ex) { + throw convertLettuceAccessException(ex); } } @@ -970,7 +970,7 @@ protected boolean isActive(RedisNode node) { try { connection = getConnection(node); return connection.sync().ping().equalsIgnoreCase("pong"); - } catch (Exception cause) { + } catch (Exception ignore) { return false; } finally { if (connection != null) { @@ -1006,8 +1006,8 @@ private T await(RedisFuture cmd) { try { return LettuceFutures.awaitOrCancel(cmd, timeout, TimeUnit.MILLISECONDS); - } catch (RuntimeException e) { - throw convertLettuceAccessException(e); + } catch (RuntimeException ex) { + throw convertLettuceAccessException(ex); } } @@ -1078,9 +1078,9 @@ private void validateCommand(ProtocolKeyword command, @Nullable byte[]... args) if (!RedisCommand.UNKNOWN.equals(redisCommand) && redisCommand.requiresArguments()) { try { redisCommand.validateArgumentCount(args != null ? args.length : 0); - } catch (IllegalArgumentException cause) { + } catch (IllegalArgumentException ex) { String message = String.format("Validation failed for %s command", command); - throw new InvalidDataAccessApiUsageException(message, cause); + throw new InvalidDataAccessApiUsageException(message, ex); } } } @@ -1089,7 +1089,7 @@ private static ProtocolKeyword getCommandType(String name) { try { return CommandType.valueOf(name); - } catch (IllegalArgumentException cause) { + } catch (IllegalArgumentException ignore) { return new CustomCommandType(name); } } diff --git a/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceConnectionFactory.java b/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceConnectionFactory.java index 17e7b6c145..f3c818a510 100644 --- a/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceConnectionFactory.java +++ b/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceConnectionFactory.java @@ -921,9 +921,9 @@ public void stop() { client.shutdown(quietPeriod.toMillis(), timeout.toMillis(), TimeUnit.MILLISECONDS); client = null; - } catch (Exception cause) { + } catch (Exception ex) { if (log.isWarnEnabled()) { - log.warn(ClassUtils.getShortName(client.getClass()) + " did not shut down gracefully.", cause); + log.warn(ClassUtils.getShortName(client.getClass()) + " did not shut down gracefully.", ex); } } } @@ -972,8 +972,8 @@ public void destroy() { try { clusterCommandExecutor.destroy(); this.clusterCommandExecutor = null; - } catch (Exception cause) { - log.warn("Cannot properly close cluster command executor", cause); + } catch (Exception ex) { + log.warn("Cannot properly close cluster command executor", ex); } } @@ -985,9 +985,9 @@ private void dispose(@Nullable LettuceConnectionProvider connectionProvider) { if (connectionProvider instanceof DisposableBean disposableBean) { try { disposableBean.destroy(); - } catch (Exception cause) { + } catch (Exception ex) { if (log.isWarnEnabled()) { - log.warn(connectionProvider + " did not shut down gracefully.", cause); + log.warn(connectionProvider + " did not shut down gracefully.", ex); } } } @@ -1577,8 +1577,8 @@ void validateConnection() { valid = true; - } catch (Exception cause) { - log.debug("Validation failed", cause); + } catch (Exception ex) { + log.debug("Validation failed", ex); } } @@ -1732,8 +1732,8 @@ public ExceptionTranslatingConnectionProvider(LettuceConnectionProvider delegate try { return delegate.getConnection(connectionType); - } catch (RuntimeException cause) { - throw translateException(cause); + } catch (RuntimeException ex) { + throw translateException(ex); } } @@ -1742,8 +1742,8 @@ public ExceptionTranslatingConnectionProvider(LettuceConnectionProvider delegate try { return ((TargetAware) delegate).getConnection(connectionType, redisURI); - } catch (RuntimeException cause) { - throw translateException(cause); + } catch (RuntimeException ex) { + throw translateException(ex); } } diff --git a/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceFutureUtils.java b/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceFutureUtils.java index ef4c1ceb51..6adaa5f4ab 100644 --- a/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceFutureUtils.java +++ b/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceFutureUtils.java @@ -66,14 +66,14 @@ static T join(CompletionStage future) throws RuntimeException, Completion try { return future.toCompletableFuture().join(); - } catch (Exception e) { + } catch (Exception ex) { - Throwable exceptionToUse = e; + Throwable exceptionToUse = ex; - if (e instanceof CompletionException) { - exceptionToUse = LettuceExceptionConverter.INSTANCE.convert((Exception) e.getCause()); + if (ex instanceof CompletionException) { + exceptionToUse = LettuceExceptionConverter.INSTANCE.convert((Exception) ex.getCause()); if (exceptionToUse == null) { - exceptionToUse = e.getCause(); + exceptionToUse = ex.getCause(); } } diff --git a/src/main/java/org/springframework/data/redis/connection/lettuce/LettucePoolingConnectionProvider.java b/src/main/java/org/springframework/data/redis/connection/lettuce/LettucePoolingConnectionProvider.java index 41cf19ccb6..c6e321b31d 100644 --- a/src/main/java/org/springframework/data/redis/connection/lettuce/LettucePoolingConnectionProvider.java +++ b/src/main/java/org/springframework/data/redis/connection/lettuce/LettucePoolingConnectionProvider.java @@ -100,8 +100,8 @@ class LettucePoolingConnectionProvider implements LettuceConnectionProvider, Red poolRef.put(connection, pool); return connectionType.cast(connection); - } catch (Exception e) { - throw new PoolException("Could not get a resource from the pool", e); + } catch (Exception ex) { + throw new PoolException("Could not get a resource from the pool", ex); } } diff --git a/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceSentinelConnection.java b/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceSentinelConnection.java index 56e0fa3574..d512e6ed77 100644 --- a/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceSentinelConnection.java +++ b/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceSentinelConnection.java @@ -158,8 +158,8 @@ public void failover(NamedNode master) { public List masters() { try { return LettuceConverters.toListOfRedisServer(getSentinelCommands().masters()); - } catch (Exception e) { - throw EXCEPTION_TRANSLATION.translate(e); + } catch (Exception ex) { + throw EXCEPTION_TRANSLATION.translate(ex); } } @@ -180,8 +180,8 @@ public List slaves(String masterName) { Assert.hasText(masterName, "Name of redis master cannot be 'null' or empty when loading replicas."); try { return LettuceConverters.toListOfRedisServer(getSentinelCommands().slaves(masterName)); - } catch (Exception e) { - throw EXCEPTION_TRANSLATION.translate(e); + } catch (Exception ex) { + throw EXCEPTION_TRANSLATION.translate(ex); } } diff --git a/src/main/java/org/springframework/data/redis/connection/lettuce/StreamConverters.java b/src/main/java/org/springframework/data/redis/connection/lettuce/StreamConverters.java index a490779475..a7ff437fdf 100644 --- a/src/main/java/org/springframework/data/redis/connection/lettuce/StreamConverters.java +++ b/src/main/java/org/springframework/data/redis/connection/lettuce/StreamConverters.java @@ -140,7 +140,7 @@ private static Object preConvertNativeValues(@Nullable Object value) { try { return NumberUtils.parseNumber(tmp, Long.class); - } catch (NumberFormatException e) { + } catch (NumberFormatException ex) { return tmp; } } diff --git a/src/main/java/org/springframework/data/redis/core/BoundOperationsProxyFactory.java b/src/main/java/org/springframework/data/redis/core/BoundOperationsProxyFactory.java index fba239ab08..d4c7a5b522 100644 --- a/src/main/java/org/springframework/data/redis/core/BoundOperationsProxyFactory.java +++ b/src/main/java/org/springframework/data/redis/core/BoundOperationsProxyFactory.java @@ -175,9 +175,9 @@ private Object doInvoke(MethodInvocation invocation, Method method, Object targe try { return backingMethod.invoke(target, args); - } catch (ReflectiveOperationException e) { - ReflectionUtils.handleReflectionException(e); - throw new UnsupportedOperationException("Should not happen", e); + } catch (ReflectiveOperationException ex) { + ReflectionUtils.handleReflectionException(ex); + throw new UnsupportedOperationException("Should not happen", ex); } } } diff --git a/src/main/java/org/springframework/data/redis/core/CloseSuppressingInvocationHandler.java b/src/main/java/org/springframework/data/redis/core/CloseSuppressingInvocationHandler.java index b454ded95d..58dce55e83 100644 --- a/src/main/java/org/springframework/data/redis/core/CloseSuppressingInvocationHandler.java +++ b/src/main/java/org/springframework/data/redis/core/CloseSuppressingInvocationHandler.java @@ -58,8 +58,8 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl // Invoke method on target RedisConnection. try { - Object retVal = method.invoke(this.target, args); - return retVal; + Object returnValue = method.invoke(this.target, args); + return returnValue; } catch (InvocationTargetException ex) { throw ex.getTargetException(); } diff --git a/src/main/java/org/springframework/data/redis/core/DefaultReactiveStreamOperations.java b/src/main/java/org/springframework/data/redis/core/DefaultReactiveStreamOperations.java index 1244af69e3..139bb2799e 100644 --- a/src/main/java/org/springframework/data/redis/core/DefaultReactiveStreamOperations.java +++ b/src/main/java/org/springframework/data/redis/core/DefaultReactiveStreamOperations.java @@ -344,9 +344,11 @@ private ByteBuffer rawKey(K key) { } private ByteBuffer rawHashKey(HK key) { + try { return serializationContext.getHashKeySerializationPair().write(key); - } catch (IllegalStateException ignore) {} + } catch (IllegalStateException ignore) { + } return ByteBuffer.wrap(objectMapper.getConversionService().convert(key, byte[].class)); } @@ -355,7 +357,8 @@ private ByteBuffer rawValue(HV value) { try { return serializationContext.getHashValueSerializationPair().write(value); - } catch (IllegalStateException ignore) {} + } catch (IllegalStateException ignore) { + } return ByteBuffer.wrap(objectMapper.getConversionService().convert(value, byte[].class)); } 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 2bd7233b76..149543027f 100644 --- a/src/main/java/org/springframework/data/redis/core/DefaultValueOperations.java +++ b/src/main/java/org/springframework/data/redis/core/DefaultValueOperations.java @@ -271,7 +271,7 @@ private boolean failsafeInvokePsetEx(RedisConnection connection) { boolean failed = false; try { connection.pSetEx(rawKey, timeout, rawValue); - } catch (UnsupportedOperationException e) { + } catch (UnsupportedOperationException ignore) { // in case the connection does not support pSetEx return false to allow fallback to other operation. failed = true; } diff --git a/src/main/java/org/springframework/data/redis/core/RedisConnectionUtils.java b/src/main/java/org/springframework/data/redis/core/RedisConnectionUtils.java index 3f3abcac74..2956c3d88a 100644 --- a/src/main/java/org/springframework/data/redis/core/RedisConnectionUtils.java +++ b/src/main/java/org/springframework/data/redis/core/RedisConnectionUtils.java @@ -497,8 +497,8 @@ private Object invoke(Method method, Object target, Object[] args) throws Throwa try { return method.invoke(target, args); - } catch (InvocationTargetException e) { - throw e.getCause(); + } catch (InvocationTargetException ex) { + throw ex.getCause(); } } 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 504219bd0d..246f876873 100644 --- a/src/main/java/org/springframework/data/redis/core/RedisTemplate.java +++ b/src/main/java/org/springframework/data/redis/core/RedisTemplate.java @@ -685,7 +685,7 @@ public Boolean expire(K key, final long timeout, final TimeUnit unit) { return doWithKeys(connection -> { try { return connection.pExpire(rawKey, rawTimeout); - } catch (Exception e) { + } catch (Exception ignore) { // Driver may not support pExpire or we may be running on Redis 2.4 return connection.expire(rawKey, TimeoutUtils.toSeconds(timeout, unit)); } @@ -700,7 +700,7 @@ public Boolean expireAt(K key, final Date date) { return doWithKeys(connection -> { try { return connection.pExpireAt(rawKey, date.getTime()); - } catch (Exception e) { + } catch (Exception ignore) { return connection.expireAt(rawKey, date.getTime() / 1000); } }); @@ -727,7 +727,7 @@ public Long getExpire(K key, TimeUnit timeUnit) { return doWithKeys(connection -> { try { return connection.pTtl(rawKey, timeUnit); - } catch (Exception e) { + } catch (Exception ignore) { // Driver may not support pTtl or we may be running on Redis 2.4 return connection.ttl(rawKey, timeUnit); } diff --git a/src/main/java/org/springframework/data/redis/core/ScanCursor.java b/src/main/java/org/springframework/data/redis/core/ScanCursor.java index d40d990f4f..1b5729dcf6 100644 --- a/src/main/java/org/springframework/data/redis/core/ScanCursor.java +++ b/src/main/java/org/springframework/data/redis/core/ScanCursor.java @@ -88,13 +88,13 @@ private void scan(long cursorId) { try { processScanResult(doScan(cursorId, this.scanOptions)); - } catch (RuntimeException e) { + } catch (RuntimeException ex) { try { close(); } catch (RuntimeException nested) { - e.addSuppressed(nested); + ex.addSuppressed(nested); } - throw e; + throw ex; } } 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 b4ab86e940..f15e0966b5 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 @@ -281,14 +281,12 @@ public Date convert(byte[] source) { String value = toString(source); try { return new Date(NumberUtils.parseNumber(value, Long.class)); - } catch (NumberFormatException nfe) { - // ignore + } catch (NumberFormatException ignore) { } try { return DateFormat.getInstance().parse(value); - } catch (ParseException e) { - // ignore + } catch (ParseException ignore) { } throw new IllegalArgumentException(String.format("Cannot parse date out of %s", Arrays.toString(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 dd84cbed0f..ac2d523c38 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 @@ -306,9 +306,9 @@ private static String toUtf8String(byte[] raw) { try { return new String(raw, CHARSET); - } catch (Exception e) { - // Ignore this one + } catch (Exception ignore) { } + return null; } 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 1ba24db98b..d53db84f77 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 @@ -571,8 +571,7 @@ RedisPersistentProperty getTargetPropertyOrNullForPath(String path, Class typ PersistentPropertyPath persistentPropertyPath = mappingContext .getPersistentPropertyPath(path, type); return persistentPropertyPath.getLeafProperty(); - } catch (Exception e) { - // that's just fine + } catch (Exception ignore) { } return null; 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 835c6a02ad..bcfacf2c88 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 @@ -177,9 +177,9 @@ private TypeInformation updateTypeHintForActualValue(TypeInformation typeH if (typeHint.equals(TypeInformation.OBJECT) || typeHint.getClass().isInterface()) { try { typeHint = mappingContext.getRequiredPersistentEntity(propertyValue.getClass()).getTypeInformation(); - } catch (Exception e) { - // ignore for cases where property value cannot be resolved as an entity, in that case the provided type - // hint has to be sufficient + } catch (Exception ignore) { + // ignore for cases where property value cannot be resolved as an entity, in that case + // the provided type hint has to be sufficient } } return typeHint; 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 b4145e38fb..653d2533fc 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 @@ -240,15 +240,18 @@ public Long getTimeToLive(Object source) { if (timeout != null && ttl != null) { return TimeUnit.SECONDS.convert(timeout.longValue(), ttl.unit()); } - } catch (IllegalAccessException e) { - throw new IllegalStateException( - "Not allowed to access method '" + timeoutMethod.getName() + "': " + e.getMessage(), e); - } catch (IllegalArgumentException e) { - throw new IllegalStateException( - "Cannot invoke method '" + timeoutMethod.getName() + " without arguments': " + e.getMessage(), e); - } catch (InvocationTargetException e) { - throw new IllegalStateException("Cannot access method '" + timeoutMethod.getName() + "': " + e.getMessage(), - e); + } catch (IllegalAccessException ex) { + String message = String.format("Not allowed to access method '%s': %s", + timeoutMethod.getName(), ex.getMessage()); + throw new IllegalStateException(message, ex); + } catch (IllegalArgumentException ex) { + String message = String.format("Cannot invoke method '%s' without arguments: %s", + timeoutMethod.getName(), ex.getMessage()); + throw new IllegalStateException(message, ex); + } catch (InvocationTargetException ex) { + String message = String.format("Cannot access method '%s': %s", + timeoutMethod.getName(), ex.getMessage()); + throw new IllegalStateException(message, ex); } } } diff --git a/src/main/java/org/springframework/data/redis/core/script/DefaultRedisScript.java b/src/main/java/org/springframework/data/redis/core/script/DefaultRedisScript.java index cd69431f13..2f85690bed 100644 --- a/src/main/java/org/springframework/data/redis/core/script/DefaultRedisScript.java +++ b/src/main/java/org/springframework/data/redis/core/script/DefaultRedisScript.java @@ -105,8 +105,8 @@ public String getScriptAsString() { try { return scriptSource.getScriptAsString(); - } catch (IOException e) { - throw new ScriptingException("Error reading script text", e); + } catch (IOException ex) { + throw new ScriptingException("Error reading script text", ex); } } 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 5dc6c84330..23032af692 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 @@ -75,10 +75,11 @@ protected T eval(RedisConnection connection, RedisScript script, ReturnTy Object result; try { result = connection.evalSha(script.getSha1(), returnType, numKeys, keysAndArgs); - } catch (Exception e) { + } catch (Exception ex) { - if (!ScriptUtils.exceptionContainsNoScriptError(e)) { - throw e instanceof RuntimeException ? (RuntimeException) e : new RedisSystemException(e.getMessage(), e); + if (!ScriptUtils.exceptionContainsNoScriptError(ex)) { + throw ex instanceof RuntimeException runtimeException ? runtimeException + : new RedisSystemException(ex.getMessage(), ex); } result = connection.eval(scriptBytes(script), returnType, numKeys, keysAndArgs); diff --git a/src/main/java/org/springframework/data/redis/core/script/DigestUtils.java b/src/main/java/org/springframework/data/redis/core/script/DigestUtils.java index 3d8f379e9b..60746f4027 100644 --- a/src/main/java/org/springframework/data/redis/core/script/DigestUtils.java +++ b/src/main/java/org/springframework/data/redis/core/script/DigestUtils.java @@ -60,7 +60,8 @@ private static MessageDigest getDigest(String algorithm) { try { return MessageDigest.getInstance(algorithm); } catch (NoSuchAlgorithmException ex) { - throw new IllegalStateException("Could not find MessageDigest with algorithm \"" + algorithm + "\"", ex); + String message = String.format("Could not find MessageDigest with algorithm \"%s\"", algorithm); + throw new IllegalStateException(message, ex); } } } diff --git a/src/main/java/org/springframework/data/redis/core/types/RedisClientInfo.java b/src/main/java/org/springframework/data/redis/core/types/RedisClientInfo.java index ffa38fe037..04b103a9d3 100644 --- a/src/main/java/org/springframework/data/redis/core/types/RedisClientInfo.java +++ b/src/main/java/org/springframework/data/redis/core/types/RedisClientInfo.java @@ -273,9 +273,9 @@ public static RedisClientInfo fromString(String source) { Properties properties = new Properties(); try { properties.load(new StringReader(source.replace(' ', '\n'))); - } catch (IOException e) { - throw new IllegalArgumentException(String.format("Properties could not be loaded from String '%s'", source), - e); + } catch (IOException ex) { + String message = String.format("Properties could not be loaded from String '%s'", source); + throw new IllegalArgumentException(message, ex); } return new RedisClientInfo(properties); } 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 669fbe4ce3..267cd9891d 100644 --- a/src/main/java/org/springframework/data/redis/hash/BeanUtilsHashMapper.java +++ b/src/main/java/org/springframework/data/redis/hash/BeanUtilsHashMapper.java @@ -71,7 +71,7 @@ public Map toHash(T object) { return result; } catch (Exception ex) { - throw new IllegalArgumentException("Cannot describe object " + object, ex); + throw new IllegalArgumentException(String.format("Cannot describe object %s", object), ex); } } } 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 6786e3c1a9..245d507b19 100644 --- a/src/main/java/org/springframework/data/redis/hash/Jackson2HashMapper.java +++ b/src/main/java/org/springframework/data/redis/hash/Jackson2HashMapper.java @@ -264,8 +264,8 @@ public Object fromHash(Map hash) { return this.typingMapper.treeToValue(this.untypedMapper.valueToTree(hash), Object.class); - } catch (IOException cause) { - throw new MappingException(cause.getMessage(), cause); + } catch (IOException ex) { + throw new MappingException(ex.getMessage(), ex); } } @@ -424,9 +424,9 @@ private void flattenElement(String propertyPrefix, Object source, Map future) { try { future.get(getMaxSubscriptionRegistrationWaitingTime(), TimeUnit.MILLISECONDS); - } catch (InterruptedException cause) { + } catch (InterruptedException ex) { Thread.currentThread().interrupt(); - } catch (ExecutionException | TimeoutException ignore) {} + } catch (ExecutionException | TimeoutException ignore) { + } } @Override @@ -690,13 +691,13 @@ private void addListener(MessageListener listener, Collection t try { future.join(); - } catch (CompletionException cause) { + } catch (CompletionException ex) { - if (cause.getCause() instanceof DataAccessException) { - throw new RedisListenerExecutionFailedException(cause.getMessage(), cause.getCause()); + if (ex.getCause() instanceof DataAccessException) { + throw new RedisListenerExecutionFailedException(ex.getMessage(), ex.getCause()); } - throw cause; + throw ex; } } } @@ -932,7 +933,7 @@ private boolean potentiallyRecover(BackOffExecution backOffExecution, Runnable r return true; - } catch (InterruptedException ignore) { + } catch (InterruptedException ex) { logDebug(() -> "Thread interrupted while sleeping the recovery interval"); Thread.currentThread().interrupt(); return false; @@ -1206,8 +1207,8 @@ public CompletableFuture initialize(BackOffExecution backOffExecution, Col } catch (Throwable t) { handleSubscriptionException(initFuture, backOffExecution, t); } - } catch (RuntimeException cause) { - initFuture.completeExceptionally(cause); + } catch (RuntimeException ex) { + initFuture.completeExceptionally(ex); } return initFuture; @@ -1304,8 +1305,8 @@ void closeSubscription(RedisConnection connection) { try { subscription.close(); - } catch (Exception cause) { - logger.warn("Unable to unsubscribe from subscriptions", cause); + } catch (Exception ex) { + logger.warn("Unable to unsubscribe from subscriptions", ex); } } } @@ -1325,8 +1326,8 @@ public void closeConnection() { logTrace(() -> "Closing connection"); try { connection.close(); - } catch (Exception cause) { - logger.warn("Error closing subscription connection", cause); + } catch (Exception ex) { + logger.warn("Error closing subscription connection", ex); } } }); @@ -1436,8 +1437,8 @@ protected void eventuallyPerformSubscription(RedisConnection connection, BackOff new SynchronizingMessageListener.SubscriptionSynchronization(patterns, Collections.emptySet(), () -> { try { subscribeChannel(channels.toArray(new byte[0][])); - } catch (Exception cause) { - handleSubscriptionException(subscriptionDone, backOffExecution, cause); + } catch (Exception ex) { + handleSubscriptionException(subscriptionDone, backOffExecution, ex); } })); } else { 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 321fb6aad2..f652faafd4 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 @@ -369,16 +369,19 @@ protected void invokeListenerMethod(String methodName, Object[] arguments) { try { invoker.invoke(arguments); } catch (InvocationTargetException ex) { + Throwable targetEx = ex.getTargetException(); - if (targetEx instanceof DataAccessException) { - throw (DataAccessException) targetEx; + + if (targetEx instanceof DataAccessException dataAccessException) { + throw dataAccessException; } else { - throw new RedisListenerExecutionFailedException("Listener method '" + methodName + "' threw exception", - targetEx); + String message = String.format("Listener method '%s' threw exception", methodName); + throw new RedisListenerExecutionFailedException(message, targetEx); } } catch (Throwable ex) { - throw new RedisListenerExecutionFailedException("Failed to invoke target method '" + methodName - + "' with arguments " + ObjectUtils.nullSafeToString(arguments), ex); + String message = String.format("Failed to invoke target method '%s' with arguments %s", methodName, + ObjectUtils.nullSafeToString(arguments)); + throw new RedisListenerExecutionFailedException(message, ex); } } diff --git a/src/main/java/org/springframework/data/redis/repository/cdi/RedisKeyValueAdapterBean.java b/src/main/java/org/springframework/data/redis/repository/cdi/RedisKeyValueAdapterBean.java index e92315af20..0cab13f6c2 100644 --- a/src/main/java/org/springframework/data/redis/repository/cdi/RedisKeyValueAdapterBean.java +++ b/src/main/java/org/springframework/data/redis/repository/cdi/RedisKeyValueAdapterBean.java @@ -87,8 +87,8 @@ public void destroy(RedisKeyValueAdapter instance, CreationalContext T deserialize(@Nullable byte[] source, Class type) throws Serializ try { return (T) reader.read(mapper, source, resolveType(source, type)); - } catch (Exception cause) { - String message = String.format("Could not read JSON:%s ", cause.getMessage()); - throw new SerializationException(message, cause); + } catch (Exception ex) { + String message = String.format("Could not read JSON:%s ", ex.getMessage()); + throw new SerializationException(message, ex); } } diff --git a/src/main/java/org/springframework/data/redis/serializer/JdkSerializationRedisSerializer.java b/src/main/java/org/springframework/data/redis/serializer/JdkSerializationRedisSerializer.java index 52b8100267..77da2a1cb2 100644 --- a/src/main/java/org/springframework/data/redis/serializer/JdkSerializationRedisSerializer.java +++ b/src/main/java/org/springframework/data/redis/serializer/JdkSerializationRedisSerializer.java @@ -90,8 +90,8 @@ public byte[] serialize(@Nullable Object value) { try { return serializer.convert(value); - } catch (Exception cause) { - throw new SerializationException("Cannot serialize", cause); + } catch (Exception ex) { + throw new SerializationException("Cannot serialize", ex); } } @@ -104,8 +104,8 @@ public Object deserialize(@Nullable byte[] bytes) { try { return deserializer.convert(bytes); - } catch (Exception cause) { - throw new SerializationException("Cannot deserialize", cause); + } catch (Exception ex) { + throw new SerializationException("Cannot deserialize", ex); } } } diff --git a/src/main/java/org/springframework/data/redis/stream/DefaultStreamReceiver.java b/src/main/java/org/springframework/data/redis/stream/DefaultStreamReceiver.java index d5e61abb3f..19b3a10d3f 100644 --- a/src/main/java/org/springframework/data/redis/stream/DefaultStreamReceiver.java +++ b/src/main/java/org/springframework/data/redis/stream/DefaultStreamReceiver.java @@ -326,8 +326,8 @@ private void scheduleIfRequired() { try { return deserializer.apply(it); - } catch (RuntimeException e) { - throw new ConversionFailedException(TypeDescriptor.forObject(it), targetType, it, e); + } catch (RuntimeException ex) { + throw new ConversionFailedException(TypeDescriptor.forObject(it), targetType, it, ex); } }).onErrorResume(throwable -> Flux.from(resumeFunction.apply(throwable)).then().map(it -> (V) new Object())) // .subscribe(getSubscriber()); diff --git a/src/main/java/org/springframework/data/redis/stream/StreamPollTask.java b/src/main/java/org/springframework/data/redis/stream/StreamPollTask.java index 39d5252c7c..2241246a28 100644 --- a/src/main/java/org/springframework/data/redis/stream/StreamPollTask.java +++ b/src/main/java/org/springframework/data/redis/stream/StreamPollTask.java @@ -127,17 +127,17 @@ private void doLoop() { List raw = readRecords(); deserializeAndEmitRecords(raw); - } catch (InterruptedException e) { + } catch (InterruptedException ex) { cancel(); Thread.currentThread().interrupt(); - } catch (RuntimeException e) { + } catch (RuntimeException ex) { - if (cancelSubscriptionOnError.test(e)) { + if (cancelSubscriptionOnError.test(ex)) { cancel(); } - errorHandler.handleError(e); + errorHandler.handleError(ex); } } while (pollState.isSubscriptionActive()); } @@ -155,17 +155,17 @@ private void deserializeAndEmitRecords(List records) { pollState.updateReadOffset(raw.getId().getValue()); V record = convertRecord(raw); listener.onMessage(record); - } catch (RuntimeException e) { + } catch (RuntimeException ex) { - if (cancelSubscriptionOnError.test(e)) { + if (cancelSubscriptionOnError.test(ex)) { cancel(); - errorHandler.handleError(e); + errorHandler.handleError(ex); return; } - errorHandler.handleError(e); + errorHandler.handleError(ex); } } } @@ -174,8 +174,8 @@ private V convertRecord(ByteRecord record) { try { return deserializer.apply(record); - } catch (RuntimeException e) { - throw new ConversionFailedException(TypeDescriptor.forObject(record), targetType, record, e); + } catch (RuntimeException ex) { + throw new ConversionFailedException(TypeDescriptor.forObject(record), targetType, record, ex); } } diff --git a/src/main/java/org/springframework/data/redis/support/collections/DefaultRedisList.java b/src/main/java/org/springframework/data/redis/support/collections/DefaultRedisList.java index d96673532d..401ffd99d9 100644 --- a/src/main/java/org/springframework/data/redis/support/collections/DefaultRedisList.java +++ b/src/main/java/org/springframework/data/redis/support/collections/DefaultRedisList.java @@ -636,8 +636,8 @@ public E next() { this.cursor = index + 1; this.lastReturnedElementIndex = index; return this.lastReturnedElement; - } catch (IndexOutOfBoundsException cause) { - throw new NoSuchElementException(cause); + } catch (IndexOutOfBoundsException ex) { + throw new NoSuchElementException(ex); } } @@ -688,7 +688,7 @@ public void add(E element) { this.lastReturnedElementIndex = -1; this.lastReturnedElement = null; this.cursor = index + 1; - } catch (IndexOutOfBoundsException cause) { + } catch (IndexOutOfBoundsException ignore) { throw new ConcurrentModificationException(); } } @@ -702,7 +702,7 @@ public E previous() { this.lastReturnedElementIndex = index; this.cursor = index; return this.lastReturnedElement; - } catch (IndexOutOfBoundsException cause) { + } catch (IndexOutOfBoundsException ignore) { throw new NoSuchElementException(); } } @@ -716,7 +716,7 @@ public void set(E element) { try { DefaultRedisList.this.set(this.lastReturnedElementIndex, element); - } catch (IndexOutOfBoundsException cause) { + } catch (IndexOutOfBoundsException ignore) { throw new ConcurrentModificationException(); } } diff --git a/src/test/java/org/springframework/data/redis/SettingsUtils.java b/src/test/java/org/springframework/data/redis/SettingsUtils.java index c317b45039..51ea95a486 100644 --- a/src/test/java/org/springframework/data/redis/SettingsUtils.java +++ b/src/test/java/org/springframework/data/redis/SettingsUtils.java @@ -49,7 +49,7 @@ public abstract class SettingsUtils { try { SETTINGS.load(SettingsUtils.class.getResourceAsStream("/org/springframework/data/redis/test.properties")); - } catch (Exception e) { + } catch (Exception ignore) { throw new IllegalArgumentException("Cannot read settings"); } } diff --git a/src/test/java/org/springframework/data/redis/cache/DefaultRedisCacheWriterTests.java b/src/test/java/org/springframework/data/redis/cache/DefaultRedisCacheWriterTests.java index f8c98b6f45..0ae1308c05 100644 --- a/src/test/java/org/springframework/data/redis/cache/DefaultRedisCacheWriterTests.java +++ b/src/test/java/org/springframework/data/redis/cache/DefaultRedisCacheWriterTests.java @@ -362,8 +362,8 @@ boolean doCheckLock(String name, RedisConnection connection) { try { writer.put(CACHE_NAME, binaryCacheKey, binaryCacheValue, Duration.ZERO); - } catch (Exception cause) { - exceptionRef.set(cause); + } catch (Exception ex) { + exceptionRef.set(ex); } finally { afterWrite.countDown(); } 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 cd597c61a5..cc616999f5 100644 --- a/src/test/java/org/springframework/data/redis/cache/LegacyRedisCacheTests.java +++ b/src/test/java/org/springframework/data/redis/cache/LegacyRedisCacheTests.java @@ -207,7 +207,7 @@ void testGetWhileClear() throws InterruptedException { Runnable putCache = () -> { try { cache.put(key1, value1); - } catch (IllegalMonitorStateException e) { + } catch (IllegalMonitorStateException ex) { monitorStateException.set(true); } finally { latch.countDown(); @@ -304,8 +304,7 @@ void cachePutWithNullShouldErrorAndLeaveExistingKeyUntouched() { try { cache.put(key, null); - } catch (IllegalArgumentException e) { - // forget this one. + } catch (IllegalArgumentException expected) { } assertThat(cache.get(key).get()).isEqualTo(value); diff --git a/src/test/java/org/springframework/data/redis/cache/RedisCacheTests.java b/src/test/java/org/springframework/data/redis/cache/RedisCacheTests.java index 26fe4ecc29..ebf1b5d8a1 100644 --- a/src/test/java/org/springframework/data/redis/cache/RedisCacheTests.java +++ b/src/test/java/org/springframework/data/redis/cache/RedisCacheTests.java @@ -461,8 +461,8 @@ public byte[] get(String name, byte[] key, @Nullable Duration ttl) { prepare.countDown(); try { prepareForReturn.await(1, TimeUnit.MINUTES); - } catch (InterruptedException e) { - throw new RuntimeException(e); + } catch (InterruptedException ex) { + throw new RuntimeException(ex); } return storage.get(); 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 b6b12293eb..f5b0d4bf41 100644 --- a/src/test/java/org/springframework/data/redis/connection/AbstractConnectionIntegrationTests.java +++ b/src/test/java/org/springframework/data/redis/connection/AbstractConnectionIntegrationTests.java @@ -158,9 +158,8 @@ public void tearDown() { // since we use more than one db we're required to flush them all connection.flushAll(); - } catch (Exception e) { - // Connection may be closed in certain cases, like after pub/sub - // tests + } catch (Exception ignore) { + // Connection may be closed in certain cases, like after pub/sub tests } connection.close(); connection = null; @@ -584,8 +583,7 @@ public void testNullKey() { try { connection.decr((String) null); fail("Decrement should fail with null key"); - } catch (Exception ex) { - // expected + } catch (Exception expected) { } } @@ -598,8 +596,7 @@ public void testNullValue() { try { connection.append(key, null); fail("Append should fail with null value"); - } catch (DataAccessException ex) { - // expected + } catch (DataAccessException expected) { } } @@ -611,8 +608,7 @@ public void testHashNullKey() { try { connection.hExists(key, null); fail("hExists should fail with null key"); - } catch (DataAccessException ex) { - // expected + } catch (DataAccessException expected) { } } @@ -626,8 +622,7 @@ public void testHashNullValue() { try { connection.hSet(key, field, null); fail("hSet should fail with null value"); - } catch (DataAccessException ex) { - // expected + } catch (DataAccessException expected) { } } @@ -665,7 +660,8 @@ public void testPubSubWithNamedChannels() throws Exception { try { Thread.sleep(500); - } catch (InterruptedException o_O) {} + } catch (InterruptedException ignore) { + } // open a new connection RedisConnection connection2 = connectionFactory.getConnection(); @@ -708,7 +704,8 @@ public void testPubSubWithPatterns() throws Exception { try { Thread.sleep(500); - } catch (InterruptedException o_O) {} + } catch (InterruptedException ignore) { + } // open a new connection RedisConnection connection2 = connectionFactory.getConnection(); 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 460f15452d..3b4927fea6 100644 --- a/src/test/java/org/springframework/data/redis/connection/AbstractConnectionPipelineIntegrationTests.java +++ b/src/test/java/org/springframework/data/redis/connection/AbstractConnectionPipelineIntegrationTests.java @@ -182,8 +182,8 @@ protected List getResults() { try { // we give redis some time to keep up Thread.sleep(10); - } catch (InterruptedException e) { - e.printStackTrace(); + } catch (InterruptedException ex) { + ex.printStackTrace(); } return connection.closePipeline(); 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 5d23c25fec..29b01ddc97 100644 --- a/src/test/java/org/springframework/data/redis/connection/ClusterCommandExecutorUnitTests.java +++ b/src/test/java/org/springframework/data/redis/connection/ClusterCommandExecutorUnitTests.java @@ -252,10 +252,10 @@ void executeCommandAsyncOnNodesShouldCompleteAndCollectErrorsOfAllNodes() { try { executor.executeCommandOnAllNodes(COMMAND_CALLBACK); - } catch (ClusterCommandExecutionFailureException cause) { + } catch (ClusterCommandExecutionFailureException ex) { - assertThat(cause.getSuppressed()).hasSize(1); - assertThat(cause.getSuppressed()[0]).isInstanceOf(DataAccessException.class); + assertThat(ex.getSuppressed()).hasSize(1); + assertThat(ex.getSuppressed()[0]).isInstanceOf(DataAccessException.class); } verify(connection1).theWheelWeavesAsTheWheelWills(); 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 13621d31fc..9e82e74bf4 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 @@ -123,8 +123,8 @@ void beforeEach() throws IOException { for (ConnectionPool pool : nativeConnection.getClusterNodes().values()) { try (Jedis jedis = new Jedis(pool.getResource())) { jedis.flushAll(); - } catch (Exception e) { - // ignore this one since we cannot remove data from replicas + } catch (Exception ignore) { + // ignore since we cannot remove data from replicas } } } @@ -2857,8 +2857,8 @@ void scriptFlushShouldRemoveScripts() { try { clusterConnection.scriptingCommands().evalSha(luaScriptBin, ReturnType.VALUE, 1, keyAndArgs); fail("expected InvalidDataAccessApiUsageException"); - } catch (InvalidDataAccessApiUsageException e) { - assertThat(e.getMessage()).contains("NOSCRIPT"); + } catch (InvalidDataAccessApiUsageException ex) { + assertThat(ex.getMessage()).contains("NOSCRIPT"); } } 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 b531db79ed..1c2a237f32 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 @@ -68,17 +68,14 @@ public class JedisConnectionIntegrationTests extends AbstractConnectionIntegrati public void tearDown() { try { connection.flushAll(); - } catch (Exception e) { - // Jedis leaves some incomplete data in OutputStream on NPE caused - // by null key/value tests - // Attempting to flush the DB or close the connection will result in - // error on sending QUIT to Redis + } catch (Exception ignore) { + // Jedis leaves some incomplete data in OutputStream on NPE caused by null key/value tests + // Attempting to flush the DB or close the connection will result in error on sending QUIT to Redis } try { connection.close(); - } catch (Exception e) { - // silently close connection + } catch (Exception ignore) { } connection = null; @@ -231,16 +228,16 @@ public void run() { RedisConnection con = connectionFactory.getConnection(); try { Thread.sleep(100); - } catch (InterruptedException e) { - e.printStackTrace(); + } catch (InterruptedException ex) { + ex.printStackTrace(); } con.publish(expectedChannel.getBytes(), expectedMessage.getBytes()); try { Thread.sleep(100); - } catch (InterruptedException e) { - e.printStackTrace(); + } catch (InterruptedException ex) { + ex.printStackTrace(); } /* @@ -289,8 +286,8 @@ public void run() { RedisConnection con = connectionFactory.getConnection(); try { Thread.sleep(100); - } catch (InterruptedException e) { - e.printStackTrace(); + } catch (InterruptedException ex) { + ex.printStackTrace(); } con.publish("channel1".getBytes(), expectedMessage.getBytes()); @@ -298,8 +295,8 @@ public void run() { try { Thread.sleep(100); - } catch (InterruptedException e) { - e.printStackTrace(); + } catch (InterruptedException ex) { + ex.printStackTrace(); } con.close(); @@ -341,8 +338,7 @@ void testPoolNPE() { try (RedisConnection conn = factory2.getConnection()) { conn.get(null); - } catch (Exception e) { - + } catch (Exception ignore) { } finally { // Make sure we don't end up with broken connection factory2.getConnection().dbSize(); diff --git a/src/test/java/org/springframework/data/redis/connection/jedis/JedisConnectionPipelineIntegrationTests.java b/src/test/java/org/springframework/data/redis/connection/jedis/JedisConnectionPipelineIntegrationTests.java index 9eeb5e4c95..1250aafd87 100644 --- a/src/test/java/org/springframework/data/redis/connection/jedis/JedisConnectionPipelineIntegrationTests.java +++ b/src/test/java/org/springframework/data/redis/connection/jedis/JedisConnectionPipelineIntegrationTests.java @@ -47,11 +47,9 @@ public void tearDown() { try { connection.flushAll(); connection.close(); - } catch (Exception e) { - // Jedis leaves some incomplete data in OutputStream on NPE caused - // by null key/value tests - // Attempting to close the connection will result in error on - // sending QUIT to Redis + } catch (Exception ignore) { + // Jedis leaves some incomplete data in OutputStream on NPE caused by null key/value tests + // Attempting to close the connection will result in error on sending QUIT to Redis } connection = null; } diff --git a/src/test/java/org/springframework/data/redis/connection/jedis/JedisConnectionTransactionIntegrationTests.java b/src/test/java/org/springframework/data/redis/connection/jedis/JedisConnectionTransactionIntegrationTests.java index 6963ec38e6..4e287e1c9e 100644 --- a/src/test/java/org/springframework/data/redis/connection/jedis/JedisConnectionTransactionIntegrationTests.java +++ b/src/test/java/org/springframework/data/redis/connection/jedis/JedisConnectionTransactionIntegrationTests.java @@ -46,11 +46,9 @@ public void tearDown() { try { connection.flushAll(); connection.close(); - } catch (Exception e) { - // Jedis leaves some incomplete data in OutputStream on NPE caused - // by null key/value tests - // Attempting to close the connection will result in error on - // sending QUIT to Redis + } catch (Exception ignore) { + // Jedis leaves some incomplete data in OutputStream on NPE caused by null key/value tests + // Attempting to close the connection will result in error on sending QUIT to Redis } connection = null; } diff --git a/src/test/java/org/springframework/data/redis/connection/jedis/JedisConnectionUnitTests.java b/src/test/java/org/springframework/data/redis/connection/jedis/JedisConnectionUnitTests.java index 7f61f9aea5..920a6e6512 100644 --- a/src/test/java/org/springframework/data/redis/connection/jedis/JedisConnectionUnitTests.java +++ b/src/test/java/org/springframework/data/redis/connection/jedis/JedisConnectionUnitTests.java @@ -65,8 +65,7 @@ void shutdownWithNullShouldDelegateCommandCorrectly() { try { connection.shutdown(null); - } catch (InvalidDataAccessApiUsageException e) { - // all good. Sometimes it throws an Exception. + } catch (InvalidDataAccessApiUsageException ignore) { } verify(jedisSpy).shutdown(); 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 ba1cef1e2a..e13715b875 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 @@ -100,8 +100,8 @@ void contextLoads() throws InterruptedException { cursorMap.next(); } cursorMap.close(); - } catch (Exception e) { - exception.set(e); + } catch (Exception ex) { + exception.set(ex); } }); } diff --git a/src/test/java/org/springframework/data/redis/connection/jedis/extension/JedisConnectionFactoryExtension.java b/src/test/java/org/springframework/data/redis/connection/jedis/extension/JedisConnectionFactoryExtension.java index 3b7e07cf4f..d1517f404a 100644 --- a/src/test/java/org/springframework/data/redis/connection/jedis/extension/JedisConnectionFactoryExtension.java +++ b/src/test/java/org/springframework/data/redis/connection/jedis/extension/JedisConnectionFactoryExtension.java @@ -227,8 +227,8 @@ public void close() throws IOException { try { mayClose = true; destroy(); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } } } 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 5328beebc9..82eeda5e0a 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 @@ -101,7 +101,7 @@ void testGetNewConnectionOnError() throws Exception { try { connection.get("test3"); fail("Expected exception using natively closed conn"); - } catch (RedisSystemException e) { + } catch (RedisSystemException expected) { // expected, shared conn is closed } DefaultStringRedisConnection conn2 = new DefaultStringRedisConnection(factory.getConnection()); @@ -122,7 +122,7 @@ void testConnectionErrorNoValidate() throws Exception { try { conn2.set("anotherkey", "anothervalue"); fail("Expected exception using natively closed conn"); - } catch (RedisSystemException e) { + } catch (RedisSystemException expected) { // expected, as we are re-using the natively closed conn } finally { conn2.close(); @@ -274,7 +274,8 @@ void testGetConnectionException() { try { factory.getConnection(); fail("Expected connection failure exception"); - } catch (RedisConnectionFailureException e) {} + } catch (RedisConnectionFailureException expected) { + } } @Test @@ -467,9 +468,9 @@ void factoryUsesElastiCacheMasterWithoutMaster() { try { connection.ping(); fail("Expected RedisException: Master is currently unknown"); - } catch (RedisSystemException e) { - assertThat(e.getCause()).isInstanceOf(RedisException.class); - assertThat(e.getCause().getMessage()).contains("Master is currently unknown"); + } catch (RedisSystemException ex) { + assertThat(ex.getCause()).isInstanceOf(RedisException.class); + assertThat(ex.getCause().getMessage()).contains("Master is currently unknown"); } finally { connection.close(); } 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 360178415a..d9843ef27e 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 @@ -97,7 +97,7 @@ void testCloseInTransaction() { try { connection.exec(); fail("Expected exception resuming tx"); - } catch (RedisSystemException e) { + } catch (RedisSystemException expected) { // expected, can't resume tx after closing conn } } @@ -115,7 +115,8 @@ void testCloseBlockingOps() { // can't do blocking ops after closing connection.bLPop(1, "what".getBytes()); fail("Expected exception using a closed conn for dedicated ops"); - } catch (RedisSystemException e) {} + } catch (RedisSystemException expected) { + } } @Test @@ -134,8 +135,8 @@ void testCloseNonPooledConnectionNotShared() { try { connection.set("foo".getBytes(), "bar".getBytes()); fail("Exception should be thrown trying to use a closed connection"); - } catch (RedisSystemException e) {} - finally { + } catch (RedisSystemException expected) { + } finally { factory2.destroy(); } diff --git a/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceReactiveCommandsTestSupport.java b/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceReactiveCommandsTestSupport.java index 1ba37c1c4a..fee8db144c 100644 --- a/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceReactiveCommandsTestSupport.java +++ b/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceReactiveCommandsTestSupport.java @@ -166,8 +166,8 @@ public void close() throws IOException { if (nativeBinaryConnectionProvider instanceof DisposableBean) { ((DisposableBean) nativeBinaryConnectionProvider).destroy(); } - } catch (Exception e) { - throw new RuntimeException(e); + } catch (Exception ex) { + throw new RuntimeException(ex); } } } diff --git a/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceSentinelIntegrationTests.java b/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceSentinelIntegrationTests.java index 562a902244..5890ecabd9 100644 --- a/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceSentinelIntegrationTests.java +++ b/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceSentinelIntegrationTests.java @@ -78,9 +78,8 @@ public void tearDown() { // since we use more than one db we're required to flush them all connection.flushAll(); - } catch (Exception e) { - // Connection may be closed in certain cases, like after pub/sub - // tests + } catch (Exception ignore) { + // Connection may be closed in certain cases, like after pub/sub tests } connection.close(); } diff --git a/src/test/java/org/springframework/data/redis/core/ConnectionSplittingInterceptorUnitTests.java b/src/test/java/org/springframework/data/redis/core/ConnectionSplittingInterceptorUnitTests.java index d023caa967..e6499c8e27 100644 --- a/src/test/java/org/springframework/data/redis/core/ConnectionSplittingInterceptorUnitTests.java +++ b/src/test/java/org/springframework/data/redis/core/ConnectionSplittingInterceptorUnitTests.java @@ -55,8 +55,8 @@ class ConnectionSplittingInterceptorUnitTests { try { WRITE_METHOD = ClassUtils.getMethod(RedisConnection.class, "expire", byte[].class, long.class); READONLY_METHOD = ClassUtils.getMethod(RedisConnection.class, "keys", byte[].class); - } catch (Exception e) { - throw new RuntimeException(e); + } catch (Exception ex) { + throw new RuntimeException(ex); } } diff --git a/src/test/java/org/springframework/data/redis/core/DefaultSetOperationsIntegrationTests.java b/src/test/java/org/springframework/data/redis/core/DefaultSetOperationsIntegrationTests.java index 6c09a72084..ce87733888 100644 --- a/src/test/java/org/springframework/data/redis/core/DefaultSetOperationsIntegrationTests.java +++ b/src/test/java/org/springframework/data/redis/core/DefaultSetOperationsIntegrationTests.java @@ -103,7 +103,8 @@ void testRandomMembersNegative() { try { setOps.randomMembers(keyFactory.instance(), -1); fail("IllegalArgumentException should be thrown"); - } catch (IllegalArgumentException e) {} + } catch (IllegalArgumentException expected) { + } } @ParameterizedRedisTest @@ -112,7 +113,8 @@ void testDistinctRandomMembersNegative() { try { setOps.distinctRandomMembers(keyFactory.instance(), -2); fail("IllegalArgumentException should be thrown"); - } catch (IllegalArgumentException e) {} + } catch (IllegalArgumentException expected) { + } } @SuppressWarnings("unchecked") diff --git a/src/test/java/org/springframework/data/redis/core/ReactiveRedisTemplateIntegrationTests.java b/src/test/java/org/springframework/data/redis/core/ReactiveRedisTemplateIntegrationTests.java index 14c1d64b90..b3b80ffa3e 100644 --- a/src/test/java/org/springframework/data/redis/core/ReactiveRedisTemplateIntegrationTests.java +++ b/src/test/java/org/springframework/data/redis/core/ReactiveRedisTemplateIntegrationTests.java @@ -95,14 +95,10 @@ void before() { @EnabledOnCommand("COPY") void copy() { - ReactiveRedisClusterConnection connection = null; - try { - connection = redisTemplate.getConnectionFactory().getReactiveClusterConnection(); - assumeThat(connection == null).isTrue(); - } catch (InvalidDataAccessApiUsageException e) {} finally { - if (connection != null) { - connection.close(); - } + try (ReactiveRedisClusterConnection connection = redisTemplate.getConnectionFactory() + .getReactiveClusterConnection()){ + assumeThat(connection).isNull(); + } catch (InvalidDataAccessApiUsageException ignore) { } K key = keyFactory.instance(); @@ -397,23 +393,17 @@ void getTtlForKeyWithoutExpiryShouldCompleteWithZeroDuration() { @ParameterizedRedisTest // DATAREDIS-602 void move() { - ReactiveRedisClusterConnection connection = null; - try { - connection = redisTemplate.getConnectionFactory().getReactiveClusterConnection(); - assumeThat(connection == null).isTrue(); - } catch (InvalidDataAccessApiUsageException e) {} finally { - if (connection != null) { - connection.close(); - } + try (ReactiveRedisClusterConnection connection = redisTemplate.getConnectionFactory() + .getReactiveClusterConnection()) { + assumeThat(connection).isNull(); + } catch (InvalidDataAccessApiUsageException ignore) { } K key = keyFactory.instance(); V value = valueFactory.instance(); redisTemplate.opsForValue().set(key, value).as(StepVerifier::create).expectNext(true).verifyComplete(); - redisTemplate.move(key, 5).as(StepVerifier::create).expectNext(true).verifyComplete(); - redisTemplate.hasKey(key).as(StepVerifier::create).expectNext(false).verifyComplete(); } 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 e20be742f6..d9ac4c7321 100644 --- a/src/test/java/org/springframework/data/redis/core/RedisKeyValueAdapterTests.java +++ b/src/test/java/org/springframework/data/redis/core/RedisKeyValueAdapterTests.java @@ -102,8 +102,7 @@ void tearDown() { try { adapter.destroy(); - } catch (Exception e) { - // ignore + } catch (Exception ignore) { } } diff --git a/src/test/java/org/springframework/data/redis/core/RedisTemplateIntegrationTests.java b/src/test/java/org/springframework/data/redis/core/RedisTemplateIntegrationTests.java index 79f5e8ff4f..755c4380c7 100644 --- a/src/test/java/org/springframework/data/redis/core/RedisTemplateIntegrationTests.java +++ b/src/test/java/org/springframework/data/redis/core/RedisTemplateIntegrationTests.java @@ -351,6 +351,7 @@ public void testExecutePipelinedTx() { V value1 = valueFactory.instance(); List pipelinedResults = redisTemplate.executePipelined(new SessionCallback() { public Object execute(RedisOperations operations) throws DataAccessException { + operations.multi(); operations.opsForList().leftPush(key1, value1); operations.opsForList().rightPop(key1); @@ -360,9 +361,12 @@ public Object execute(RedisOperations operations) throws DataAccessException { try { // Await EXEC completion as it's executed on a dedicated connection. Thread.sleep(100); - } catch (InterruptedException e) {} + } catch (InterruptedException ignore) { + } + operations.opsForValue().set(key1, value1); operations.opsForValue().get(key1); + return null; } }); @@ -719,7 +723,8 @@ public List execute(RedisOperations operations) throws DataAccessExcepti th.start(); try { th.join(); - } catch (InterruptedException e) {} + } catch (InterruptedException ignore) { + } operations.multi(); operations.opsForValue().set(key1, value3); @@ -751,7 +756,8 @@ public List execute(RedisOperations operations) throws DataAccessExcepti th.start(); try { th.join(); - } catch (InterruptedException e) {} + } catch (InterruptedException ignore) { + } operations.unwatch(); operations.multi(); @@ -788,7 +794,8 @@ public List execute(RedisOperations operations) throws DataAccessExcepti th.start(); try { th.join(); - } catch (InterruptedException e) {} + } catch (InterruptedException ignore) { + } operations.multi(); operations.opsForValue().set(key1, value3); diff --git a/src/test/java/org/springframework/data/redis/test/condition/EnabledOnRedisAvailableCondition.java b/src/test/java/org/springframework/data/redis/test/condition/EnabledOnRedisAvailableCondition.java index 731c82217a..0b3e29c170 100644 --- a/src/test/java/org/springframework/data/redis/test/condition/EnabledOnRedisAvailableCondition.java +++ b/src/test/java/org/springframework/data/redis/test/condition/EnabledOnRedisAvailableCondition.java @@ -54,13 +54,14 @@ public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext con EnabledOnRedisAvailable annotation = optional.get(); try (Socket socket = new Socket()) { + socket.connect(new InetSocketAddress(SettingsUtils.getHost(), annotation.value()), 100); - return enabled( - String.format("Connection successful to Redis at %s:%d", SettingsUtils.getHost(), annotation.value())); - } catch (IOException e) { - return disabled( - String.format("Cannot connect to Redis at %s:%d (%s)", SettingsUtils.getHost(), annotation.value(), e)); + return enabled(String.format("Connection successful to Redis at %s:%d", SettingsUtils.getHost(), + annotation.value())); + } catch (IOException ex) { + return disabled(String.format("Cannot connect to Redis at %s:%d (%s)", SettingsUtils.getHost(), + annotation.value(), ex)); } } diff --git a/src/test/java/org/springframework/data/redis/test/condition/RedisConditions.java b/src/test/java/org/springframework/data/redis/test/condition/RedisConditions.java index 12bbe80395..c63a79808c 100644 --- a/src/test/java/org/springframework/data/redis/test/condition/RedisConditions.java +++ b/src/test/java/org/springframework/data/redis/test/condition/RedisConditions.java @@ -57,8 +57,8 @@ private RedisConditions(RedisClusterCommands commands) { p.load(inputStream); version = Version.parse(p.getProperty("redis_version")); - } catch (IOException e) { - throw new IllegalStateException(e); + } catch (IOException ex) { + throw new IllegalStateException(ex); } } diff --git a/src/test/java/org/springframework/data/redis/test/condition/RedisDetector.java b/src/test/java/org/springframework/data/redis/test/condition/RedisDetector.java index 3bef7b9013..5413a35e3b 100644 --- a/src/test/java/org/springframework/data/redis/test/condition/RedisDetector.java +++ b/src/test/java/org/springframework/data/redis/test/condition/RedisDetector.java @@ -39,7 +39,7 @@ public class RedisDetector { cluster.getConnectionFromSlot(1).close(); return true; - } catch (Exception e) { + } catch (Exception ignore) { return false; } }); @@ -54,9 +54,8 @@ public static boolean canConnectToPort(int port) { socket.connect(new InetSocketAddress(SettingsUtils.getHost(), port), 100); return true; - } catch (IOException e) { + } catch (IOException ignore) { return false; } } - } diff --git a/src/test/java/org/springframework/data/redis/test/extension/parametrized/ParameterizedRedisTestExtension.java b/src/test/java/org/springframework/data/redis/test/extension/parametrized/ParameterizedRedisTestExtension.java index 2f1128d132..fe4ace599c 100644 --- a/src/test/java/org/springframework/data/redis/test/extension/parametrized/ParameterizedRedisTestExtension.java +++ b/src/test/java/org/springframework/data/redis/test/extension/parametrized/ParameterizedRedisTestExtension.java @@ -147,8 +147,8 @@ private ParameterizedTestNameFormatter createNameFormatter(Method templateMethod protected static Stream arguments(ArgumentsProvider provider, ExtensionContext context) { try { return provider.provideArguments(context); - } catch (Exception e) { - throw ExceptionUtils.throwAsUncheckedException(e); + } catch (Exception ex) { + throw ExceptionUtils.throwAsUncheckedException(ex); } } diff --git a/src/test/java/org/springframework/data/redis/util/ConnectionVerifier.java b/src/test/java/org/springframework/data/redis/util/ConnectionVerifier.java index 3effdb5ba0..7db1865834 100644 --- a/src/test/java/org/springframework/data/redis/util/ConnectionVerifier.java +++ b/src/test/java/org/springframework/data/redis/util/ConnectionVerifier.java @@ -81,8 +81,8 @@ private void initializeFactoryIfRequired(T factory) { if (factory instanceof InitializingBean initializingBean) { try { initializingBean.afterPropertiesSet(); - } catch (Exception e) { - throw new RuntimeException(e); + } catch (Exception ex) { + throw new RuntimeException(ex); } } if (factory instanceof SmartLifecycle smartLifecycle) { @@ -97,14 +97,14 @@ private void disposeFactoryIfNeeded(T it) { if (it instanceof DisposableBean bean) { try { bean.destroy(); - } catch (Exception e) { - throw new DataAccessResourceFailureException("Cannot close resource", e); + } catch (Exception ex) { + throw new DataAccessResourceFailureException("Cannot close resource", ex); } } else if (it instanceof Closeable closeable) { try { closeable.close(); - } catch (IOException e) { - throw new DataAccessResourceFailureException("Cannot close resource", e); + } catch (IOException ex) { + throw new DataAccessResourceFailureException("Cannot close resource", ex); } } else if (it instanceof SmartLifecycle smartLifecycle && smartLifecycle.isRunning()) { smartLifecycle.stop();