From 3d7cb3dd60199b5222f33ea3a7b4b4c355472544 Mon Sep 17 00:00:00 2001 From: John Blum Date: Thu, 19 Oct 2023 14:53:12 -0700 Subject: [PATCH 1/2] Prepare issue branch for #2751. --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index c3b30527e5..fdc3105546 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-2751-SNAPSHOT Spring Data Redis Spring Data module for Redis From d27118238cee09bf41536494a9d2c42a6123b69f Mon Sep 17 00:00:00 2001 From: John Blum Date: Thu, 19 Oct 2023 14:53:44 -0700 Subject: [PATCH 2/2] Replace use of String.format(..) with formatted Strings. Closes #2751 --- .../data/redis/ClusterRedirectException.java | 2 +- .../redis/cache/DefaultRedisCacheWriter.java | 5 +- .../data/redis/cache/RedisCache.java | 17 ++--- .../redis/cache/RedisCacheConfiguration.java | 8 +-- .../connection/ClusterCommandExecutor.java | 13 ++-- .../redis/connection/ClusterTopology.java | 16 ++--- .../data/redis/connection/RedisNode.java | 16 ++--- .../data/redis/connection/RedisPassword.java | 2 +- .../RedisSentinelConfiguration.java | 2 +- .../connection/RedisSocketConfiguration.java | 2 +- .../RedisStandaloneConfiguration.java | 6 +- ...RedisStaticMasterReplicaConfiguration.java | 2 +- .../redis/connection/convert/Converters.java | 2 +- .../jedis/JedisClusterConnection.java | 8 +-- .../jedis/JedisClusterServerCommands.java | 7 ++- .../jedis/JedisClusterZSetCommands.java | 16 ++--- .../jedis/JedisConnectionFactory.java | 10 +-- .../connection/jedis/JedisConverters.java | 6 +- .../connection/jedis/JedisServerCommands.java | 2 +- .../connection/jedis/JedisZSetCommands.java | 16 ++--- .../lettuce/ClusterConnectionProvider.java | 5 +- .../lettuce/LettuceClusterConnection.java | 6 +- .../connection/lettuce/LettuceConnection.java | 16 +++-- .../lettuce/LettuceConnectionFactory.java | 8 +-- .../connection/lettuce/LettuceConverters.java | 4 +- .../LettucePoolingConnectionProvider.java | 5 +- .../lettuce/LettuceReactiveListCommands.java | 4 +- .../LettuceReactivePubSubCommands.java | 2 +- .../LettuceReactiveServerCommands.java | 2 +- .../LettuceReactiveStringCommands.java | 2 +- .../connection/lettuce/LettuceScanCursor.java | 4 +- .../lettuce/LettuceServerCommands.java | 2 +- .../lettuce/LettuceZSetCommands.java | 16 ++--- ...StaticMasterReplicaConnectionProvider.java | 4 +- .../MicrometerTracingAdapter.java | 6 +- .../redis/connection/stream/Consumer.java | 2 +- .../connection/stream/StreamRecords.java | 3 +- .../data/redis/core/IndexWriter.java | 12 ++-- .../data/redis/core/RedisCommand.java | 16 ++--- .../data/redis/core/RedisConnectionUtils.java | 4 +- .../redis/core/convert/BinaryConverters.java | 2 +- .../core/convert/MappingRedisConverter.java | 29 +++++---- .../redis/core/index/GeoIndexDefinition.java | 5 +- .../mapping/BasicRedisPersistentEntity.java | 14 ++--- .../core/mapping/RedisMappingContext.java | 15 ++--- .../data/redis/core/script/DigestUtils.java | 3 +- .../redis/core/types/RedisClientInfo.java | 4 +- .../data/redis/domain/geo/BoundingBox.java | 2 +- .../data/redis/hash/BeanUtilsHashMapper.java | 2 +- .../data/redis/hash/Jackson2HashMapper.java | 4 +- .../RedisMessageListenerContainer.java | 15 +++-- .../adapter/MessageListenerAdapter.java | 9 ++- .../data/redis/repository/cdi/CdiBean.java | 5 +- .../cdi/RedisRepositoryExtension.java | 28 ++++----- .../core/MappingRedisEntityInformation.java | 6 +- .../repository/query/ExampleQueryMapper.java | 5 +- .../repository/query/RedisQueryCreator.java | 26 +++----- .../serializer/DefaultRedisElementWriter.java | 8 ++- .../GenericJackson2JsonRedisSerializer.java | 6 +- .../redis/stream/DefaultStreamReceiver.java | 62 ++++++++++--------- .../support/atomic/RedisAtomicDouble.java | 3 +- .../support/atomic/RedisAtomicInteger.java | 3 +- .../redis/support/atomic/RedisAtomicLong.java | 3 +- .../collections/AbstractRedisCollection.java | 9 +-- .../RedisCollectionFactoryBean.java | 4 +- .../collections/ReversedRedisListView.java | 4 +- .../data/redis/util/RedisAssertions.java | 4 +- .../data/redis/SettingsUtils.java | 12 ++-- .../connection/ClusterSlotHashUtilsTests.java | 2 +- .../JedisConnectionIntegrationTests.java | 4 +- .../LettuceConnectionFactoryTests.java | 9 +-- ...tiveScriptingCommandsIntegrationTests.java | 2 +- .../redis/core/RedisKeyValueAdapterTests.java | 2 +- .../BasicRedisPersistentEntityUnitTests.java | 6 +- .../EnabledOnRedisAvailableCondition.java | 4 +- .../EnabledOnRedisClusterCondition.java | 4 +- .../EnabledOnRedisDriverCondition.java | 7 +-- .../EnabledOnRedisSentinelCondition.java | 7 +-- .../EnabledOnRedisVersionCondition.java | 15 +++-- .../ParameterizedRedisTestExtension.java | 23 +++---- .../ParameterizedTestNameFormatter.java | 5 +- .../data/redis/test/util/MockitoUtils.java | 2 +- .../data/redis/test/util/RedisTestData.java | 2 +- 83 files changed, 316 insertions(+), 351 deletions(-) diff --git a/src/main/java/org/springframework/data/redis/ClusterRedirectException.java b/src/main/java/org/springframework/data/redis/ClusterRedirectException.java index bfe3ea3e2f..723d874ad7 100644 --- a/src/main/java/org/springframework/data/redis/ClusterRedirectException.java +++ b/src/main/java/org/springframework/data/redis/ClusterRedirectException.java @@ -43,7 +43,7 @@ public class ClusterRedirectException extends DataRetrievalFailureException { */ public ClusterRedirectException(int slot, String targetHost, int targetPort, Throwable e) { - super(String.format("Redirect: slot %s to %s:%s.", slot, targetHost, targetPort), e); + super("Redirect: slot %s to %s:%s.".formatted(slot, targetHost, targetPort), e); this.slot = slot; this.host = targetHost; 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 5d997bee42..cdf9bc90e1 100644 --- a/src/main/java/org/springframework/data/redis/cache/DefaultRedisCacheWriter.java +++ b/src/main/java/org/springframework/data/redis/cache/DefaultRedisCacheWriter.java @@ -382,9 +382,8 @@ private void checkAndPotentiallyWaitUntilUnlocked(String name, RedisConnection c // Re-interrupt current Thread to allow other participants to react. Thread.currentThread().interrupt(); - String message = String.format("Interrupted while waiting to unlock cache %s", name); - - throw new PessimisticLockingFailureException(message, ex); + throw new PessimisticLockingFailureException("Interrupted while waiting to unlock cache %s" + .formatted(name), 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 11debd8710..059ba13f0a 100644 --- a/src/main/java/org/springframework/data/redis/cache/RedisCache.java +++ b/src/main/java/org/springframework/data/redis/cache/RedisCache.java @@ -324,12 +324,9 @@ private Object processAndCheckValue(@Nullable Object value) { Object cacheValue = preProcessCacheValue(value); if (nullCacheValueIsNotAllowed(cacheValue)) { - - String message = String.format("Cache '%s' does not allow 'null' values; Avoid storing null" + throw new IllegalArgumentException(("Cache '%s' does not allow 'null' values; Avoid storing null" + " via '@Cacheable(unless=\"#result == null\")' or configure RedisCache to allow 'null'" - + " via RedisCacheConfiguration", getName()); - - throw new IllegalArgumentException(message); + + " via RedisCacheConfiguration").formatted(getName())); } return cacheValue; @@ -440,11 +437,9 @@ protected String convertKey(Object key) { return key.toString(); } - String message = String.format("Cannot convert cache key %s to String; Please register a suitable Converter" - + " via 'RedisCacheConfiguration.configureKeyConverters(...)' or override '%s.toString()'", - source, key.getClass().getName()); - - throw new IllegalStateException(message); + throw new IllegalStateException(("Cannot convert cache key %s to String; Please register a suitable Converter" + + " via 'RedisCacheConfiguration.configureKeyConverters(...)' or override '%s.toString()'") + .formatted(source, key.getClass().getName())); } private CompletableFuture retrieveValue(Object key) { @@ -502,7 +497,7 @@ private String convertCollectionLikeOrMapKey(Object key, TypeDescriptor source) return "[" + stringJoiner + "]"; } - throw new IllegalArgumentException(String.format("Cannot convert cache key [%s] to String", key)); + throw new IllegalArgumentException("Cannot convert cache key [%s] to String".formatted(key)); } private byte[] createAndConvertCacheKey(Object key) { diff --git a/src/main/java/org/springframework/data/redis/cache/RedisCacheConfiguration.java b/src/main/java/org/springframework/data/redis/cache/RedisCacheConfiguration.java index 202ddee446..2e90962041 100644 --- a/src/main/java/org/springframework/data/redis/cache/RedisCacheConfiguration.java +++ b/src/main/java/org/springframework/data/redis/cache/RedisCacheConfiguration.java @@ -424,11 +424,9 @@ public void addCacheKeyConverter(Converter cacheKeyConverter) { public void configureKeyConverters(Consumer registryConsumer) { if (!(getConversionService() instanceof ConverterRegistry)) { - - String message = "'%s' returned by getConversionService() does not allow Converter registration;" - + " Please make sure to provide a ConversionService that implements ConverterRegistry"; - - throw new IllegalStateException(String.format(message, getConversionService().getClass().getName())); + throw new IllegalStateException(("'%s' returned by getConversionService() does not allow Converter registration;" + + " Please make sure to provide a ConversionService that implements ConverterRegistry") + .formatted(getConversionService().getClass().getName())); } registryConsumer.accept((ConverterRegistry) getConversionService()); 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 0b28fbd05c..672c7b8611 100644 --- a/src/main/java/org/springframework/data/redis/connection/ClusterCommandExecutor.java +++ b/src/main/java/org/springframework/data/redis/connection/ClusterCommandExecutor.java @@ -130,12 +130,9 @@ private NodeResult executeCommandOnSingleNode(ClusterCommandCallback 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); + throw new TooManyClusterRedirectionsException(("Cannot follow Cluster Redirects over more than %s legs;" + + " Consider increasing the number of redirects to follow; Current value is: %s") + .formatted(redirectCount, this.maxRedirects)); } RedisClusterNode nodeToUse = lookupNode(node); @@ -178,7 +175,7 @@ private RedisClusterNode lookupNode(RedisClusterNode node) { try { return topologyProvider.getTopology().lookup(node); } catch (ClusterStateFailureException ex) { - throw new IllegalArgumentException(String.format("Node %s is unknown to cluster", node), ex); + throw new IllegalArgumentException("Node %s is unknown to cluster".formatted(node), ex); } } @@ -215,7 +212,7 @@ public MultiNodeResult executeCommandAsyncOnNodes(ClusterCommandCallba try { resolvedRedisClusterNodes.add(topology.lookup(node)); } catch (ClusterStateFailureException ex) { - throw new IllegalArgumentException(String.format("Node %s is unknown to cluster", node), ex); + throw new IllegalArgumentException("Node %s is unknown to cluster".formatted(node), ex); } } 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 f49236b188..8187e99274 100644 --- a/src/main/java/org/springframework/data/redis/connection/ClusterTopology.java +++ b/src/main/java/org/springframework/data/redis/connection/ClusterTopology.java @@ -140,8 +140,8 @@ public RedisClusterNode getKeyServingMasterNode(byte[] key) { } } - throw new ClusterStateFailureException( - String.format("Could not find master node serving slot %s for key '%s',", slot, Arrays.toString(key))); + throw new ClusterStateFailureException("Could not find master node serving slot %s for key '%s'," + .formatted(slot, Arrays.toString(key))); } /** @@ -160,8 +160,8 @@ public RedisClusterNode lookup(String host, int port) { } } - throw new ClusterStateFailureException( - String.format("Could not find node at %s:%s; Is your cluster info up to date", host, port)); + throw new ClusterStateFailureException("Could not find node at %s:%d; Is your cluster info up to date" + .formatted(host, port)); } /** @@ -181,8 +181,8 @@ public RedisClusterNode lookup(String nodeId) { } } - throw new ClusterStateFailureException( - String.format("Could not find node at %s; Is your cluster info up to date", nodeId)); + throw new ClusterStateFailureException("Could not find node at %s; Is your cluster info up to date" + .formatted(nodeId)); } /** @@ -209,8 +209,8 @@ public RedisClusterNode lookup(RedisClusterNode node) { return lookup(node.getId()); } - throw new ClusterStateFailureException( - String.format("Could not find node at %s; Have you provided either host and port or the nodeId", node)); + throw new ClusterStateFailureException(("Could not find node at %s;" + + " Have you provided either host and port or the nodeId").formatted(node)); } /** 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 7c66f5a1e9..5d599f4e20 100644 --- a/src/main/java/org/springframework/data/redis/connection/RedisNode.java +++ b/src/main/java/org/springframework/data/redis/connection/RedisNode.java @@ -102,11 +102,11 @@ public static RedisNode fromString(String hostPortString) { try { port = Integer.parseInt(portString); } catch (RuntimeException ignore) { - throw new IllegalArgumentException(String.format("Unparseable port number: %s", hostPortString)); + throw new IllegalArgumentException("Unparseable port number: %s".formatted(hostPortString)); } if (!isValidPort(port)) { - throw new IllegalArgumentException(String.format("Port number out of range: %s", hostPortString)); + throw new IllegalArgumentException("Port number out of range: %s".formatted(hostPortString)); } return new RedisNode(host, port); @@ -122,15 +122,15 @@ public static RedisNode fromString(String hostPortString) { private static String[] getHostAndPortFromBracketedHost(String hostPortString) { if (hostPortString.charAt(0) != '[') { - throw new IllegalArgumentException( - String.format("Bracketed host-port string must start with a bracket: %s", hostPortString)); + throw new IllegalArgumentException("Bracketed host-port string must start with a bracket: %s" + .formatted(hostPortString)); } int colonIndex = hostPortString.indexOf(':'); int closeBracketIndex = hostPortString.lastIndexOf(']'); if (!(colonIndex > -1 && closeBracketIndex > colonIndex)) { - throw new IllegalArgumentException(String.format("Invalid bracketed host/port: %s", hostPortString)); + throw new IllegalArgumentException("Invalid bracketed host/port: %s".formatted(hostPortString)); } String host = hostPortString.substring(1, closeBracketIndex); @@ -138,12 +138,12 @@ private static String[] getHostAndPortFromBracketedHost(String hostPortString) { return new String[] { host, "" }; } else { if (!(hostPortString.charAt(closeBracketIndex + 1) == ':')) { - throw new IllegalArgumentException( - String.format("Only a colon may follow a close bracket: %s", hostPortString)); + throw new IllegalArgumentException("Only a colon may follow a close bracket: %s" + .formatted(hostPortString)); } for (int i = closeBracketIndex + 2; i < hostPortString.length(); ++i) { if (!Character.isDigit(hostPortString.charAt(i))) { - throw new IllegalArgumentException(String.format("Port must be numeric: %s", hostPortString)); + throw new IllegalArgumentException("Port must be numeric: %s".formatted(hostPortString)); } } return new String[] { host, hostPortString.substring(closeBracketIndex + 2) }; diff --git a/src/main/java/org/springframework/data/redis/connection/RedisPassword.java b/src/main/java/org/springframework/data/redis/connection/RedisPassword.java index f39a04bd9d..c3eda3fb72 100644 --- a/src/main/java/org/springframework/data/redis/connection/RedisPassword.java +++ b/src/main/java/org/springframework/data/redis/connection/RedisPassword.java @@ -140,7 +140,7 @@ public Optional toOptional() { @Override public String toString() { - return String.format("%s[%s]", getClass().getSimpleName(), isPresent() ? "*****" : ""); + return "%s[%s]".formatted(getClass().getSimpleName(), isPresent() ? "*****" : ""); } @Override diff --git a/src/main/java/org/springframework/data/redis/connection/RedisSentinelConfiguration.java b/src/main/java/org/springframework/data/redis/connection/RedisSentinelConfiguration.java index bb8ae9c5dd..92f2a58824 100644 --- a/src/main/java/org/springframework/data/redis/connection/RedisSentinelConfiguration.java +++ b/src/main/java/org/springframework/data/redis/connection/RedisSentinelConfiguration.java @@ -223,7 +223,7 @@ public int getDatabase() { @Override public void setDatabase(int index) { - Assert.isTrue(index >= 0, () -> String.format("Invalid DB index '%d'; non-negative index required", index)); + Assert.isTrue(index >= 0, "Invalid DB index '%d'; non-negative index required".formatted(index)); this.database = index; } diff --git a/src/main/java/org/springframework/data/redis/connection/RedisSocketConfiguration.java b/src/main/java/org/springframework/data/redis/connection/RedisSocketConfiguration.java index ad80862396..0c05056d30 100644 --- a/src/main/java/org/springframework/data/redis/connection/RedisSocketConfiguration.java +++ b/src/main/java/org/springframework/data/redis/connection/RedisSocketConfiguration.java @@ -74,7 +74,7 @@ public int getDatabase() { @Override public void setDatabase(int index) { - Assert.isTrue(index >= 0, () -> String.format("Invalid DB index '%s' (a positive index required)", index)); + Assert.isTrue(index >= 0, () -> "Invalid DB index '%s'; non-negative index required".formatted(index)); this.database = index; } diff --git a/src/main/java/org/springframework/data/redis/connection/RedisStandaloneConfiguration.java b/src/main/java/org/springframework/data/redis/connection/RedisStandaloneConfiguration.java index 7b471e9594..1c731ad0f9 100644 --- a/src/main/java/org/springframework/data/redis/connection/RedisStandaloneConfiguration.java +++ b/src/main/java/org/springframework/data/redis/connection/RedisStandaloneConfiguration.java @@ -69,8 +69,8 @@ public RedisStandaloneConfiguration(String hostName) { public RedisStandaloneConfiguration(String hostName, int port) { Assert.hasText(hostName, "Host name must not be null or empty"); - Assert.isTrue(port >= 1 && port <= 65535, - () -> String.format("Port %d must be a valid TCP port in the range between 1-65535", port)); + Assert.isTrue(port >= 1 && port <= 65535, "Port %d must be a valid TCP port in the range between 1-65535" + .formatted(port)); this.hostName = hostName; this.port = port; @@ -103,7 +103,7 @@ public int getDatabase() { @Override public void setDatabase(int index) { - Assert.isTrue(index >= 0, () -> String.format("Invalid DB index '%s' (a positive index required)", index)); + Assert.isTrue(index >= 0, "Invalid DB index '%d'; non-negative index required".formatted(index)); this.database = index; } diff --git a/src/main/java/org/springframework/data/redis/connection/RedisStaticMasterReplicaConfiguration.java b/src/main/java/org/springframework/data/redis/connection/RedisStaticMasterReplicaConfiguration.java index da8cb7eeb0..4989f5ee0b 100644 --- a/src/main/java/org/springframework/data/redis/connection/RedisStaticMasterReplicaConfiguration.java +++ b/src/main/java/org/springframework/data/redis/connection/RedisStaticMasterReplicaConfiguration.java @@ -118,7 +118,7 @@ public int getDatabase() { @Override public void setDatabase(int index) { - Assert.isTrue(index >= 0, () -> String.format("Invalid DB index '%s' (a positive index required)", index)); + Assert.isTrue(index >= 0, "Invalid DB index '%d'; non-negative index required".formatted(index)); this.database = index; this.nodes.forEach(it -> it.setDatabase(database)); 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 94dbc9087d..c8f607b882 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 @@ -410,7 +410,7 @@ public static Object parse(Object source, String sourcePath, Map entry : errors.entrySet()) { - stringBuilder.append(String.format("\r\n\t- %s failed: %s", entry.getKey(), entry.getValue().getMessage())); + stringBuilder.append("\r\n\t- %s failed: %s".formatted(entry.getKey(), entry.getValue().getMessage())); } throw new ClusterStateFailureException( diff --git a/src/main/java/org/springframework/data/redis/connection/jedis/JedisClusterServerCommands.java b/src/main/java/org/springframework/data/redis/connection/jedis/JedisClusterServerCommands.java index 5e920cc85c..ae5f828fac 100644 --- a/src/main/java/org/springframework/data/redis/connection/jedis/JedisClusterServerCommands.java +++ b/src/main/java/org/springframework/data/redis/connection/jedis/JedisClusterServerCommands.java @@ -347,10 +347,11 @@ public Long time(RedisClusterNode node, TimeUnit timeUnit) { public void killClient(String host, int port) { Assert.hasText(host, "Host for 'CLIENT KILL' must not be 'null' or 'empty'"); - String hostAndPort = String.format("%s:%s", host, port); + String hostAndPort = "%s:%d".formatted(host, port); - connection.getClusterCommandExecutor() - .executeCommandOnAllNodes((JedisClusterCommandCallback) client -> client.clientKill(hostAndPort)); + JedisClusterCommandCallback command = client -> client.clientKill(hostAndPort); + + connection.getClusterCommandExecutor().executeCommandOnAllNodes(command); } @Override diff --git a/src/main/java/org/springframework/data/redis/connection/jedis/JedisClusterZSetCommands.java b/src/main/java/org/springframework/data/redis/connection/jedis/JedisClusterZSetCommands.java index c090186086..616ee81930 100644 --- a/src/main/java/org/springframework/data/redis/connection/jedis/JedisClusterZSetCommands.java +++ b/src/main/java/org/springframework/data/redis/connection/jedis/JedisClusterZSetCommands.java @@ -908,8 +908,8 @@ public Set zInterWithScores(Aggregate aggregate, Weights weights, byte[]. Assert.notNull(sets, "Sets must not be null"); Assert.noNullElements(sets, "Source sets must not contain null elements"); - Assert.isTrue(weights.size() == sets.length, () -> String - .format("The number of weights (%d) must match the number of source sets (%d)", weights.size(), sets.length)); + Assert.isTrue(weights.size() == sets.length, () -> + "The number of weights %d must match the number of source sets %d".formatted(weights.size(), sets.length)); if (ClusterSlotHashUtil.isSameSlotForAllKeys(sets)) { @@ -951,8 +951,8 @@ public Long zInterStore(byte[] destKey, Aggregate aggregate, Weights weights, by Assert.notNull(destKey, "Destination key must not be null"); Assert.notNull(sets, "Source sets must not be null"); Assert.noNullElements(sets, "Source sets must not contain null elements"); - Assert.isTrue(weights.size() == sets.length, () -> String - .format("The number of weights (%d) must match the number of source sets (%d)", weights.size(), sets.length)); + Assert.isTrue(weights.size() == sets.length, + "The number of weights %d must match the number of source sets %d".formatted(weights.size(), sets.length)); byte[][] allKeys = ByteUtils.mergeArrays(destKey, sets); @@ -1008,8 +1008,8 @@ public Set zUnionWithScores(Aggregate aggregate, Weights weights, byte[]. Assert.notNull(sets, "Sets must not be null"); Assert.noNullElements(sets, "Source sets must not contain null elements"); - Assert.isTrue(weights.size() == sets.length, () -> String - .format("The number of weights (%d) must match the number of source sets (%d)", weights.size(), sets.length)); + Assert.isTrue(weights.size() == sets.length, () -> + "The number of weights %d must match the number of source sets %d".formatted(weights.size(), sets.length)); if (ClusterSlotHashUtil.isSameSlotForAllKeys(sets)) { @@ -1052,8 +1052,8 @@ public Long zUnionStore(byte[] destKey, Aggregate aggregate, Weights weights, by Assert.notNull(destKey, "Destination key must not be null"); Assert.notNull(sets, "Source sets must not be null"); Assert.noNullElements(sets, "Source sets must not contain null elements"); - Assert.isTrue(weights.size() == sets.length, () -> String - .format("The number of weights (%d) must match the number of source sets (%d)", weights.size(), sets.length)); + Assert.isTrue(weights.size() == sets.length, + "The number of weights %d must match the number of source sets %d".formatted(weights.size(), sets.length)); byte[][] allKeys = ByteUtils.mergeArrays(destKey, sets); 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 ba3575536a..2068443f78 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 @@ -952,7 +952,7 @@ private Jedis getActiveSentinel() { return jedis; } } catch (Exception ex) { - log.warn(String.format("Ping failed for sentinel host: %s", node.getHost()), ex); + log.warn("Ping failed for sentinel host: %s".formatted(node.getHost()), ex); } finally { if (!success && jedis != null) { jedis.close(); @@ -989,8 +989,8 @@ private int getConnectTimeout() { private MutableJedisClientConfiguration getMutableConfiguration() { Assert.state(clientConfiguration instanceof MutableJedisClientConfiguration, - () -> String.format("Client configuration must be instance of MutableJedisClientConfiguration but is %s", - ClassUtils.getShortName(clientConfiguration.getClass()))); + () -> "Client configuration must be instance of MutableJedisClientConfiguration but is %s" + .formatted(ClassUtils.getShortName(clientConfiguration.getClass()))); return (MutableJedisClientConfiguration) clientConfiguration; } @@ -1005,10 +1005,10 @@ private void assertInitialized() { switch (current) { case CREATED, STOPPED -> throw new IllegalStateException( - String.format("JedisConnectionFactory has been %s. Use start() to initialize it", current)); + "JedisConnectionFactory has been %s. Use start() to initialize it".formatted(current)); case DESTROYED -> throw new IllegalStateException( "JedisConnectionFactory was destroyed and cannot be used anymore"); - default -> throw new IllegalStateException(String.format("JedisConnectionFactory is %s", current)); + default -> throw new IllegalStateException("JedisConnectionFactory is %s".formatted(current)); } } 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 ac689c75ca..e562678ed8 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 @@ -481,7 +481,7 @@ private static byte[] boundaryToBytes(org.springframework.data.domain.Range.Boun } else if (theValue instanceof String) { value = toBytes((String) theValue); } else { - throw new IllegalArgumentException(String.format("Cannot convert %s to binary format", boundary.getValue())); + throw new IllegalArgumentException("Cannot convert %s to binary format".formatted(boundary.getValue())); } ByteBuffer buffer = ByteBuffer.allocate(prefix.length + value.length); @@ -780,7 +780,7 @@ private static GeoSearchParam getGeoSearchParam(GeoShape predicate, GeoSearchPar return param; } - throw new IllegalArgumentException(String.format("Cannot convert %s to Jedis GeoSearchParam", predicate)); + throw new IllegalArgumentException("Cannot convert %s to Jedis GeoSearchParam".formatted(predicate)); } private static void configureGeoReference(GeoReference reference, GeoSearchParam param) { @@ -798,7 +798,7 @@ private static void configureGeoReference(GeoReference reference, GeoSea return; } - throw new IllegalArgumentException(String.format("Cannot extract Geo Reference from %s", reference)); + throw new IllegalArgumentException("Cannot extract Geo Reference from %s".formatted(reference)); } /** diff --git a/src/main/java/org/springframework/data/redis/connection/jedis/JedisServerCommands.java b/src/main/java/org/springframework/data/redis/connection/jedis/JedisServerCommands.java index fddd3cc374..90e93b60d8 100644 --- a/src/main/java/org/springframework/data/redis/connection/jedis/JedisServerCommands.java +++ b/src/main/java/org/springframework/data/redis/connection/jedis/JedisServerCommands.java @@ -161,7 +161,7 @@ public void killClient(String host, int port) { Assert.hasText(host, "Host for 'CLIENT KILL' must not be 'null' or 'empty'"); - connection.invokeStatus().just(it -> it.clientKill(String.format("%s:%s", host, port))); + connection.invokeStatus().just(it -> it.clientKill("%s:%s".formatted(host, port))); } @Override diff --git a/src/main/java/org/springframework/data/redis/connection/jedis/JedisZSetCommands.java b/src/main/java/org/springframework/data/redis/connection/jedis/JedisZSetCommands.java index a19247a8d1..1a9cf839e9 100644 --- a/src/main/java/org/springframework/data/redis/connection/jedis/JedisZSetCommands.java +++ b/src/main/java/org/springframework/data/redis/connection/jedis/JedisZSetCommands.java @@ -473,8 +473,8 @@ public Set zInterWithScores(Aggregate aggregate, Weights weights, byte[]. Assert.notNull(sets, "Sets must not be null"); Assert.noNullElements(sets, "Source sets must not contain null elements"); - Assert.isTrue(weights.size() == sets.length, () -> String - .format("The number of weights (%d) must match the number of source sets (%d)", weights.size(), sets.length)); + Assert.isTrue(weights.size() == sets.length, + "The number of weights (%d) must match the number of source sets (%d)".formatted(weights.size(), sets.length)); return connection.invoke().fromMany(Jedis::zinterWithScores, PipelineBinaryCommands::zinterWithScores, toZParams(aggregate, weights), sets).toSet(JedisConverters::toTuple); @@ -486,8 +486,8 @@ public Long zInterStore(byte[] destKey, Aggregate aggregate, Weights weights, by Assert.notNull(destKey, "Destination key must not be null"); Assert.notNull(sets, "Source sets must not be null"); Assert.noNullElements(sets, "Source sets must not contain null elements"); - Assert.isTrue(weights.size() == sets.length, () -> String - .format("The number of weights (%d) must match the number of source sets (%d)", weights.size(), sets.length)); + Assert.isTrue(weights.size() == sets.length, + "The number of weights %d must match the number of source sets %d".formatted(weights.size(), sets.length)); ZParams zparams = toZParams(aggregate, weights); @@ -527,8 +527,8 @@ public Set zUnionWithScores(Aggregate aggregate, Weights weights, byte[]. Assert.notNull(sets, "Sets must not be null"); Assert.noNullElements(sets, "Source sets must not contain null elements"); - Assert.isTrue(weights.size() == sets.length, () -> String - .format("The number of weights (%d) must match the number of source sets (%d)", weights.size(), sets.length)); + Assert.isTrue(weights.size() == sets.length, + "The number of weights %d must match the number of source sets %d".formatted(weights.size(), sets.length)); return connection.invoke().fromMany(Jedis::zunionWithScores, PipelineBinaryCommands::zunionWithScores, toZParams(aggregate, weights), sets).toSet(JedisConverters::toTuple); @@ -541,8 +541,8 @@ public Long zUnionStore(byte[] destKey, Aggregate aggregate, Weights weights, by Assert.notNull(sets, "Source sets must not be null"); Assert.notNull(weights, "Weights must not be null"); Assert.noNullElements(sets, "Source sets must not contain null elements"); - Assert.isTrue(weights.size() == sets.length, () -> String - .format("The number of weights (%d) must match the number of source sets (%d)", weights.size(), sets.length)); + Assert.isTrue(weights.size() == sets.length, + "The number of weights %d must match the number of source sets %d".formatted(weights.size(), sets.length)); ZParams zparams = toZParams(aggregate, weights); diff --git a/src/main/java/org/springframework/data/redis/connection/lettuce/ClusterConnectionProvider.java b/src/main/java/org/springframework/data/redis/connection/lettuce/ClusterConnectionProvider.java index c30d0a9351..15f27a84a6 100644 --- a/src/main/java/org/springframework/data/redis/connection/lettuce/ClusterConnectionProvider.java +++ b/src/main/java/org/springframework/data/redis/connection/lettuce/ClusterConnectionProvider.java @@ -120,9 +120,8 @@ private Optional getReadFrom() { }); } - String message = String.format("Connection type %s not supported", connectionType); - - return LettuceFutureUtils.failed(new InvalidDataAccessApiUsageException(message)); + return LettuceFutureUtils.failed(new InvalidDataAccessApiUsageException("Connection type %s not supported" + .formatted(connectionType))); } @Override 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 5d2f53618f..c01029bc9d 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 @@ -216,10 +216,8 @@ private RedisClusterClient getClient() { return (RedisClusterClient) redisClientProvider.getRedisClient(); } - String message = String.format("Connection provider %s does not implement RedisClientProvider", - connectionProvider.getClass().getName()); - - throw new IllegalStateException(message); + throw new IllegalStateException("Connection provider %s does not implement RedisClientProvider" + .formatted(connectionProvider.getClass().getName())); } @Override 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 01ba6a780c..e4ba50cd13 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 @@ -324,7 +324,7 @@ public Object execute(String command, byte[]... args) { @SuppressWarnings({ "rawtypes", "unchecked" }) public Object execute(String command, @Nullable CommandOutput commandOutputTypeHint, byte[]... args) { - Assert.hasText(command, () -> String.format("A valid command [%s] needs to be specified", command)); + Assert.hasText(command, () -> "A valid command [%s] needs to be specified".formatted(command)); ProtocolKeyword commandType = getCommandType(command.trim().toUpperCase()); @@ -925,9 +925,8 @@ RedisClusterCommands getDedicatedConnection() { return statefulClusterConnection.sync(); } - String message = String.format("%s is not a supported connection type", connection.getClass().getName()); - - throw new IllegalStateException(message); + throw new IllegalStateException("%s is not a supported connection type" + .formatted(connection.getClass().getName())); } protected RedisClusterAsyncCommands getAsyncDedicatedConnection() { @@ -941,13 +940,13 @@ protected RedisClusterAsyncCommands getAsyncDedicatedConnection( if (connection instanceof StatefulRedisConnection statefulConnection) { return statefulConnection.async(); } + if (asyncDedicatedConnection instanceof StatefulRedisClusterConnection statefulClusterConnection) { return statefulClusterConnection.async(); } - String message = String.format("%s is not a supported connection type", connection.getClass().getName()); - - throw new IllegalStateException(message); + throw new IllegalStateException("%s is not a supported connection type" + .formatted(connection.getClass().getName())); } @SuppressWarnings("unchecked") @@ -1079,8 +1078,7 @@ private void validateCommand(ProtocolKeyword command, @Nullable byte[]... args) try { redisCommand.validateArgumentCount(args != null ? args.length : 0); } catch (IllegalArgumentException ex) { - String message = String.format("Validation failed for %s command", command); - throw new InvalidDataAccessApiUsageException(message, ex); + throw new InvalidDataAccessApiUsageException("Validation failed for %s command".formatted(command), ex); } } } 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 f3c818a510..ae6d0c0c54 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 @@ -1398,10 +1398,10 @@ private void assertStarted() { switch (current) { case CREATED, STOPPED -> throw new IllegalStateException( - String.format("LettuceConnectionFactory has been %s. Use start() to initialize it", current)); + "LettuceConnectionFactory has been %s. Use start() to initialize it".formatted(current)); case DESTROYED -> throw new IllegalStateException( "LettuceConnectionFactory was destroyed and cannot be used anymore"); - default -> throw new IllegalStateException(String.format("LettuceConnectionFactory is %s", current)); + default -> throw new IllegalStateException("LettuceConnectionFactory is %s".formatted(current)); } } @@ -1456,8 +1456,8 @@ private RedisURI.Builder applyAuthentication(RedisURI.Builder builder) { private MutableLettuceClientConfiguration getMutableConfiguration() { Assert.state(clientConfiguration instanceof MutableLettuceClientConfiguration, - () -> String.format("Client configuration must be instance of MutableLettuceClientConfiguration but is %s", - ClassUtils.getShortName(clientConfiguration.getClass()))); + () -> "Client configuration must be instance of MutableLettuceClientConfiguration but is %s" + .formatted(ClassUtils.getShortName(clientConfiguration.getClass()))); return (MutableLettuceClientConfiguration) clientConfiguration; } diff --git a/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceConverters.java b/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceConverters.java index 8990995599..178cd87eb2 100644 --- a/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceConverters.java +++ b/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceConverters.java @@ -871,7 +871,7 @@ static GeoSearch.GeoPredicate toGeoPredicate(GeoShape predicate) { toGeoArgsUnit(boxPredicate.getMetric())); } - throw new IllegalArgumentException(String.format("Cannot convert %s to Lettuce GeoPredicate", predicate)); + throw new IllegalArgumentException("Cannot convert %s to Lettuce GeoPredicate".formatted(predicate)); } static GeoSearch.GeoRef toGeoRef(GeoReference reference) { @@ -887,7 +887,7 @@ static GeoSearch.GeoRef toGeoRef(GeoReference reference) { return GeoSearch.fromCoordinates(coordinates.getLongitude(), coordinates.getLatitude()); } - throw new IllegalArgumentException(String.format("Cannot convert %s to Lettuce GeoRef", reference)); + throw new IllegalArgumentException("Cannot convert %s to Lettuce GeoRef".formatted(reference)); } static FlushMode toFlushMode(@Nullable RedisServerCommands.FlushOption option) { 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 c6e321b31d..17e8fc294d 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 @@ -135,9 +135,8 @@ public AbstractRedisClient getRedisClient() { return ((RedisClientProvider) connectionProvider).getRedisClient(); } - throw new IllegalStateException( - String.format("Underlying connection provider %s does not implement RedisClientProvider", - connectionProvider.getClass().getName())); + throw new IllegalStateException("Underlying connection provider %s does not implement RedisClientProvider" + .formatted(connectionProvider.getClass().getName())); } @Override diff --git a/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceReactiveListCommands.java b/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceReactiveListCommands.java index 68682a78f6..f16e62ce74 100644 --- a/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceReactiveListCommands.java +++ b/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceReactiveListCommands.java @@ -73,8 +73,8 @@ public Flux> push(Publisher comm Assert.notEmpty(command.getValues(), "Values must not be null or empty"); if (!command.getUpsert() && command.getValues().size() > 1) { - throw new InvalidDataAccessApiUsageException( - String.format("%s PUSHX only allows one value", command.getDirection())); + throw new InvalidDataAccessApiUsageException("%s PUSHX only allows one value" + .formatted(command.getDirection())); } Mono pushResult; diff --git a/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceReactivePubSubCommands.java b/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceReactivePubSubCommands.java index e81bcea995..027f20ba16 100644 --- a/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceReactivePubSubCommands.java +++ b/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceReactivePubSubCommands.java @@ -233,7 +233,7 @@ static boolean deallocate(ByteBuffer buffer, Map targe @Override public String toString() { - return String.format("%s: Subscribers: %s", new String(raw), SUBSCRIBERS.get(this)); + return "%s: Subscribers: %s".formatted(new String(raw), SUBSCRIBERS.get(this)); } } } diff --git a/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceReactiveServerCommands.java b/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceReactiveServerCommands.java index 15c203b894..f893f1e3d8 100644 --- a/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceReactiveServerCommands.java +++ b/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceReactiveServerCommands.java @@ -154,7 +154,7 @@ public Mono killClient(String host, int port) { Assert.notNull(host, "Host must not be null or empty"); - return connection.execute(c -> c.clientKill(String.format("%s:%s", host, port))).next(); + return connection.execute(c -> c.clientKill("%s:%d".formatted(host, port))).next(); } @Override diff --git a/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceReactiveStringCommands.java b/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceReactiveStringCommands.java index 77021a0d03..27f74f2172 100644 --- a/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceReactiveStringCommands.java +++ b/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceReactiveStringCommands.java @@ -364,7 +364,7 @@ public Flux> bitOp(Publisher c Assert.isTrue(sourceKeys.length == 1, "BITOP NOT does not allow more than 1 source key."); yield reactiveCommands.bitopNot(destinationKey, sourceKeys[0]); } - default -> throw new IllegalArgumentException(String.format("Unknown BITOP '%s'", command.getBitOp())); + default -> throw new IllegalArgumentException("Unknown BITOP '%s'".formatted(command.getBitOp())); }; return result.map(value -> new NumericResponse<>(command, value)); diff --git a/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceScanCursor.java b/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceScanCursor.java index e5276b2fb7..b3ac18d528 100644 --- a/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceScanCursor.java +++ b/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceScanCursor.java @@ -59,8 +59,8 @@ protected ScanIteration doScan(long cursorId, ScanOptions options) { } } - throw new IllegalArgumentException(String.format("Current scan %s state and cursor %d do not match", - state != null ? state.getCursor() : "(none)", cursorId)); + throw new IllegalArgumentException("Current scan %s state and cursor %d do not match" + .formatted(state != null ? state.getCursor() : "(none)", cursorId)); } @Override diff --git a/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceServerCommands.java b/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceServerCommands.java index 1acb7dff1c..1cf14acffd 100644 --- a/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceServerCommands.java +++ b/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceServerCommands.java @@ -173,7 +173,7 @@ public void killClient(String host, int port) { Assert.hasText(host, "Host for 'CLIENT KILL' must not be 'null' or 'empty'"); - String client = String.format("%s:%s", host, port); + String client ="%s:%d".formatted(host, port); connection.invoke().just(RedisServerAsyncCommands::clientKill, client); } diff --git a/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceZSetCommands.java b/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceZSetCommands.java index cc3e63601d..7c2219436a 100644 --- a/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceZSetCommands.java +++ b/src/main/java/org/springframework/data/redis/connection/lettuce/LettuceZSetCommands.java @@ -440,8 +440,8 @@ public Set zInterWithScores(Aggregate aggregate, Weights weights, byte[]. Assert.notNull(sets, "Sets must not be null"); Assert.noNullElements(sets, "Source sets must not contain null elements"); - Assert.isTrue(weights.size() == sets.length, () -> String - .format("The number of weights (%d) must match the number of source sets (%d)", weights.size(), sets.length)); + Assert.isTrue(weights.size() == sets.length, + "The number of weights %d must match the number of source sets %d".formatted(weights.size(), sets.length)); ZAggregateArgs zAggregateArgs = zAggregateArgs(aggregate, weights); @@ -455,8 +455,8 @@ public Long zInterStore(byte[] destKey, Aggregate aggregate, Weights weights, by Assert.notNull(destKey, "Destination key must not be null"); Assert.notNull(sets, "Source sets must not be null"); Assert.noNullElements(sets, "Source sets must not contain null elements"); - Assert.isTrue(weights.size() == sets.length, () -> String - .format("The number of weights (%d) must match the number of source sets (%d)", weights.size(), sets.length)); + Assert.isTrue(weights.size() == sets.length, + "The number of weights %d must match the number of source sets %d".formatted(weights.size(), sets.length)); ZStoreArgs storeArgs = zStoreArgs(aggregate, weights); @@ -495,8 +495,8 @@ public Set zUnionWithScores(Aggregate aggregate, Weights weights, byte[]. Assert.notNull(sets, "Sets must not be null"); Assert.noNullElements(sets, "Source sets must not contain null elements"); - Assert.isTrue(weights.size() == sets.length, () -> String - .format("The number of weights (%d) must match the number of source sets (%d)", weights.size(), sets.length)); + Assert.isTrue(weights.size() == sets.length, + "The number of weights %d must match the number of source sets %d".formatted(weights.size(), sets.length)); ZAggregateArgs zAggregateArgs = zAggregateArgs(aggregate, weights); @@ -510,8 +510,8 @@ public Long zUnionStore(byte[] destKey, Aggregate aggregate, Weights weights, by Assert.notNull(destKey, "Destination key must not be null"); Assert.notNull(sets, "Source sets must not be null"); Assert.noNullElements(sets, "Source sets must not contain null elements"); - Assert.isTrue(weights.size() == sets.length, () -> String - .format("The number of weights (%d) must match the number of source sets (%d)", weights.size(), sets.length)); + Assert.isTrue(weights.size() == sets.length, + "The number of weights %d must match the number of source sets %d".formatted(weights.size(), sets.length)); ZStoreArgs storeArgs = zStoreArgs(aggregate, weights); diff --git a/src/main/java/org/springframework/data/redis/connection/lettuce/StaticMasterReplicaConnectionProvider.java b/src/main/java/org/springframework/data/redis/connection/lettuce/StaticMasterReplicaConnectionProvider.java index 51f3d7958b..f45f9bcced 100644 --- a/src/main/java/org/springframework/data/redis/connection/lettuce/StaticMasterReplicaConnectionProvider.java +++ b/src/main/java/org/springframework/data/redis/connection/lettuce/StaticMasterReplicaConnectionProvider.java @@ -79,7 +79,7 @@ class StaticMasterReplicaConnectionProvider implements LettuceConnectionProvider return connectionType.cast(connection); } - throw new UnsupportedOperationException(String.format("Connection type %s not supported", connectionType)); + throw new UnsupportedOperationException("Connection type %s not supported".formatted(connectionType)); } @Override @@ -97,6 +97,6 @@ class StaticMasterReplicaConnectionProvider implements LettuceConnectionProvider }); } - throw new UnsupportedOperationException(String.format("Connection type %s not supported", connectionType)); + throw new UnsupportedOperationException("Connection type %s not supported".formatted(connectionType)); } } diff --git a/src/main/java/org/springframework/data/redis/connection/lettuce/observability/MicrometerTracingAdapter.java b/src/main/java/org/springframework/data/redis/connection/lettuce/observability/MicrometerTracingAdapter.java index 72aa9fdc96..863557af95 100644 --- a/src/main/java/org/springframework/data/redis/connection/lettuce/observability/MicrometerTracingAdapter.java +++ b/src/main/java/org/springframework/data/redis/connection/lettuce/observability/MicrometerTracingAdapter.java @@ -214,7 +214,7 @@ public Span start(RedisCommand command) { this.command = command; if (log.isDebugEnabled()) { - log.debug(String.format("Starting Observation for Command %s", command)); + log.debug("Starting Observation for Command %s".formatted(command)); } if (command instanceof CompleteableCommand completeableCommand) { @@ -262,7 +262,7 @@ public Span tag(String key, String value) { public Span error(Throwable throwable) { if (log.isDebugEnabled()) { - log.debug(String.format("Attaching error to Observation for Command %s", command)); + log.debug("Attaching error to Observation for Command %s".formatted(command)); } observation.error(throwable); @@ -280,7 +280,7 @@ public Span remoteEndpoint(Endpoint endpoint) { public void finish() { if (log.isDebugEnabled()) { - log.debug(String.format("Stopping Observation for Command %s", command)); + log.debug("Stopping Observation for Command %s".formatted(command)); } observation.stop(); diff --git a/src/main/java/org/springframework/data/redis/connection/stream/Consumer.java b/src/main/java/org/springframework/data/redis/connection/stream/Consumer.java index 00add551b2..d3dc761c78 100644 --- a/src/main/java/org/springframework/data/redis/connection/stream/Consumer.java +++ b/src/main/java/org/springframework/data/redis/connection/stream/Consumer.java @@ -53,7 +53,7 @@ public static Consumer from(String group, String name) { @Override public String toString() { - return String.format("%s:%s", group, name); + return "%s:%s".formatted(group, name); } public String getGroup() { diff --git a/src/main/java/org/springframework/data/redis/connection/stream/StreamRecords.java b/src/main/java/org/springframework/data/redis/connection/stream/StreamRecords.java index 47536fc5ac..eb3cb99c4e 100644 --- a/src/main/java/org/springframework/data/redis/connection/stream/StreamRecords.java +++ b/src/main/java/org/springframework/data/redis/connection/stream/StreamRecords.java @@ -216,7 +216,8 @@ public ByteBufferRecord ofBuffer(Map value) { } else if (stream instanceof byte[]) { streamKey = ByteBuffer.wrap((byte[]) stream); } else { - throw new IllegalArgumentException(String.format("Stream key %s cannot be converted to byte buffer", stream)); + throw new IllegalArgumentException("Stream key %s cannot be converted to byte buffer" + .formatted(stream)); } return new ByteBufferMapBackedRecord(streamKey, id, value); diff --git a/src/main/java/org/springframework/data/redis/core/IndexWriter.java b/src/main/java/org/springframework/data/redis/core/IndexWriter.java index f933112b60..afc6eaae0a 100644 --- a/src/main/java/org/springframework/data/redis/core/IndexWriter.java +++ b/src/main/java/org/springframework/data/redis/core/IndexWriter.java @@ -237,8 +237,8 @@ protected void addKeyToIndex(byte[] key, IndexedData indexedData) { // keep track of indexes used for the object connection.sAdd(ByteUtils.concatAll(toBytes(indexedData.getKeyspace() + ":"), key, toBytes(":idx")), indexKey); } else { - throw new IllegalArgumentException( - String.format("Cannot write index data for unknown index type %s", indexedData.getClass())); + throw new IllegalArgumentException("Cannot write index data for unknown index type %s" + .formatted(indexedData.getClass())); } } @@ -256,10 +256,10 @@ private byte[] toBytes(@Nullable Object source) { return converter.getConversionService().convert(source, byte[].class); } - throw new InvalidDataAccessApiUsageException(String.format( - "Cannot convert %s to binary representation for index key generation; " - + "Are you missing a Converter; Did you register a non PathBasedRedisIndexDefinition that might apply to a complex type", - source.getClass())); + throw new InvalidDataAccessApiUsageException( + ("Cannot convert %s to binary representation for index key generation;" + + " Are you missing a Converter; Did you register a non PathBasedRedisIndexDefinition" + + " that might apply to a complex type").formatted(source.getClass())); } /** 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 12da22abac..824864e3ae 100644 --- a/src/main/java/org/springframework/data/redis/core/RedisCommand.java +++ b/src/main/java/org/springframework/data/redis/core/RedisCommand.java @@ -377,16 +377,17 @@ public void validateArgumentCount(int argumentCount) { if (requiresArguments()) { if (requiresExactNumberOfArguments()) { if (argumentCount != this.maxArgs) { - throw newIllegalArgumentException("%s command requires %d %s", name(), this.maxArgs, arguments(this.maxArgs)); + throw new IllegalArgumentException("%s command requires %d %s" + .formatted(name(), this.maxArgs, arguments(this.maxArgs))); } } if (argumentCount < this.minArgs) { - throw newIllegalArgumentException("%s command requires at least %d %s", name(), this.minArgs, - arguments(this.maxArgs)); + throw new IllegalArgumentException("%s command requires at least %d %s" + .formatted(name(), this.minArgs, arguments(this.maxArgs))); } if (this.maxArgs > 0 && argumentCount > this.maxArgs) { - throw newIllegalArgumentException("%s command requires at most %s %s", name(), this.maxArgs, - arguments(this.maxArgs)); + throw new IllegalArgumentException("%s command requires at most %s %s" + .formatted(name(), this.maxArgs, arguments(this.maxArgs))); } } } @@ -394,9 +395,4 @@ public void validateArgumentCount(int argumentCount) { private String arguments(int count) { return count == 1 ? "argument" : "arguments"; } - - private IllegalArgumentException newIllegalArgumentException(String message, Object... arguments) { - return new IllegalArgumentException(String.format(message, arguments)); - } - } 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 2956c3d88a..7436efc25d 100644 --- a/src/main/java/org/springframework/data/redis/core/RedisConnectionUtils.java +++ b/src/main/java/org/springframework/data/redis/core/RedisConnectionUtils.java @@ -471,14 +471,14 @@ public Object intercept(Object obj, Method method, Object[] args) throws Throwab if (isPotentiallyThreadBoundCommand(commandToExecute)) { if (log.isDebugEnabled()) { - log.debug(String.format("Invoke '%s' on bound connection", method.getName())); + log.debug("Invoke '%s' on bound connection".formatted(method.getName())); } return invoke(method, obj, args); } if (log.isDebugEnabled()) { - log.debug(String.format("Invoke '%s' on unbound connection", method.getName())); + log.debug("Invoke '%s' on unbound connection".formatted(method.getName())); } RedisConnection connection = factory.getConnection(); 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 f15e0966b5..2a8275dcca 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 @@ -289,7 +289,7 @@ public Date convert(byte[] source) { } catch (ParseException ignore) { } - throw new IllegalArgumentException(String.format("Cannot parse date out of %s", Arrays.toString(source))); + throw new IllegalArgumentException("Cannot parse date out of %s".formatted(Arrays.toString(source))); } } 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 d53db84f77..dec80299ba 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 @@ -539,9 +539,8 @@ private void writePartialPropertyUpdate(PartialUpdate update, PropertyUpdate } else if (pUpdate.getValue() instanceof Entry) { map.put(((Entry) pUpdate.getValue()).getKey(), ((Entry) pUpdate.getValue()).getValue()); } else { - throw new MappingException( - String.format("Cannot set update value for map property '%s' to '%s'; Please use a Map or Map.Entry", - pUpdate.getPropertyPath(), pUpdate.getValue())); + throw new MappingException(("Cannot set update value for map property '%s' to '%s';" + + " Please use a Map or Map.Entry").formatted(pUpdate.getPropertyPath(), pUpdate.getValue())); } writeMap(entity.getKeySpace(), pUpdate.getPropertyPath(), targetProperty.getMapValueType(), map, sink); @@ -601,8 +600,8 @@ private void writeInternal(@Nullable String keyspace, String path, @Nullable Obj } else { if (!ClassUtils.isAssignable(typeHint.getType(), value.getClass())) { - throw new MappingException( - String.format(INVALID_TYPE_ASSIGNMENT, value.getClass(), path, typeHint.getType())); + throw new MappingException(INVALID_TYPE_ASSIGNMENT + .formatted(value.getClass(), path, typeHint.getType())); } writeToBucket(path, value, sink, typeHint.getType()); } @@ -750,8 +749,8 @@ private void writeCollection(@Nullable String keyspace, String path, @Nullable I String currentPath = path + (path.equals("") ? "" : ".") + "[" + i + "]"; if (!ClassUtils.isAssignable(typeHint.getType(), value.getClass())) { - throw new MappingException( - String.format(INVALID_TYPE_ASSIGNMENT, value.getClass(), currentPath, typeHint.getType())); + throw new MappingException(INVALID_TYPE_ASSIGNMENT + .formatted(value.getClass(), currentPath, typeHint.getType())); } if (customConversions.hasCustomWriteTarget(value.getClass())) { @@ -793,8 +792,8 @@ private void writeToBucket(String path, @Nullable Object value, RedisData sink, } else if (targetType.filter(it -> ClassUtils.isAssignable(byte[].class, it)).isPresent()) { sink.getBucket().put(path, toBytes(value)); } else { - throw new IllegalArgumentException( - String.format("Cannot convert value '%s' of type %s to bytes", value, value.getClass())); + throw new IllegalArgumentException("Cannot convert value '%s' of type %s to bytes" + .formatted(value, value.getClass())); } } } @@ -854,8 +853,8 @@ private void writeMap(@Nullable String keyspace, String path, Class mapValueT String currentPath = path + ".[" + mapMapKey(entry.getKey()) + "]"; if (!ClassUtils.isAssignable(mapValueType, entry.getValue().getClass())) { - throw new MappingException( - String.format(INVALID_TYPE_ASSIGNMENT, entry.getValue().getClass(), currentPath, mapValueType)); + throw new MappingException(INVALID_TYPE_ASSIGNMENT + .formatted(entry.getValue().getClass(), currentPath, mapValueType)); } if (customConversions.hasCustomWriteTarget(entry.getValue().getClass())) { @@ -945,8 +944,8 @@ private Object extractMapKeyForPath(String path, String key, Class targetType Matcher matcher = pattern.matcher(key); if (!matcher.find()) { - throw new IllegalArgumentException( - String.format("Cannot extract map value for key '%s' in path '%s'.", key, path)); + throw new IllegalArgumentException("Cannot extract map value for key '%s' in path '%s'" + .formatted(key, path)); } Object mapKey = matcher.group(2); @@ -1219,7 +1218,7 @@ private KeyspaceIdentifier(String keyspace, String id, boolean phantomKey) { */ public static KeyspaceIdentifier of(String key) { - Assert.isTrue(isValid(key), String.format("Invalid key %s", key)); + Assert.isTrue(isValid(key), () -> "Invalid key %s".formatted(key)); boolean phantomKey = key.endsWith(PHANTOM_SUFFIX); int keyspaceEndIndex = key.indexOf(DELIMITER); @@ -1299,7 +1298,7 @@ private BinaryKeyspaceIdentifier(byte[] keyspace, byte[] id, boolean phantomKey) */ public static BinaryKeyspaceIdentifier of(byte[] key) { - Assert.isTrue(isValid(key), String.format("Invalid key %s", new String(key))); + Assert.isTrue(isValid(key), () -> "Invalid key %s".formatted(new String(key))); boolean phantomKey = ByteUtils.startsWith(key, PHANTOM_SUFFIX, key.length - PHANTOM_SUFFIX.length); diff --git a/src/main/java/org/springframework/data/redis/core/index/GeoIndexDefinition.java b/src/main/java/org/springframework/data/redis/core/index/GeoIndexDefinition.java index dcf88f8f10..8ecdc37322 100644 --- a/src/main/java/org/springframework/data/redis/core/index/GeoIndexDefinition.java +++ b/src/main/java/org/springframework/data/redis/core/index/GeoIndexDefinition.java @@ -65,9 +65,8 @@ public Point convert(@Nullable Object source) { return ((GeoLocation) source).getPoint(); } - throw new IllegalArgumentException( - String.format("Cannot convert %s to %s; GeoIndexed property needs to be of type Point or GeoLocation", - source.getClass(), Point.class)); + throw new IllegalArgumentException(("Cannot convert %s to %s; GeoIndexed property needs to be of type Point" + + " or GeoLocation").formatted(source.getClass(), Point.class)); } } } diff --git a/src/main/java/org/springframework/data/redis/core/mapping/BasicRedisPersistentEntity.java b/src/main/java/org/springframework/data/redis/core/mapping/BasicRedisPersistentEntity.java index 14c49a4572..81140150cc 100644 --- a/src/main/java/org/springframework/data/redis/core/mapping/BasicRedisPersistentEntity.java +++ b/src/main/java/org/springframework/data/redis/core/mapping/BasicRedisPersistentEntity.java @@ -25,6 +25,8 @@ import org.springframework.lang.Nullable; import org.springframework.util.Assert; +import kotlin.reflect.jvm.internal.impl.util.Check; + /** * {@link RedisPersistentEntity} implementation. * @@ -89,16 +91,14 @@ protected RedisPersistentProperty returnPropertyIfBetterIdPropertyCandidateOrNul boolean newIdPropertyIsExplicit = property.isAnnotationPresent(Id.class); if (currentIdPropertyIsExplicit && newIdPropertyIsExplicit) { - throw new MappingException(String.format( - "Attempt to add explicit id property %s but already have an property %s registered " - + "as explicit id; Check your mapping configuration", - property.getField(), currentIdProperty.getField())); + throw new MappingException(("Attempt to add explicit id property %s but already have a property %s" + + " registered as explicit id; Check your mapping configuration") + .formatted(property.getField(), currentIdProperty.getField())); } if (!currentIdPropertyIsExplicit && !newIdPropertyIsExplicit) { - throw new MappingException( - String.format("Attempt to add id property %s but already have an property %s registered " - + "as id; Check your mapping configuration", property.getField(), currentIdProperty.getField())); + throw new MappingException(("Attempt to add id property %s but already have a property %s registered as id;" + + " Check your mapping configuration").formatted(property.getField(), currentIdProperty.getField())); } if (newIdPropertyIsExplicit) { 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 653d2533fc..1dfb6dce7e 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 @@ -241,17 +241,14 @@ public Long getTimeToLive(Object source) { return TimeUnit.SECONDS.convert(timeout.longValue(), ttl.unit()); } } catch (IllegalAccessException ex) { - String message = String.format("Not allowed to access method '%s': %s", - timeoutMethod.getName(), ex.getMessage()); - throw new IllegalStateException(message, ex); + throw new IllegalStateException("Not allowed to access method '%s': %s" + .formatted(timeoutMethod.getName(), ex.getMessage()), ex); } catch (IllegalArgumentException ex) { - String message = String.format("Cannot invoke method '%s' without arguments: %s", - timeoutMethod.getName(), ex.getMessage()); - throw new IllegalStateException(message, ex); + throw new IllegalStateException("Cannot invoke method '%s' without arguments: %s" + .formatted(timeoutMethod.getName(), ex.getMessage()), ex); } catch (InvocationTargetException ex) { - String message = String.format("Cannot access method '%s': %s", - timeoutMethod.getName(), ex.getMessage()); - throw new IllegalStateException(message, ex); + throw new IllegalStateException("Cannot access method '%s': %s" + .formatted(timeoutMethod.getName(), ex.getMessage()), ex); } } } 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 60746f4027..3be3db61e1 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,8 +60,7 @@ private static MessageDigest getDigest(String algorithm) { try { return MessageDigest.getInstance(algorithm); } catch (NoSuchAlgorithmException ex) { - String message = String.format("Could not find MessageDigest with algorithm \"%s\"", algorithm); - throw new IllegalStateException(message, ex); + throw new IllegalStateException("MessageDigest with algorithm '%s' not found".formatted(algorithm), 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 04b103a9d3..cd89734744 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 @@ -274,8 +274,8 @@ public static RedisClientInfo fromString(String source) { try { properties.load(new StringReader(source.replace(' ', '\n'))); } catch (IOException ex) { - String message = String.format("Properties could not be loaded from String '%s'", source); - throw new IllegalArgumentException(message, ex); + throw new IllegalArgumentException("Properties could not be loaded from String '%s'".formatted(source), + ex); } return new RedisClientInfo(properties); } diff --git a/src/main/java/org/springframework/data/redis/domain/geo/BoundingBox.java b/src/main/java/org/springframework/data/redis/domain/geo/BoundingBox.java index 1881c50831..cdda731355 100644 --- a/src/main/java/org/springframework/data/redis/domain/geo/BoundingBox.java +++ b/src/main/java/org/springframework/data/redis/domain/geo/BoundingBox.java @@ -106,6 +106,6 @@ public boolean equals(@Nullable Object o) { @Override public String toString() { - return String.format("Bounding box: [width=%s, height=%s]", width, height); + return "Bounding box: [width=%s, height=%s]".formatted(width, height); } } 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 267cd9891d..c6236816d8 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(String.format("Cannot describe object %s", object), ex); + throw new IllegalArgumentException("Cannot describe object %s".formatted(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 245d507b19..d8ef4e5371 100644 --- a/src/main/java/org/springframework/data/redis/hash/Jackson2HashMapper.java +++ b/src/main/java/org/springframework/data/redis/hash/Jackson2HashMapper.java @@ -425,8 +425,8 @@ private void flattenElement(String propertyPrefix, Object source, Map t Collection collection = resolveMessageListeners(this.channelMapping, serializedTopic); collection.add(listener); channels.add(serializedTopic.getArray()); - logTrace(() -> String.format("Adding listener '%s' on channel '%s'", listener, topic.getTopic())); + logTrace(() -> "Adding listener '%s' on channel '%s'".formatted(listener, topic.getTopic())); } else if (topic instanceof PatternTopic) { Collection collection = resolveMessageListeners(this.patternMapping, serializedTopic); collection.add(listener); patterns.add(serializedTopic.getArray()); - logTrace(() -> String.format("Adding listener '%s' for pattern '%s'", listener, topic.getTopic())); + logTrace(() -> "Adding listener '%s' for pattern '%s'".formatted(listener, topic.getTopic())); } else { - throw new IllegalArgumentException(String.format("Unknown topic type '%s'", topic.getClass())); + throw new IllegalArgumentException("Unknown topic type '%s'".formatted(topic.getClass())); } } boolean wasListening = isListening(); @@ -754,12 +754,12 @@ private void removeListener(@Nullable MessageListener listener, Collection String.format("Removing listener '%s' from channel '%s'", listener, topic.getTopic())); + logTrace(() -> "Removing listener '%s' from channel '%s'".formatted(listener, topic.getTopic())); } else if (topic instanceof PatternTopic) { remove(listener, topic, holder, patternMapping, patternsToRemove); - logTrace(() -> String.format("Removing listener '%s' from pattern '%s'", listener, topic.getTopic())); + logTrace(() -> "Removing listener '%s' from pattern '%s'".formatted(listener, topic.getTopic())); } } @@ -880,9 +880,8 @@ protected void handleSubscriptionException(CompletableFuture future, BackO long recoveryInterval = backOffExecution.nextBackOff(); if (recoveryInterval != BackOffExecution.STOP) { - String message = String.format("Connection failure occurred: %s; Restarting subscription task after %s ms", - cause, recoveryInterval); - logger.error(message, cause); + logger.error("Connection failure occurred: %s; Restarting subscription task after %s ms" + .formatted(cause, recoveryInterval), cause); } return recoveryInterval; 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 f652faafd4..68c60487ec 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 @@ -375,13 +375,12 @@ protected void invokeListenerMethod(String methodName, Object[] arguments) { if (targetEx instanceof DataAccessException dataAccessException) { throw dataAccessException; } else { - String message = String.format("Listener method '%s' threw exception", methodName); - throw new RedisListenerExecutionFailedException(message, targetEx); + throw new RedisListenerExecutionFailedException("Listener method '%s' threw exception" + .formatted(methodName), targetEx); } } catch (Throwable ex) { - String message = String.format("Failed to invoke target method '%s' with arguments %s", methodName, - ObjectUtils.nullSafeToString(arguments)); - throw new RedisListenerExecutionFailedException(message, ex); + throw new RedisListenerExecutionFailedException("Failed to invoke target method '%s' with arguments %s" + .formatted(methodName, ObjectUtils.nullSafeToString(arguments)), ex); } } 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 a13253738d..eb3f380fb4 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 @@ -149,8 +149,7 @@ public final void initialize() { public void destroy(T instance, CreationalContext creationalContext) { if (log.isDebugEnabled()) { - log.debug(String.format("Destroying bean instance %s for repository type '%s'.", instance.toString(), - beanClass.getName())); + log.debug("Destroying bean instance %s for repository type '%s'".formatted(instance, beanClass.getName())); } creationalContext.release(); @@ -206,7 +205,7 @@ public String getId() { @Override public String toString() { - return String.format("CdiBean: type='%s', qualifiers=%s", beanClass.getName(), qualifiers.toString()); + return "CdiBean: type='%s', qualifiers=%s".formatted(beanClass.getName(), qualifiers.toString()); } } 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 9a345ed837..a4d5969394 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 @@ -80,7 +80,7 @@ void processBean(@Observes ProcessBean processBean) { if (beanType instanceof Class && RedisKeyValueTemplate.class.isAssignableFrom((Class) beanType)) { if (log.isDebugEnabled()) { - log.debug(String.format("Discovered %s with qualifiers %s.", RedisKeyValueTemplate.class.getName(), + log.debug("Discovered %s with qualifiers %s.".formatted(RedisKeyValueTemplate.class.getName(), bean.getQualifiers())); } @@ -90,7 +90,7 @@ void processBean(@Observes ProcessBean processBean) { if (beanType instanceof Class && RedisKeyValueAdapter.class.isAssignableFrom((Class) beanType)) { if (log.isDebugEnabled()) { - log.debug(String.format("Discovered %s with qualifiers %s.", RedisKeyValueAdapter.class.getName(), + log.debug("Discovered %s with qualifiers %s.".formatted(RedisKeyValueAdapter.class.getName(), bean.getQualifiers())); } @@ -100,7 +100,7 @@ void processBean(@Observes ProcessBean processBean) { if (beanType instanceof Class && RedisOperations.class.isAssignableFrom((Class) beanType)) { if (log.isDebugEnabled()) { - log.debug(String.format("Discovered %s with qualifiers %s.", RedisOperations.class.getName(), + log.debug("Discovered %s with qualifiers %s.".formatted(RedisOperations.class.getName(), bean.getQualifiers())); } @@ -123,7 +123,7 @@ void afterBeanDiscovery(@Observes AfterBeanDiscovery afterBeanDiscovery, BeanMan CdiRepositoryBean repositoryBean = createRepositoryBean(repositoryType, qualifiers, beanManager); if (log.isInfoEnabled()) { - log.info(String.format("Registering bean for %s with qualifiers %s.", repositoryType.getName(), qualifiers)); + log.info("Registering bean for %s with qualifiers %s.".formatted(repositoryType.getName(), qualifiers)); } // Register the bean to the container. @@ -148,8 +148,8 @@ private void registerDependenciesIfNecessary(@Observes AfterBeanDiscovery afterB if (!redisKeyValueAdapters.containsKey(qualifiers)) { if (log.isInfoEnabled()) { - log.info(String.format("Registering bean for %s with qualifiers %s.", RedisKeyValueAdapter.class.getName(), - qualifiers)); + log.info("Registering bean for %s with qualifiers %s." + .formatted(RedisKeyValueAdapter.class.getName(), qualifiers)); } RedisKeyValueAdapterBean redisKeyValueAdapterBean = createRedisKeyValueAdapterBean(qualifiers, beanManager); redisKeyValueAdapters.put(qualifiers, redisKeyValueAdapterBean); @@ -158,8 +158,8 @@ private void registerDependenciesIfNecessary(@Observes AfterBeanDiscovery afterB if (!redisKeyValueTemplates.containsKey(qualifiers)) { if (log.isInfoEnabled()) { - log.info(String.format("Registering bean for %s with qualifiers %s.", RedisKeyValueTemplate.class.getName(), - qualifiers)); + log.info("Registering bean for %s with qualifiers %s." + .formatted(RedisKeyValueTemplate.class.getName(), qualifiers)); } RedisKeyValueTemplateBean redisKeyValueTemplateBean = createRedisKeyValueTemplateBean(qualifiers, beanManager); @@ -186,8 +186,8 @@ private CdiRepositoryBean createRepositoryBean(Class repositoryType, S Bean redisKeyValueTemplate = this.redisKeyValueTemplates.get(qualifiers); if (redisKeyValueTemplate == null) { - throw new UnsatisfiedResolutionException(String.format("Unable to resolve a bean for '%s' with qualifiers %s.", - RedisKeyValueTemplate.class.getName(), qualifiers)); + throw new UnsatisfiedResolutionException("Unable to resolve a bean for '%s' with qualifiers %s" + .formatted(RedisKeyValueTemplate.class.getName(), qualifiers)); } // Construct and return the repository bean. @@ -208,8 +208,8 @@ private RedisKeyValueAdapterBean createRedisKeyValueAdapterBean(Set Bean> redisOperationsBean = this.redisOperations.get(qualifiers); if (redisOperationsBean == null) { - throw new UnsatisfiedResolutionException(String.format("Unable to resolve a bean for '%s' with qualifiers %s.", - RedisOperations.class.getName(), qualifiers)); + throw new UnsatisfiedResolutionException("Unable to resolve a bean for '%s' with qualifiers %s." + .formatted(RedisOperations.class.getName(), qualifiers)); } // Construct and return the repository bean. @@ -230,8 +230,8 @@ private RedisKeyValueTemplateBean createRedisKeyValueTemplateBean(Set redisKeyValueAdapterBean = this.redisKeyValueAdapters.get(qualifiers); if (redisKeyValueAdapterBean == null) { - throw new UnsatisfiedResolutionException(String.format("Unable to resolve a bean for '%s' with qualifiers %s.", - RedisKeyValueAdapter.class.getName(), qualifiers)); + throw new UnsatisfiedResolutionException("Unable to resolve a bean for '%s' with qualifiers %s" + .formatted(RedisKeyValueAdapter.class.getName(), qualifiers)); } // Construct and return the repository bean. diff --git a/src/main/java/org/springframework/data/redis/repository/core/MappingRedisEntityInformation.java b/src/main/java/org/springframework/data/redis/repository/core/MappingRedisEntityInformation.java index ef8355c1f1..b5666364bd 100644 --- a/src/main/java/org/springframework/data/redis/repository/core/MappingRedisEntityInformation.java +++ b/src/main/java/org/springframework/data/redis/repository/core/MappingRedisEntityInformation.java @@ -40,10 +40,8 @@ public MappingRedisEntityInformation(RedisPersistentEntity entity) { super(entity); if (!entity.hasIdProperty()) { - - throw new MappingException( - String.format("Entity %s requires to have an explicit id field; Did you forget to provide one using @Id", - entity.getName())); + throw new MappingException(("Entity %s requires to have an explicit id field;" + + " Did you forget to provide one using @Id").formatted(entity.getName())); } } } diff --git a/src/main/java/org/springframework/data/redis/repository/query/ExampleQueryMapper.java b/src/main/java/org/springframework/data/redis/repository/query/ExampleQueryMapper.java index 8838ebae80..3cbd2b8582 100644 --- a/src/main/java/org/springframework/data/redis/repository/query/ExampleQueryMapper.java +++ b/src/main/java/org/springframework/data/redis/repository/query/ExampleQueryMapper.java @@ -138,9 +138,8 @@ private void applyPropertySpec(String path, Predicate hasIndex, ExampleM } if (!SUPPORTED_MATCHERS.contains(stringMatcher)) { - throw new InvalidDataAccessApiUsageException( - String.format("Redis Query-by-Example does not support string matcher %s; Supported matchers are: %s.", - stringMatcher, SUPPORTED_MATCHERS)); + throw new InvalidDataAccessApiUsageException(("Redis Query-by-Example does not support string matcher %s;" + + " Supported matchers are: %s.").formatted(stringMatcher, SUPPORTED_MATCHERS)); } if (exampleSpecAccessor.hasPropertySpecifier(path)) { 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 1b6afa8a43..60a2762aa3 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 @@ -17,6 +17,7 @@ import java.util.Iterator; +import org.springframework.dao.DataAccessException; import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.data.domain.Sort; import org.springframework.data.geo.Circle; @@ -57,10 +58,8 @@ private RedisOperationChain from(Part part, Iterator iterator, RedisOper case TRUE -> sink.sismember(part.getProperty().toDotPath(), true); case FALSE -> sink.sismember(part.getProperty().toDotPath(), false); case WITHIN, NEAR -> sink.near(getNearPath(part, iterator)); - default -> { - String message = String.format("%s is not supported for Redis query derivation", part.getType()); - throw new IllegalArgumentException(message); - } + default -> throw new IllegalArgumentException("%s is not supported for Redis query derivation" + .formatted(part.getType())); } return sink; @@ -112,28 +111,23 @@ private NearPath getNearPath(Part part, Iterator iterator) { point = (Point) value; if (!iterator.hasNext()) { - String message = "Expected to find distance value for geo query; Are you missing a parameter"; - throw new InvalidDataAccessApiUsageException(message); + throw new InvalidDataAccessApiUsageException("Expected to find distance value for geo query;" + + " Are you missing a parameter"); } Object distObject = iterator.next(); + if (distObject instanceof Distance) { distance = (Distance) distObject; } else if (distObject instanceof Number) { distance = new Distance(((Number) distObject).doubleValue(), Metrics.KILOMETERS); } else { - - String message = String.format("Expected to find Distance or Numeric value for geo query but was %s", - distObject.getClass()); - - throw new InvalidDataAccessApiUsageException(message); + throw new InvalidDataAccessApiUsageException("Expected to find Distance or Numeric value for geo query;" + + " but was %s".formatted(distObject.getClass())); } } else { - - String message = String.format("Expected to find a Circle or Point/Distance for geo query but was %s.", - value.getClass()); - - throw new InvalidDataAccessApiUsageException(message); + throw new InvalidDataAccessApiUsageException("Expected to find a Circle or Point/Distance for geo query;" + + " but was %s".formatted(value.getClass())); } return new NearPath(part.getProperty().toDotPath(), point, distance); diff --git a/src/main/java/org/springframework/data/redis/serializer/DefaultRedisElementWriter.java b/src/main/java/org/springframework/data/redis/serializer/DefaultRedisElementWriter.java index 4d4cb3b707..11f520d890 100644 --- a/src/main/java/org/springframework/data/redis/serializer/DefaultRedisElementWriter.java +++ b/src/main/java/org/springframework/data/redis/serializer/DefaultRedisElementWriter.java @@ -18,6 +18,7 @@ import java.nio.ByteBuffer; import org.springframework.lang.Nullable; +import org.springframework.util.ObjectUtils; /** * Default implementation of {@link RedisElementWriter}. @@ -38,7 +39,8 @@ class DefaultRedisElementWriter implements RedisElementWriter { public ByteBuffer write(@Nullable T value) { if (serializer != null && (value == null || serializer.canSerialize(value.getClass()))) { - return ByteBuffer.wrap(serializer.serialize(value)); + byte[] serializedValue = serializer.serialize(value); + return serializedValue != null ? ByteBuffer.wrap(serializedValue) : ByteBuffer.wrap(new byte[0]); } if (value instanceof byte[]) { @@ -49,7 +51,7 @@ public ByteBuffer write(@Nullable T value) { return (ByteBuffer) value; } - throw new IllegalStateException( - String.format("Cannot serialize value of type %s without a serializer", value.getClass())); + throw new IllegalStateException("Cannot serialize value of type %s without a serializer" + .formatted(ObjectUtils.nullSafeClassName(value))); } } diff --git a/src/main/java/org/springframework/data/redis/serializer/GenericJackson2JsonRedisSerializer.java b/src/main/java/org/springframework/data/redis/serializer/GenericJackson2JsonRedisSerializer.java index a85ddd17f9..7ef1d781bd 100644 --- a/src/main/java/org/springframework/data/redis/serializer/GenericJackson2JsonRedisSerializer.java +++ b/src/main/java/org/springframework/data/redis/serializer/GenericJackson2JsonRedisSerializer.java @@ -251,8 +251,7 @@ public byte[] serialize(@Nullable Object value) throws SerializationException { try { return writer.write(mapper, value); } catch (IOException ex) { - String message = String.format("Could not write JSON: %s", ex.getMessage()); - throw new SerializationException(message, ex); + throw new SerializationException("Could not write JSON: %s".formatted(ex.getMessage()), ex); } } @@ -288,8 +287,7 @@ public T deserialize(@Nullable byte[] source, Class type) throws Serializ try { return (T) reader.read(mapper, source, resolveType(source, type)); } catch (Exception ex) { - String message = String.format("Could not read JSON:%s ", ex.getMessage()); - throw new SerializationException(message, ex); + throw new SerializationException("Could not read JSON:%s ".formatted(ex.getMessage()), 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 19b3a10d3f..e46a38fc9c 100644 --- a/src/main/java/org/springframework/data/redis/stream/DefaultStreamReceiver.java +++ b/src/main/java/org/springframework/data/redis/stream/DefaultStreamReceiver.java @@ -105,7 +105,7 @@ class DefaultStreamReceiver> implements StreamReceiver public Flux receive(StreamOffset streamOffset) { if (logger.isDebugEnabled()) { - logger.debug(String.format("receive(%s)", streamOffset)); + logger.debug("receive(%s)".formatted(streamOffset)); } RedisSerializationContext.SerializationPair keySerializer = template.getSerializationContext() @@ -125,11 +125,10 @@ public Flux receive(StreamOffset streamOffset) { } @Override - @SuppressWarnings("unchecked") public Flux receiveAutoAck(Consumer consumer, StreamOffset streamOffset) { if (logger.isDebugEnabled()) { - logger.debug(String.format("receiveAutoAck(%s, %s)", consumer, streamOffset)); + logger.debug("receiveAutoAck(%s, %s)".formatted(consumer, streamOffset)); } Function> readFunction = getConsumeReadFunction(streamOffset.getKey(), consumer, @@ -146,11 +145,10 @@ public Flux receiveAutoAck(Consumer consumer, StreamOffset streamOffset) { } @Override - @SuppressWarnings("unchecked") public Flux receive(Consumer consumer, StreamOffset streamOffset) { if (logger.isDebugEnabled()) { - logger.debug(String.format("receive(%s, %s)", consumer, streamOffset)); + logger.debug("receive(%s, %s)".formatted(consumer, streamOffset)); } Function> readFunction = getConsumeReadFunction(streamOffset.getKey(), consumer, @@ -229,7 +227,7 @@ void arm() { sink.onRequest(toAdd -> { if (logger.isDebugEnabled()) { - logger.debug(String.format("[stream: %s] onRequest(%d)", key, toAdd)); + logger.debug("[stream: %s] onRequest(%d)".formatted(key, toAdd)); } if (pollState.isSubscriptionActive()) { @@ -251,7 +249,8 @@ void arm() { } } else { if (logger.isDebugEnabled()) { - logger.debug(String.format("[stream: %s] onRequest(%d): Dropping, subscription canceled", key, toAdd)); + logger.debug("[stream: %s] onRequest(%d): Dropping, subscription canceled" + .formatted(key, toAdd)); } } }); @@ -263,26 +262,26 @@ void arm() { private void scheduleIfRequired() { if (logger.isDebugEnabled()) { - logger.debug(String.format("[stream: %s] scheduleIfRequired()", key)); + logger.debug("[stream: %s] scheduleIfRequired()".formatted(key)); } if (pollState.isScheduled()) { if (logger.isDebugEnabled()) { - logger.debug(String.format("[stream: %s] scheduleIfRequired(): Already scheduled", key)); + logger.debug("[stream: %s] scheduleIfRequired(): Already scheduled".formatted(key)); } return; } if (!pollState.isSubscriptionActive()) { if (logger.isDebugEnabled()) { - logger.debug(String.format("[stream: %s] scheduleIfRequired(): Subscription cancelled", key)); + logger.debug("[stream: %s] scheduleIfRequired(): Subscription cancelled".formatted(key)); } return; } if (pollState.getRequested() > 0 && !overflow.isEmpty()) { if (logger.isDebugEnabled()) { - logger.info(String.format("[stream: %s] scheduleIfRequired(): Requested: %d Emit from buffer", key, - pollState.getRequested())); + logger.info("[stream: %s] scheduleIfRequired(): Requested: %d Emit from buffer" + .formatted(key, pollState.getRequested())); } emitBuffer(); } @@ -290,8 +289,8 @@ private void scheduleIfRequired() { if (pollState.getRequested() == 0) { if (logger.isDebugEnabled()) { - logger.debug(String - .format("[stream: %s] scheduleIfRequired(): Subscriber has no demand; Suspending subscription", key)); + logger.debug("[stream: %s] scheduleIfRequired(): Subscriber has no demand; Suspending subscription" + .formatted(key)); } return; } @@ -303,14 +302,14 @@ private void scheduleIfRequired() { if (pollState.activateSchedule()) { if (logger.isDebugEnabled()) { - logger.debug(String.format("[stream: %s] scheduleIfRequired(): Activating subscription", key)); + logger.debug("[stream: %s] scheduleIfRequired(): Activating subscription".formatted(key)); } ReadOffset readOffset = pollState.getCurrentReadOffset(); if (logger.isDebugEnabled()) { - logger.debug( - String.format("[stream: %s] scheduleIfRequired(): Activating subscription, offset %s", key, readOffset)); + logger.debug("[stream: %s] scheduleIfRequired(): Activating subscription, offset %s" + .formatted(key, readOffset)); } Flux poll = readFunction.apply(readOffset) @@ -319,7 +318,7 @@ private void scheduleIfRequired() { poll.map(it -> { if (logger.isDebugEnabled()) { - logger.debug(String.format("[stream: %s] onStreamMessage(%s)", key, it)); + logger.debug("[stream: %s] onStreamMessage(%s)".formatted(key, it)); } pollState.updateReadOffset(it.getId().getValue()); @@ -357,7 +356,7 @@ public void onError(Throwable t) { public void onComplete() { if (logger.isDebugEnabled()) { - logger.debug(String.format("[stream: %s] onComplete()", key)); + logger.debug("[stream: %s] onComplete()".formatted(key)); } pollState.scheduleCompleted(); @@ -381,20 +380,23 @@ private void onStreamMessage(V message) { if (requested == Long.MAX_VALUE) { if (logger.isDebugEnabled()) { - logger.debug(String.format("[stream: %s] onStreamMessage(%s): Emitting item, fast-path", key, message)); + logger.debug("[stream: %s] onStreamMessage(%s): Emitting item, fast-path" + .formatted(key, message)); } sink.next(message); } else { if (pollState.decrementRequested()) { if (logger.isDebugEnabled()) { - logger.debug(String.format("[stream: %s] onStreamMessage(%s): Emitting item, slow-path", key, message)); + logger.debug("[stream: %s] onStreamMessage(%s): Emitting item, slow-path" + .formatted(key, message)); } sink.next(message); } else { if (logger.isDebugEnabled()) { - logger.debug(String.format("[stream: %s] onStreamMessage(%s): Buffering overflow", key, message)); + logger.debug("[stream: %s] onStreamMessage(%s): Buffering overflow" + .formatted(key, message)); } overflow.offer(message); } @@ -403,7 +405,7 @@ private void onStreamMessage(V message) { } else { if (logger.isDebugEnabled()) { - logger.debug(String.format("[stream: %s] onStreamMessage(%s): Buffering overflow", key, message)); + logger.debug("[stream: %s] onStreamMessage(%s): Buffering overflow".formatted(key, message)); } overflow.offer(message); } @@ -412,7 +414,7 @@ private void onStreamMessage(V message) { private void onStreamError(Throwable t) { if (logger.isDebugEnabled()) { - logger.debug(String.format("[stream: %s] onStreamError(%s)", key, t)); + logger.debug("[stream: %s] onStreamError(%s)".formatted(key, t)); } pollState.cancel(); @@ -435,14 +437,14 @@ private void emitBuffer() { if (message == null) { if (logger.isDebugEnabled()) { - logger.debug(String.format("[stream: %s] emitBuffer(): emission missed", key)); + logger.debug("[stream: %s] emitBuffer(): emission missed".formatted(key)); } break; } if (logger.isDebugEnabled()) { - logger.debug( - String.format("[stream: %s] emitBuffer(%s): Emitting item from buffer, fast-path", key, message)); + logger.debug("[stream: %s] emitBuffer(%s): Emitting item from buffer, fast-path" + .formatted(key, message)); } sink.next(message); @@ -454,15 +456,15 @@ private void emitBuffer() { if (message == null) { if (logger.isDebugEnabled()) { - logger.debug(String.format("[stream: %s] emitBuffer(): emission missed", key)); + logger.debug("[stream: %s] emitBuffer(): emission missed".formatted(key)); } pollState.incrementRequested(); break; } if (logger.isDebugEnabled()) { - logger.debug( - String.format("[stream: %s] emitBuffer(%s): Emitting item from buffer, slow-path", key, message)); + logger.debug("[stream: %s] emitBuffer(%s): Emitting item from buffer, slow-path" + .formatted(key, message)); } sink.next(message); 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 19a0c7dd58..eb512aa07d 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 @@ -158,11 +158,12 @@ private void initializeIfAbsent() { public double get() { Double value = operations.get(key); + if (value != null) { return value; } - throw new DataRetrievalFailureException(String.format("The key '%s' seems to no longer exist", key)); + throw new DataRetrievalFailureException("The key '%s' seems to no longer exist".formatted(key)); } /** 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 fc22a8b5c5..5e47bd0a11 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 @@ -158,11 +158,12 @@ private void initializeIfAbsent() { public int get() { Integer value = operations.get(key); + if (value != null) { return value; } - throw new DataRetrievalFailureException(String.format("The key '%s' seems to no longer exist", key)); + throw new DataRetrievalFailureException("The key '%s' seems to no longer exist".formatted(key)); } /** 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 d2a7178b70..573d9b6a6f 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 @@ -159,11 +159,12 @@ private void initializeIfAbsent() { public long get() { Long value = operations.get(key); + if (value != null) { return value; } - throw new DataRetrievalFailureException(String.format("The key '%s' seems to no longer exist", key)); + throw new DataRetrievalFailureException("The key '%s' seems to no longer exist".formatted(key)); } /** diff --git a/src/main/java/org/springframework/data/redis/support/collections/AbstractRedisCollection.java b/src/main/java/org/springframework/data/redis/support/collections/AbstractRedisCollection.java index 11a4b72fc6..a5b77df13a 100644 --- a/src/main/java/org/springframework/data/redis/support/collections/AbstractRedisCollection.java +++ b/src/main/java/org/springframework/data/redis/support/collections/AbstractRedisCollection.java @@ -166,13 +166,6 @@ public int hashCode() { @Override public String toString() { - - StringBuilder sb = new StringBuilder(); - - sb.append(String.format("%s for key:", getClass().getSimpleName())); - sb.append(getKey()); - - return sb.toString(); + return "%s for key: %s".formatted(getClass().getSimpleName(), getKey()); } - } diff --git a/src/main/java/org/springframework/data/redis/support/collections/RedisCollectionFactoryBean.java b/src/main/java/org/springframework/data/redis/support/collections/RedisCollectionFactoryBean.java index d97a63dc50..eb6ee64ff8 100644 --- a/src/main/java/org/springframework/data/redis/support/collections/RedisCollectionFactoryBean.java +++ b/src/main/java/org/springframework/data/redis/support/collections/RedisCollectionFactoryBean.java @@ -139,8 +139,8 @@ public void afterPropertiesSet() { } if (keyType != null && DataType.NONE != keyType && this.type.dataType() != keyType) { - throw new IllegalArgumentException( - "Cannot create collection type '%s' for a key containing '%s'".formatted(this.type, keyType)); + throw new IllegalArgumentException("Cannot create collection type '%s' for a key containing '%s'" + .formatted(this.type, keyType)); } return createStore(this.type, key, template); diff --git a/src/main/java/org/springframework/data/redis/support/collections/ReversedRedisListView.java b/src/main/java/org/springframework/data/redis/support/collections/ReversedRedisListView.java index e71716cbcc..cd1f87b5d1 100644 --- a/src/main/java/org/springframework/data/redis/support/collections/ReversedRedisListView.java +++ b/src/main/java/org/springframework/data/redis/support/collections/ReversedRedisListView.java @@ -639,8 +639,8 @@ class DescendingListIterator implements ListIterator { DescendingListIterator(int size, int position) { if (position < 0 || position > size) { - String message = String.format("Position [%d] is out of bounds: [0, %d]", position, size); - throw new IndexOutOfBoundsException(message); + throw new IndexOutOfBoundsException(("Position [%d] is out of bounds;" + + " position must be greater than equal to 0 and less than size %d").formatted(position, size)); } this.it = base.listIterator(size - position); diff --git a/src/main/java/org/springframework/data/redis/util/RedisAssertions.java b/src/main/java/org/springframework/data/redis/util/RedisAssertions.java index bc63a3b9b3..e1f2cb4c31 100644 --- a/src/main/java/org/springframework/data/redis/util/RedisAssertions.java +++ b/src/main/java/org/springframework/data/redis/util/RedisAssertions.java @@ -40,7 +40,7 @@ public abstract class RedisAssertions { * @see #requireNonNull(Object, Supplier) */ public static T requireNonNull(@Nullable T target, String message, Object... arguments) { - return requireNonNull(target, () -> String.format(message, arguments)); + return requireNonNull(target, () -> message.formatted(arguments)); } /** @@ -88,7 +88,7 @@ public static T requireNonNull(@Nullable T target, RuntimeExceptionSupplier * @see #requireNonNull(Object, Supplier) */ public static T requireState(@Nullable T target, String message, Object... arguments) { - return requireState(target, () -> String.format(message, arguments)); + return requireState(target, () -> message.formatted(arguments)); } /** diff --git a/src/test/java/org/springframework/data/redis/SettingsUtils.java b/src/test/java/org/springframework/data/redis/SettingsUtils.java index 51ea95a486..ead8bbabe1 100644 --- a/src/test/java/org/springframework/data/redis/SettingsUtils.java +++ b/src/test/java/org/springframework/data/redis/SettingsUtils.java @@ -18,6 +18,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.HashSet; +import java.util.List; import java.util.Properties; import org.springframework.data.redis.connection.RedisClusterConfiguration; @@ -114,9 +115,11 @@ public static RedisStandaloneConfiguration standaloneConfiguration() { * @return a new {@link RedisSentinelConfiguration} initialized with test endpoint settings. */ public static RedisSentinelConfiguration sentinelConfiguration() { - return new RedisSentinelConfiguration(getSentinelMaster(), - new HashSet<>(Arrays.asList(String.format("%s:%d", getHost(), getSentinelPort()), - String.format("%s:%d", getHost(), getSentinelPort() + 1)))); + + List sentinelHostPorts = List.of("%s:%d".formatted(getHost(), getSentinelPort()), + "%s:%d".formatted(getHost(), getSentinelPort() + 1)); + + return new RedisSentinelConfiguration(getSentinelMaster(), new HashSet<>(sentinelHostPorts)); } /** @@ -125,8 +128,7 @@ public static RedisSentinelConfiguration sentinelConfiguration() { * @return a new {@link RedisClusterConfiguration} initialized with test endpoint settings. */ public static RedisClusterConfiguration clusterConfiguration() { - return new RedisClusterConfiguration( - Collections.singletonList(String.format("%s:%d", getHost(), getClusterPort()))); + return new RedisClusterConfiguration(List.of("%s:%d".formatted(getHost(), getClusterPort()))); } /** diff --git a/src/test/java/org/springframework/data/redis/connection/ClusterSlotHashUtilsTests.java b/src/test/java/org/springframework/data/redis/connection/ClusterSlotHashUtilsTests.java index 2fd5d55886..67dcec39cb 100644 --- a/src/test/java/org/springframework/data/redis/connection/ClusterSlotHashUtilsTests.java +++ b/src/test/java/org/springframework/data/redis/connection/ClusterSlotHashUtilsTests.java @@ -60,7 +60,7 @@ void localCalculationShouldMatchServers() { Long serverSlot = jedis.clusterKeySlot(key); assertThat(slot) - .as(String.format("Expected slot for key '%s' to be %s but server calculated %s.", key, slot, serverSlot)) + .describedAs("Expected slot for key '%s' to be %s but server calculated %s", key, slot, serverSlot) .isEqualTo(serverSlot.intValue()); } 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 1c2a237f32..031d9529f9 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 @@ -404,8 +404,8 @@ void pExpireShouldSupportExiprationForValuesLargerThanInteger() { long ttl = connection.pTtl("pexpireKey"); assertThat(millis - ttl < 20L) - .as(String.format("difference between millis=%s and ttl=%s should not be greater than 20ms but is %s", millis, - ttl, millis - ttl)) + .describedAs("difference between millis=%s and ttl=%s should not be greater than 20ms but is %s", + millis, ttl, millis - ttl) .isTrue(); } 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 82eeda5e0a..48f8c8130e 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 @@ -402,7 +402,7 @@ void connectsThroughRedisSocket() { @Test // DATAREDIS-762, DATAREDIS-869 void factoryUsesElastiCacheMasterReplicaConnections() { - assumeTrue(String.format("No replicas connected to %s:%s.", SettingsUtils.getHost(), SettingsUtils.getPort()), + assumeTrue("No replicas connected to %s:%d".formatted(SettingsUtils.getHost(), SettingsUtils.getPort()), connection.info("replication").getProperty("connected_slaves", "0").compareTo("0") > 0); LettuceClientConfiguration configuration = LettuceTestClientConfiguration.builder().readFrom(ReadFrom.REPLICA) @@ -429,7 +429,7 @@ void factoryUsesElastiCacheMasterReplicaConnections() { @Test // DATAREDIS-1093 void pubSubDoesNotSupportMasterReplicaConnections() { - assumeTrue(String.format("No replicas connected to %s:%s.", SettingsUtils.getHost(), SettingsUtils.getPort()), + assumeTrue("No replicas connected to %s:%d".formatted(SettingsUtils.getHost(), SettingsUtils.getPort()), connection.info("replication").getProperty("connected_slaves", "0").compareTo("0") > 0); RedisStaticMasterReplicaConfiguration elastiCache = new RedisStaticMasterReplicaConfiguration( @@ -451,7 +451,7 @@ void pubSubDoesNotSupportMasterReplicaConnections() { @Test // DATAREDIS-762, DATAREDIS-869 void factoryUsesElastiCacheMasterWithoutMaster() { - assumeTrue(String.format("No replicas connected to %s:%s.", SettingsUtils.getHost(), SettingsUtils.getPort()), + assumeTrue("No replicas connected to %s:%d.".formatted(SettingsUtils.getHost(), SettingsUtils.getPort()), connection.info("replication").getProperty("connected_slaves", "0").compareTo("0") > 0); LettuceClientConfiguration configuration = LettuceTestClientConfiguration.builder().readFrom(ReadFrom.MASTER) @@ -481,7 +481,7 @@ void factoryUsesElastiCacheMasterWithoutMaster() { @Test // DATAREDIS-580, DATAREDIS-869 void factoryUsesMasterReplicaConnections() { - assumeTrue(String.format("No replicas connected to %s:%s.", SettingsUtils.getHost(), SettingsUtils.getPort()), + assumeTrue("No replicas connected to %s:%d".formatted(SettingsUtils.getHost(), SettingsUtils.getPort()), connection.info("replication").getProperty("connected_slaves", "0").compareTo("0") > 0); LettuceClientConfiguration configuration = LettuceTestClientConfiguration.builder().readFrom(ReadFrom.SLAVE) @@ -489,6 +489,7 @@ void factoryUsesMasterReplicaConnections() { LettuceConnectionFactory factory = new LettuceConnectionFactory(SettingsUtils.standaloneConfiguration(), configuration); + factory.start(); RedisConnection connection = factory.getConnection(); diff --git a/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceReactiveScriptingCommandsIntegrationTests.java b/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceReactiveScriptingCommandsIntegrationTests.java index 6886c21a5c..8f19a3314a 100644 --- a/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceReactiveScriptingCommandsIntegrationTests.java +++ b/src/test/java/org/springframework/data/redis/connection/lettuce/LettuceReactiveScriptingCommandsIntegrationTests.java @@ -111,7 +111,7 @@ void evalShaShouldFail() { @ParameterizedRedisTest // DATAREDIS-683 void evalShouldReturnStatus() { - ByteBuffer script = wrap(String.format("return redis.call('set','%s','ghk')", SAME_SLOT_KEY_1)); + ByteBuffer script = wrap("return redis.call('set','%s','ghk')".formatted(SAME_SLOT_KEY_1)); connection.scriptingCommands().eval(script, ReturnType.STATUS, 1, SAME_SLOT_KEY_1_BBUFFER.duplicate()) .as(StepVerifier::create) // 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 d9ac4c7321..efefef752f 100644 --- a/src/test/java/org/springframework/data/redis/core/RedisKeyValueAdapterTests.java +++ b/src/test/java/org/springframework/data/redis/core/RedisKeyValueAdapterTests.java @@ -803,7 +803,7 @@ private static void waitUntilKeyIsGone(RedisTemplate template, String while (template.hasKey(key)) { if (waitedMs > limitMs) { - throw new TimeoutException(String.format("Key '%s' after %d %s still present", key, timeout, timeUnit)); + throw new TimeoutException("Key '%s' after %d %s still present".formatted(key, timeout, timeUnit)); } Thread.sleep(sleepMs); 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 3a7cac75cc..ea60e96019 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 @@ -34,7 +34,6 @@ * @author Christoph Strobl * @author Mark Paluch * @param - * @param */ @ExtendWith(MockitoExtension.class) class BasicRedisPersistentEntityUnitTests { @@ -66,7 +65,8 @@ void addingMultipleIdPropertiesWithoutAnExplicitOneThrowsException() { entity.addPersistentProperty(property1); assertThatExceptionOfType(MappingException.class).isThrownBy(() -> entity.addPersistentProperty(property2)) - .withMessageContaining("Attempt to add id property").withMessageContaining("but already have an property"); + .withMessageContaining("Attempt to add id property") + .withMessageContaining("but already have a property"); } @Test // DATAREDIS-425 @@ -84,7 +84,7 @@ void addingMultipleExplicitIdPropertiesThrowsException() { entity.addPersistentProperty(property1); assertThatExceptionOfType(MappingException.class).isThrownBy(() -> entity.addPersistentProperty(property2)) .withMessageContaining("Attempt to add explicit id property") - .withMessageContaining("but already have an property"); + .withMessageContaining("but already have a property"); } @Test // DATAREDIS-425 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 0b3e29c170..32811d8115 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 @@ -57,10 +57,10 @@ public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext con socket.connect(new InetSocketAddress(SettingsUtils.getHost(), annotation.value()), 100); - return enabled(String.format("Connection successful to Redis at %s:%d", SettingsUtils.getHost(), + return enabled("Connection successful to Redis at %s:%d".formatted(SettingsUtils.getHost(), annotation.value())); } catch (IOException ex) { - return disabled(String.format("Cannot connect to Redis at %s:%d (%s)", SettingsUtils.getHost(), + return disabled("Cannot connect to Redis at %s:%d (%s)".formatted(SettingsUtils.getHost(), annotation.value(), ex)); } } diff --git a/src/test/java/org/springframework/data/redis/test/condition/EnabledOnRedisClusterCondition.java b/src/test/java/org/springframework/data/redis/test/condition/EnabledOnRedisClusterCondition.java index 6a2fd640b8..37ad0df4dd 100644 --- a/src/test/java/org/springframework/data/redis/test/condition/EnabledOnRedisClusterCondition.java +++ b/src/test/java/org/springframework/data/redis/test/condition/EnabledOnRedisClusterCondition.java @@ -48,11 +48,11 @@ public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext con } if (RedisDetector.isClusterAvailable()) { - return enabled(String.format("Connection successful to Redis Cluster at %s:%d", SettingsUtils.getHost(), + return enabled("Connection successful to Redis Cluster at %s:%d".formatted(SettingsUtils.getHost(), SettingsUtils.getClusterPort())); } - return disabled(String.format("Cannot connect to Redis Cluster at %s:%d", SettingsUtils.getHost(), + return disabled("Cannot connect to Redis Cluster at %s:%d".formatted(SettingsUtils.getHost(), SettingsUtils.getClusterPort())); } diff --git a/src/test/java/org/springframework/data/redis/test/condition/EnabledOnRedisDriverCondition.java b/src/test/java/org/springframework/data/redis/test/condition/EnabledOnRedisDriverCondition.java index fb85bfe3bc..53f42bb319 100644 --- a/src/test/java/org/springframework/data/redis/test/condition/EnabledOnRedisDriverCondition.java +++ b/src/test/java/org/springframework/data/redis/test/condition/EnabledOnRedisDriverCondition.java @@ -81,13 +81,12 @@ public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext con } if (!foundMatch) { - return disabled(String.format("Driver %s not supported; Supported driver(s): %s", - formatUnsupportedDriver(value), - Arrays.toString(annotation.value()))); + return disabled("Driver %s not supported; Supported driver(s): %s" + .formatted(formatUnsupportedDriver(value), Arrays.toString(annotation.value()))); } } - return enabled("Found enabled driver(s): " + Arrays.toString(annotation.value())); + return enabled("Found enabled driver(s): %s".formatted(Arrays.toString(annotation.value()))); } diff --git a/src/test/java/org/springframework/data/redis/test/condition/EnabledOnRedisSentinelCondition.java b/src/test/java/org/springframework/data/redis/test/condition/EnabledOnRedisSentinelCondition.java index 13bce43cd8..33d32dd65d 100644 --- a/src/test/java/org/springframework/data/redis/test/condition/EnabledOnRedisSentinelCondition.java +++ b/src/test/java/org/springframework/data/redis/test/condition/EnabledOnRedisSentinelCondition.java @@ -52,12 +52,11 @@ public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext con if (RedisDetector.canConnectToPort(annotation.value())) { - return enabled(String.format("Connection successful to Redis Sentinel at %s:%d", SettingsUtils.getHost(), + return enabled("Connection successful to Redis Sentinel at %s:%d".formatted(SettingsUtils.getHost(), annotation.value())); } - return disabled( - String.format("Cannot connect to Redis Sentinel at %s:%d", SettingsUtils.getHost(), annotation.value())); - + return disabled("Cannot connect to Redis Sentinel at %s:%d".formatted(SettingsUtils.getHost(), + annotation.value())); } } diff --git a/src/test/java/org/springframework/data/redis/test/condition/EnabledOnRedisVersionCondition.java b/src/test/java/org/springframework/data/redis/test/condition/EnabledOnRedisVersionCondition.java index 5a082873be..489a3eb0b1 100644 --- a/src/test/java/org/springframework/data/redis/test/condition/EnabledOnRedisVersionCondition.java +++ b/src/test/java/org/springframework/data/redis/test/condition/EnabledOnRedisVersionCondition.java @@ -61,11 +61,14 @@ public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext con } }, RedisConditions.class); - boolean versionMet = conditions.hasVersionGreaterOrEqualsTo(requiredVersion); - return versionMet - ? enabled( - String.format("Enabled on version %s (actual version: %s)", requiredVersion, conditions.getRedisVersion())) - : disabled(String.format("Disabled, version %s not available on Redis version %s", requiredVersion, - conditions.getRedisVersion())); + boolean requiredVersionMet = conditions.hasVersionGreaterOrEqualsTo(requiredVersion); + + if (requiredVersionMet) { + return enabled("Enabled on version %s; actual version: %s".formatted(requiredVersion, + conditions.getRedisVersion())); + } + + return disabled("Disabled; version %s not available on Redis version %s".formatted(requiredVersion, + conditions.getRedisVersion())); } } 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 fe4ace599c..6ea6e20074 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 @@ -61,10 +61,11 @@ public boolean supportsTestTemplate(ExtensionContext context) { ParameterizedTestContext methodContext = new ParameterizedTestContext(testMethod); ParameterizedTestContext constructorContext = new ParameterizedTestContext(declaredConstructor); - Preconditions.condition(methodContext.hasPotentiallyValidSignature(), - () -> String.format("@ParameterizedRedisTest method [%s] declares formal parameters in an invalid order: " + Preconditions.condition(methodContext.hasPotentiallyValidSignature(), () -> + ("@ParameterizedRedisTest method [%s] declares formal parameters in an invalid order: " + "argument aggregators must be declared after any indexed arguments " - + "and before any arguments resolved by another ParameterResolver.", testMethod.toGenericString())); + + "and before any arguments resolved by another ParameterResolver.") + .formatted(testMethod.toGenericString())); getStore(context).put(METHOD_CONTEXT_KEY, methodContext); getStore(context).put(CONSTRUCTOR_CONTEXT_KEY, constructorContext); @@ -115,10 +116,9 @@ private ArgumentsProvider instantiateArgumentsProvider(Class String.format( - "Configuration error: @ParameterizedRedisTest on method [%s] must be declared with a non-empty name.", - templateMethod)); + + String pattern = Preconditions.notBlank(parameterizedTest.name().trim(), () -> + "Configuration error: @ParameterizedRedisTest on method [%s] must be declared with a non-empty name" + .formatted(templateMethod)); + return new ParameterizedTestNameFormatter(pattern, displayName, methodContext, argumentMaxLength); } diff --git a/src/test/java/org/springframework/data/redis/test/extension/parametrized/ParameterizedTestNameFormatter.java b/src/test/java/org/springframework/data/redis/test/extension/parametrized/ParameterizedTestNameFormatter.java index b8b15b57d8..1ce15b4b2c 100644 --- a/src/test/java/org/springframework/data/redis/test/extension/parametrized/ParameterizedTestNameFormatter.java +++ b/src/test/java/org/springframework/data/redis/test/extension/parametrized/ParameterizedTestNameFormatter.java @@ -53,9 +53,8 @@ String format(int invocationIndex, Object... arguments) { try { return formatSafely(invocationIndex, arguments); } catch (Exception ex) { - String message = "The display name pattern defined for the parameterized test is invalid; " - + "See nested exception for further details."; - throw new JUnitException(message, ex); + throw new JUnitException("The display name pattern defined for the parameterized test is invalid;" + + " See nested exception for further details.", ex); } } 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 c70d6e8ad5..75b7b20435 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 @@ -68,7 +68,7 @@ public boolean matches(Invocation actual) { @Override public String toString() { - return String.format("%s for method: %s", mode, method); + return "%s for method: %s".formatted(mode, method); } })); } diff --git a/src/test/java/org/springframework/data/redis/test/util/RedisTestData.java b/src/test/java/org/springframework/data/redis/test/util/RedisTestData.java index 4689be3e13..9bdf610fc7 100644 --- a/src/test/java/org/springframework/data/redis/test/util/RedisTestData.java +++ b/src/test/java/org/springframework/data/redis/test/util/RedisTestData.java @@ -86,7 +86,7 @@ public RedisBucketAssert containingTypeHint(String path, Class type) { isNotNull(); - String hint = String.format("Type hint for <%s> at <%s>", type.getName(), path); + String hint = "Type hint for <%s> at <%s>".formatted(type.getName(), path); if (!actual.containsKey(path)) {