Replace use of String.format(…) with formatted Strings.

Original pull request: #2752
Closes #2751
This commit is contained in:
John Blum
2023-10-19 14:53:44 -07:00
committed by Mark Paluch
parent 6eac1d1ad0
commit 44aa79e2b2
82 changed files with 285 additions and 328 deletions

View File

@@ -46,7 +46,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;

View File

@@ -445,9 +445,7 @@ class DefaultRedisCacheWriter implements RedisCacheWriter {
// 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);
}

View File

@@ -298,12 +298,9 @@ public class RedisCache extends AbstractValueAdaptingCache {
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;
@@ -414,12 +411,9 @@ public class RedisCache extends AbstractValueAdaptingCache {
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<ValueWrapper> retrieveValue(Object key) {
@@ -484,7 +478,7 @@ public class RedisCache extends AbstractValueAdaptingCache {
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) {

View File

@@ -424,11 +424,9 @@ public class RedisCacheConfiguration {
public void configureKeyConverters(Consumer<ConverterRegistry> 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());

View File

@@ -130,12 +130,9 @@ public class ClusterCommandExecutor implements DisposableBean {
Assert.notNull(node, "RedisClusterNode must not be null");
if (redirectCount > this.maxRedirects) {
String message = String.format("Cannot follow Cluster Redirects over more than %s legs; "
+ "Consider increasing the number of redirects to follow; Current value is: %s.",
redirectCount, this.maxRedirects);
throw new TooManyClusterRedirectionsException(message);
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 @@ public class ClusterCommandExecutor implements DisposableBean {
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 class ClusterCommandExecutor implements DisposableBean {
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);
}
}

View File

@@ -141,7 +141,7 @@ public class ClusterTopology {
}
throw new ClusterStateFailureException(
String.format("Could not find master node serving slot %s for key '%s',", slot, Arrays.toString(key)));
"Could not find master node serving slot %s for key '%s',".formatted(slot, Arrays.toString(key)));
}
/**
@@ -161,7 +161,7 @@ public class ClusterTopology {
}
throw new ClusterStateFailureException(
String.format("Could not find node at %s:%s; Is your cluster info up to date", host, port));
"Could not find node at %s:%d; Is your cluster info up to date".formatted(host, port));
}
/**
@@ -182,7 +182,7 @@ public class ClusterTopology {
}
throw new ClusterStateFailureException(
String.format("Could not find node at %s; Is your cluster info up to date", nodeId));
"Could not find node at %s; Is your cluster info up to date".formatted(nodeId));
}
/**
@@ -210,7 +210,7 @@ public class ClusterTopology {
}
throw new ClusterStateFailureException(
String.format("Could not find node at %s; Have you provided either host and port or the nodeId", node));
("Could not find node at %s;" + " Have you provided either host and port or the nodeId").formatted(node));
}
/**

View File

@@ -102,11 +102,11 @@ public class RedisNode implements NamedNode {
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);
@@ -123,14 +123,14 @@ public class RedisNode implements NamedNode {
if (hostPortString.charAt(0) != '[') {
throw new IllegalArgumentException(
String.format("Bracketed host-port string must start with a bracket: %s", hostPortString));
"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,11 @@ public class RedisNode implements NamedNode {
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) };

View File

@@ -140,7 +140,7 @@ public class RedisPassword {
@Override
public String toString() {
return String.format("%s[%s]", getClass().getSimpleName(), isPresent() ? "*****" : "<none>");
return "%s[%s]".formatted(getClass().getSimpleName(), isPresent() ? "*****" : "<none>");
}
@Override

View File

@@ -150,7 +150,7 @@ public class RedisSentinelConfiguration implements RedisConfiguration, SentinelC
try {
database = Integer.parseInt(databaseSource);
} catch (NumberFormatException ex) {
throw new IllegalArgumentException(String.format("Invalid DB index '%s'; integer required", databaseSource));
throw new IllegalArgumentException("Invalid DB index '%s'; integer required".formatted(databaseSource));
}
this.setDatabase(database);
}
@@ -266,7 +266,7 @@ public class RedisSentinelConfiguration implements RedisConfiguration, SentinelC
@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;
}

View File

@@ -74,7 +74,7 @@ public class RedisSocketConfiguration implements RedisConfiguration, DomainSocke
@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;
}

View File

@@ -70,7 +70,7 @@ public class RedisStandaloneConfiguration
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));
"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 class RedisStandaloneConfiguration
@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;
}

View File

@@ -118,7 +118,7 @@ public class RedisStaticMasterReplicaConfiguration implements RedisConfiguration
@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));

View File

@@ -410,7 +410,7 @@ public abstract class Converters {
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format("parsing %s (%s) as %s", sourcePath, path, targetType));
LOGGER.debug("parsing %s (%s) as %s".formatted(sourcePath, path, targetType));
}
if (targetType == Object.class) {

View File

@@ -761,7 +761,7 @@ public class JedisClusterConnection implements RedisClusterConnection {
return new Jedis(connection);
}
throw new DataAccessResourceFailureException(String.format("Node %s is unknown to cluster", node));
throw new DataAccessResourceFailureException("Node %s is unknown to cluster".formatted(node));
}
private ConnectionPool getResourcePoolForSpecificNode(RedisClusterNode node) {
@@ -779,8 +779,8 @@ public class JedisClusterConnection implements RedisClusterConnection {
RedisClusterNode member = topologyProvider.getTopology().lookup(node);
if (!member.hasValidHost()) {
throw new DataAccessResourceFailureException(String
.format("Cannot obtain connection to node %ss as it is not associated with a hostname", node.getId()));
throw new DataAccessResourceFailureException(
"Cannot obtain connection to node %ss; " + "it is not associated with a hostname".formatted(node.getId()));
}
if (member != null && connectionHandler != null) {
@@ -872,7 +872,7 @@ public class JedisClusterConnection implements RedisClusterConnection {
StringBuilder stringBuilder = new StringBuilder();
for (Entry<String, Exception> 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(

View File

@@ -347,10 +347,11 @@ class JedisClusterServerCommands implements RedisClusterServerCommands {
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<String>) client -> client.clientKill(hostAndPort));
JedisClusterCommandCallback<String> command = client -> client.clientKill(hostAndPort);
connection.getClusterCommandExecutor().executeCommandOnAllNodes(command);
}
@Override

View File

@@ -908,8 +908,9 @@ class JedisClusterZSetCommands implements RedisZSetCommands {
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 +952,8 @@ class JedisClusterZSetCommands implements RedisZSetCommands {
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 +1009,9 @@ class JedisClusterZSetCommands implements RedisZSetCommands {
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 +1054,8 @@ class JedisClusterZSetCommands implements RedisZSetCommands {
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);

View File

@@ -1003,7 +1003,7 @@ public class JedisConnectionFactory
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();
@@ -1040,8 +1040,8 @@ public class JedisConnectionFactory
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;
}
@@ -1056,10 +1056,10 @@ public class JedisConnectionFactory
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));
}
}

View File

@@ -472,7 +472,7 @@ abstract class JedisConverters extends Converters {
} else if (theValue instanceof String string) {
value = toBytes(string);
} 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);
@@ -770,7 +770,7 @@ abstract class JedisConverters extends Converters {
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<byte[]> reference, GeoSearchParam param) {
@@ -787,7 +787,7 @@ abstract class JedisConverters extends Converters {
return;
}
throw new IllegalArgumentException(String.format("Cannot extract Geo Reference from %s", reference));
throw new IllegalArgumentException("Cannot extract Geo Reference from %s".formatted(reference));
}
/**

View File

@@ -161,7 +161,7 @@ class JedisServerCommands implements RedisServerCommands {
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

View File

@@ -474,8 +474,8 @@ class JedisZSetCommands implements RedisZSetCommands {
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);
@@ -487,8 +487,8 @@ class JedisZSetCommands implements RedisZSetCommands {
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);
@@ -528,8 +528,8 @@ class JedisZSetCommands implements RedisZSetCommands {
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);
@@ -542,8 +542,8 @@ class JedisZSetCommands implements RedisZSetCommands {
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);

View File

@@ -120,9 +120,8 @@ class ClusterConnectionProvider implements LettuceConnectionProvider, RedisClien
});
}
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

View File

@@ -216,10 +216,8 @@ public class LettuceClusterConnection extends LettuceConnection
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

View File

@@ -328,7 +328,7 @@ public class LettuceConnection extends AbstractRedisConnection {
@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());
@@ -937,9 +937,7 @@ public class LettuceConnection extends AbstractRedisConnection {
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<byte[], byte[]> getAsyncDedicatedConnection() {
@@ -953,13 +951,12 @@ public class LettuceConnection extends AbstractRedisConnection {
if (connection instanceof StatefulRedisConnection<byte[], byte[]> statefulConnection) {
return statefulConnection.async();
}
if (asyncDedicatedConnection instanceof StatefulRedisClusterConnection<byte[], byte[]> 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")
@@ -1091,8 +1088,7 @@ public class LettuceConnection extends AbstractRedisConnection {
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);
}
}
}

View File

@@ -1444,10 +1444,10 @@ public class LettuceConnectionFactory implements RedisConnectionFactory, Reactiv
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));
}
}
@@ -1500,8 +1500,8 @@ public class LettuceConnectionFactory implements RedisConnectionFactory, Reactiv
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;
}

View File

@@ -871,7 +871,7 @@ public abstract class LettuceConverters extends Converters {
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 <T> GeoSearch.GeoRef<T> toGeoRef(GeoReference<T> reference) {
@@ -885,7 +885,7 @@ public abstract class LettuceConverters extends Converters {
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) {

View File

@@ -135,9 +135,8 @@ class LettucePoolingConnectionProvider implements LettuceConnectionProvider, Red
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

View File

@@ -74,7 +74,7 @@ class LettuceReactiveListCommands implements ReactiveListCommands {
if (!command.getUpsert() && command.getValues().size() > 1) {
throw new InvalidDataAccessApiUsageException(
String.format("%s PUSHX only allows one value", command.getDirection()));
"%s PUSHX only allows one value".formatted(command.getDirection()));
}
Mono<Long> pushResult;

View File

@@ -233,7 +233,7 @@ class LettuceReactivePubSubCommands implements ReactivePubSubCommands {
@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));
}
}
}

View File

@@ -154,7 +154,7 @@ class LettuceReactiveServerCommands implements ReactiveServerCommands {
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

View File

@@ -364,7 +364,7 @@ class LettuceReactiveStringCommands implements ReactiveStringCommands {
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));

View File

@@ -59,8 +59,8 @@ abstract class LettuceScanCursor<T> extends ScanCursor<T> {
}
}
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

View File

@@ -26,7 +26,6 @@ import java.util.Properties;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisServerCommands;
import org.springframework.data.redis.core.types.RedisClientInfo;
@@ -173,7 +172,7 @@ class LettuceServerCommands implements RedisServerCommands {
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);
}

View File

@@ -441,8 +441,8 @@ class LettuceZSetCommands implements RedisZSetCommands {
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);
@@ -456,8 +456,8 @@ class LettuceZSetCommands implements RedisZSetCommands {
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);
@@ -496,8 +496,8 @@ class LettuceZSetCommands implements RedisZSetCommands {
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);
@@ -511,8 +511,8 @@ class LettuceZSetCommands implements RedisZSetCommands {
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);

View File

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

View File

@@ -217,7 +217,7 @@ public class MicrometerTracingAdapter implements Tracing {
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) {
@@ -265,7 +265,7 @@ public class MicrometerTracingAdapter implements Tracing {
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);
@@ -283,7 +283,7 @@ public class MicrometerTracingAdapter implements Tracing {
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();

View File

@@ -53,7 +53,7 @@ public class Consumer {
@Override
public String toString() {
return String.format("%s:%s", group, name);
return "%s:%s".formatted(group, name);
}
public String getGroup() {

View File

@@ -216,7 +216,7 @@ public class StreamRecords {
} 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);

View File

@@ -238,7 +238,7 @@ class IndexWriter {
connection.sAdd(createIndexKey(indexedData.getKeyspace(), key), indexKey);
} else {
throw new IllegalArgumentException(
String.format("Cannot write index data for unknown index type %s", indexedData.getClass()));
"Cannot write index data for unknown index type %s".formatted(indexedData.getClass()));
}
}
@@ -292,10 +292,9 @@ class IndexWriter {
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()));
}
/**

View File

@@ -377,16 +377,17 @@ public enum RedisCommand {
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 enum RedisCommand {
private String arguments(int count) {
return count == 1 ? "argument" : "arguments";
}
private IllegalArgumentException newIllegalArgumentException(String message, Object... arguments) {
return new IllegalArgumentException(String.format(message, arguments));
}
}

View File

@@ -495,14 +495,14 @@ public abstract class RedisConnectionUtils {
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();

View File

@@ -289,7 +289,7 @@ final class BinaryConverters {
} 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)));
}
}

View File

@@ -540,8 +540,8 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean {
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()));
("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 +601,7 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean {
} 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());
}
@@ -751,7 +750,7 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean {
if (!ClassUtils.isAssignable(typeHint.getType(), value.getClass())) {
throw new MappingException(
String.format(INVALID_TYPE_ASSIGNMENT, value.getClass(), currentPath, typeHint.getType()));
INVALID_TYPE_ASSIGNMENT.formatted(value.getClass(), currentPath, typeHint.getType()));
}
if (customConversions.hasCustomWriteTarget(value.getClass())) {
@@ -794,7 +793,7 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean {
sink.getBucket().put(path, toBytes(value));
} else {
throw new IllegalArgumentException(
String.format("Cannot convert value '%s' of type %s to bytes", value, value.getClass()));
"Cannot convert value '%s' of type %s to bytes".formatted(value, value.getClass()));
}
}
}
@@ -855,7 +854,7 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean {
if (!ClassUtils.isAssignable(mapValueType, entry.getValue().getClass())) {
throw new MappingException(
String.format(INVALID_TYPE_ASSIGNMENT, entry.getValue().getClass(), currentPath, mapValueType));
INVALID_TYPE_ASSIGNMENT.formatted(entry.getValue().getClass(), currentPath, mapValueType));
}
if (customConversions.hasCustomWriteTarget(entry.getValue().getClass())) {
@@ -945,8 +944,7 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean {
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);
@@ -1224,7 +1222,7 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean {
*/
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);
@@ -1304,7 +1302,7 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean {
*/
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);

View File

@@ -66,8 +66,8 @@ public class GeoIndexDefinition extends RedisIndexDefinition implements PathBase
}
throw new IllegalArgumentException(
String.format("Cannot convert %s to %s; GeoIndexed property needs to be of type Point or GeoLocation",
source.getClass(), Point.class));
("Cannot convert %s to %s; GeoIndexed property needs to be of type Point" + " or GeoLocation")
.formatted(source.getClass(), Point.class));
}
}
}

View File

@@ -84,16 +84,14 @@ public class BasicRedisPersistentEntity<T> extends BasicKeyValuePersistentEntity
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) {

View File

@@ -241,17 +241,15 @@ public class RedisMappingContext extends KeyValueMappingContext<RedisPersistentE
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);
}
}
}

View File

@@ -60,8 +60,7 @@ abstract public class DigestUtils {
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);
}
}
}

View File

@@ -274,8 +274,7 @@ public class RedisClientInfo {
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);
}

View File

@@ -107,6 +107,6 @@ public class BoundingBox implements Shape {
@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);
}
}

View File

@@ -71,7 +71,7 @@ public class BeanUtilsHashMapper<T> implements HashMapper<T, String, String> {
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);
}
}
}

View File

@@ -412,8 +412,7 @@ public class Jackson2HashMapper implements HashMapper<Object, String, Object> {
resultMap.put(propertyPrefix, next.binaryValue());
}
catch (IOException ex) {
String message = String.format("Cannot read binary value of '%s'", propertyPrefix);
throw new IllegalStateException(message, ex);
throw new IllegalStateException("Cannot read binary value '%s'".formatted(propertyPrefix), ex);
}
break;

View File

@@ -657,14 +657,14 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
Collection<MessageListener> 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<MessageListener> 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();
@@ -748,12 +748,12 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
if (topic instanceof ChannelTopic) {
remove(listener, topic, holder, channelMapping, channelsToRemove);
logTrace(() -> 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()));
}
}
@@ -874,9 +874,8 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
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;

View File

@@ -375,13 +375,12 @@ public class MessageListenerAdapter implements InitializingBean, MessageListener
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);
}
}

View File

@@ -149,8 +149,7 @@ public abstract class CdiBean<T> implements Bean<T>, PassivationCapable {
public void destroy(T instance, CreationalContext<T> 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 abstract class CdiBean<T> implements Bean<T>, PassivationCapable {
@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());
}
}

View File

@@ -80,7 +80,7 @@ public class RedisRepositoryExtension extends CdiRepositoryExtensionSupport {
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 @@ public class RedisRepositoryExtension extends CdiRepositoryExtensionSupport {
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,8 @@ public class RedisRepositoryExtension extends CdiRepositoryExtensionSupport {
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 +124,7 @@ public class RedisRepositoryExtension extends CdiRepositoryExtensionSupport {
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,7 +149,7 @@ public class RedisRepositoryExtension extends CdiRepositoryExtensionSupport {
if (!redisKeyValueAdapters.containsKey(qualifiers)) {
if (log.isInfoEnabled()) {
log.info(String.format("Registering bean for %s with qualifiers %s.", RedisKeyValueAdapter.class.getName(),
log.info("Registering bean for %s with qualifiers %s.".formatted(RedisKeyValueAdapter.class.getName(),
qualifiers));
}
RedisKeyValueAdapterBean redisKeyValueAdapterBean = createRedisKeyValueAdapterBean(qualifiers, beanManager);
@@ -158,7 +159,7 @@ public class RedisRepositoryExtension extends CdiRepositoryExtensionSupport {
if (!redisKeyValueTemplates.containsKey(qualifiers)) {
if (log.isInfoEnabled()) {
log.info(String.format("Registering bean for %s with qualifiers %s.", RedisKeyValueTemplate.class.getName(),
log.info("Registering bean for %s with qualifiers %s.".formatted(RedisKeyValueTemplate.class.getName(),
qualifiers));
}
@@ -186,8 +187,8 @@ public class RedisRepositoryExtension extends CdiRepositoryExtensionSupport {
Bean<KeyValueOperations> 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 +209,8 @@ public class RedisRepositoryExtension extends CdiRepositoryExtensionSupport {
Bean<RedisOperations<?, ?>> 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 +231,8 @@ public class RedisRepositoryExtension extends CdiRepositoryExtensionSupport {
Bean<RedisKeyValueAdapter> 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.

View File

@@ -40,10 +40,9 @@ public class MappingRedisEntityInformation<T, ID> extends PersistentEntityInform
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()));
("Entity %s requires to have an explicit id field;" + " Did you forget to provide one using @Id")
.formatted(entity.getName()));
}
}
}

View File

@@ -139,8 +139,8 @@ public class ExampleQueryMapper {
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));
("Redis Query-by-Example does not support string matcher %s;" + " Supported matchers are: %s.")
.formatted(stringMatcher, SUPPORTED_MATCHERS));
}
if (exampleSpecAccessor.hasPropertySpecifier(path)) {

View File

@@ -61,10 +61,8 @@ public class RedisQueryCreator extends AbstractQueryCreator<KeyValueQuery<RedisO
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;
@@ -111,8 +109,8 @@ public class RedisQueryCreator extends AbstractQueryCreator<KeyValueQuery<RedisO
if (value instanceof Point point) {
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?");
}
Distance distance;
@@ -124,17 +122,16 @@ public class RedisQueryCreator extends AbstractQueryCreator<KeyValueQuery<RedisO
distance = new Distance(num.doubleValue(), Metrics.KILOMETERS);
} else {
String message = String.format("Expected to find Distance or Numeric value for geo query but was %s",
ClassUtils.getDescriptiveType(distObject));
throw new InvalidDataAccessApiUsageException(message);
throw new InvalidDataAccessApiUsageException(
"Expected to find Distance or Numeric value for geo query but was %s"
.formatted(ClassUtils.getDescriptiveType(distObject)));
}
return new NearPath(path, point, distance);
}
String message = String.format("Expected to find a Circle or Point/Distance for geo query but was %s",
ClassUtils.getDescriptiveType(value.getClass()));
throw new InvalidDataAccessApiUsageException(message);
throw new InvalidDataAccessApiUsageException("Expected to find a Circle or Point/Distance for geo query but was %s"
.formatted(ClassUtils.getDescriptiveType(value.getClass())));
}
private static boolean containsExactlyOne(Collection<?> collection) {

View File

@@ -18,6 +18,7 @@ package org.springframework.data.redis.serializer;
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<T> implements RedisElementWriter<T> {
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[]) {
@@ -50,6 +52,6 @@ class DefaultRedisElementWriter<T> implements RedisElementWriter<T> {
}
throw new IllegalStateException(
String.format("Cannot serialize value of type %s without a serializer", value.getClass()));
"Cannot serialize value of type %s without a serializer".formatted(ObjectUtils.nullSafeClassName(value)));
}
}

View File

@@ -266,8 +266,7 @@ public class GenericJackson2JsonRedisSerializer implements RedisSerializer<Objec
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);
}
}
@@ -303,8 +302,7 @@ public class GenericJackson2JsonRedisSerializer implements RedisSerializer<Objec
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);
}
}

View File

@@ -105,7 +105,7 @@ class DefaultStreamReceiver<K, V extends Record<K, ?>> implements StreamReceiver
public Flux<V> receive(StreamOffset<K> streamOffset) {
if (logger.isDebugEnabled()) {
logger.debug(String.format("receive(%s)", streamOffset));
logger.debug("receive(%s)".formatted(streamOffset));
}
RedisSerializationContext.SerializationPair<K> keySerializer = template.getSerializationContext()
@@ -125,11 +125,10 @@ class DefaultStreamReceiver<K, V extends Record<K, ?>> implements StreamReceiver
}
@Override
@SuppressWarnings("unchecked")
public Flux<V> receiveAutoAck(Consumer consumer, StreamOffset<K> streamOffset) {
if (logger.isDebugEnabled()) {
logger.debug(String.format("receiveAutoAck(%s, %s)", consumer, streamOffset));
logger.debug("receiveAutoAck(%s, %s)".formatted(consumer, streamOffset));
}
Function<ReadOffset, Flux<ByteBufferRecord>> readFunction = getConsumeReadFunction(streamOffset.getKey(), consumer,
@@ -146,11 +145,10 @@ class DefaultStreamReceiver<K, V extends Record<K, ?>> implements StreamReceiver
}
@Override
@SuppressWarnings("unchecked")
public Flux<V> receive(Consumer consumer, StreamOffset<K> streamOffset) {
if (logger.isDebugEnabled()) {
logger.debug(String.format("receive(%s, %s)", consumer, streamOffset));
logger.debug("receive(%s, %s)".formatted(consumer, streamOffset));
}
Function<ReadOffset, Flux<ByteBufferRecord>> readFunction = getConsumeReadFunction(streamOffset.getKey(), consumer,
@@ -229,7 +227,7 @@ class DefaultStreamReceiver<K, V extends Record<K, ?>> implements StreamReceiver
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,7 @@ class DefaultStreamReceiver<K, V extends Record<K, ?>> implements StreamReceiver
}
} 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,25 +261,25 @@ class DefaultStreamReceiver<K, V extends Record<K, ?>> implements StreamReceiver
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,
logger.info("[stream: %s] scheduleIfRequired(): Requested: %d Emit from buffer".formatted(key,
pollState.getRequested()));
}
emitBuffer();
@@ -290,8 +288,8 @@ class DefaultStreamReceiver<K, V extends Record<K, ?>> implements StreamReceiver
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 +301,14 @@ class DefaultStreamReceiver<K, V extends Record<K, ?>> implements StreamReceiver
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));
"[stream: %s] scheduleIfRequired(): Activating subscription, offset %s".formatted(key, readOffset));
}
Flux<ByteBufferRecord> poll = readFunction.apply(readOffset)
@@ -319,7 +317,7 @@ class DefaultStreamReceiver<K, V extends Record<K, ?>> implements StreamReceiver
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 +355,7 @@ class DefaultStreamReceiver<K, V extends Record<K, ?>> implements StreamReceiver
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 +379,20 @@ class DefaultStreamReceiver<K, V extends Record<K, ?>> implements StreamReceiver
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 +401,7 @@ class DefaultStreamReceiver<K, V extends Record<K, ?>> implements StreamReceiver
} 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 +410,7 @@ class DefaultStreamReceiver<K, V extends Record<K, ?>> implements StreamReceiver
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 +433,13 @@ class DefaultStreamReceiver<K, V extends Record<K, ?>> implements StreamReceiver
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 +451,14 @@ class DefaultStreamReceiver<K, V extends Record<K, ?>> implements StreamReceiver
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);

View File

@@ -160,11 +160,12 @@ public class RedisAtomicDouble extends Number implements Serializable, BoundKeyO
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));
}
/**

View File

@@ -160,11 +160,12 @@ public class RedisAtomicInteger extends Number implements Serializable, BoundKey
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));
}
/**

View File

@@ -161,11 +161,12 @@ public class RedisAtomicLong extends Number implements Serializable, BoundKeyOpe
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));
}
/**

View File

@@ -166,13 +166,6 @@ public abstract class AbstractRedisCollection<E> extends AbstractCollection<E> i
@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());
}
}

View File

@@ -639,8 +639,9 @@ class ReversedRedisListView<E> implements RedisList<E> {
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);

View File

@@ -40,7 +40,7 @@ public abstract class RedisAssertions {
* @see #requireNonNull(Object, Supplier)
*/
public static <T> 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 abstract class RedisAssertions {
* @see #requireNonNull(Object, Supplier)
*/
public static <T> T requireState(@Nullable T target, String message, Object... arguments) {
return requireState(target, () -> String.format(message, arguments));
return requireState(target, () -> message.formatted(arguments));
}
/**

View File

@@ -18,6 +18,7 @@ package org.springframework.data.redis;
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 abstract class SettingsUtils {
* @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<String> 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 abstract class SettingsUtils {
* @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())));
}
/**

View File

@@ -60,7 +60,7 @@ public class ClusterSlotHashUtilsTests {
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());
}

View File

@@ -404,8 +404,8 @@ public class JedisConnectionIntegrationTests extends AbstractConnectionIntegrati
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();
}

View File

@@ -402,7 +402,7 @@ class LettuceConnectionFactoryTests {
@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 @@ class LettuceConnectionFactoryTests {
@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 @@ class LettuceConnectionFactoryTests {
@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 @@ class LettuceConnectionFactoryTests {
@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 @@ class LettuceConnectionFactoryTests {
LettuceConnectionFactory factory = new LettuceConnectionFactory(SettingsUtils.standaloneConfiguration(),
configuration);
factory.start();
RedisConnection connection = factory.getConnection();

View File

@@ -111,7 +111,7 @@ public class LettuceReactiveScriptingCommandsIntegrationTests extends LettuceRea
@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) //

View File

@@ -821,7 +821,7 @@ public class RedisKeyValueAdapterTests {
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);

View File

@@ -34,7 +34,6 @@ import org.springframework.data.util.TypeInformation;
* @author Christoph Strobl
* @author Mark Paluch
* @param <T>
* @param <ID>
*/
@ExtendWith(MockitoExtension.class)
class BasicRedisPersistentEntityUnitTests<T> {
@@ -66,7 +65,8 @@ class BasicRedisPersistentEntityUnitTests<T> {
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 @@ class BasicRedisPersistentEntityUnitTests<T> {
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

View File

@@ -57,10 +57,10 @@ class EnabledOnRedisAvailableCondition implements ExecutionCondition {
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));
}
}

View File

@@ -48,11 +48,11 @@ class EnabledOnRedisClusterCondition implements ExecutionCondition {
}
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()));
}

View File

@@ -81,13 +81,12 @@ class EnabledOnRedisDriverCondition implements ExecutionCondition {
}
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())));
}

View File

@@ -52,12 +52,11 @@ class EnabledOnRedisSentinelCondition implements ExecutionCondition {
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()));
}
}

View File

@@ -61,11 +61,14 @@ class EnabledOnRedisVersionCondition implements ExecutionCondition {
}
}, 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()));
}
}

View File

@@ -61,10 +61,11 @@ class ParameterizedRedisTestExtension implements TestTemplateInvocationContextPr
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 @@ class ParameterizedRedisTestExtension implements TestTemplateInvocationContextPr
return ReflectionUtils.newInstance(clazz);
} catch (Exception ex) {
if (ex instanceof NoSuchMethodException) {
String message = String.format("Failed to find a no-argument constructor for ArgumentsProvider [%s]; "
+ "Please ensure that a no-argument constructor exists and "
+ "that the class is either a top-level class or a static nested class", clazz.getName());
throw new JUnitException(message, ex);
throw new JUnitException(("Failed to find a no-argument constructor for ArgumentsProvider [%s];"
+ " Please ensure that a no-argument constructor exists and that the class is either"
+ " a top-level class or a static nested class").formatted(clazz.getName()), ex);
}
throw ex;
}
@@ -137,10 +137,11 @@ class ParameterizedRedisTestExtension implements TestTemplateInvocationContextPr
ParameterizedTestContext methodContext, String displayName, int argumentMaxLength) {
ParameterizedRedisTest parameterizedTest = findAnnotation(templateMethod, ParameterizedRedisTest.class).get();
String pattern = Preconditions.notBlank(parameterizedTest.name().trim(),
() -> 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);
}

View File

@@ -53,9 +53,8 @@ class ParameterizedTestNameFormatter {
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);
}
}

View File

@@ -68,7 +68,7 @@ public abstract class MockitoUtils {
@Override
public String toString() {
return String.format("%s for method: %s", mode, method);
return "%s for method: %s".formatted(mode, method);
}
}));
}

View File

@@ -86,7 +86,7 @@ public class RedisTestData implements AssertProvider<RedisTestData.RedisBucketAs
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)) {