diff --git a/build.gradle b/build.gradle index a86c93fcd8a6..c87a29205c59 100644 --- a/build.gradle +++ b/build.gradle @@ -1,12 +1,12 @@ plugins { - id 'io.freefair.aspectj' version '8.13.1' apply false - // kotlinVersion is managed in gradle.properties - id 'org.jetbrains.kotlin.plugin.serialization' version "${kotlinVersion}" apply false - id 'org.jetbrains.dokka' id 'com.github.bjornvester.xjc' version '1.8.2' apply false id 'com.gradleup.shadow' version "9.2.2" apply false - id 'me.champeau.jmh' version '0.7.2' apply false + id 'io.freefair.aspectj' version '8.13.1' apply false id 'io.spring.nullability' version '0.0.8' apply false + id 'me.champeau.jmh' version '0.7.2' apply false + id 'org.jetbrains.dokka' + id 'org.jetbrains.kotlin.plugin.serialization' version "${kotlinVersion}" apply false // kotlinVersion is managed in gradle.properties + id 'org.openrewrite.rewrite' version '7.20.0' apply false } ext { @@ -16,6 +16,8 @@ ext { description = "Spring Framework" +apply from: "$rootDir/gradle/rewrite.gradle" + configure(allprojects) { project -> apply plugin: "org.springframework.build.localdev" group = "org.springframework" diff --git a/gradle/rewrite.gradle b/gradle/rewrite.gradle new file mode 100644 index 000000000000..af3ff64b98c8 --- /dev/null +++ b/gradle/rewrite.gradle @@ -0,0 +1,24 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + */ + +project.apply plugin: 'org.openrewrite.rewrite' + +rewrite { + activeRecipe('org.opensearch.openrewrite.SanityCheck') + setExportDatatables(true) + setFailOnDryRunResults(true) +} + +dependencies { + rewrite(platform("org.openrewrite.recipe:rewrite-recipe-bom:3.18.0")) + rewrite("org.openrewrite.recipe:rewrite-migrate-java:3.21.1") + rewrite("org.openrewrite.recipe:rewrite-java-security:3.20.0") + rewrite("org.openrewrite.recipe:rewrite-rewrite:0.15.0") + rewrite("org.openrewrite.recipe:rewrite-static-analysis:2.21.0") + rewrite("org.openrewrite.recipe:rewrite-third-party:0.30.0") +} diff --git a/integration-tests/src/test/java/org/springframework/aop/config/AopNamespaceHandlerAdviceOrderIntegrationTests.java b/integration-tests/src/test/java/org/springframework/aop/config/AopNamespaceHandlerAdviceOrderIntegrationTests.java index 73bce9a78b1a..ec3b6fadf02c 100644 --- a/integration-tests/src/test/java/org/springframework/aop/config/AopNamespaceHandlerAdviceOrderIntegrationTests.java +++ b/integration-tests/src/test/java/org/springframework/aop/config/AopNamespaceHandlerAdviceOrderIntegrationTests.java @@ -78,8 +78,8 @@ void afterAdviceIsInvokedLast(@Autowired Echo echo, @Autowired InvocationTrackin static class Echo { Object echo(Object obj) throws Exception { - if (obj instanceof Exception) { - throw (Exception) obj; + if (obj instanceof Exception exception) { + throw exception; } return obj; } diff --git a/integration-tests/src/test/java/org/springframework/aop/framework/autoproxy/AspectJAutoProxyAdviceOrderIntegrationTests.java b/integration-tests/src/test/java/org/springframework/aop/framework/autoproxy/AspectJAutoProxyAdviceOrderIntegrationTests.java index b645ebd6423f..0304468e798e 100644 --- a/integration-tests/src/test/java/org/springframework/aop/framework/autoproxy/AspectJAutoProxyAdviceOrderIntegrationTests.java +++ b/integration-tests/src/test/java/org/springframework/aop/framework/autoproxy/AspectJAutoProxyAdviceOrderIntegrationTests.java @@ -133,8 +133,8 @@ Echo echo() { static class Echo { Object echo(Object obj) throws Exception { - if (obj instanceof Exception) { - throw (Exception) obj; + if (obj instanceof Exception exception) { + throw exception; } return obj; } diff --git a/rewrite.yml b/rewrite.yml new file mode 100644 index 000000000000..a8e23cab0648 --- /dev/null +++ b/rewrite.yml @@ -0,0 +1,16 @@ +--- +type: specs.openrewrite.org/v1beta/recipe +name: org.opensearch.openrewrite.SanityCheck +displayName: Apply all Java & Gradle best practices +description: Comprehensive code quality recipe combining modernization, security, and best practices. +tags: + - java + - gradle + - static-analysis + - cleanup +recipeList: + - org.openrewrite.gradle.EnableGradleBuildCache + - org.openrewrite.gradle.EnableGradleParallelExecution + - org.openrewrite.gradle.GradleBestPractices + - org.openrewrite.java.migrate.UpgradeToJava17 +--- diff --git a/spring-aop/src/main/java/org/springframework/aop/framework/AdvisedSupport.java b/spring-aop/src/main/java/org/springframework/aop/framework/AdvisedSupport.java index f91792694f06..c25e88f9b195 100644 --- a/spring-aop/src/main/java/org/springframework/aop/framework/AdvisedSupport.java +++ b/spring-aop/src/main/java/org/springframework/aop/framework/AdvisedSupport.java @@ -18,6 +18,7 @@ import java.io.IOException; import java.io.ObjectInputStream; +import java.io.Serial; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; @@ -68,7 +69,7 @@ public class AdvisedSupport extends ProxyConfig implements Advised { /** use serialVersionUID from Spring 2.0 for interoperability. */ - private static final long serialVersionUID = 2651364800145442165L; + @Serial private static final long serialVersionUID = 2651364800145442165L; private static final Advisor[] EMPTY_ADVISOR_ARRAY = new Advisor[0]; diff --git a/spring-aop/src/main/java/org/springframework/aop/framework/DefaultAopProxyFactory.java b/spring-aop/src/main/java/org/springframework/aop/framework/DefaultAopProxyFactory.java index b732c535ebdc..9b7bec30c539 100644 --- a/spring-aop/src/main/java/org/springframework/aop/framework/DefaultAopProxyFactory.java +++ b/spring-aop/src/main/java/org/springframework/aop/framework/DefaultAopProxyFactory.java @@ -16,6 +16,7 @@ package org.springframework.aop.framework; +import java.io.Serial; import java.io.Serializable; import java.lang.reflect.Proxy; @@ -53,7 +54,7 @@ public class DefaultAopProxyFactory implements AopProxyFactory, Serializable { */ public static final DefaultAopProxyFactory INSTANCE = new DefaultAopProxyFactory(); - private static final long serialVersionUID = 7930414337282325166L; + @Serial private static final long serialVersionUID = 7930414337282325166L; @Override diff --git a/spring-aop/src/main/java/org/springframework/aop/framework/JdkDynamicAopProxy.java b/spring-aop/src/main/java/org/springframework/aop/framework/JdkDynamicAopProxy.java index b0016b00c039..548032cbd4db 100644 --- a/spring-aop/src/main/java/org/springframework/aop/framework/JdkDynamicAopProxy.java +++ b/spring-aop/src/main/java/org/springframework/aop/framework/JdkDynamicAopProxy.java @@ -18,6 +18,7 @@ import java.io.IOException; import java.io.ObjectInputStream; +import java.io.Serial; import java.io.Serializable; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; @@ -70,7 +71,7 @@ final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable { /** use serialVersionUID from Spring 1.2 for interoperability. */ - private static final long serialVersionUID = 5531744639992436476L; + @Serial private static final long serialVersionUID = 5531744639992436476L; private static final String COROUTINES_FLOW_CLASS_NAME = "kotlinx.coroutines.flow.Flow"; diff --git a/spring-aop/src/main/java/org/springframework/aop/framework/ProxyConfig.java b/spring-aop/src/main/java/org/springframework/aop/framework/ProxyConfig.java index ca21266ba0ec..dfd102d220f2 100644 --- a/spring-aop/src/main/java/org/springframework/aop/framework/ProxyConfig.java +++ b/spring-aop/src/main/java/org/springframework/aop/framework/ProxyConfig.java @@ -16,6 +16,7 @@ package org.springframework.aop.framework; +import java.io.Serial; import java.io.Serializable; import org.jspecify.annotations.Nullable; @@ -33,7 +34,7 @@ public class ProxyConfig implements Serializable { /** use serialVersionUID from Spring 1.2 for interoperability. */ - private static final long serialVersionUID = -8409359707199703185L; + @Serial private static final long serialVersionUID = -8409359707199703185L; private @Nullable Boolean proxyTargetClass; diff --git a/spring-aop/src/main/java/org/springframework/aop/support/ComposablePointcut.java b/spring-aop/src/main/java/org/springframework/aop/support/ComposablePointcut.java index 572c5e057e83..dd3fcbb2748e 100644 --- a/spring-aop/src/main/java/org/springframework/aop/support/ComposablePointcut.java +++ b/spring-aop/src/main/java/org/springframework/aop/support/ComposablePointcut.java @@ -16,6 +16,7 @@ package org.springframework.aop.support; +import java.io.Serial; import java.io.Serializable; import org.jspecify.annotations.Nullable; @@ -45,7 +46,7 @@ public class ComposablePointcut implements Pointcut, Serializable { /** use serialVersionUID from Spring 1.2 for interoperability. */ - private static final long serialVersionUID = -2743223737633663832L; + @Serial private static final long serialVersionUID = -2743223737633663832L; @SuppressWarnings("serial") private ClassFilter classFilter; diff --git a/spring-aop/src/main/java/org/springframework/aop/target/AbstractBeanFactoryBasedTargetSource.java b/spring-aop/src/main/java/org/springframework/aop/target/AbstractBeanFactoryBasedTargetSource.java index 912efdd9677f..be8faa86e2a7 100644 --- a/spring-aop/src/main/java/org/springframework/aop/target/AbstractBeanFactoryBasedTargetSource.java +++ b/spring-aop/src/main/java/org/springframework/aop/target/AbstractBeanFactoryBasedTargetSource.java @@ -16,6 +16,7 @@ package org.springframework.aop.target; +import java.io.Serial; import java.io.Serializable; import java.util.Objects; @@ -53,7 +54,7 @@ public abstract class AbstractBeanFactoryBasedTargetSource implements TargetSource, BeanFactoryAware, Serializable { /** use serialVersionUID from Spring 1.2.7 for interoperability. */ - private static final long serialVersionUID = -4721607536018568393L; + @Serial private static final long serialVersionUID = -4721607536018568393L; /** Logger available to subclasses. */ diff --git a/spring-aop/src/main/java/org/springframework/aop/target/EmptyTargetSource.java b/spring-aop/src/main/java/org/springframework/aop/target/EmptyTargetSource.java index 8460d4103046..338260c08d07 100644 --- a/spring-aop/src/main/java/org/springframework/aop/target/EmptyTargetSource.java +++ b/spring-aop/src/main/java/org/springframework/aop/target/EmptyTargetSource.java @@ -16,6 +16,7 @@ package org.springframework.aop.target; +import java.io.Serial; import java.io.Serializable; import java.util.Objects; @@ -35,7 +36,7 @@ public final class EmptyTargetSource implements TargetSource, Serializable { /** use serialVersionUID from Spring 1.2 for interoperability. */ - private static final long serialVersionUID = 3680494563553489691L; + @Serial private static final long serialVersionUID = 3680494563553489691L; //--------------------------------------------------------------------- diff --git a/spring-aop/src/main/java/org/springframework/aop/target/HotSwappableTargetSource.java b/spring-aop/src/main/java/org/springframework/aop/target/HotSwappableTargetSource.java index 161bf92d8f8b..2a673ab5ae09 100644 --- a/spring-aop/src/main/java/org/springframework/aop/target/HotSwappableTargetSource.java +++ b/spring-aop/src/main/java/org/springframework/aop/target/HotSwappableTargetSource.java @@ -16,6 +16,7 @@ package org.springframework.aop.target; +import java.io.Serial; import java.io.Serializable; import org.jspecify.annotations.Nullable; @@ -40,7 +41,7 @@ public class HotSwappableTargetSource implements TargetSource, Serializable { /** use serialVersionUID from Spring 1.2 for interoperability. */ - private static final long serialVersionUID = 7497929212653839187L; + @Serial private static final long serialVersionUID = 7497929212653839187L; /** The current target object. */ diff --git a/spring-aop/src/main/java/org/springframework/aop/target/SingletonTargetSource.java b/spring-aop/src/main/java/org/springframework/aop/target/SingletonTargetSource.java index 5422682d91ed..99eadc218bb6 100644 --- a/spring-aop/src/main/java/org/springframework/aop/target/SingletonTargetSource.java +++ b/spring-aop/src/main/java/org/springframework/aop/target/SingletonTargetSource.java @@ -16,6 +16,7 @@ package org.springframework.aop.target; +import java.io.Serial; import java.io.Serializable; import org.jspecify.annotations.Nullable; @@ -40,7 +41,7 @@ public class SingletonTargetSource implements TargetSource, Serializable { /** use serialVersionUID from Spring 1.2 for interoperability. */ - private static final long serialVersionUID = 9031246629662423738L; + @Serial private static final long serialVersionUID = 9031246629662423738L; /** Target cached and invoked using reflection. */ diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/TrickyAspectJPointcutExpressionTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/TrickyAspectJPointcutExpressionTests.java index 7fe2ec7e8859..6805b3786888 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/TrickyAspectJPointcutExpressionTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/TrickyAspectJPointcutExpressionTests.java @@ -54,7 +54,7 @@ void testManualProxyJavaWithStaticPointcut() { TestService target = new TestServiceImpl(); LogUserAdvice logAdvice = new LogUserAdvice(); AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); - pointcut.setExpression(String.format("execution(* %s.TestService.*(..))", getClass().getName())); + pointcut.setExpression("execution(* %s.TestService.*(..))".formatted(getClass().getName())); testAdvice(new DefaultPointcutAdvisor(pointcut, logAdvice), logAdvice, target, "TestServiceImpl"); } @@ -63,7 +63,7 @@ void testManualProxyJavaWithDynamicPointcut() { TestService target = new TestServiceImpl(); LogUserAdvice logAdvice = new LogUserAdvice(); AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); - pointcut.setExpression(String.format("@within(%s.Log)", getClass().getName())); + pointcut.setExpression("@within(%s.Log)".formatted(getClass().getName())); testAdvice(new DefaultPointcutAdvisor(pointcut, logAdvice), logAdvice, target, "TestServiceImpl"); } @@ -72,7 +72,7 @@ void testManualProxyJavaWithDynamicPointcutAndProxyTargetClass() { TestService target = new TestServiceImpl(); LogUserAdvice logAdvice = new LogUserAdvice(); AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); - pointcut.setExpression(String.format("@within(%s.Log)", getClass().getName())); + pointcut.setExpression("@within(%s.Log)".formatted(getClass().getName())); testAdvice(new DefaultPointcutAdvisor(pointcut, logAdvice), logAdvice, target, "TestServiceImpl", true); } @@ -81,7 +81,7 @@ void testManualProxyJavaWithStaticPointcutAndTwoClassLoaders() throws Exception LogUserAdvice logAdvice = new LogUserAdvice(); AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); - pointcut.setExpression(String.format("execution(* %s.TestService.*(..))", getClass().getName())); + pointcut.setExpression("execution(* %s.TestService.*(..))".formatted(getClass().getName())); // Test with default class loader first... testAdvice(new DefaultPointcutAdvisor(pointcut, logAdvice), logAdvice, new TestServiceImpl(), "TestServiceImpl"); diff --git a/spring-beans/src/main/java/org/springframework/beans/ExtendedBeanInfo.java b/spring-beans/src/main/java/org/springframework/beans/ExtendedBeanInfo.java index a346ae41d38d..603d45274409 100644 --- a/spring-beans/src/main/java/org/springframework/beans/ExtendedBeanInfo.java +++ b/spring-beans/src/main/java/org/springframework/beans/ExtendedBeanInfo.java @@ -342,7 +342,7 @@ public int hashCode() { @Override public String toString() { - return String.format("%s[name=%s, propertyType=%s, readMethod=%s, writeMethod=%s]", + return "%s[name=%s, propertyType=%s, readMethod=%s, writeMethod=%s]".formatted( getClass().getSimpleName(), getName(), getPropertyType(), this.readMethod, this.writeMethod); } } diff --git a/spring-beans/src/main/java/org/springframework/beans/propertyeditors/PathEditor.java b/spring-beans/src/main/java/org/springframework/beans/propertyeditors/PathEditor.java index de26e7b70671..0f1b5a93af91 100644 --- a/spring-beans/src/main/java/org/springframework/beans/propertyeditors/PathEditor.java +++ b/spring-beans/src/main/java/org/springframework/beans/propertyeditors/PathEditor.java @@ -22,7 +22,6 @@ import java.net.URISyntaxException; import java.nio.file.FileSystemNotFoundException; import java.nio.file.Path; -import java.nio.file.Paths; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceEditor; @@ -33,7 +32,7 @@ * Editor for {@code java.nio.file.Path}, to directly populate a Path * property instead of using a String property as bridge. * - *

Based on {@link Paths#get(URI)}'s resolution algorithm, checking + *

Based on {@link Path#of(URI)}'s resolution algorithm, checking * registered NIO file system providers, including the default file system * for "file:..." paths. Also supports Spring-style URL notation: any fully * qualified standard URL and Spring's special "classpath:" pseudo-URL, as @@ -44,7 +43,7 @@ * @author Juergen Hoeller * @since 4.3.2 * @see java.nio.file.Path - * @see Paths#get(URI) + * @see Path#of(URI) * @see ResourceEditor * @see org.springframework.core.io.ResourceLoader * @see FileEditor @@ -83,7 +82,7 @@ public void setAsText(String text) throws IllegalArgumentException { // No NIO candidate except for "C:" style drive letters nioPathCandidate = (scheme.length() == 1); // Let's try NIO file system providers via Paths.get(URI) - setValue(Paths.get(uri).normalize()); + setValue(Path.of(uri).normalize()); return; } } @@ -104,7 +103,7 @@ public void setAsText(String text) throws IllegalArgumentException { setValue(null); } else if (nioPathCandidate && (!resource.isFile() || !resource.exists())) { - setValue(Paths.get(text).normalize()); + setValue(Path.of(text).normalize()); } else { try { diff --git a/spring-beans/src/test/java/org/springframework/beans/AbstractPropertyAccessorTests.java b/spring-beans/src/test/java/org/springframework/beans/AbstractPropertyAccessorTests.java index a221cdc8f852..d9342279a606 100644 --- a/spring-beans/src/test/java/org/springframework/beans/AbstractPropertyAccessorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/AbstractPropertyAccessorTests.java @@ -577,8 +577,8 @@ void setStringPropertyWithCustomEditor() { accessor.registerCustomEditor(String.class, "name", new PropertyEditorSupport() { @Override public void setValue(Object value) { - if (value instanceof String[]) { - setValue(StringUtils.arrayToDelimitedString(((String[]) value), "-")); + if (value instanceof String[] strings) { + setValue(StringUtils.arrayToDelimitedString(strings, "-")); } else { super.setValue(value != null ? value : ""); @@ -929,8 +929,8 @@ void setPrimitiveArrayPropertyLargeMatchingWithSpecificEditor() { accessor.registerCustomEditor(int.class, "array", new PropertyEditorSupport() { @Override public void setValue(Object value) { - if (value instanceof Integer) { - super.setValue((Integer) value + 1); + if (value instanceof Integer integer) { + super.setValue(integer + 1); } } }); @@ -947,8 +947,8 @@ void setPrimitiveArrayPropertyLargeMatchingWithIndexSpecificEditor() { accessor.registerCustomEditor(int.class, "array[1]", new PropertyEditorSupport() { @Override public void setValue(Object value) { - if (value instanceof Integer) { - super.setValue((Integer) value + 1); + if (value instanceof Integer integer) { + super.setValue(integer + 1); } } }); diff --git a/spring-beans/src/test/java/org/springframework/beans/ConcurrentBeanWrapperTests.java b/spring-beans/src/test/java/org/springframework/beans/ConcurrentBeanWrapperTests.java index 260996841b3f..2910ac80d548 100644 --- a/spring-beans/src/test/java/org/springframework/beans/ConcurrentBeanWrapperTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/ConcurrentBeanWrapperTests.java @@ -22,6 +22,7 @@ import java.util.Properties; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ThreadLocalRandom; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -84,7 +85,7 @@ private static void performSet() { for (Iterator i = p.entrySet().iterator(); i.hasNext();) { i.next(); - if (Math.random() > 0.9) { + if (ThreadLocalRandom.current().nextDouble() > 0.9) { i.remove(); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/ProtectedLifecycleBean.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/ProtectedLifecycleBean.java index 5d51fa814064..5dea77672b05 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/ProtectedLifecycleBean.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/ProtectedLifecycleBean.java @@ -150,16 +150,16 @@ public static class PostProcessor implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException { - if (bean instanceof ProtectedLifecycleBean) { - ((ProtectedLifecycleBean) bean).postProcessBeforeInit(); + if (bean instanceof ProtectedLifecycleBean lifecycleBean) { + lifecycleBean.postProcessBeforeInit(); } return bean; } @Override public Object postProcessAfterInitialization(Object bean, String name) throws BeansException { - if (bean instanceof ProtectedLifecycleBean) { - ((ProtectedLifecycleBean) bean).postProcessAfterInit(); + if (bean instanceof ProtectedLifecycleBean lifecycleBean) { + lifecycleBean.postProcessAfterInit(); } return bean; } diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PathEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PathEditorTests.java index 4ee774e89d61..96665bcc4b14 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PathEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PathEditorTests.java @@ -19,7 +19,6 @@ import java.beans.PropertyEditor; import java.io.File; import java.nio.file.Path; -import java.nio.file.Paths; import org.junit.jupiter.api.Test; @@ -106,7 +105,7 @@ void testCurrentDirectory() { Object value = pathEditor.getValue(); assertThat(value).isInstanceOf(Path.class); Path path = (Path) value; - assertThat(path).isEqualTo(Paths.get(".")); + assertThat(path).isEqualTo(Path.of(".")); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PropertiesEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PropertiesEditorTests.java index 76d77e50f6a4..b42dcae7d946 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PropertiesEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PropertiesEditorTests.java @@ -47,8 +47,9 @@ void oneProperty() { @Test void twoProperties() { - String s = "foo=bar with whitespace\n" + - "me=mi"; + String s = """ + foo=bar with whitespace + me=mi"""; PropertiesEditor pe= new PropertiesEditor(); pe.setAsText(s); Properties p = (Properties) pe.getValue(); @@ -124,12 +125,14 @@ void ignoresCommentLinesAndEmptyLines() { */ @Test void ignoresLeadingSpacesAndTabs() { - String s = " #Ignore this comment\n" + - "\t\tfoo=bar\n" + - "\t#Another comment more junk \n" + - " me=mi\n" + - "x=x\n" + - "\n"; + String s = """ + #Ignore this comment + foo=bar + #Another comment more junk\s + me=mi + x=x + + """; PropertiesEditor pe= new PropertiesEditor(); pe.setAsText(s); Properties p = (Properties) pe.getValue(); diff --git a/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/LifecycleBean.java b/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/LifecycleBean.java index 2096f4d7c4f7..f717fe01cde3 100644 --- a/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/LifecycleBean.java +++ b/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/LifecycleBean.java @@ -152,16 +152,16 @@ public static class PostProcessor implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException { - if (bean instanceof LifecycleBean) { - ((LifecycleBean) bean).postProcessBeforeInit(); + if (bean instanceof LifecycleBean lifecycleBean) { + lifecycleBean.postProcessBeforeInit(); } return bean; } @Override public Object postProcessAfterInitialization(Object bean, String name) throws BeansException { - if (bean instanceof LifecycleBean) { - ((LifecycleBean) bean).postProcessAfterInit(); + if (bean instanceof LifecycleBean lifecycleBean) { + lifecycleBean.postProcessAfterInit(); } return bean; } diff --git a/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/SerializablePerson.java b/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/SerializablePerson.java index 9d286c0fd2f8..d672e021f68a 100644 --- a/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/SerializablePerson.java +++ b/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/SerializablePerson.java @@ -57,8 +57,8 @@ public void setAge(int age) { @Override public Object echo(Object o) throws Throwable { - if (o instanceof Throwable) { - throw (Throwable) o; + if (o instanceof Throwable throwable) { + throw throwable; } return o; } diff --git a/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/TestBean.java b/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/TestBean.java index 76ea5a53fed5..793e4e747fa1 100644 --- a/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/TestBean.java +++ b/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/TestBean.java @@ -488,8 +488,8 @@ public int hashCode() { @Override public int compareTo(Object other) { - if (this.name != null && other instanceof TestBean) { - return this.name.compareTo(((TestBean) other).getName()); + if (this.name != null && other instanceof TestBean bean) { + return this.name.compareTo(bean.getName()); } else { return 1; diff --git a/spring-context-indexer/spring-context-indexer.gradle b/spring-context-indexer/spring-context-indexer.gradle index a0f311ee6d59..df154ab355de 100644 --- a/spring-context-indexer/spring-context-indexer.gradle +++ b/spring-context-indexer/spring-context-indexer.gradle @@ -1,6 +1,8 @@ description = "Spring Context Indexer" dependencies { + compileOnly "jakarta.annotation:jakarta.annotation-api:1.3.5" + testImplementation(project(":spring-context")) testImplementation("jakarta.annotation:jakarta.annotation-api") testImplementation("jakarta.inject:jakarta.inject-api") diff --git a/spring-context/src/main/java/org/springframework/cache/Cache.java b/spring-context/src/main/java/org/springframework/cache/Cache.java index fb5c7bf07998..c267d21f1a1f 100644 --- a/spring-context/src/main/java/org/springframework/cache/Cache.java +++ b/spring-context/src/main/java/org/springframework/cache/Cache.java @@ -309,7 +309,7 @@ class ValueRetrievalException extends RuntimeException { private final @Nullable Object key; public ValueRetrievalException(@Nullable Object key, Callable loader, @Nullable Throwable ex) { - super(String.format("Value for key '%s' could not be loaded using '%s'", key, loader), ex); + super("Value for key '%s' could not be loaded using '%s'".formatted(key, loader), ex); this.key = key; } diff --git a/spring-context/src/main/java/org/springframework/cache/interceptor/LoggingCacheErrorHandler.java b/spring-context/src/main/java/org/springframework/cache/interceptor/LoggingCacheErrorHandler.java index ff7cb2e59564..69df705f21b1 100644 --- a/spring-context/src/main/java/org/springframework/cache/interceptor/LoggingCacheErrorHandler.java +++ b/spring-context/src/main/java/org/springframework/cache/interceptor/LoggingCacheErrorHandler.java @@ -98,28 +98,28 @@ public LoggingCacheErrorHandler(String loggerName, boolean logStackTraces) { @Override public void handleCacheGetError(RuntimeException exception, Cache cache, Object key) { logCacheError( - () -> String.format("Cache '%s' failed to get entry with key '%s'", cache.getName(), key), + () -> "Cache '%s' failed to get entry with key '%s'".formatted(cache.getName(), key), exception); } @Override public void handleCachePutError(RuntimeException exception, Cache cache, Object key, @Nullable Object value) { logCacheError( - () -> String.format("Cache '%s' failed to put entry with key '%s'", cache.getName(), key), + () -> "Cache '%s' failed to put entry with key '%s'".formatted(cache.getName(), key), exception); } @Override public void handleCacheEvictError(RuntimeException exception, Cache cache, Object key) { logCacheError( - () -> String.format("Cache '%s' failed to evict entry with key '%s'", cache.getName(), key), + () -> "Cache '%s' failed to evict entry with key '%s'".formatted(cache.getName(), key), exception); } @Override public void handleCacheClearError(RuntimeException exception, Cache cache) { logCacheError( - () -> String.format("Cache '%s' failed to clear entries", cache.getName()), + () -> "Cache '%s' failed to clear entries".formatted(cache.getName()), exception); } diff --git a/spring-context/src/main/java/org/springframework/cache/support/NullValue.java b/spring-context/src/main/java/org/springframework/cache/support/NullValue.java index 6e20a95c77d2..be9bba997c9b 100644 --- a/spring-context/src/main/java/org/springframework/cache/support/NullValue.java +++ b/spring-context/src/main/java/org/springframework/cache/support/NullValue.java @@ -16,6 +16,7 @@ package org.springframework.cache.support; +import java.io.Serial; import java.io.Serializable; import org.jspecify.annotations.Nullable; @@ -38,7 +39,7 @@ public final class NullValue implements Serializable { */ public static final Object INSTANCE = new NullValue(); - private static final long serialVersionUID = 1L; + @Serial private static final long serialVersionUID = 1L; private NullValue() { diff --git a/spring-context/src/main/java/org/springframework/context/ApplicationEvent.java b/spring-context/src/main/java/org/springframework/context/ApplicationEvent.java index f53c0eebfa87..5a0324b756ea 100644 --- a/spring-context/src/main/java/org/springframework/context/ApplicationEvent.java +++ b/spring-context/src/main/java/org/springframework/context/ApplicationEvent.java @@ -16,6 +16,7 @@ package org.springframework.context; +import java.io.Serial; import java.time.Clock; import java.util.EventObject; @@ -31,7 +32,7 @@ public abstract class ApplicationEvent extends EventObject { /** use serialVersionUID from Spring 1.2 for interoperability. */ - private static final long serialVersionUID = 7099057708183571937L; + @Serial private static final long serialVersionUID = 7099057708183571937L; /** System time when the event happened. */ private final long timestamp; diff --git a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java index 6ae194adfb23..2345d13f06c7 100644 --- a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java +++ b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java @@ -127,7 +127,7 @@ public Class enhance(Class configClass, @Nullable ClassLoader classLoader) Enhancer enhancer = newEnhancer(configClass, classLoader); Class enhancedClass = createClass(enhancer, classLoaderMismatch); if (logger.isTraceEnabled()) { - logger.trace(String.format("Successfully enhanced %s; enhanced class name is: %s", + logger.trace("Successfully enhanced %s; enhanced class name is: %s".formatted( configClass.getName(), enhancedClass.getName())); } return enhancedClass; diff --git a/spring-context/src/main/java/org/springframework/context/annotation/ImportAwareAotBeanPostProcessor.java b/spring-context/src/main/java/org/springframework/context/annotation/ImportAwareAotBeanPostProcessor.java index c0c196aa5b1f..6548486071d6 100644 --- a/spring-context/src/main/java/org/springframework/context/annotation/ImportAwareAotBeanPostProcessor.java +++ b/spring-context/src/main/java/org/springframework/context/annotation/ImportAwareAotBeanPostProcessor.java @@ -72,7 +72,7 @@ private void setAnnotationMetadata(ImportAware instance) { instance.setImportMetadata(metadataReader.getAnnotationMetadata()); } catch (IOException ex) { - throw new IllegalStateException(String.format("Failed to read metadata for '%s'", importingClass), ex); + throw new IllegalStateException("Failed to read metadata for '%s'".formatted(importingClass), ex); } } diff --git a/spring-context/src/main/java/org/springframework/context/aot/ContextAotProcessor.java b/spring-context/src/main/java/org/springframework/context/aot/ContextAotProcessor.java index ddfc13b5f38c..8ba11c69e01c 100644 --- a/spring-context/src/main/java/org/springframework/context/aot/ContextAotProcessor.java +++ b/spring-context/src/main/java/org/springframework/context/aot/ContextAotProcessor.java @@ -157,7 +157,7 @@ private void writeNativeImageProperties(List args) { } StringBuilder sb = new StringBuilder(); sb.append("Args = "); - sb.append(String.join(String.format(" \\%n"), args)); + sb.append(String.join(" \\%n".formatted(), args)); Path file = getSettings().getResourceOutput().resolve("META-INF/native-image/" + getSettings().getGroupId() + "/" + getSettings().getArtifactId() + "/native-image.properties"); try { diff --git a/spring-context/src/main/java/org/springframework/format/datetime/DateFormatter.java b/spring-context/src/main/java/org/springframework/format/datetime/DateFormatter.java index e9c89586b088..b8d639054571 100644 --- a/spring-context/src/main/java/org/springframework/format/datetime/DateFormatter.java +++ b/spring-context/src/main/java/org/springframework/format/datetime/DateFormatter.java @@ -238,7 +238,7 @@ public Date parse(String text, Locale locale) throws ParseException { } if (this.source != null) { ParseException parseException = new ParseException( - String.format("Unable to parse date time value \"%s\" using configuration from %s", text, this.source), + "Unable to parse date time value \"%s\" using configuration from %s".formatted(text, this.source), ex.getErrorOffset()); parseException.initCause(ex); throw parseException; diff --git a/spring-context/src/main/java/org/springframework/format/datetime/standard/TemporalAccessorParser.java b/spring-context/src/main/java/org/springframework/format/datetime/standard/TemporalAccessorParser.java index 291f36cdb0df..34c6bc367563 100644 --- a/spring-context/src/main/java/org/springframework/format/datetime/standard/TemporalAccessorParser.java +++ b/spring-context/src/main/java/org/springframework/format/datetime/standard/TemporalAccessorParser.java @@ -115,7 +115,7 @@ public TemporalAccessor parse(String text, Locale locale) throws ParseException } if (this.source != null) { throw new DateTimeParseException( - String.format("Unable to parse date time value \"%s\" using configuration from %s", text, this.source), + "Unable to parse date time value \"%s\" using configuration from %s".formatted(text, this.source), text, ex.getErrorIndex(), ex); } // else rethrow original exception diff --git a/spring-context/src/main/java/org/springframework/scheduling/support/CronExpression.java b/spring-context/src/main/java/org/springframework/scheduling/support/CronExpression.java index c81c0687f4af..3cf1a78882fc 100644 --- a/spring-context/src/main/java/org/springframework/scheduling/support/CronExpression.java +++ b/spring-context/src/main/java/org/springframework/scheduling/support/CronExpression.java @@ -180,8 +180,7 @@ public static CronExpression parse(String expression) { String[] fields = StringUtils.tokenizeToStringArray(expression, " "); if (fields.length != 6) { - throw new IllegalArgumentException(String.format( - "Cron expression must consist of 6 fields (found %d in \"%s\")", fields.length, expression)); + throw new IllegalArgumentException("Cron expression must consist of 6 fields (found %d in \"%s\")".formatted(fields.length, expression)); } try { CronField seconds = CronField.parseSeconds(fields[0]); diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTestTypes.java b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTestTypes.java index 83370a3e06ca..1cd4618e9880 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTestTypes.java +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTestTypes.java @@ -563,16 +563,16 @@ public static class PostProcessor implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException { - if (bean instanceof ProtectedLifecycleBean) { - ((ProtectedLifecycleBean) bean).postProcessBeforeInit(); + if (bean instanceof ProtectedLifecycleBean lifecycleBean) { + lifecycleBean.postProcessBeforeInit(); } return bean; } @Override public Object postProcessAfterInitialization(Object bean, String name) throws BeansException { - if (bean instanceof ProtectedLifecycleBean) { - ((ProtectedLifecycleBean) bean).postProcessAfterInit(); + if (bean instanceof ProtectedLifecycleBean lifecycleBean) { + lifecycleBean.postProcessAfterInit(); } return bean; } diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/support/CustomNamespaceHandlerTests.java b/spring-context/src/test/java/org/springframework/beans/factory/xml/support/CustomNamespaceHandlerTests.java index d3d6bba777ca..f0fc8d56533f 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/support/CustomNamespaceHandlerTests.java +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/support/CustomNamespaceHandlerTests.java @@ -59,7 +59,6 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; -import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -77,9 +76,9 @@ class CustomNamespaceHandlerTests { private static final String CLASSNAME = CLASS.getSimpleName(); private static final String FQ_PATH = "org/springframework/beans/factory/xml/support"; - private static final String NS_PROPS = format("%s/%s.properties", FQ_PATH, CLASSNAME); - private static final String NS_XML = format("%s/%s-context.xml", FQ_PATH, CLASSNAME); - private static final String TEST_XSD = format("%s/%s.xsd", FQ_PATH, CLASSNAME); + private static final String NS_PROPS = "%s/%s.properties".formatted(FQ_PATH, CLASSNAME); + private static final String NS_XML = "%s/%s-context.xml".formatted(FQ_PATH, CLASSNAME); + private static final String TEST_XSD = "%s/%s.xsd".formatted(FQ_PATH, CLASSNAME); private GenericApplicationContext beanFactory; diff --git a/spring-context/src/test/java/org/springframework/cache/interceptor/CacheProxyFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/cache/interceptor/CacheProxyFactoryBeanTests.java index 7965dfd9a9c2..6d30fbd2c9dc 100644 --- a/spring-context/src/test/java/org/springframework/cache/interceptor/CacheProxyFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/cache/interceptor/CacheProxyFactoryBeanTests.java @@ -106,7 +106,7 @@ default String greet() { default String greet(String name) { setCacheMiss(); - return String.format("Hello %s!", name); + return "Hello %s!".formatted(name); } } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/AnnotationConfigApplicationContextTests.java b/spring-context/src/test/java/org/springframework/context/annotation/AnnotationConfigApplicationContextTests.java index 1864d8899e38..288ec534837c 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/AnnotationConfigApplicationContextTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/AnnotationConfigApplicationContextTests.java @@ -41,7 +41,6 @@ import org.springframework.core.ResolvableType; import org.springframework.util.ObjectUtils; -import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.util.StringUtils.uncapitalize; @@ -137,7 +136,7 @@ void getBeanByTypeRaisesNoSuchBeanDefinitionException() { Class targetType = Pattern.class; assertThatExceptionOfType(NoSuchBeanDefinitionException.class) .isThrownBy(() -> context.getBean(targetType)) - .withMessageContaining(format("No qualifying bean of type '%s'", targetType.getName())); + .withMessageContaining("No qualifying bean of type '%s'".formatted(targetType.getName())); } @Test diff --git a/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java b/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java index 33b9c663d99a..03606c037b67 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java @@ -532,24 +532,24 @@ public static class InitDestroyBeanPostProcessor implements DestructionAwareBean @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { - if (bean instanceof AnnotatedInitDestroyBean) { - assertThat(((AnnotatedInitDestroyBean) bean).initCalled).isFalse(); + if (bean instanceof AnnotatedInitDestroyBean destroyBean) { + assertThat(destroyBean.initCalled).isFalse(); } return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { - if (bean instanceof AnnotatedInitDestroyBean) { - assertThat(((AnnotatedInitDestroyBean) bean).initCalled).isTrue(); + if (bean instanceof AnnotatedInitDestroyBean destroyBean) { + assertThat(destroyBean.initCalled).isTrue(); } return bean; } @Override public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException { - if (bean instanceof AnnotatedInitDestroyBean) { - assertThat(((AnnotatedInitDestroyBean) bean).destroyCalled).isFalse(); + if (bean instanceof AnnotatedInitDestroyBean destroyBean) { + assertThat(destroyBean.destroyCalled).isFalse(); } } diff --git a/spring-context/src/test/java/org/springframework/jmx/support/JmxUtilsTests.java b/spring-context/src/test/java/org/springframework/jmx/support/JmxUtilsTests.java index 10e56fe318a3..0634d9c8c463 100644 --- a/spring-context/src/test/java/org/springframework/jmx/support/JmxUtilsTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/support/JmxUtilsTests.java @@ -196,7 +196,7 @@ public void dontExposeMe() { } - public interface FooMBean { + public public interface FooMBean { String getName(); } @@ -211,7 +211,7 @@ public String getName() { } - public interface FooMXBean { + public public interface FooMXBean { String getName(); } @@ -234,7 +234,7 @@ public static class Abc extends Bar { } - private interface JmxInterfaceMBean { + public interface JmxInterfaceMBean { } @@ -246,7 +246,7 @@ private interface SpecializedJmxInterface extends JmxInterface { } - private interface JmxClassMBean { + public interface JmxClassMBean { } diff --git a/spring-context/src/test/java/org/springframework/scheduling/concurrent/AbstractSchedulingTaskExecutorTests.java b/spring-context/src/test/java/org/springframework/scheduling/concurrent/AbstractSchedulingTaskExecutorTests.java index db2bbb79d59e..cc1a59fc120f 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/concurrent/AbstractSchedulingTaskExecutorTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/concurrent/AbstractSchedulingTaskExecutorTests.java @@ -290,8 +290,7 @@ public void run() { } if (expectedRunCount >= 0) { if (actualRunCount.incrementAndGet() > expectedRunCount) { - RuntimeException exception = new RuntimeException(String.format( - "%s failure for test '%s': expectedRunCount:<%d>, actualRunCount:<%d>", + RuntimeException exception = new RuntimeException("%s failure for test '%s': expectedRunCount:<%d>, actualRunCount:<%d>".formatted( getClass().getSimpleName(), this.testName, expectedRunCount, actualRunCount.get())); this.exception.set(exception); throw exception; @@ -324,8 +323,7 @@ public String call() { } if (expectedRunCount >= 0) { if (actualRunCount.incrementAndGet() > expectedRunCount) { - throw new RuntimeException(String.format( - "%s failure for test '%s': expectedRunCount:<%d>, actualRunCount:<%d>", + throw new RuntimeException("%s failure for test '%s': expectedRunCount:<%d>, actualRunCount:<%d>".formatted( getClass().getSimpleName(), this.testName, expectedRunCount, actualRunCount.get())); } } diff --git a/spring-context/src/test/java/org/springframework/scheduling/concurrent/ConcurrentTaskExecutorTests.java b/spring-context/src/test/java/org/springframework/scheduling/concurrent/ConcurrentTaskExecutorTests.java index b56150a99605..784f5cb168d1 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/concurrent/ConcurrentTaskExecutorTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/concurrent/ConcurrentTaskExecutorTests.java @@ -52,8 +52,8 @@ protected AsyncTaskExecutor buildExecutor() { @Override void shutdownExecutor() { for (Runnable task : concurrentExecutor.shutdownNow()) { - if (task instanceof Future) { - ((Future) task).cancel(true); + if (task instanceof Future future) { + future.cancel(true); } } } diff --git a/spring-context/src/test/java/org/springframework/scheduling/concurrent/ConcurrentTaskSchedulerTests.java b/spring-context/src/test/java/org/springframework/scheduling/concurrent/ConcurrentTaskSchedulerTests.java index 314a855a83d9..a03173c01e08 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/concurrent/ConcurrentTaskSchedulerTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/concurrent/ConcurrentTaskSchedulerTests.java @@ -66,8 +66,8 @@ protected AsyncTaskExecutor buildExecutor() { @Override void shutdownExecutor() { for (Runnable task : ((ExecutorService) scheduler.getConcurrentExecutor()).shutdownNow()) { - if (task instanceof Future) { - ((Future) task).cancel(true); + if (task instanceof Future future) { + future.cancel(true); } } } diff --git a/spring-context/src/test/java/org/springframework/scheduling/support/BitsCronFieldTests.java b/spring-context/src/test/java/org/springframework/scheduling/support/BitsCronFieldTests.java index bb28e0f3ec1e..b3b52c57adcd 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/support/BitsCronFieldTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/support/BitsCronFieldTests.java @@ -114,7 +114,7 @@ void names() { private static Condition set(int... indices) { - return new Condition<>(String.format("set bits %s", Arrays.toString(indices))) { + return new Condition<>("set bits %s".formatted(Arrays.toString(indices))) { @Override public boolean matches(BitsCronField value) { for (int index : indices) { @@ -128,7 +128,7 @@ public boolean matches(BitsCronField value) { } private static Condition setRange(int min, int max) { - return new Condition<>(String.format("set range %d-%d", min, max)) { + return new Condition<>("set range %d-%d".formatted(min, max)) { @Override public boolean matches(BitsCronField value) { for (int i = min; i < max; i++) { @@ -142,7 +142,7 @@ public boolean matches(BitsCronField value) { } private static Condition clear(int... indices) { - return new Condition<>(String.format("clear bits %s", Arrays.toString(indices))) { + return new Condition<>("clear bits %s".formatted(Arrays.toString(indices))) { @Override public boolean matches(BitsCronField value) { for (int index : indices) { @@ -156,7 +156,7 @@ public boolean matches(BitsCronField value) { } private static Condition clearRange(int min, int max) { - return new Condition<>(String.format("clear range %d-%d", min, max)) { + return new Condition<>("clear range %d-%d".formatted(min, max)) { @Override public boolean matches(BitsCronField value) { for (int i = min; i < max; i++) { diff --git a/spring-context/src/test/java/org/springframework/scheduling/support/PeriodicTriggerTests.java b/spring-context/src/test/java/org/springframework/scheduling/support/PeriodicTriggerTests.java index fe06d3fadc95..388b854e0715 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/support/PeriodicTriggerTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/support/PeriodicTriggerTests.java @@ -231,12 +231,12 @@ private static TriggerContext context(@Nullable Object scheduled, @Nullable Obje if (o == null) { return null; } - if (o instanceof Instant) { - return (Instant) o; + if (o instanceof Instant instant) { + return instant; } - if (o instanceof Number) { + if (o instanceof Number number) { return Instant.now() - .plus(NumberUtils.convertNumberToTargetClass((Number) o, Long.class), + .plus(NumberUtils.convertNumberToTargetClass(number, Long.class), ChronoUnit.MILLIS); } throw new IllegalArgumentException( diff --git a/spring-context/src/testFixtures/java/org/springframework/context/testfixture/jndi/SimpleNamingContextBuilder.java b/spring-context/src/testFixtures/java/org/springframework/context/testfixture/jndi/SimpleNamingContextBuilder.java index 182f8ce85198..8f754e8af3d2 100644 --- a/spring-context/src/testFixtures/java/org/springframework/context/testfixture/jndi/SimpleNamingContextBuilder.java +++ b/spring-context/src/testFixtures/java/org/springframework/context/testfixture/jndi/SimpleNamingContextBuilder.java @@ -204,11 +204,11 @@ public InitialContextFactory createInitialContextFactory(@Nullable Hashtable icfClass; - if (icf instanceof Class) { - icfClass = (Class) icf; + if (icf instanceof Class class1) { + icfClass = class1; } - else if (icf instanceof String) { - icfClass = ClassUtils.resolveClassName((String) icf, getClass().getClassLoader()); + else if (icf instanceof String string) { + icfClass = ClassUtils.resolveClassName(string, getClass().getClassLoader()); } else { throw new IllegalArgumentException("Invalid value type for environment key [" + diff --git a/spring-core-test/spring-core-test.gradle b/spring-core-test/spring-core-test.gradle index a398ed30c3bf..f80bcf9b2d94 100644 --- a/spring-core-test/spring-core-test.gradle +++ b/spring-core-test/spring-core-test.gradle @@ -2,7 +2,8 @@ description = "Spring Core Test" dependencies { api(project(":spring-core")) - optional("org.assertj:assertj-core") + compileOnly "jakarta.annotation:jakarta.annotation-api:1.3.5" + optional("org.assertj:assertj-core") optional("org.junit.jupiter:junit-jupiter-api") compileOnly("org.junit.jupiter:junit-jupiter-params") // Used in CompileWithForkedClassLoaderExtension Javadoc compileOnly("org.junit.platform:junit-platform-launcher") // Used in CompileWithForkedClassLoaderExtension diff --git a/spring-core/src/jmh/java/org/springframework/core/codec/StringDecoderBenchmark.java b/spring-core/src/jmh/java/org/springframework/core/codec/StringDecoderBenchmark.java index 4345a09e5884..61b9ad6cb37f 100644 --- a/spring-core/src/jmh/java/org/springframework/core/codec/StringDecoderBenchmark.java +++ b/spring-core/src/jmh/java/org/springframework/core/codec/StringDecoderBenchmark.java @@ -87,7 +87,7 @@ public void setup() { """; - int eventLength = String.format(eventTemplate, String.format("%05d", 1)).length(); + int eventLength = eventTemplate.formatted("%05d".formatted(1)).length(); int eventCount = this.totalSize / eventLength; DataBufferFactory bufferFactory = new DefaultDataBufferFactory(); diff --git a/spring-core/src/main/java/org/springframework/aot/generate/GeneratedClass.java b/spring-core/src/main/java/org/springframework/aot/generate/GeneratedClass.java index e7137dc1e3a3..72b61cb337f4 100644 --- a/spring-core/src/main/java/org/springframework/aot/generate/GeneratedClass.java +++ b/spring-core/src/main/java/org/springframework/aot/generate/GeneratedClass.java @@ -83,7 +83,7 @@ public void reserveMethodNames(String... reservedMethodNames) { for (String reservedMethodName : reservedMethodNames) { String generatedName = generateSequencedMethodName(MethodName.of(reservedMethodNames)); Assert.state(generatedName.equals(reservedMethodName), - () -> String.format("Unable to reserve method name '%s'", reservedMethodName)); + () -> "Unable to reserve method name '%s'".formatted(reservedMethodName)); } } diff --git a/spring-core/src/main/java/org/springframework/aot/generate/ValueCodeGeneratorDelegates.java b/spring-core/src/main/java/org/springframework/aot/generate/ValueCodeGeneratorDelegates.java index b402d623a280..8fe866ecdd3c 100644 --- a/spring-core/src/main/java/org/springframework/aot/generate/ValueCodeGeneratorDelegates.java +++ b/spring-core/src/main/java/org/springframework/aot/generate/ValueCodeGeneratorDelegates.java @@ -238,7 +238,7 @@ private String escape(char ch) { return escaped; } return (!Character.isISOControl(ch)) ? Character.toString(ch) : - String.format("\\u%04x", (int) ch); + "\\u%04x".formatted((int) ch); } } diff --git a/spring-core/src/main/java/org/springframework/aot/nativex/BasicJsonWriter.java b/spring-core/src/main/java/org/springframework/aot/nativex/BasicJsonWriter.java index f581b752fae1..1bffbd1203cf 100644 --- a/spring-core/src/main/java/org/springframework/aot/nativex/BasicJsonWriter.java +++ b/spring-core/src/main/java/org/springframework/aot/nativex/BasicJsonWriter.java @@ -164,7 +164,7 @@ private static String escape(CharSequence input) { case '\t' -> "\\t"; default -> { if (c <= 0x1F) { - yield String.format("\\u%04x", c); + yield "\\u%04x".formatted(c); } else { yield (char) c; diff --git a/spring-core/src/main/java/org/springframework/asm/AnnotationWriter.java b/spring-core/src/main/java/org/springframework/asm/AnnotationWriter.java index 50f054b9e2a6..8d0b6d7573de 100644 --- a/spring-core/src/main/java/org/springframework/asm/AnnotationWriter.java +++ b/spring-core/src/main/java/org/springframework/asm/AnnotationWriter.java @@ -194,63 +194,55 @@ public void visit(final String name, final Object value) { if (useNamedValues) { annotation.putShort(symbolTable.addConstantUtf8(name)); } - if (value instanceof String) { - annotation.put12('s', symbolTable.addConstantUtf8((String) value)); - } else if (value instanceof Byte) { - annotation.put12('B', symbolTable.addConstantInteger(((Byte) value).byteValue()).index); - } else if (value instanceof Boolean) { - int booleanValue = ((Boolean) value).booleanValue() ? 1 : 0; + if (value instanceof String string) { + annotation.put12('s', symbolTable.addConstantUtf8(string)); + } else if (value instanceof Byte byte1) { + annotation.put12('B', symbolTable.addConstantInteger(byte1.byteValue()).index); + } else if (value instanceof Boolean boolean1) { + int booleanValue = boolean1.booleanValue() ? 1 : 0; annotation.put12('Z', symbolTable.addConstantInteger(booleanValue).index); - } else if (value instanceof Character) { - annotation.put12('C', symbolTable.addConstantInteger(((Character) value).charValue()).index); - } else if (value instanceof Short) { - annotation.put12('S', symbolTable.addConstantInteger(((Short) value).shortValue()).index); - } else if (value instanceof Type) { - annotation.put12('c', symbolTable.addConstantUtf8(((Type) value).getDescriptor())); - } else if (value instanceof byte[]) { - byte[] byteArray = (byte[]) value; + } else if (value instanceof Character character) { + annotation.put12('C', symbolTable.addConstantInteger(character.charValue()).index); + } else if (value instanceof Short short1) { + annotation.put12('S', symbolTable.addConstantInteger(short1.shortValue()).index); + } else if (value instanceof Type type) { + annotation.put12('c', symbolTable.addConstantUtf8(type.getDescriptor())); + } else if (value instanceof byte[] byteArray) { annotation.put12('[', byteArray.length); for (byte byteValue : byteArray) { annotation.put12('B', symbolTable.addConstantInteger(byteValue).index); } - } else if (value instanceof boolean[]) { - boolean[] booleanArray = (boolean[]) value; + } else if (value instanceof boolean[] booleanArray) { annotation.put12('[', booleanArray.length); for (boolean booleanValue : booleanArray) { annotation.put12('Z', symbolTable.addConstantInteger(booleanValue ? 1 : 0).index); } - } else if (value instanceof short[]) { - short[] shortArray = (short[]) value; + } else if (value instanceof short[] shortArray) { annotation.put12('[', shortArray.length); for (short shortValue : shortArray) { annotation.put12('S', symbolTable.addConstantInteger(shortValue).index); } - } else if (value instanceof char[]) { - char[] charArray = (char[]) value; + } else if (value instanceof char[] charArray) { annotation.put12('[', charArray.length); for (char charValue : charArray) { annotation.put12('C', symbolTable.addConstantInteger(charValue).index); } - } else if (value instanceof int[]) { - int[] intArray = (int[]) value; + } else if (value instanceof int[] intArray) { annotation.put12('[', intArray.length); for (int intValue : intArray) { annotation.put12('I', symbolTable.addConstantInteger(intValue).index); } - } else if (value instanceof long[]) { - long[] longArray = (long[]) value; + } else if (value instanceof long[] longArray) { annotation.put12('[', longArray.length); for (long longValue : longArray) { annotation.put12('J', symbolTable.addConstantLong(longValue).index); } - } else if (value instanceof float[]) { - float[] floatArray = (float[]) value; + } else if (value instanceof float[] floatArray) { annotation.put12('[', floatArray.length); for (float floatValue : floatArray) { annotation.put12('F', symbolTable.addConstantFloat(floatValue).index); } - } else if (value instanceof double[]) { - double[] doubleArray = (double[]) value; + } else if (value instanceof double[] doubleArray) { annotation.put12('[', doubleArray.length); for (double doubleValue : doubleArray) { annotation.put12('D', symbolTable.addConstantDouble(doubleValue).index); diff --git a/spring-core/src/main/java/org/springframework/asm/ClassReader.java b/spring-core/src/main/java/org/springframework/asm/ClassReader.java index 5fc6edbe7e89..18b25d4a750c 100644 --- a/spring-core/src/main/java/org/springframework/asm/ClassReader.java +++ b/spring-core/src/main/java/org/springframework/asm/ClassReader.java @@ -1371,8 +1371,7 @@ private int readMethod( // adapter between the reader and the writer. In this case, it might be possible to copy // the method attributes directly into the writer. If so, return early without visiting // the content of these attributes. - if (methodVisitor instanceof MethodWriter) { - MethodWriter methodWriter = (MethodWriter) methodVisitor; + if (methodVisitor instanceof MethodWriter methodWriter) { if (methodWriter.canCopyMethodAttributes( this, synthetic, diff --git a/spring-core/src/main/java/org/springframework/asm/ClassTooLargeException.java b/spring-core/src/main/java/org/springframework/asm/ClassTooLargeException.java index bc6a96dede4c..195d57acab84 100644 --- a/spring-core/src/main/java/org/springframework/asm/ClassTooLargeException.java +++ b/spring-core/src/main/java/org/springframework/asm/ClassTooLargeException.java @@ -27,6 +27,8 @@ // THE POSSIBILITY OF SUCH DAMAGE. package org.springframework.asm; +import java.io.Serial; + /** * Exception thrown when the constant pool of a class produced by a {@link ClassWriter} is too * large. @@ -34,7 +36,7 @@ * @author Jason Zaugg */ public final class ClassTooLargeException extends IndexOutOfBoundsException { - private static final long serialVersionUID = 160715609518896765L; + @Serial private static final long serialVersionUID = 160715609518896765L; private final String className; private final int constantPoolCount; diff --git a/spring-core/src/main/java/org/springframework/asm/Frame.java b/spring-core/src/main/java/org/springframework/asm/Frame.java index d70e18096ac2..39919217e92d 100644 --- a/spring-core/src/main/java/org/springframework/asm/Frame.java +++ b/spring-core/src/main/java/org/springframework/asm/Frame.java @@ -282,10 +282,10 @@ final void copyFrom(final Frame frame) { * @return the abstract type corresponding to the given frame element type. */ static int getAbstractTypeFromApiFormat(final SymbolTable symbolTable, final Object type) { - if (type instanceof Integer) { - return CONSTANT_KIND | ((Integer) type).intValue(); - } else if (type instanceof String) { - String descriptor = Type.getObjectType((String) type).getDescriptor(); + if (type instanceof Integer integer) { + return CONSTANT_KIND | integer.intValue(); + } else if (type instanceof String string) { + String descriptor = Type.getObjectType(string).getDescriptor(); return getAbstractTypeFromDescriptor(symbolTable, descriptor, 0); } else { Label label = (Label) type; diff --git a/spring-core/src/main/java/org/springframework/asm/MethodTooLargeException.java b/spring-core/src/main/java/org/springframework/asm/MethodTooLargeException.java index b41ec8b588ea..4cdd2fead518 100644 --- a/spring-core/src/main/java/org/springframework/asm/MethodTooLargeException.java +++ b/spring-core/src/main/java/org/springframework/asm/MethodTooLargeException.java @@ -27,6 +27,8 @@ // THE POSSIBILITY OF SUCH DAMAGE. package org.springframework.asm; +import java.io.Serial; + /** * Exception thrown when the Code attribute of a method produced by a {@link ClassWriter} is too * large. @@ -34,7 +36,7 @@ * @author Jason Zaugg */ public final class MethodTooLargeException extends IndexOutOfBoundsException { - private static final long serialVersionUID = 6807380416709738314L; + @Serial private static final long serialVersionUID = 6807380416709738314L; private final String className; private final String methodName; diff --git a/spring-core/src/main/java/org/springframework/asm/MethodVisitor.java b/spring-core/src/main/java/org/springframework/asm/MethodVisitor.java index 7fc511d4e625..f15011d7c47b 100644 --- a/spring-core/src/main/java/org/springframework/asm/MethodVisitor.java +++ b/spring-core/src/main/java/org/springframework/asm/MethodVisitor.java @@ -551,7 +551,7 @@ public void visitLabel(final Label label) { public void visitLdcInsn(final Object value) { if (api < Opcodes.ASM5 && (value instanceof Handle - || (value instanceof Type && ((Type) value).getSort() == Type.METHOD))) { + || (value instanceof Type type && type.getSort() == Type.METHOD))) { throw new UnsupportedOperationException(REQUIRES_ASM5); } if (api < Opcodes.ASM7 && value instanceof ConstantDynamic) { diff --git a/spring-core/src/main/java/org/springframework/asm/MethodWriter.java b/spring-core/src/main/java/org/springframework/asm/MethodWriter.java index 0e7eab3817d8..eb05fca78fae 100644 --- a/spring-core/src/main/java/org/springframework/asm/MethodWriter.java +++ b/spring-core/src/main/java/org/springframework/asm/MethodWriter.java @@ -1973,12 +1973,12 @@ private void putAbstractTypes(final int start, final int end) { * a NEW instruction (for uninitialized types). */ private void putFrameType(final Object type) { - if (type instanceof Integer) { - stackMapTableEntries.putByte(((Integer) type).intValue()); - } else if (type instanceof String) { + if (type instanceof Integer integer) { + stackMapTableEntries.putByte(integer.intValue()); + } else if (type instanceof String string) { stackMapTableEntries .putByte(Frame.ITEM_OBJECT) - .putShort(symbolTable.addConstantClass((String) type).index); + .putShort(symbolTable.addConstantClass(string).index); } else { stackMapTableEntries.putByte(Frame.ITEM_UNINITIALIZED); ((Label) type).put(stackMapTableEntries); diff --git a/spring-core/src/main/java/org/springframework/asm/SymbolTable.java b/spring-core/src/main/java/org/springframework/asm/SymbolTable.java index 09e3d8e56444..0388580c4f52 100644 --- a/spring-core/src/main/java/org/springframework/asm/SymbolTable.java +++ b/spring-core/src/main/java/org/springframework/asm/SymbolTable.java @@ -480,26 +480,25 @@ private void add(final Entry entry) { * @return a new or already existing Symbol with the given value. */ Symbol addConstant(final Object value) { - if (value instanceof Integer) { - return addConstantInteger(((Integer) value).intValue()); - } else if (value instanceof Byte) { - return addConstantInteger(((Byte) value).intValue()); - } else if (value instanceof Character) { - return addConstantInteger(((Character) value).charValue()); - } else if (value instanceof Short) { - return addConstantInteger(((Short) value).intValue()); - } else if (value instanceof Boolean) { - return addConstantInteger(((Boolean) value).booleanValue() ? 1 : 0); - } else if (value instanceof Float) { - return addConstantFloat(((Float) value).floatValue()); - } else if (value instanceof Long) { - return addConstantLong(((Long) value).longValue()); - } else if (value instanceof Double) { - return addConstantDouble(((Double) value).doubleValue()); - } else if (value instanceof String) { - return addConstantString((String) value); - } else if (value instanceof Type) { - Type type = (Type) value; + if (value instanceof Integer integer) { + return addConstantInteger(integer.intValue()); + } else if (value instanceof Byte byte1) { + return addConstantInteger(byte1.intValue()); + } else if (value instanceof Character character) { + return addConstantInteger(character.charValue()); + } else if (value instanceof Short short1) { + return addConstantInteger(short1.intValue()); + } else if (value instanceof Boolean boolean1) { + return addConstantInteger(boolean1.booleanValue() ? 1 : 0); + } else if (value instanceof Float float1) { + return addConstantFloat(float1.floatValue()); + } else if (value instanceof Long long1) { + return addConstantLong(long1.longValue()); + } else if (value instanceof Double double1) { + return addConstantDouble(double1.doubleValue()); + } else if (value instanceof String string) { + return addConstantString(string); + } else if (value instanceof Type type) { int typeSort = type.getSort(); if (typeSort == Type.OBJECT) { return addConstantClass(type.getInternalName()); @@ -508,16 +507,14 @@ Symbol addConstant(final Object value) { } else { // type is a primitive or array type. return addConstantClass(type.getDescriptor()); } - } else if (value instanceof Handle) { - Handle handle = (Handle) value; + } else if (value instanceof Handle handle) { return addConstantMethodHandle( handle.getTag(), handle.getOwner(), handle.getName(), handle.getDesc(), handle.isInterface()); - } else if (value instanceof ConstantDynamic) { - ConstantDynamic constantDynamic = (ConstantDynamic) value; + } else if (value instanceof ConstantDynamic constantDynamic) { return addConstantDynamic( constantDynamic.getName(), constantDynamic.getDescriptor(), diff --git a/spring-core/src/main/java/org/springframework/core/AttributeAccessor.java b/spring-core/src/main/java/org/springframework/core/AttributeAccessor.java index 17472414bfad..9e4117dbcc68 100644 --- a/spring-core/src/main/java/org/springframework/core/AttributeAccessor.java +++ b/spring-core/src/main/java/org/springframework/core/AttributeAccessor.java @@ -77,7 +77,7 @@ default T computeAttribute(String name, Function computeFunction) if (value == null) { value = computeFunction.apply(name); Assert.state(value != null, - () -> String.format("Compute function must not return null for attribute named '%s'", name)); + () -> "Compute function must not return null for attribute named '%s'".formatted(name)); setAttribute(name, value); } return (T) value; diff --git a/spring-core/src/main/java/org/springframework/core/AttributeAccessorSupport.java b/spring-core/src/main/java/org/springframework/core/AttributeAccessorSupport.java index b20a5008bcc1..c7a58ba5ba70 100644 --- a/spring-core/src/main/java/org/springframework/core/AttributeAccessorSupport.java +++ b/spring-core/src/main/java/org/springframework/core/AttributeAccessorSupport.java @@ -68,7 +68,7 @@ public T computeAttribute(String name, Function computeFunction) Assert.notNull(computeFunction, "Compute function must not be null"); Object value = this.attributes.computeIfAbsent(name, computeFunction); Assert.state(value != null, - () -> String.format("Compute function must not return null for attribute named '%s'", name)); + () -> "Compute function must not return null for attribute named '%s'".formatted(name)); return (T) value; } diff --git a/spring-core/src/main/java/org/springframework/core/NestedCheckedException.java b/spring-core/src/main/java/org/springframework/core/NestedCheckedException.java index ee48c93138f0..6ce046358259 100644 --- a/spring-core/src/main/java/org/springframework/core/NestedCheckedException.java +++ b/spring-core/src/main/java/org/springframework/core/NestedCheckedException.java @@ -16,6 +16,8 @@ package org.springframework.core; +import java.io.Serial; + import org.jspecify.annotations.Nullable; /** @@ -34,7 +36,7 @@ public abstract class NestedCheckedException extends Exception { /** Use serialVersionUID from Spring 1.2 for interoperability. */ - private static final long serialVersionUID = 7100714597678207546L; + @Serial private static final long serialVersionUID = 7100714597678207546L; /** diff --git a/spring-core/src/main/java/org/springframework/core/NestedRuntimeException.java b/spring-core/src/main/java/org/springframework/core/NestedRuntimeException.java index 8b43cc80e663..45b89d844090 100644 --- a/spring-core/src/main/java/org/springframework/core/NestedRuntimeException.java +++ b/spring-core/src/main/java/org/springframework/core/NestedRuntimeException.java @@ -16,6 +16,8 @@ package org.springframework.core; +import java.io.Serial; + import org.jspecify.annotations.Nullable; /** @@ -34,7 +36,7 @@ public abstract class NestedRuntimeException extends RuntimeException { /** Use serialVersionUID from Spring 1.2 for interoperability. */ - private static final long serialVersionUID = 5439915454935047936L; + @Serial private static final long serialVersionUID = 5439915454935047936L; /** diff --git a/spring-core/src/main/java/org/springframework/core/annotation/AnnotationAttributes.java b/spring-core/src/main/java/org/springframework/core/annotation/AnnotationAttributes.java index a4be0aef1dd6..e368a9c6861a 100644 --- a/spring-core/src/main/java/org/springframework/core/annotation/AnnotationAttributes.java +++ b/spring-core/src/main/java/org/springframework/core/annotation/AnnotationAttributes.java @@ -350,13 +350,11 @@ private T getRequiredAttribute(String attributeName, Class expectedType) Assert.hasText(attributeName, "'attributeName' must not be null or empty"); Object value = get(attributeName); if (value == null) { - throw new IllegalArgumentException(String.format( - "Attribute '%s' not found in attributes for annotation [%s]", + throw new IllegalArgumentException("Attribute '%s' not found in attributes for annotation [%s]".formatted( attributeName, this.displayName)); } if (value instanceof Throwable throwable) { - throw new IllegalArgumentException(String.format( - "Attribute '%s' for annotation [%s] was not resolvable due to exception [%s]", + throw new IllegalArgumentException("Attribute '%s' for annotation [%s] was not resolvable due to exception [%s]".formatted( attributeName, this.displayName, value), throwable); } if (!expectedType.isInstance(value) && expectedType.isArray() && @@ -366,8 +364,7 @@ private T getRequiredAttribute(String attributeName, Class expectedType) value = array; } if (!expectedType.isInstance(value)) { - throw new IllegalArgumentException(String.format( - "Attribute '%s' is of type %s, but %s was expected in attributes for annotation [%s]", + throw new IllegalArgumentException("Attribute '%s' is of type %s, but %s was expected in attributes for annotation [%s]".formatted( attributeName, value.getClass().getSimpleName(), expectedType.getSimpleName(), this.displayName)); } diff --git a/spring-core/src/main/java/org/springframework/core/annotation/AnnotationTypeMapping.java b/spring-core/src/main/java/org/springframework/core/annotation/AnnotationTypeMapping.java index 51aaadbf99c2..0b08bc59e8f4 100644 --- a/spring-core/src/main/java/org/springframework/core/annotation/AnnotationTypeMapping.java +++ b/spring-core/src/main/java/org/springframework/core/annotation/AnnotationTypeMapping.java @@ -152,12 +152,10 @@ private Method resolveAliasTarget(Method attribute, AliasFor aliasFor, boolean c Method target = AttributeMethods.forAnnotationType(targetAnnotation).get(targetAttributeName); if (target == null) { if (targetAnnotation == this.annotationType) { - throw new AnnotationConfigurationException(String.format( - "@AliasFor declaration on %s declares an alias for '%s' which is not present.", + throw new AnnotationConfigurationException("@AliasFor declaration on %s declares an alias for '%s' which is not present.".formatted( AttributeMethods.describe(attribute), targetAttributeName)); } - throw new AnnotationConfigurationException(String.format( - "%s is declared as an @AliasFor nonexistent %s.", + throw new AnnotationConfigurationException("%s is declared as an @AliasFor nonexistent %s.".formatted( StringUtils.capitalize(AttributeMethods.describe(attribute)), AttributeMethods.describe(targetAnnotation, targetAttributeName))); } @@ -168,8 +166,7 @@ private Method resolveAliasTarget(Method attribute, AliasFor aliasFor, boolean c AttributeMethods.describe(attribute))); } if (!isCompatibleReturnType(attribute.getReturnType(), target.getReturnType())) { - throw new AnnotationConfigurationException(String.format( - "Misconfigured aliases: %s and %s must declare the same return type.", + throw new AnnotationConfigurationException("Misconfigured aliases: %s and %s must declare the same return type.".formatted( AttributeMethods.describe(attribute), AttributeMethods.describe(target))); } @@ -178,8 +175,7 @@ private Method resolveAliasTarget(Method attribute, AliasFor aliasFor, boolean c if (targetAliasFor != null) { Method mirror = resolveAliasTarget(target, targetAliasFor, false); if (!mirror.equals(attribute)) { - throw new AnnotationConfigurationException(String.format( - "%s must be declared as an @AliasFor %s, not %s.", + throw new AnnotationConfigurationException("%s must be declared as an @AliasFor %s, not %s.".formatted( StringUtils.capitalize(AttributeMethods.describe(target)), AttributeMethods.describe(attribute), AttributeMethods.describe(mirror))); } @@ -320,8 +316,7 @@ private void validateAllAliasesClaimed() { AliasFor aliasFor = AnnotationsScanner.getDeclaredAnnotation(attribute, AliasFor.class); if (aliasFor != null && !this.claimedAliases.contains(attribute)) { Method target = resolveAliasTarget(attribute, aliasFor); - throw new AnnotationConfigurationException(String.format( - "@AliasFor declaration on %s declares an alias for %s which is not meta-present.", + throw new AnnotationConfigurationException("@AliasFor declaration on %s declares an alias for %s which is not meta-present.".formatted( AttributeMethods.describe(attribute), AttributeMethods.describe(target))); } } @@ -334,13 +329,11 @@ private void validateMirrorSet(MirrorSet mirrorSet) { Method mirrorAttribute = mirrorSet.get(i); Object mirrorDefaultValue = mirrorAttribute.getDefaultValue(); if (firstDefaultValue == null || mirrorDefaultValue == null) { - throw new AnnotationConfigurationException(String.format( - "Misconfigured aliases: %s and %s must declare default values.", + throw new AnnotationConfigurationException("Misconfigured aliases: %s and %s must declare default values.".formatted( AttributeMethods.describe(firstAttribute), AttributeMethods.describe(mirrorAttribute))); } if (!ObjectUtils.nullSafeEquals(firstDefaultValue, mirrorDefaultValue)) { - throw new AnnotationConfigurationException(String.format( - "Misconfigured aliases: %s and %s must declare the same default value.", + throw new AnnotationConfigurationException("Misconfigured aliases: %s and %s must declare the same default value.".formatted( AttributeMethods.describe(firstAttribute), AttributeMethods.describe(mirrorAttribute))); } } diff --git a/spring-core/src/main/java/org/springframework/core/annotation/SynthesizedMergedAnnotationInvocationHandler.java b/spring-core/src/main/java/org/springframework/core/annotation/SynthesizedMergedAnnotationInvocationHandler.java index 8c8f5fc358bd..a92f01ad78dd 100644 --- a/spring-core/src/main/java/org/springframework/core/annotation/SynthesizedMergedAnnotationInvocationHandler.java +++ b/spring-core/src/main/java/org/springframework/core/annotation/SynthesizedMergedAnnotationInvocationHandler.java @@ -85,8 +85,7 @@ public Object invoke(Object proxy, Method method, Object[] args) { if (ReflectionUtils.isEqualsMethod(method)) { return annotationEquals(args[0]); } - throw new AnnotationConfigurationException(String.format( - "Method [%s] is unsupported for synthesized annotation type [%s]", method, this.type)); + throw new AnnotationConfigurationException("Method [%s] is unsupported for synthesized annotation type [%s]".formatted(method, this.type)); } /** @@ -174,7 +173,7 @@ private String toString(Object value) { return '\'' + value.toString() + '\''; } if (value instanceof Byte) { - return String.format("(byte) 0x%02X", value); + return "(byte) 0x%02X".formatted(value); } if (value instanceof Long longValue) { return Long.toString(longValue) + 'L'; diff --git a/spring-core/src/main/java/org/springframework/core/io/PathResource.java b/spring-core/src/main/java/org/springframework/core/io/PathResource.java index 9b8eaaefe83e..cf2b8ff5641c 100644 --- a/spring-core/src/main/java/org/springframework/core/io/PathResource.java +++ b/spring-core/src/main/java/org/springframework/core/io/PathResource.java @@ -30,7 +30,6 @@ import java.nio.file.NoSuchFileException; import java.nio.file.OpenOption; import java.nio.file.Path; -import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import org.jspecify.annotations.Nullable; @@ -82,11 +81,11 @@ public PathResource(Path path) { * via {@link #createRelative}, the relative path will be built underneath * the given root: for example, Paths.get("C:/dir1/"), relative path "dir2" → "C:/dir1/dir2"! * @param path a path - * @see java.nio.file.Paths#get(String, String...) + * @see Path#of(String, String...) */ public PathResource(String path) { Assert.notNull(path, "Path must not be null"); - this.path = Paths.get(path).normalize(); + this.path = Path.of(path).normalize(); } /** @@ -95,11 +94,11 @@ public PathResource(String path) { * via {@link #createRelative}, the relative path will be built underneath * the given root: for example, Paths.get("C:/dir1/"), relative path "dir2" → "C:/dir1/dir2"! * @param uri a path URI - * @see java.nio.file.Paths#get(URI) + * @see Path#of(URI) */ public PathResource(URI uri) { Assert.notNull(uri, "URI must not be null"); - this.path = Paths.get(uri).normalize(); + this.path = Path.of(uri).normalize(); } diff --git a/spring-core/src/main/java/org/springframework/core/io/buffer/DefaultDataBuffer.java b/spring-core/src/main/java/org/springframework/core/io/buffer/DefaultDataBuffer.java index fe9469b878d6..12457ae40584 100644 --- a/spring-core/src/main/java/org/springframework/core/io/buffer/DefaultDataBuffer.java +++ b/spring-core/src/main/java/org/springframework/core/io/buffer/DefaultDataBuffer.java @@ -188,7 +188,7 @@ public DataBuffer capacity(int capacity) { private void setCapacity(int newCapacity) { if (newCapacity < 0) { - throw new IllegalArgumentException(String.format("'newCapacity' %d must be 0 or higher", newCapacity)); + throw new IllegalArgumentException("'newCapacity' %d must be 0 or higher".formatted(newCapacity)); } int readPosition = readPosition(); int writePosition = writePosition(); @@ -497,7 +497,7 @@ public int hashCode() { @Override public String toString() { - return String.format("DefaultDataBuffer (r: %d, w: %d, c: %d)", + return "DefaultDataBuffer (r: %d, w: %d, c: %d)".formatted( this.readPosition, this.writePosition, this.capacity); } @@ -519,7 +519,7 @@ private void checkLength(int length) { private void assertIndex(boolean expression, String format, Object... args) { if (!expression) { - String message = String.format(format, args); + String message = format.formatted(args); throw new IndexOutOfBoundsException(message); } } diff --git a/spring-core/src/main/java/org/springframework/core/io/buffer/JettyDataBuffer.java b/spring-core/src/main/java/org/springframework/core/io/buffer/JettyDataBuffer.java index 5b2f30e0f6af..1631ca1dd52d 100644 --- a/spring-core/src/main/java/org/springframework/core/io/buffer/JettyDataBuffer.java +++ b/spring-core/src/main/java/org/springframework/core/io/buffer/JettyDataBuffer.java @@ -312,7 +312,7 @@ public int hashCode() { @Override public String toString() { - return String.format("JettyDataBuffer (r: %d, w: %d, c: %d)", + return "JettyDataBuffer (r: %d, w: %d, c: %d)".formatted( readPosition(), writePosition(), capacity()); } diff --git a/spring-core/src/main/java/org/springframework/core/log/LogMessage.java b/spring-core/src/main/java/org/springframework/core/log/LogMessage.java index 706c57bd4e3e..c526e7d85af7 100644 --- a/spring-core/src/main/java/org/springframework/core/log/LogMessage.java +++ b/spring-core/src/main/java/org/springframework/core/log/LogMessage.java @@ -89,7 +89,7 @@ public static LogMessage of(Supplier supplier) { * Build a lazily formatted message from the given format string and argument. * @param format the format string (following {@link String#format} rules) * @param arg1 the argument (can be {@code null}) - * @see String#format(String, Object...) + * @see String#formatted(Object...) */ public static LogMessage format(String format, @Nullable Object arg1) { return new FormatMessage1(format, arg1); @@ -100,7 +100,7 @@ public static LogMessage format(String format, @Nullable Object arg1) { * @param format the format string (following {@link String#format} rules) * @param arg1 the first argument (can be {@code null}) * @param arg2 the second argument (can be {@code null}) - * @see String#format(String, Object...) + * @see String#formatted(Object...) */ public static LogMessage format(String format, @Nullable Object arg1, @Nullable Object arg2) { return new FormatMessage2(format, arg1, arg2); @@ -112,7 +112,7 @@ public static LogMessage format(String format, @Nullable Object arg1, @Nullable * @param arg1 the first argument (can be {@code null}) * @param arg2 the second argument (can be {@code null}) * @param arg3 the third argument (can be {@code null}) - * @see String#format(String, Object...) + * @see String#formatted(Object...) */ public static LogMessage format(String format, @Nullable Object arg1, @Nullable Object arg2, @Nullable Object arg3) { return new FormatMessage3(format, arg1, arg2, arg3); @@ -125,7 +125,7 @@ public static LogMessage format(String format, @Nullable Object arg1, @Nullable * @param arg2 the second argument (can be {@code null}) * @param arg3 the third argument (can be {@code null}) * @param arg4 the fourth argument (can be {@code null}) - * @see String#format(String, Object...) + * @see String#formatted(Object...) */ public static LogMessage format(String format, @Nullable Object arg1, @Nullable Object arg2, @Nullable Object arg3, @Nullable Object arg4) { @@ -140,7 +140,7 @@ public static LogMessage format(String format, @Nullable Object arg1, @Nullable * @param format the format string (following {@link String#format} rules) * @param args the varargs array (can be {@code null} and can contain {@code null} * elements) - * @see String#format(String, Object...) + * @see String#formatted(Object...) */ public static LogMessage format(String format, @Nullable Object... args) { return new FormatMessageX(format, args); @@ -185,7 +185,7 @@ private static final class FormatMessage1 extends FormatMessage { @Override protected String buildString() { - return String.format(this.format, this.arg1); + return this.format.formatted(this.arg1); } } @@ -204,7 +204,7 @@ private static final class FormatMessage2 extends FormatMessage { @Override String buildString() { - return String.format(this.format, this.arg1, this.arg2); + return this.format.formatted(this.arg1, this.arg2); } } @@ -226,7 +226,7 @@ private static final class FormatMessage3 extends FormatMessage { @Override String buildString() { - return String.format(this.format, this.arg1, this.arg2, this.arg3); + return this.format.formatted(this.arg1, this.arg2, this.arg3); } } @@ -252,7 +252,7 @@ private static final class FormatMessage4 extends FormatMessage { @Override String buildString() { - return String.format(this.format, this.arg1, this.arg2, this.arg3, this.arg4); + return this.format.formatted(this.arg1, this.arg2, this.arg3, this.arg4); } } @@ -268,7 +268,7 @@ private static final class FormatMessageX extends FormatMessage { @Override String buildString() { - return String.format(this.format, this.args); + return this.format.formatted(this.args); } } diff --git a/spring-core/src/main/java/org/springframework/core/style/SimpleValueStyler.java b/spring-core/src/main/java/org/springframework/core/style/SimpleValueStyler.java index 3892df69aabc..dc4128cda346 100644 --- a/spring-core/src/main/java/org/springframework/core/style/SimpleValueStyler.java +++ b/spring-core/src/main/java/org/springframework/core/style/SimpleValueStyler.java @@ -135,7 +135,7 @@ private static String toSimpleMethodSignature(Method method) { String parameterList = Arrays.stream(method.getParameterTypes()) .map(Class::getSimpleName) .collect(Collectors.joining(", ")); - return String.format("%s(%s)", method.getName(), parameterList); + return "%s(%s)".formatted(method.getName(), parameterList); } } diff --git a/spring-core/src/main/java/org/springframework/util/LinkedMultiValueMap.java b/spring-core/src/main/java/org/springframework/util/LinkedMultiValueMap.java index 574b0eec83d8..ca6c4a6b8bee 100644 --- a/spring-core/src/main/java/org/springframework/util/LinkedMultiValueMap.java +++ b/spring-core/src/main/java/org/springframework/util/LinkedMultiValueMap.java @@ -16,6 +16,7 @@ package org.springframework.util; +import java.io.Serial; import java.io.Serializable; import java.util.ArrayList; import java.util.LinkedHashMap; @@ -37,7 +38,7 @@ */ public class LinkedMultiValueMap extends MultiValueMapAdapter implements Serializable, Cloneable { - private static final long serialVersionUID = 3801124242820219131L; + @Serial private static final long serialVersionUID = 3801124242820219131L; /** diff --git a/spring-core/src/main/java/org/springframework/util/MimeType.java b/spring-core/src/main/java/org/springframework/util/MimeType.java index 7e02f5528da2..4348f0d1c8d2 100644 --- a/spring-core/src/main/java/org/springframework/util/MimeType.java +++ b/spring-core/src/main/java/org/springframework/util/MimeType.java @@ -18,6 +18,7 @@ import java.io.IOException; import java.io.ObjectInputStream; +import java.io.Serial; import java.io.Serializable; import java.nio.charset.Charset; import java.util.BitSet; @@ -52,7 +53,7 @@ */ public class MimeType implements Comparable, Serializable { - private static final long serialVersionUID = 4085923477777865903L; + @Serial private static final long serialVersionUID = 4085923477777865903L; protected static final String WILDCARD_TYPE = "*"; diff --git a/spring-core/src/main/java/org/springframework/util/StopWatch.java b/spring-core/src/main/java/org/springframework/util/StopWatch.java index 50a3cb179a39..20cffb224ab3 100644 --- a/spring-core/src/main/java/org/springframework/util/StopWatch.java +++ b/spring-core/src/main/java/org/springframework/util/StopWatch.java @@ -332,7 +332,7 @@ public String prettyPrint(TimeUnit timeUnit) { String line = "-".repeat(width) + "\n"; String unitName = timeUnit.name(); unitName = unitName.charAt(0) + unitName.substring(1).toLowerCase(Locale.ENGLISH); - unitName = String.format("%-12s", unitName); + unitName = "%-12s".formatted(unitName); sb.append(line); sb.append(unitName).append(" % Task name\n"); sb.append(line); @@ -345,9 +345,9 @@ public String prettyPrint(TimeUnit timeUnit) { nf.setMaximumFractionDigits(10 - digits); for (TaskInfo task : this.taskList) { - sb.append(String.format("%-14s", (timeUnit == TimeUnit.NANOSECONDS ? + sb.append("%-14s".formatted((timeUnit == TimeUnit.NANOSECONDS ? nf.format(task.getTimeNanos()) : nf.format(task.getTime(timeUnit))))); - sb.append(String.format("%-8s", + sb.append("%-8s".formatted( pf.format(task.getTimeSeconds() / getTotalTimeSeconds()))); sb.append(task.getTaskName()).append('\n'); } diff --git a/spring-core/src/main/java/org/springframework/util/UnmodifiableMultiValueMap.java b/spring-core/src/main/java/org/springframework/util/UnmodifiableMultiValueMap.java index 8db025670c2c..e107591db63a 100644 --- a/spring-core/src/main/java/org/springframework/util/UnmodifiableMultiValueMap.java +++ b/spring-core/src/main/java/org/springframework/util/UnmodifiableMultiValueMap.java @@ -16,6 +16,7 @@ package org.springframework.util; +import java.io.Serial; import java.io.Serializable; import java.util.Collection; import java.util.Collections; @@ -45,7 +46,7 @@ */ final class UnmodifiableMultiValueMap implements MultiValueMap, Serializable { - private static final long serialVersionUID = -8697084563854098920L; + @Serial private static final long serialVersionUID = -8697084563854098920L; @SuppressWarnings("serial") private final MultiValueMap delegate; @@ -263,7 +264,7 @@ public void clear() { private static class UnmodifiableEntrySet implements Set>>, Serializable { - private static final long serialVersionUID = 2407578793783925203L; + @Serial private static final long serialVersionUID = 2407578793783925203L; @SuppressWarnings("serial") private final Set>> delegate; @@ -512,7 +513,7 @@ public String toString() { private static class UnmodifiableValueCollection implements Collection>, Serializable { - private static final long serialVersionUID = 5518377583904339588L; + @Serial private static final long serialVersionUID = 5518377583904339588L; @SuppressWarnings("serial") private final Collection> delegate; diff --git a/spring-core/src/main/java/org/springframework/util/backoff/ExponentialBackOff.java b/spring-core/src/main/java/org/springframework/util/backoff/ExponentialBackOff.java index c641f2887e0e..1c820eb2e908 100644 --- a/spring-core/src/main/java/org/springframework/util/backoff/ExponentialBackOff.java +++ b/spring-core/src/main/java/org/springframework/util/backoff/ExponentialBackOff.java @@ -17,6 +17,7 @@ package org.springframework.util.backoff; import java.util.StringJoiner; +import java.util.concurrent.ThreadLocalRandom; import org.springframework.util.Assert; @@ -308,7 +309,7 @@ private long applyJitter(long interval) { long applicableJitter = jitter * (interval / initialInterval); long min = Math.max(interval - applicableJitter, initialInterval); long max = Math.min(interval + applicableJitter, getMaxInterval()); - return min + (long) (Math.random() * (max - min)); + return min + (long) (ThreadLocalRandom.current().nextDouble() * (max - min)); } return interval; } diff --git a/spring-core/src/main/java/org/springframework/util/unit/DataSize.java b/spring-core/src/main/java/org/springframework/util/unit/DataSize.java index 41180643202c..2912360011a4 100644 --- a/spring-core/src/main/java/org/springframework/util/unit/DataSize.java +++ b/spring-core/src/main/java/org/springframework/util/unit/DataSize.java @@ -252,7 +252,7 @@ public int compareTo(DataSize other) { @Override public String toString() { - return String.format("%dB", this.bytes); + return "%dB".formatted(this.bytes); } diff --git a/spring-core/src/test/java/org/springframework/core/codec/CharBufferDecoderTests.java b/spring-core/src/test/java/org/springframework/core/codec/CharBufferDecoderTests.java index 824998b5a0b9..0d186c21bb0d 100644 --- a/spring-core/src/test/java/org/springframework/core/codec/CharBufferDecoderTests.java +++ b/spring-core/src/test/java/org/springframework/core/codec/CharBufferDecoderTests.java @@ -70,7 +70,7 @@ protected void decode() { CharBuffer u = charBuffer("ü"); CharBuffer e = charBuffer("é"); CharBuffer o = charBuffer("ø"); - String s = String.format("%s\n%s\n%s", u, e, o); + String s = "%s\n%s\n%s".formatted(u, e, o); Flux input = toDataBuffers(s, 1, UTF_8); testDecodeAll(input, TYPE, step -> step.expectNext(u, e, o).verifyComplete(), null, null); @@ -81,7 +81,7 @@ void decodeMultibyteCharacterUtf16() { CharBuffer u = charBuffer("ü"); CharBuffer e = charBuffer("é"); CharBuffer o = charBuffer("ø"); - String s = String.format("%s\n%s\n%s", u, e, o); + String s = "%s\n%s\n%s".formatted(u, e, o); Flux source = toDataBuffers(s, 2, UTF_16BE); MimeType mimeType = MimeTypeUtils.parseMimeType("text/plain;charset=utf-16be"); diff --git a/spring-core/src/test/java/org/springframework/core/codec/CharSequenceEncoderTests.java b/spring-core/src/test/java/org/springframework/core/codec/CharSequenceEncoderTests.java index 688420275311..3e2649998d6b 100644 --- a/spring-core/src/test/java/org/springframework/core/codec/CharSequenceEncoderTests.java +++ b/spring-core/src/test/java/org/springframework/core/codec/CharSequenceEncoderTests.java @@ -82,7 +82,7 @@ void calculateCapacity() { .forEach(charset -> { int capacity = this.encoder.calculateCapacity(sequence, charset); int length = sequence.length(); - assertThat(capacity).as(String.format("%s has capacity %d; length %d", charset, capacity, length)) + assertThat(capacity).as("%s has capacity %d; length %d".formatted(charset, capacity, length)) .isGreaterThanOrEqualTo(length); }); } diff --git a/spring-core/src/test/java/org/springframework/core/codec/StringDecoderTests.java b/spring-core/src/test/java/org/springframework/core/codec/StringDecoderTests.java index 8caad8611450..df5cac21d95a 100644 --- a/spring-core/src/test/java/org/springframework/core/codec/StringDecoderTests.java +++ b/spring-core/src/test/java/org/springframework/core/codec/StringDecoderTests.java @@ -73,7 +73,7 @@ protected void decode() { String u = "ü"; String e = "é"; String o = "ø"; - String s = String.format("%s\n%s\n%s", u, e, o); + String s = "%s\n%s\n%s".formatted(u, e, o); Flux input = toDataBuffers(s, 1, UTF_8); testDecodeAll(input, TYPE, step -> step.expectNext(u, e, o).verifyComplete(), null, null); @@ -92,7 +92,7 @@ void decodeMultibyteCharacterUtf16() { String u = "ü"; String e = "é"; String o = "ø"; - String s = String.format("%s\n%s\n%s", u, e, o); + String s = "%s\n%s\n%s".formatted(u, e, o); Flux source = toDataBuffers(s, 2, UTF_16BE); MimeType mimeType = MimeTypeUtils.parseMimeType("text/plain;charset=utf-16be"); diff --git a/spring-core/src/test/java/org/springframework/core/io/PathResourceTests.java b/spring-core/src/test/java/org/springframework/core/io/PathResourceTests.java index 5823195032f5..209b8edab361 100644 --- a/spring-core/src/test/java/org/springframework/core/io/PathResourceTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/PathResourceTests.java @@ -27,7 +27,6 @@ import java.nio.file.AccessDeniedException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -88,7 +87,7 @@ void nullUri() { @Test void createFromPath() { - Path path = Paths.get(TEST_FILE); + Path path = Path.of(TEST_FILE); PathResource resource = new PathResource(path); assertThat(resource.getPath()).isEqualTo(TEST_FILE); } diff --git a/spring-core/src/test/java/org/springframework/core/io/ResourceTests.java b/spring-core/src/test/java/org/springframework/core/io/ResourceTests.java index 9385a210f99a..dce26e6f108a 100644 --- a/spring-core/src/test/java/org/springframework/core/io/ResourceTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/ResourceTests.java @@ -32,7 +32,6 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Base64; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Stream; @@ -132,7 +131,7 @@ void resourceCreateRelativeUnknown(Resource resource) throws Exception { private static Stream resource() throws URISyntaxException { URL resourceClass = ResourceTests.class.getResource("ResourceTests.class"); - Path resourceClassFilePath = Paths.get(resourceClass.toURI()); + Path resourceClassFilePath = Path.of(resourceClass.toURI()); return Stream.of( argumentSet("ClassPathResource", new ClassPathResource("org/springframework/core/io/ResourceTests.class")), argumentSet("ClassPathResource with ClassLoader", new ClassPathResource("org/springframework/core/io/ResourceTests.class", ResourceTests.class.getClassLoader())), @@ -252,7 +251,7 @@ void sameResourceFromFileIsEqual() { @Test void sameResourceFromFilePathIsEqual() throws Exception { - Path filePath = Paths.get(getClass().getResource("ResourceTests.class").toURI()); + Path filePath = Path.of(getClass().getResource("ResourceTests.class").toURI()); Resource resource = new FileSystemResource(filePath); assertThat(resource).isEqualTo(new FileSystemResource(filePath)); } diff --git a/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferUtilsTests.java b/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferUtilsTests.java index 00d95af03a18..c397d75b4ea1 100644 --- a/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferUtilsTests.java @@ -31,7 +31,6 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.time.Duration; import java.util.ArrayList; @@ -99,7 +98,7 @@ void readByteChannel(DataBufferFactory bufferFactory) throws Exception { URI uri = this.resource.getURI(); Flux result = - DataBufferUtils.readByteChannel(() -> FileChannel.open(Paths.get(uri), StandardOpenOption.READ), + DataBufferUtils.readByteChannel(() -> FileChannel.open(Path.of(uri), StandardOpenOption.READ), super.bufferFactory, 3); verifyReadData(result); @@ -134,7 +133,7 @@ void readByteChannelCancel(DataBufferFactory bufferFactory) throws Exception { URI uri = this.resource.getURI(); Flux result = - DataBufferUtils.readByteChannel(() -> FileChannel.open(Paths.get(uri), StandardOpenOption.READ), + DataBufferUtils.readByteChannel(() -> FileChannel.open(Path.of(uri), StandardOpenOption.READ), super.bufferFactory, 3); StepVerifier.create(result) @@ -149,7 +148,7 @@ void readAsynchronousFileChannel(DataBufferFactory bufferFactory) throws Excepti URI uri = this.resource.getURI(); Flux flux = DataBufferUtils.readAsynchronousFileChannel( - () -> AsynchronousFileChannel.open(Paths.get(uri), StandardOpenOption.READ), + () -> AsynchronousFileChannel.open(Path.of(uri), StandardOpenOption.READ), super.bufferFactory, 3); verifyReadData(flux); @@ -161,7 +160,7 @@ void readAsynchronousFileChannelPosition(DataBufferFactory bufferFactory) throws URI uri = this.resource.getURI(); Flux flux = DataBufferUtils.readAsynchronousFileChannel( - () -> AsynchronousFileChannel.open(Paths.get(uri), StandardOpenOption.READ), + () -> AsynchronousFileChannel.open(Path.of(uri), StandardOpenOption.READ), 9, super.bufferFactory, 3); StepVerifier.create(flux) @@ -207,7 +206,7 @@ void readAsynchronousFileChannelCancel(DataBufferFactory bufferFactory) throws E URI uri = this.resource.getURI(); Flux flux = DataBufferUtils.readAsynchronousFileChannel( - () -> AsynchronousFileChannel.open(Paths.get(uri), StandardOpenOption.READ), + () -> AsynchronousFileChannel.open(Path.of(uri), StandardOpenOption.READ), super.bufferFactory, 3); StepVerifier.create(flux) @@ -222,7 +221,7 @@ void readAsynchronousFileChannelCancelWithoutDemand(DataBufferFactory bufferFact URI uri = this.resource.getURI(); Flux flux = DataBufferUtils.readAsynchronousFileChannel( - () -> AsynchronousFileChannel.open(Paths.get(uri), StandardOpenOption.READ), + () -> AsynchronousFileChannel.open(Path.of(uri), StandardOpenOption.READ), super.bufferFactory, 3); BaseSubscriber subscriber = new ZeroDemandSubscriber(); @@ -891,7 +890,7 @@ void inputStreamSubscriberClose(DataBufferFactory bufferFactory) throws Interrup void readAndWriteByteChannel(DataBufferFactory bufferFactory) throws Exception { super.bufferFactory = bufferFactory; - Path source = Paths.get( + Path source = Path.of( DataBufferUtilsTests.class.getResource("DataBufferUtilsTests.txt").toURI()); Flux sourceFlux = DataBufferUtils @@ -925,7 +924,7 @@ void readAndWriteByteChannel(DataBufferFactory bufferFactory) throws Exception { void readAndWriteAsynchronousFileChannel(DataBufferFactory bufferFactory) throws Exception { super.bufferFactory = bufferFactory; - Path source = Paths.get( + Path source = Path.of( DataBufferUtilsTests.class.getResource("DataBufferUtilsTests.txt").toURI()); Flux sourceFlux = DataBufferUtils.readAsynchronousFileChannel( () -> AsynchronousFileChannel.open(source, StandardOpenOption.READ), @@ -1283,7 +1282,7 @@ void matcher3(DataBufferFactory bufferFactory) { @ParameterizedDataBufferAllocatingTest void propagateContextByteChannel(DataBufferFactory bufferFactory) throws IOException { - Path path = Paths.get(this.resource.getURI()); + Path path = Path.of(this.resource.getURI()); try (SeekableByteChannel out = Files.newByteChannel(this.tempFile, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) { Flux result = DataBufferUtils.read(path, bufferFactory, 1024, StandardOpenOption.READ) .transformDeferredContextual((f, ctx) -> { @@ -1307,7 +1306,7 @@ void propagateContextByteChannel(DataBufferFactory bufferFactory) throws IOExcep @ParameterizedDataBufferAllocatingTest void propagateContextAsynchronousFileChannel(DataBufferFactory bufferFactory) throws IOException { - Path path = Paths.get(this.resource.getURI()); + Path path = Path.of(this.resource.getURI()); try (AsynchronousFileChannel out = AsynchronousFileChannel.open(this.tempFile, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) { Flux result = DataBufferUtils.read(path, bufferFactory, 1024, StandardOpenOption.READ) .transformDeferredContextual((f, ctx) -> { @@ -1331,7 +1330,7 @@ void propagateContextAsynchronousFileChannel(DataBufferFactory bufferFactory) th @ParameterizedDataBufferAllocatingTest void propagateContextPath(DataBufferFactory bufferFactory) throws IOException { - Path path = Paths.get(this.resource.getURI()); + Path path = Path.of(this.resource.getURI()); Path out = Files.createTempFile("data-buffer-utils-tests", ".tmp"); Flux result = DataBufferUtils.read(path, bufferFactory, 1024, StandardOpenOption.READ) diff --git a/spring-core/src/test/java/org/springframework/core/io/support/PathMatchingResourcePatternResolverTests.java b/spring-core/src/test/java/org/springframework/core/io/support/PathMatchingResourcePatternResolverTests.java index e0390b6c7b03..78005547bc83 100644 --- a/spring-core/src/test/java/org/springframework/core/io/support/PathMatchingResourcePatternResolverTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/support/PathMatchingResourcePatternResolverTests.java @@ -30,7 +30,6 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Arrays; import java.util.Enumeration; import java.util.List; @@ -118,8 +117,8 @@ void classpathStarWithPatternOnFileSystem() { @Test // gh-31111 void usingFileProtocolWithWildcardInPatternAndNonexistentRootPath() throws IOException { - Path testResourcesDir = Paths.get("src/test/resources").toAbsolutePath(); - String pattern = String.format("file:%s/example/bogus/**", testResourcesDir); + Path testResourcesDir = Path.of("src/test/resources").toAbsolutePath(); + String pattern = "file:%s/example/bogus/**".formatted(testResourcesDir); assertThat(resolver.getResources(pattern)).isEmpty(); // When the log level for the resolver is set to at least INFO, we should see // a log entry similar to the following. @@ -131,7 +130,7 @@ void usingFileProtocolWithWildcardInPatternAndNonexistentRootPath() throws IOExc @Test void encodedHashtagInPath() throws IOException { - Path rootDir = Paths.get("src/test/resources/custom%23root").toAbsolutePath(); + Path rootDir = Path.of("src/test/resources/custom%23root").toAbsolutePath(); URL root = new URL("file:" + rootDir + "/"); resolver = new PathMatchingResourcePatternResolver(new DefaultResourceLoader(new URLClassLoader(new URL[] {root}))); resolver.setUseCaches(false); @@ -164,8 +163,8 @@ void usingClasspathStarProtocolWithWildcardInPatternAndNotEndingInSlash() throws @Test void usingFileProtocolWithWildcardInPatternAndNotEndingInSlash() throws Exception { - Path testResourcesDir = Paths.get("src/test/resources").toAbsolutePath(); - String pattern = String.format("file:%s/org/springframework/core/io/sup*", testResourcesDir); + Path testResourcesDir = Path.of("src/test/resources").toAbsolutePath(); + String pattern = "file:%s/org/springframework/core/io/sup*".formatted(testResourcesDir); String pathPrefix = ".+org/springframework/core/io/"; List actualSubPaths = getSubPathsIgnoringClassFilesEtc(pattern, pathPrefix); @@ -195,8 +194,8 @@ void usingClasspathStarProtocolWithWildcardInPatternAndEndingInSlash() throws Ex @Test void usingFileProtocolWithWildcardInPatternAndEndingInSlash() throws Exception { - Path testResourcesDir = Paths.get("src/test/resources").toAbsolutePath(); - String pattern = String.format("file:%s/org/springframework/core/io/sup*/", testResourcesDir); + Path testResourcesDir = Path.of("src/test/resources").toAbsolutePath(); + String pattern = "file:%s/org/springframework/core/io/sup*/".formatted(testResourcesDir); String pathPrefix = ".+org/springframework/core/io/"; List actualSubPaths = getSubPathsIgnoringClassFilesEtc(pattern, pathPrefix); @@ -229,8 +228,8 @@ private List getSubPathsIgnoringClassFilesEtc(String pattern, String pat @Test void usingFileProtocolWithoutWildcardInPatternAndEndingInSlashStarStar() { - Path testResourcesDir = Paths.get("src/test/resources").toAbsolutePath(); - String pattern = String.format("file:%s/scanned-resources/**", testResourcesDir); + Path testResourcesDir = Path.of("src/test/resources").toAbsolutePath(); + String pattern = "file:%s/scanned-resources/**".formatted(testResourcesDir); String pathPrefix = ".+?resources/"; // We do NOT find "scanned-resources" if the pattern ENDS with "/**" AND does NOT otherwise contain a wildcard. @@ -241,8 +240,8 @@ void usingFileProtocolWithoutWildcardInPatternAndEndingInSlashStarStar() { @Test void usingFileProtocolWithWildcardInPatternAndEndingInSlashStarStar() { - Path testResourcesDir = Paths.get("src/test/resources").toAbsolutePath(); - String pattern = String.format("file:%s/scanned*resources/**", testResourcesDir); + Path testResourcesDir = Path.of("src/test/resources").toAbsolutePath(); + String pattern = "file:%s/scanned*resources/**".formatted(testResourcesDir); String pathPrefix = ".+?resources/"; // We DO find "scanned-resources" if the pattern ENDS with "/**" AND DOES otherwise contain a wildcard. @@ -253,7 +252,7 @@ void usingFileProtocolWithWildcardInPatternAndEndingInSlashStarStar() { @Test void usingFileProtocolAndAssertingUrlAndUriSyntax() throws Exception { - Path testResourcesDir = Paths.get("src/test/resources").toAbsolutePath(); + Path testResourcesDir = Path.of("src/test/resources").toAbsolutePath(); String pattern = "file:%s/scanned-resources/**/resource#test1.txt".formatted(testResourcesDir); Resource[] resources = resolver.getResources(pattern); assertThat(resources).hasSize(1); diff --git a/spring-core/src/test/java/org/springframework/tests/sample/objects/TestObject.java b/spring-core/src/test/java/org/springframework/tests/sample/objects/TestObject.java index 016b00d374fe..64b6f5aa2688 100644 --- a/spring-core/src/test/java/org/springframework/tests/sample/objects/TestObject.java +++ b/spring-core/src/test/java/org/springframework/tests/sample/objects/TestObject.java @@ -68,8 +68,8 @@ public void absquatulate() { @Override public int compareTo(Object o) { - if (this.name != null && o instanceof TestObject) { - return this.name.compareTo(((TestObject) o).getName()); + if (this.name != null && o instanceof TestObject object) { + return this.name.compareTo(object.getName()); } else { return 1; diff --git a/spring-core/src/test/java/org/springframework/util/AutoPopulatingListTests.java b/spring-core/src/test/java/org/springframework/util/AutoPopulatingListTests.java index 41eee5a7d911..e518e36ec02e 100644 --- a/spring-core/src/test/java/org/springframework/util/AutoPopulatingListTests.java +++ b/spring-core/src/test/java/org/springframework/util/AutoPopulatingListTests.java @@ -83,8 +83,8 @@ private void doTestWithElementFactory(AutoPopulatingList list) { for (int x = 0; x < list.size(); x++) { Object element = list.get(x); - if (element instanceof TestObject) { - assertThat(((TestObject) element).getAge()).isEqualTo(x); + if (element instanceof TestObject object) { + assertThat(object.getAge()).isEqualTo(x); } } } diff --git a/spring-core/src/test/java/org/springframework/util/xml/AbstractStaxXMLReaderTests.java b/spring-core/src/test/java/org/springframework/util/xml/AbstractStaxXMLReaderTests.java index 747584700e36..f68f7509c407 100644 --- a/spring-core/src/test/java/org/springframework/util/xml/AbstractStaxXMLReaderTests.java +++ b/spring-core/src/test/java/org/springframework/util/xml/AbstractStaxXMLReaderTests.java @@ -218,9 +218,9 @@ private static class CharArrayToStringAdapter implements InvocationArgumentsAdap @Override public Object[] adaptArguments(Object[] arguments) { - if (arguments.length == 3 && arguments[0] instanceof char[] && - arguments[1] instanceof Integer && arguments[2] instanceof Integer) { - return new Object[] {new String((char[]) arguments[0], (Integer) arguments[1], (Integer) arguments[2])}; + if (arguments.length == 3 && arguments[0] instanceof char[] chars && + arguments[1] instanceof Integer integer && arguments[2] instanceof Integer integer1) { + return new Object[] {new String(chars, integer, integer1)}; } return arguments; } @@ -232,8 +232,8 @@ private static class PartialAttributesAdapter implements InvocationArgumentsAdap @Override public Object[] adaptArguments(Object[] arguments) { for (int i = 0; i < arguments.length; i++) { - if (arguments[i] instanceof Attributes) { - arguments[i] = new PartialAttributes((Attributes) arguments[i]); + if (arguments[i] instanceof Attributes attributes) { + arguments[i] = new PartialAttributes(attributes); } } return arguments; diff --git a/spring-core/src/testFixtures/java/org/springframework/core/testfixture/io/ResourceTestUtils.java b/spring-core/src/testFixtures/java/org/springframework/core/testfixture/io/ResourceTestUtils.java index eee455ee0fae..867ceecc8cff 100644 --- a/spring-core/src/testFixtures/java/org/springframework/core/testfixture/io/ResourceTestUtils.java +++ b/spring-core/src/testFixtures/java/org/springframework/core/testfixture/io/ResourceTestUtils.java @@ -33,7 +33,7 @@ public abstract class ResourceTestUtils { *

Intended for use loading context configuration XML files within JUnit tests. */ public static ClassPathResource qualifiedResource(Class clazz, String resourceSuffix) { - return new ClassPathResource(String.format("%s-%s", clazz.getSimpleName(), resourceSuffix), clazz); + return new ClassPathResource("%s-%s".formatted(clazz.getSimpleName(), resourceSuffix), clazz); } } diff --git a/spring-core/src/testFixtures/java/org/springframework/core/testfixture/io/buffer/LeakAwareDataBufferFactory.java b/spring-core/src/testFixtures/java/org/springframework/core/testfixture/io/buffer/LeakAwareDataBufferFactory.java index 368fe698ab1c..6eff57411a71 100644 --- a/spring-core/src/testFixtures/java/org/springframework/core/testfixture/io/buffer/LeakAwareDataBufferFactory.java +++ b/spring-core/src/testFixtures/java/org/springframework/core/testfixture/io/buffer/LeakAwareDataBufferFactory.java @@ -146,7 +146,7 @@ public DataBuffer wrap(byte[] bytes) { public DataBuffer join(List dataBuffers) { // Remove LeakAwareDataBuffer wrapper so delegate can find native buffers dataBuffers = dataBuffers.stream() - .map(o -> o instanceof LeakAwareDataBuffer ? ((LeakAwareDataBuffer) o).dataBuffer() : o) + .map(o -> o instanceof LeakAwareDataBuffer ladb ? ladb.dataBuffer() : o) .toList(); return new LeakAwareDataBuffer(this.delegate.join(dataBuffers), this); } diff --git a/spring-core/src/testFixtures/java/org/springframework/core/testfixture/net/TestSocketUtils.java b/spring-core/src/testFixtures/java/org/springframework/core/testfixture/net/TestSocketUtils.java index 18e75dcc95f4..5b90dac55043 100644 --- a/spring-core/src/testFixtures/java/org/springframework/core/testfixture/net/TestSocketUtils.java +++ b/spring-core/src/testFixtures/java/org/springframework/core/testfixture/net/TestSocketUtils.java @@ -76,8 +76,7 @@ public static int findAvailableTcpPort() { int searchCounter = 0; do { if (searchCounter > MAX_ATTEMPTS) { - throw new IllegalStateException(String.format( - "Could not find an available TCP port in the range [%d, %d] after %d attempts", + throw new IllegalStateException("Could not find an available TCP port in the range [%d, %d] after %d attempts".formatted( PORT_RANGE_MIN, PORT_RANGE_MAX, MAX_ATTEMPTS)); } candidatePort = PORT_RANGE_MIN + random.nextInt(PORT_RANGE + 1); diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationCoverageTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationCoverageTests.java index f0ab0fe7eb77..ad0559d138c9 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationCoverageTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationCoverageTests.java @@ -7260,7 +7260,7 @@ public static int sumFloat(float... values) { public static class DelegatingStringFormat { public static String format(String s, Object... args) { - return String.format(s, args); + return s.formatted(args); } } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java index a4f292605333..f9dc606ee4cf 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java @@ -2225,8 +2225,8 @@ public TestClass2(String string) { @Override public boolean equals(@Nullable Object other) { - return (this == other || (other instanceof TestClass2 && - this.string.equals(((TestClass2) other).string))); + return (this == other || (other instanceof TestClass2 tc && + this.string.equals(tc.string))); } @Override diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/TestScenarioCreator.java b/spring-expression/src/test/java/org/springframework/expression/spel/TestScenarioCreator.java index 0343e22c2ebc..db6de0c27852 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/TestScenarioCreator.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/TestScenarioCreator.java @@ -186,7 +186,7 @@ public static String message(String template, String... args) { } public static String formatObjectVarargs(String format, Object... args) { - return String.format(format, args); + return format.formatted(args); } public static String formatPrimitiveVarargs(String format, int... nums) { @@ -194,7 +194,7 @@ public static String formatPrimitiveVarargs(String format, int... nums) { for (int i = 0; i < nums.length; i++) { args[i] = nums[i]; } - return String.format(format, args); + return format.formatted(args); } public static int add(int x, int y) { diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/testresources/Inventor.java b/spring-expression/src/test/java/org/springframework/expression/spel/testresources/Inventor.java index 8d91888e3bdd..8f56cade4b96 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/testresources/Inventor.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/testresources/Inventor.java @@ -214,7 +214,7 @@ public String aVarargsMethod3(String str1, String... strings) { } public String formatObjectVarargs(String format, Object... args) { - return String.format(format, args); + return format.formatted(args); } public String formatPrimitiveVarargs(String format, int... nums) { @@ -222,7 +222,7 @@ public String formatPrimitiveVarargs(String format, int... nums) { for (int i = 0; i < nums.length; i++) { args[i] = nums[i]; } - return String.format(format, args); + return format.formatted(args); } diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/DriverManagerDataSource.java b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/DriverManagerDataSource.java index 6a8160063f1b..19da8114457b 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/DriverManagerDataSource.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/DriverManagerDataSource.java @@ -155,4 +155,26 @@ protected Connection getConnectionFromDriverManager(String url, Properties props return DriverManager.getConnection(url, props); } + public boolean isWrapperFor(Class iface) throws java.sql.SQLException { + // TODO Auto-generated method stub + return iface != null && iface.isAssignableFrom(this.getClass()); + } + + public T unwrap(Class iface) throws java.sql.SQLException { + // TODO Auto-generated method stub + try { + if (iface != null && iface.isAssignableFrom(this.getClass())) { + return (T) this; + } + throw new java.sql.SQLException("Auto-generated unwrap failed; Revisit implementation"); + } catch (Exception e) { + throw new java.sql.SQLException(e); + } + } + + public java.util.logging.Logger getParentLogger() { + // TODO Auto-generated method stub + return null; + } + } diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/IsolationLevelDataSourceAdapter.java b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/IsolationLevelDataSourceAdapter.java index 419913c9b20c..6b3ddffe041d 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/IsolationLevelDataSourceAdapter.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/IsolationLevelDataSourceAdapter.java @@ -173,4 +173,26 @@ protected Connection doGetConnection(@Nullable String username, @Nullable String return (txReadOnly ? Boolean.TRUE : null); } + public boolean isWrapperFor(Class iface) throws java.sql.SQLException { + // TODO Auto-generated method stub + return iface != null && iface.isAssignableFrom(this.getClass()); + } + + public T unwrap(Class iface) throws java.sql.SQLException { + // TODO Auto-generated method stub + try { + if (iface != null && iface.isAssignableFrom(this.getClass())) { + return (T) this; + } + throw new java.sql.SQLException("Auto-generated unwrap failed; Revisit implementation"); + } catch (Exception e) { + throw new java.sql.SQLException(e); + } + } + + public java.util.logging.Logger getParentLogger() { + // TODO Auto-generated method stub + return null; + } + } diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/LazyConnectionDataSourceProxy.java b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/LazyConnectionDataSourceProxy.java index 2cc269a0aad7..566add56fa24 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/LazyConnectionDataSourceProxy.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/LazyConnectionDataSourceProxy.java @@ -509,4 +509,26 @@ private DataSource getDataSourceToUse() { } } + public boolean isWrapperFor(Class iface) throws java.sql.SQLException { + // TODO Auto-generated method stub + return iface != null && iface.isAssignableFrom(this.getClass()); + } + + public T unwrap(Class iface) throws java.sql.SQLException { + // TODO Auto-generated method stub + try { + if (iface != null && iface.isAssignableFrom(this.getClass())) { + return (T) this; + } + throw new java.sql.SQLException("Auto-generated unwrap failed; Revisit implementation"); + } catch (Exception e) { + throw new java.sql.SQLException(e); + } + } + + public java.util.logging.Logger getParentLogger() { + // TODO Auto-generated method stub + return null; + } + } diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/ShardingKeyDataSourceAdapter.java b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/ShardingKeyDataSourceAdapter.java index b51f9b39d0e0..c2d3fa197405 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/ShardingKeyDataSourceAdapter.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/ShardingKeyDataSourceAdapter.java @@ -134,4 +134,26 @@ public ConnectionBuilder createConnectionBuilder() throws SQLException { return connectionBuilder.shardingKey(shardingKey).superShardingKey(superShardingKey); } + public boolean isWrapperFor(Class iface) throws java.sql.SQLException { + // TODO Auto-generated method stub + return iface != null && iface.isAssignableFrom(this.getClass()); + } + + public T unwrap(Class iface) throws java.sql.SQLException { + // TODO Auto-generated method stub + try { + if (iface != null && iface.isAssignableFrom(this.getClass())) { + return (T) this; + } + throw new java.sql.SQLException("Auto-generated unwrap failed; Revisit implementation"); + } catch (Exception e) { + throw new java.sql.SQLException(e); + } + } + + public java.util.logging.Logger getParentLogger() { + // TODO Auto-generated method stub + return null; + } + } diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/SimpleDriverDataSource.java b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/SimpleDriverDataSource.java index 27c1ad7b9d01..722470d73931 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/SimpleDriverDataSource.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/SimpleDriverDataSource.java @@ -143,4 +143,26 @@ protected Connection getConnectionFromDriver(Properties props) throws SQLExcepti return driver.connect(url, props); } + public boolean isWrapperFor(Class iface) throws java.sql.SQLException { + // TODO Auto-generated method stub + return iface != null && iface.isAssignableFrom(this.getClass()); + } + + public T unwrap(Class iface) throws java.sql.SQLException { + // TODO Auto-generated method stub + try { + if (iface != null && iface.isAssignableFrom(this.getClass())) { + return (T) this; + } + throw new java.sql.SQLException("Auto-generated unwrap failed; Revisit implementation"); + } catch (Exception e) { + throw new java.sql.SQLException(e); + } + } + + public java.util.logging.Logger getParentLogger() { + // TODO Auto-generated method stub + return null; + } + } diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/SingleConnectionDataSource.java b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/SingleConnectionDataSource.java index 6cc44269bbb1..2b3d2d05f1d8 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/SingleConnectionDataSource.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/SingleConnectionDataSource.java @@ -393,4 +393,26 @@ public CloseSuppressingInvocationHandler(Connection target) { } } + public boolean isWrapperFor(Class iface) throws java.sql.SQLException { + // TODO Auto-generated method stub + return iface != null && iface.isAssignableFrom(this.getClass()); + } + + public T unwrap(Class iface) throws java.sql.SQLException { + // TODO Auto-generated method stub + try { + if (iface != null && iface.isAssignableFrom(this.getClass())) { + return (T) this; + } + throw new java.sql.SQLException("Auto-generated unwrap failed; Revisit implementation"); + } catch (Exception e) { + throw new java.sql.SQLException(e); + } + } + + public java.util.logging.Logger getParentLogger() { + // TODO Auto-generated method stub + return null; + } + } diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/TransactionAwareDataSourceProxy.java b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/TransactionAwareDataSourceProxy.java index 3a2f08a87a48..efc0ed358617 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/TransactionAwareDataSourceProxy.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/TransactionAwareDataSourceProxy.java @@ -289,4 +289,26 @@ public TransactionAwareInvocationHandler(DataSource targetDataSource) { } } + public boolean isWrapperFor(Class iface) throws java.sql.SQLException { + // TODO Auto-generated method stub + return iface != null && iface.isAssignableFrom(this.getClass()); + } + + public T unwrap(Class iface) throws java.sql.SQLException { + // TODO Auto-generated method stub + try { + if (iface != null && iface.isAssignableFrom(this.getClass())) { + return (T) this; + } + throw new java.sql.SQLException("Auto-generated unwrap failed; Revisit implementation"); + } catch (Exception e) { + throw new java.sql.SQLException(e); + } + } + + public java.util.logging.Logger getParentLogger() { + // TODO Auto-generated method stub + return null; + } + } diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/UserCredentialsDataSourceAdapter.java b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/UserCredentialsDataSourceAdapter.java index 03ef91a79d59..4b5da2f70c05 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/UserCredentialsDataSourceAdapter.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/UserCredentialsDataSourceAdapter.java @@ -217,4 +217,26 @@ public String toString() { } } + public boolean isWrapperFor(Class iface) throws java.sql.SQLException { + // TODO Auto-generated method stub + return iface != null && iface.isAssignableFrom(this.getClass()); + } + + public T unwrap(Class iface) throws java.sql.SQLException { + // TODO Auto-generated method stub + try { + if (iface != null && iface.isAssignableFrom(this.getClass())) { + return (T) this; + } + throw new java.sql.SQLException("Auto-generated unwrap failed; Revisit implementation"); + } catch (Exception e) { + throw new java.sql.SQLException(e); + } + } + + public java.util.logging.Logger getParentLogger() { + // TODO Auto-generated method stub + return null; + } + } diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/DerbyEmbeddedDatabaseConfigurer.java b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/DerbyEmbeddedDatabaseConfigurer.java index 0070a72c3734..1e8ef0e4515a 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/DerbyEmbeddedDatabaseConfigurer.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/DerbyEmbeddedDatabaseConfigurer.java @@ -62,7 +62,7 @@ private DerbyEmbeddedDatabaseConfigurer() { @Override public void configureConnectionProperties(ConnectionProperties properties, String databaseName) { properties.setDriverClass(EmbeddedDriver.class); - properties.setUrl(String.format(URL_TEMPLATE, databaseName, "create=true")); + properties.setUrl(URL_TEMPLATE.formatted(databaseName, "create=true")); properties.setUsername("sa"); properties.setPassword(""); } @@ -71,7 +71,7 @@ public void configureConnectionProperties(ConnectionProperties properties, Strin public void shutdown(DataSource dataSource, String databaseName) { try { new EmbeddedDriver().connect( - String.format(URL_TEMPLATE, databaseName, "drop=true"), new Properties()); + URL_TEMPLATE.formatted(databaseName, "drop=true"), new Properties()); } catch (SQLException ex) { // Error code that indicates successful shutdown diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseFactory.java b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseFactory.java index 17bf09414f11..f12a1666dd53 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseFactory.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseFactory.java @@ -193,11 +193,11 @@ protected void initDatabase() { if (logger.isInfoEnabled()) { if (this.dataSource instanceof SimpleDriverDataSource simpleDriverDataSource) { - logger.info(String.format("Starting embedded database: url='%s', username='%s'", + logger.info("Starting embedded database: url='%s', username='%s'".formatted( simpleDriverDataSource.getUrl(), simpleDriverDataSource.getUsername())); } else { - logger.info(String.format("Starting embedded database '%s'", this.databaseName)); + logger.info("Starting embedded database '%s'".formatted(this.databaseName)); } } @@ -224,11 +224,11 @@ protected void shutdownDatabase() { if (this.dataSource != null) { if (logger.isInfoEnabled()) { if (this.dataSource instanceof SimpleDriverDataSource simpleDriverDataSource) { - logger.info(String.format("Shutting down embedded database: url='%s'", + logger.info("Shutting down embedded database: url='%s'".formatted( simpleDriverDataSource.getUrl())); } else { - logger.info(String.format("Shutting down embedded database '%s'", this.databaseName)); + logger.info("Shutting down embedded database '%s'".formatted(this.databaseName)); } } if (this.databaseConfigurer != null) { diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/H2EmbeddedDatabaseConfigurer.java b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/H2EmbeddedDatabaseConfigurer.java index 98c4fb18397b..8d1fdb7f459e 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/H2EmbeddedDatabaseConfigurer.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/H2EmbeddedDatabaseConfigurer.java @@ -61,7 +61,7 @@ private H2EmbeddedDatabaseConfigurer(Class driverClass) { @Override public void configureConnectionProperties(ConnectionProperties properties, String databaseName) { properties.setDriverClass(this.driverClass); - properties.setUrl(String.format("jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false", databaseName)); + properties.setUrl("jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false".formatted(databaseName)); properties.setUsername("sa"); properties.setPassword(""); } diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/init/ScriptParseException.java b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/init/ScriptParseException.java index e9918af32018..fa5cfaf0afc0 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/init/ScriptParseException.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/init/ScriptParseException.java @@ -50,7 +50,7 @@ public ScriptParseException(String message, @Nullable EncodedResource resource, private static String buildMessage(String message, @Nullable EncodedResource resource) { - return String.format("Failed to parse SQL script from resource [%s]: %s", + return "Failed to parse SQL script from resource [%s]: %s".formatted( (resource == null ? "" : resource), message); } diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/lookup/IsolationLevelDataSourceRouter.java b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/lookup/IsolationLevelDataSourceRouter.java index 84c8c2025b61..7e29a93f1ef4 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/lookup/IsolationLevelDataSourceRouter.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/lookup/IsolationLevelDataSourceRouter.java @@ -138,4 +138,26 @@ else if (lookupKey instanceof String constantName) { return TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); } + public boolean isWrapperFor(Class iface) throws java.sql.SQLException { + // TODO Auto-generated method stub + return iface != null && iface.isAssignableFrom(this.getClass()); + } + + public T unwrap(Class iface) throws java.sql.SQLException { + // TODO Auto-generated method stub + try { + if (iface != null && iface.isAssignableFrom(this.getClass())) { + return (T) this; + } + throw new java.sql.SQLException("Auto-generated unwrap failed; Revisit implementation"); + } catch (Exception e) { + throw new java.sql.SQLException(e); + } + } + + public java.util.logging.Logger getParentLogger() { + // TODO Auto-generated method stub + return null; + } + } diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/support/rowset/ResultSetWrappingSqlRowSet.java b/spring-jdbc/src/main/java/org/springframework/jdbc/support/rowset/ResultSetWrappingSqlRowSet.java index fca9c306187c..f041ab75c06d 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/support/rowset/ResultSetWrappingSqlRowSet.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/support/rowset/ResultSetWrappingSqlRowSet.java @@ -16,6 +16,7 @@ package org.springframework.jdbc.support.rowset; +import java.io.Serial; import java.math.BigDecimal; import java.sql.Date; import java.sql.ResultSet; @@ -67,7 +68,7 @@ public class ResultSetWrappingSqlRowSet implements SqlRowSet { /** use serialVersionUID from Spring 1.2 for interoperability. */ - private static final long serialVersionUID = -4688694393146734764L; + @Serial private static final long serialVersionUID = -4688694393146734764L; @SuppressWarnings("serial") private final ResultSet resultSet; diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/AutoCommitDisabledH2EmbeddedDatabaseConfigurer.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/AutoCommitDisabledH2EmbeddedDatabaseConfigurer.java index f826abd7b6d9..5303b9fd2a0e 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/AutoCommitDisabledH2EmbeddedDatabaseConfigurer.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/AutoCommitDisabledH2EmbeddedDatabaseConfigurer.java @@ -40,7 +40,7 @@ public AutoCommitDisabledH2EmbeddedDatabaseConfigurer() throws Exception { @Override public void configureConnectionProperties(ConnectionProperties properties, String databaseName) { - String url = String.format("jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false;AUTOCOMMIT=false", databaseName); + String url = "jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false;AUTOCOMMIT=false".formatted(databaseName); properties.setDriverClass(this.driverClass); properties.setUrl(url); diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/support/rowset/ResultSetWrappingRowSetTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/support/rowset/ResultSetWrappingRowSetTests.java index b75ad9f543c8..ab33df34beae 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/support/rowset/ResultSetWrappingRowSetTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/support/rowset/ResultSetWrappingRowSetTests.java @@ -200,8 +200,8 @@ void testGetBooleanString() throws Exception { private void doTest(Method rsetMethod, Method rowsetMethod, Object arg, Object ret) throws Exception { - if (arg instanceof String) { - given(resultSet.findColumn((String) arg)).willReturn(1); + if (arg instanceof String string) { + given(resultSet.findColumn(string)).willReturn(1); given(rsetMethod.invoke(resultSet, 1)).willReturn(ret).willThrow(new SQLException("test")); } else { diff --git a/spring-messaging/spring-messaging.gradle b/spring-messaging/spring-messaging.gradle index a611cf669825..547f519cce75 100644 --- a/spring-messaging/spring-messaging.gradle +++ b/spring-messaging/spring-messaging.gradle @@ -39,8 +39,7 @@ dependencies { testImplementation("org.xmlunit:xmlunit-matchers") testRuntimeOnly(project(":spring-context")) testRuntimeOnly("com.sun.activation:jakarta.activation") - testRuntimeOnly("com.sun.xml.bind:jaxb-core") - testRuntimeOnly("com.sun.xml.bind:jaxb-impl") + testRuntimeOnly("org.glassfish.jaxb:jaxb-runtime") testRuntimeOnly("jakarta.json:jakarta.json-api") testRuntimeOnly("org.eclipse:yasson") } diff --git a/spring-messaging/src/main/java/org/springframework/messaging/MessageHeaders.java b/spring-messaging/src/main/java/org/springframework/messaging/MessageHeaders.java index 5d6e9be42b11..dd324d9c18a6 100644 --- a/spring-messaging/src/main/java/org/springframework/messaging/MessageHeaders.java +++ b/spring-messaging/src/main/java/org/springframework/messaging/MessageHeaders.java @@ -19,6 +19,7 @@ import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; +import java.io.Serial; import java.io.Serializable; import java.util.Collection; import java.util.Collections; @@ -106,7 +107,7 @@ public class MessageHeaders implements Map, Serializable { public static final String ERROR_CHANNEL = "errorChannel"; - private static final long serialVersionUID = 7035068984263400920L; + @Serial private static final long serialVersionUID = 7035068984263400920L; private static final Log logger = LogFactory.getLog(MessageHeaders.class); diff --git a/spring-messaging/src/main/java/org/springframework/messaging/support/ErrorMessage.java b/spring-messaging/src/main/java/org/springframework/messaging/support/ErrorMessage.java index e08387eb2ee5..3d9dab427508 100644 --- a/spring-messaging/src/main/java/org/springframework/messaging/support/ErrorMessage.java +++ b/spring-messaging/src/main/java/org/springframework/messaging/support/ErrorMessage.java @@ -16,6 +16,7 @@ package org.springframework.messaging.support; +import java.io.Serial; import java.util.Map; import org.jspecify.annotations.Nullable; @@ -44,7 +45,7 @@ */ public class ErrorMessage extends GenericMessage { - private static final long serialVersionUID = -5470210965279837728L; + @Serial private static final long serialVersionUID = -5470210965279837728L; @SuppressWarnings("serial") private final @Nullable Message originalMessage; diff --git a/spring-messaging/src/main/java/org/springframework/messaging/support/GenericMessage.java b/spring-messaging/src/main/java/org/springframework/messaging/support/GenericMessage.java index e2b8f7126a06..08c457e17f22 100644 --- a/spring-messaging/src/main/java/org/springframework/messaging/support/GenericMessage.java +++ b/spring-messaging/src/main/java/org/springframework/messaging/support/GenericMessage.java @@ -16,6 +16,7 @@ package org.springframework.messaging.support; +import java.io.Serial; import java.io.Serializable; import java.util.Map; @@ -37,7 +38,7 @@ */ public class GenericMessage implements Message, Serializable { - private static final long serialVersionUID = 4268801052358035098L; + @Serial private static final long serialVersionUID = 4268801052358035098L; @SuppressWarnings("serial") private final T payload; diff --git a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/PayloadMethodArgumentResolverTests.java b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/PayloadMethodArgumentResolverTests.java index b6668600cb33..fe41c786fef3 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/PayloadMethodArgumentResolverTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/PayloadMethodArgumentResolverTests.java @@ -202,7 +202,7 @@ public boolean supports(Class clazz) { @Override public void validate(@Nullable Object target, Errors errors) { - if (target instanceof String && ((String) target).length() < 8) { + if (target instanceof String string && string.length() < 8) { errors.reject("Invalid length"); } } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/protobuf/Msg.java b/spring-messaging/src/test/java/org/springframework/messaging/protobuf/Msg.java index a7e43397b437..e6299c78c146 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/protobuf/Msg.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/protobuf/Msg.java @@ -62,8 +62,8 @@ public boolean hasFoo() { @java.lang.Override public java.lang.String getFoo() { java.lang.Object ref = foo_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; + if (ref instanceof java.lang.String string) { + return string; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; @@ -82,10 +82,10 @@ public java.lang.String getFoo() { public com.google.protobuf.ByteString getFooBytes() { java.lang.Object ref = foo_; - if (ref instanceof java.lang.String) { + if (ref instanceof java.lang.String string) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( - (java.lang.String) ref); + string); foo_ = b; return b; } else { @@ -391,8 +391,8 @@ private void buildPartial0(org.springframework.messaging.protobuf.Msg result) { @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof org.springframework.messaging.protobuf.Msg) { - return mergeFrom((org.springframework.messaging.protobuf.Msg)other); + if (other instanceof org.springframework.messaging.protobuf.Msg msg) { + return mergeFrom(msg); } else { super.mergeFrom(other); return this; @@ -497,10 +497,10 @@ public java.lang.String getFoo() { public com.google.protobuf.ByteString getFooBytes() { java.lang.Object ref = foo_; - if (ref instanceof String) { + if (ref instanceof java.lang.String string) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( - (java.lang.String) ref); + string); foo_ = b; return b; } else { diff --git a/spring-messaging/src/test/java/org/springframework/messaging/protobuf/OuterSample.java b/spring-messaging/src/test/java/org/springframework/messaging/protobuf/OuterSample.java index cbfdd4ac6b61..1aa2f07ab99e 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/protobuf/OuterSample.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/protobuf/OuterSample.java @@ -44,10 +44,19 @@ public static void registerAllExtensions( descriptor; static { java.lang.String[] descriptorData = { - "\n\014sample.proto\",\n\003Msg\022\013\n\003foo\030\001 \001(\t\022\030\n\004bl" + - "ah\030\002 \001(\0132\n.SecondMsg\"\031\n\tSecondMsg\022\014\n\004bla" + - "h\030\001 \001(\005B7\n&org.springframework.messaging" + - ".protobufB\013OuterSampleP\001" + """ + + sample.proto", + Msg + foo (  + bl\ + ah ( 2 + .SecondMsg" + SecondMsg + bla\ + h (B7 + &org.springframework.messaging\ + .protobufB OuterSampleP""" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, diff --git a/spring-messaging/src/test/java/org/springframework/messaging/protobuf/SecondMsg.java b/spring-messaging/src/test/java/org/springframework/messaging/protobuf/SecondMsg.java index 923927096caa..cd59033781e0 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/protobuf/SecondMsg.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/protobuf/SecondMsg.java @@ -302,8 +302,8 @@ private void buildPartial0(org.springframework.messaging.protobuf.SecondMsg resu @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof org.springframework.messaging.protobuf.SecondMsg) { - return mergeFrom((org.springframework.messaging.protobuf.SecondMsg)other); + if (other instanceof org.springframework.messaging.protobuf.SecondMsg msg) { + return mergeFrom(msg); } else { super.mergeFrom(other); return this; diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/AbstractStompBrokerRelayIntegrationTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/AbstractStompBrokerRelayIntegrationTests.java index 985ce165b5cb..444788c9087c 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/AbstractStompBrokerRelayIntegrationTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/AbstractStompBrokerRelayIntegrationTests.java @@ -528,8 +528,8 @@ protected boolean matchInternal(StompHeaderAccessor headers, Object payload) { return false; } - if (payload instanceof byte[] && this.payload instanceof byte[]) { - return Arrays.equals((byte[]) payload, (byte[]) this.payload); + if (payload instanceof byte[] bytes && this.payload instanceof byte[] bytes1) { + return Arrays.equals(bytes, bytes1); } else { return this.payload.equals(payload); @@ -543,8 +543,8 @@ public String toString() { } protected String getPayloadAsText() { - return (this.payload instanceof byte[]) ? - new String((byte[]) this.payload, StandardCharsets.UTF_8) : this.payload.toString(); + return (this.payload instanceof byte[] bs) ? + new String(bs, StandardCharsets.UTF_8) : this.payload.toString(); } } diff --git a/spring-oxm/spring-oxm.gradle b/spring-oxm/spring-oxm.gradle index dea37ac797e1..df4305b4fc32 100644 --- a/spring-oxm/spring-oxm.gradle +++ b/spring-oxm/spring-oxm.gradle @@ -22,8 +22,7 @@ dependencies { } testImplementation("org.xmlunit:xmlunit-assertj") testImplementation("org.xmlunit:xmlunit-matchers") - testRuntimeOnly("com.sun.xml.bind:jaxb-core") - testRuntimeOnly("com.sun.xml.bind:jaxb-impl") + testRuntimeOnly("org.glassfish.jaxb:jaxb-runtime") } tasks.named("xjc").configure { xjc -> diff --git a/spring-r2dbc/src/main/java/org/springframework/r2dbc/connection/init/ScriptParseException.java b/spring-r2dbc/src/main/java/org/springframework/r2dbc/connection/init/ScriptParseException.java index d5ef011d2ac0..865675c6bebe 100644 --- a/spring-r2dbc/src/main/java/org/springframework/r2dbc/connection/init/ScriptParseException.java +++ b/spring-r2dbc/src/main/java/org/springframework/r2dbc/connection/init/ScriptParseException.java @@ -51,7 +51,7 @@ public ScriptParseException(String message, @Nullable EncodedResource resource, private static String buildMessage(String message, @Nullable EncodedResource resource) { - return String.format("Failed to parse SQL script from resource [%s]: %s", + return "Failed to parse SQL script from resource [%s]: %s".formatted( (resource == null ? "" : resource), message); } diff --git a/spring-r2dbc/src/main/java/org/springframework/r2dbc/connection/lookup/AbstractRoutingConnectionFactory.java b/spring-r2dbc/src/main/java/org/springframework/r2dbc/connection/lookup/AbstractRoutingConnectionFactory.java index 3e2789ff4a1f..a6e6924ad820 100644 --- a/spring-r2dbc/src/main/java/org/springframework/r2dbc/connection/lookup/AbstractRoutingConnectionFactory.java +++ b/spring-r2dbc/src/main/java/org/springframework/r2dbc/connection/lookup/AbstractRoutingConnectionFactory.java @@ -228,8 +228,7 @@ protected Mono determineTargetConnectionFactory() { connectionFactory = this.resolvedDefaultConnectionFactory; } if (connectionFactory == null) { - sink.error(new IllegalStateException(String.format( - "Cannot determine target ConnectionFactory for lookup key '%s'", key == FALLBACK_MARKER ? null : key))); + sink.error(new IllegalStateException("Cannot determine target ConnectionFactory for lookup key '%s'".formatted(key == FALLBACK_MARKER ? null : key))); return; } sink.next(connectionFactory); diff --git a/spring-r2dbc/src/main/java/org/springframework/r2dbc/connection/lookup/BeanFactoryConnectionFactoryLookup.java b/spring-r2dbc/src/main/java/org/springframework/r2dbc/connection/lookup/BeanFactoryConnectionFactoryLookup.java index ebf6171d1e0c..a641c5d61220 100644 --- a/spring-r2dbc/src/main/java/org/springframework/r2dbc/connection/lookup/BeanFactoryConnectionFactoryLookup.java +++ b/spring-r2dbc/src/main/java/org/springframework/r2dbc/connection/lookup/BeanFactoryConnectionFactoryLookup.java @@ -78,7 +78,7 @@ public ConnectionFactory getConnectionFactory(String connectionFactoryName) } catch (BeansException ex) { throw new ConnectionFactoryLookupFailureException( - String.format("Failed to look up ConnectionFactory bean with name '%s'", connectionFactoryName), ex); + "Failed to look up ConnectionFactory bean with name '%s'".formatted(connectionFactoryName), ex); } } diff --git a/spring-r2dbc/src/main/java/org/springframework/r2dbc/core/DefaultDatabaseClient.java b/spring-r2dbc/src/main/java/org/springframework/r2dbc/core/DefaultDatabaseClient.java index ee957d4c3f84..5fd4a0ac8a16 100644 --- a/spring-r2dbc/src/main/java/org/springframework/r2dbc/core/DefaultDatabaseClient.java +++ b/spring-r2dbc/src/main/java/org/springframework/r2dbc/core/DefaultDatabaseClient.java @@ -263,8 +263,7 @@ else if (value instanceof org.springframework.r2dbc.core.Parameter param) { @Override public DefaultGenericExecuteSpec bind(int index, Object value) { assertNotPreparedOperation(); - Assert.notNull(value, () -> String.format( - "Value at index %d must not be null. Use bindNull(…) instead.", index)); + Assert.notNull(value, () -> "Value at index %d must not be null. Use bindNull(…) instead.".formatted(index)); Map byIndex = new LinkedHashMap<>(this.byIndex); byIndex.put(index, resolveParameter(value)); @@ -287,8 +286,7 @@ public DefaultGenericExecuteSpec bind(String name, Object value) { assertNotPreparedOperation(); Assert.hasText(name, "Parameter name must not be null or empty"); - Assert.notNull(value, () -> String.format( - "Value for parameter %s must not be null. Use bindNull(…) instead.", name)); + Assert.notNull(value, () -> "Value for parameter %s must not be null. Use bindNull(…) instead.".formatted(name)); Map byName = new LinkedHashMap<>(this.byName); byName.put(name, resolveParameter(value)); @@ -466,7 +464,7 @@ private MapBindParameterSource retrieveParameters(String sql, List param Parameter parameter = getParameter(remainderByName, remainderByIndex, parameterNames, parameterName); if (parameter == null) { throw new InvalidDataAccessApiUsageException( - String.format("No parameter specified for [%s] in query [%s]", parameterName, sql)); + "No parameter specified for [%s] in query [%s]".formatted(parameterName, sql)); } namedBindings.put(parameterName, parameter); } diff --git a/spring-r2dbc/src/main/java/org/springframework/r2dbc/core/DefaultFetchSpec.java b/spring-r2dbc/src/main/java/org/springframework/r2dbc/core/DefaultFetchSpec.java index 3a8230107e30..bf739fd75905 100644 --- a/spring-r2dbc/src/main/java/org/springframework/r2dbc/core/DefaultFetchSpec.java +++ b/spring-r2dbc/src/main/java/org/springframework/r2dbc/core/DefaultFetchSpec.java @@ -61,7 +61,7 @@ class DefaultFetchSpec implements FetchSpec { public Mono one() { return all().singleOrEmpty() .onErrorMap(IndexOutOfBoundsException.class, ex -> { - String message = String.format("Query [%s] returned non unique result.", this.resultFunction.getSql()); + String message = "Query [%s] returned non unique result.".formatted(this.resultFunction.getSql()); return new IncorrectResultSizeDataAccessException(message, 1); }); } diff --git a/spring-r2dbc/src/main/java/org/springframework/r2dbc/core/NamedParameterUtils.java b/spring-r2dbc/src/main/java/org/springframework/r2dbc/core/NamedParameterUtils.java index 01b08282d24c..fef0e9c1077d 100644 --- a/spring-r2dbc/src/main/java/org/springframework/r2dbc/core/NamedParameterUtils.java +++ b/spring-r2dbc/src/main/java/org/springframework/r2dbc/core/NamedParameterUtils.java @@ -587,8 +587,7 @@ private void bind(BindTarget target, String identifier, Parameter parameter) { } private void bind(BindTarget target, Iterator markers, Object valueToBind) { - Assert.isTrue(markers.hasNext(), () -> String.format( - "No bind marker for value [%s] in SQL [%s]. Check that the query was expanded using the same arguments.", + Assert.isTrue(markers.hasNext(), () -> "No bind marker for value [%s] in SQL [%s]. Check that the query was expanded using the same arguments.".formatted( valueToBind, toQuery())); markers.next().bind(target, valueToBind); } diff --git a/spring-r2dbc/src/test/java/org/springframework/r2dbc/core/DefaultDatabaseClientTests.java b/spring-r2dbc/src/test/java/org/springframework/r2dbc/core/DefaultDatabaseClientTests.java index 769c203b4474..e93e402eb74a 100644 --- a/spring-r2dbc/src/test/java/org/springframework/r2dbc/core/DefaultDatabaseClientTests.java +++ b/spring-r2dbc/src/test/java/org/springframework/r2dbc/core/DefaultDatabaseClientTests.java @@ -441,7 +441,7 @@ void sqlSupplierInvocationIsDeferredUntilSubscription() { Mono> operation = databaseClient .sql(() -> { int idMax = 2 + invoked.incrementAndGet(); - return String.format("SELECT id FROM test WHERE id < '%s'", idMax); + return "SELECT id FROM test WHERE id < '%s'".formatted(idMax); }) .map(r -> r.get("id", Integer.class)) .all() diff --git a/spring-test/spring-test.gradle b/spring-test/spring-test.gradle index ea631c65786b..9ac78bf94e5d 100644 --- a/spring-test/spring-test.gradle +++ b/spring-test/spring-test.gradle @@ -83,8 +83,7 @@ dependencies { testImplementation("org.hsqldb:hsqldb") testImplementation("org.junit.platform:junit-platform-testkit") testImplementation("tools.jackson.core:jackson-databind") - testRuntimeOnly("com.sun.xml.bind:jaxb-core") - testRuntimeOnly("com.sun.xml.bind:jaxb-impl") + testRuntimeOnly("org.glassfish.jaxb:jaxb-runtime") testRuntimeOnly("org.glassfish:jakarta.el") testRuntimeOnly("org.junit.support:testng-engine") testRuntimeOnly("org.junit.vintage:junit-vintage-engine") { diff --git a/spring-test/src/main/java/org/springframework/test/context/BootstrapUtils.java b/spring-test/src/main/java/org/springframework/test/context/BootstrapUtils.java index 2113cb0100e6..57577999a1ab 100644 --- a/spring-test/src/main/java/org/springframework/test/context/BootstrapUtils.java +++ b/spring-test/src/main/java/org/springframework/test/context/BootstrapUtils.java @@ -190,8 +190,7 @@ attribute or make the default bootstrapper class available.""".formatted(clazz), return bootstrapWith.value(); } - throw new IllegalStateException(String.format( - "Configuration error: found multiple declarations of @BootstrapWith for test class [%s]: %s", + throw new IllegalStateException("Configuration error: found multiple declarations of @BootstrapWith for test class [%s]: %s".formatted( testClass.getName(), annotations)); } diff --git a/spring-test/src/main/java/org/springframework/test/context/MergedContextConfiguration.java b/spring-test/src/main/java/org/springframework/test/context/MergedContextConfiguration.java index 2eed29617c8b..bd7fd701eef9 100644 --- a/spring-test/src/main/java/org/springframework/test/context/MergedContextConfiguration.java +++ b/spring-test/src/main/java/org/springframework/test/context/MergedContextConfiguration.java @@ -16,6 +16,7 @@ package org.springframework.test.context; +import java.io.Serial; import java.io.Serializable; import java.util.Arrays; import java.util.Collections; @@ -71,7 +72,7 @@ */ public class MergedContextConfiguration implements Serializable { - private static final long serialVersionUID = -3290560718464957422L; + @Serial private static final long serialVersionUID = -3290560718464957422L; private static final String[] EMPTY_STRING_ARRAY = new String[0]; diff --git a/spring-test/src/main/java/org/springframework/test/context/NestedTestConfiguration.java b/spring-test/src/main/java/org/springframework/test/context/NestedTestConfiguration.java index fb4576ff1814..fc530057655a 100644 --- a/spring-test/src/main/java/org/springframework/test/context/NestedTestConfiguration.java +++ b/spring-test/src/main/java/org/springframework/test/context/NestedTestConfiguration.java @@ -177,9 +177,8 @@ enum EnclosingConfiguration { catch (IllegalArgumentException ex) { Log logger = LogFactory.getLog(EnclosingConfiguration.class); if (logger.isDebugEnabled()) { - logger.debug(String.format( - "Failed to parse enclosing configuration mode from '%s': %s", - name, ex.getMessage())); + logger.debug("Failed to parse enclosing configuration mode from '%s': %s".formatted( + name, ex.getMessage())); } return null; } diff --git a/spring-test/src/main/java/org/springframework/test/context/TestConstructor.java b/spring-test/src/main/java/org/springframework/test/context/TestConstructor.java index 9803c83438b4..e949ff1c03bd 100644 --- a/spring-test/src/main/java/org/springframework/test/context/TestConstructor.java +++ b/spring-test/src/main/java/org/springframework/test/context/TestConstructor.java @@ -160,7 +160,7 @@ enum AutowireMode { catch (IllegalArgumentException ex) { Log logger = LogFactory.getLog(AutowireMode.class); if (logger.isDebugEnabled()) { - logger.debug(String.format("Failed to parse autowire mode from '%s': %s", name, ex.getMessage())); + logger.debug("Failed to parse autowire mode from '%s': %s".formatted(name, ex.getMessage())); } return null; } diff --git a/spring-test/src/main/java/org/springframework/test/context/cache/AotMergedContextConfiguration.java b/spring-test/src/main/java/org/springframework/test/context/cache/AotMergedContextConfiguration.java index 86081399a0b7..c214b9a53685 100644 --- a/spring-test/src/main/java/org/springframework/test/context/cache/AotMergedContextConfiguration.java +++ b/spring-test/src/main/java/org/springframework/test/context/cache/AotMergedContextConfiguration.java @@ -16,6 +16,7 @@ package org.springframework.test.context.cache; +import java.io.Serial; import java.util.Collections; import org.jspecify.annotations.Nullable; @@ -42,7 +43,7 @@ */ final class AotMergedContextConfiguration extends MergedContextConfiguration { - private static final long serialVersionUID = 1963364911008547843L; + @Serial private static final long serialVersionUID = 1963364911008547843L; private final Class> contextInitializerClass; diff --git a/spring-test/src/main/java/org/springframework/test/context/junit/jupiter/AbstractExpressionEvaluatingCondition.java b/spring-test/src/main/java/org/springframework/test/context/junit/jupiter/AbstractExpressionEvaluatingCondition.java index fe59f8e686d8..85ad0c916282 100644 --- a/spring-test/src/main/java/org/springframework/test/context/junit/jupiter/AbstractExpressionEvaluatingCondition.java +++ b/spring-test/src/main/java/org/springframework/test/context/junit/jupiter/AbstractExpressionEvaluatingCondition.java @@ -94,7 +94,7 @@ protected ConditionEvaluationResult evaluateAnnotation(Cl Optional annotation = findMergedAnnotation(element, annotationType); if (annotation.isEmpty()) { - String reason = String.format("%s is enabled since @%s is not present", element, + String reason = "%s is enabled since @%s is not present".formatted(element, annotationType.getSimpleName()); if (logger.isDebugEnabled()) { logger.debug(reason); @@ -103,8 +103,7 @@ protected ConditionEvaluationResult evaluateAnnotation(Cl } String expression = annotation.map(expressionExtractor).map(String::trim).filter(StringUtils::hasLength) - .orElseThrow(() -> new IllegalStateException(String.format( - "The expression in @%s on [%s] must not be blank", annotationType.getSimpleName(), element))); + .orElseThrow(() -> new IllegalStateException("The expression in @%s on [%s] must not be blank".formatted(annotationType.getSimpleName(), element))); boolean loadContext = loadContextExtractor.apply(annotation.get()); boolean evaluatedToTrue = evaluateExpression(expression, loadContext, annotationType, context); @@ -113,8 +112,8 @@ protected ConditionEvaluationResult evaluateAnnotation(Cl if (evaluatedToTrue) { String adjective = (enabledOnTrue ? "enabled" : "disabled"); String reason = annotation.map(reasonExtractor).filter(StringUtils::hasText).orElseGet( - () -> String.format("%s is %s because @%s(\"%s\") evaluated to true", element, adjective, - annotationType.getSimpleName(), expression)); + () -> "%s is %s because @%s(\"%s\") evaluated to true".formatted(element, adjective, + annotationType.getSimpleName(), expression)); if (logger.isInfoEnabled()) { logger.info(reason); } @@ -123,7 +122,7 @@ protected ConditionEvaluationResult evaluateAnnotation(Cl } else { String adjective = (enabledOnTrue ? "disabled" : "enabled"); - String reason = String.format("%s is %s because @%s(\"%s\") did not evaluate to true", + String reason = "%s is %s because @%s(\"%s\") did not evaluate to true".formatted( element, adjective, annotationType.getSimpleName(), expression); if (logger.isDebugEnabled()) { logger.debug(reason); @@ -196,12 +195,12 @@ else if (result instanceof String str) { return true; } Assert.state("false".equals(str), - () -> String.format("@%s(\"%s\") on %s must evaluate to \"true\" or \"false\", not \"%s\"", - annotationType.getSimpleName(), expression, element, result)); + () -> "@%s(\"%s\") on %s must evaluate to \"true\" or \"false\", not \"%s\"".formatted( + annotationType.getSimpleName(), expression, element, result)); return false; } else { - String message = String.format("@%s(\"%s\") on %s must evaluate to a String or a Boolean, not %s", + String message = "@%s(\"%s\") on %s must evaluate to a String or a Boolean, not %s".formatted( annotationType.getSimpleName(), expression, element, (result != null ? result.getClass().getName() : "null")); throw new IllegalStateException(message); diff --git a/spring-test/src/main/java/org/springframework/test/context/junit4/statements/ProfileValueChecker.java b/spring-test/src/main/java/org/springframework/test/context/junit4/statements/ProfileValueChecker.java index 86c634890c59..865ebab64d3c 100644 --- a/spring-test/src/main/java/org/springframework/test/context/junit4/statements/ProfileValueChecker.java +++ b/spring-test/src/main/java/org/springframework/test/context/junit4/statements/ProfileValueChecker.java @@ -90,15 +90,13 @@ public void evaluate() throws Throwable { if (this.testMethod == null) { if (!ProfileValueUtils.isTestEnabledInThisEnvironment(this.testClass)) { Annotation ann = AnnotatedElementUtils.findMergedAnnotation(this.testClass, IfProfileValue.class); - throw new AssumptionViolatedException(String.format( - "Profile configured via [%s] is not enabled in this environment for test class [%s].", + throw new AssumptionViolatedException("Profile configured via [%s] is not enabled in this environment for test class [%s].".formatted( ann, this.testClass.getName())); } } else { if (!ProfileValueUtils.isTestEnabledInThisEnvironment(this.testMethod, this.testClass)) { - throw new AssumptionViolatedException(String.format( - "Profile configured via @IfProfileValue is not enabled in this environment for test method [%s].", + throw new AssumptionViolatedException("Profile configured via @IfProfileValue is not enabled in this environment for test method [%s].".formatted( this.testMethod)); } } diff --git a/spring-test/src/main/java/org/springframework/test/context/junit4/statements/SpringFailOnTimeout.java b/spring-test/src/main/java/org/springframework/test/context/junit4/statements/SpringFailOnTimeout.java index ae386d089a9f..3940bd2fd046 100644 --- a/spring-test/src/main/java/org/springframework/test/context/junit4/statements/SpringFailOnTimeout.java +++ b/spring-test/src/main/java/org/springframework/test/context/junit4/statements/SpringFailOnTimeout.java @@ -96,7 +96,7 @@ public void evaluate() throws Throwable { long elapsed = System.currentTimeMillis() - startTime; if (elapsed > this.timeout) { throw new TimeoutException( - String.format("Test took %s ms; limit was %s ms.", elapsed, this.timeout)); + "Test took %s ms; limit was %s ms.".formatted(elapsed, this.timeout)); } } } diff --git a/spring-test/src/main/java/org/springframework/test/context/junit4/statements/SpringRepeat.java b/spring-test/src/main/java/org/springframework/test/context/junit4/statements/SpringRepeat.java index f142adfa70d4..528124f5f784 100644 --- a/spring-test/src/main/java/org/springframework/test/context/junit4/statements/SpringRepeat.java +++ b/spring-test/src/main/java/org/springframework/test/context/junit4/statements/SpringRepeat.java @@ -82,7 +82,7 @@ public SpringRepeat(Statement next, Method testMethod, int repeat) { public void evaluate() throws Throwable { for (int i = 0; i < this.repeat; i++) { if (this.repeat > 1 && logger.isTraceEnabled()) { - logger.trace(String.format("Repetition %d of test %s#%s()", (i + 1), + logger.trace("Repetition %d of test %s#%s()".formatted((i + 1), this.testMethod.getDeclaringClass().getSimpleName(), this.testMethod.getName())); } this.next.evaluate(); diff --git a/spring-test/src/main/java/org/springframework/test/context/support/AbstractContextLoader.java b/spring-test/src/main/java/org/springframework/test/context/support/AbstractContextLoader.java index 421cde5267d8..5a1fa34ed7b2 100644 --- a/spring-test/src/main/java/org/springframework/test/context/support/AbstractContextLoader.java +++ b/spring-test/src/main/java/org/springframework/test/context/support/AbstractContextLoader.java @@ -256,7 +256,7 @@ protected String[] generateDefaultLocations(Class clazz) { if (classPathResource.exists()) { String prefixedResourcePath = ResourceUtils.CLASSPATH_URL_PREFIX + SLASH + resourcePath; if (logger.isDebugEnabled()) { - logger.debug(String.format("Detected default resource location \"%s\" for test class [%s]", + logger.debug("Detected default resource location \"%s\" for test class [%s]".formatted( prefixedResourcePath, clazz.getName())); } return new String[] {prefixedResourcePath}; diff --git a/spring-test/src/main/java/org/springframework/test/context/support/AbstractDelegatingSmartContextLoader.java b/spring-test/src/main/java/org/springframework/test/context/support/AbstractDelegatingSmartContextLoader.java index 2e16c7215e5f..3ffe653a9507 100644 --- a/spring-test/src/main/java/org/springframework/test/context/support/AbstractDelegatingSmartContextLoader.java +++ b/spring-test/src/main/java/org/springframework/test/context/support/AbstractDelegatingSmartContextLoader.java @@ -150,13 +150,12 @@ else if (configAttributes.hasClasses()) { if (xmlLoaderDetectedDefaults) { if (logger.isTraceEnabled()) { - logger.trace(String.format("%s detected default locations for context configuration %s", + logger.trace("%s detected default locations for context configuration %s".formatted( name(getXmlLoader()), configAttributes)); } } - Assert.state(!configAttributes.hasClasses(), () -> String.format( - "%s should NOT have detected default configuration classes for context configuration %s", + Assert.state(!configAttributes.hasClasses(), () -> "%s should NOT have detected default configuration classes for context configuration %s".formatted( name(getXmlLoader()), configAttributes)); // Now let the annotation config loader process the configuration. @@ -164,13 +163,12 @@ else if (configAttributes.hasClasses()) { if (configAttributes.hasClasses()) { if (logger.isTraceEnabled()) { - logger.trace(String.format("%s detected default configuration classes for context configuration %s", + logger.trace("%s detected default configuration classes for context configuration %s".formatted( name(getAnnotationConfigLoader()), configAttributes)); } } - Assert.state(xmlLoaderDetectedDefaults || !configAttributes.hasLocations(), () -> String.format( - "%s should NOT have detected default locations for context configuration %s", + Assert.state(xmlLoaderDetectedDefaults || !configAttributes.hasLocations(), () -> "%s should NOT have detected default locations for context configuration %s".formatted( name(getAnnotationConfigLoader()), configAttributes)); if (configAttributes.hasLocations() && configAttributes.hasClasses()) { diff --git a/spring-test/src/main/java/org/springframework/test/context/support/AbstractTestContextBootstrapper.java b/spring-test/src/main/java/org/springframework/test/context/support/AbstractTestContextBootstrapper.java index 7cc828dd0888..98052219e034 100644 --- a/spring-test/src/main/java/org/springframework/test/context/support/AbstractTestContextBootstrapper.java +++ b/spring-test/src/main/java/org/springframework/test/context/support/AbstractTestContextBootstrapper.java @@ -121,7 +121,7 @@ public final List getTestExecutionListeners() { // Use defaults? if (descriptor == null) { if (logger.isTraceEnabled()) { - logger.trace(String.format("@TestExecutionListeners is not present for class [%s]: using defaults.", + logger.trace("@TestExecutionListeners is not present for class [%s]: using defaults.".formatted( clazz.getName())); } usingDefaults = true; @@ -133,7 +133,7 @@ public final List getTestExecutionListeners() { Class declaringClass = descriptor.getDeclaringClass(); TestExecutionListeners testExecutionListeners = descriptor.getAnnotation(); if (logger.isTraceEnabled()) { - logger.trace(String.format("Retrieved @TestExecutionListeners [%s] for declaring class [%s].", + logger.trace("Retrieved @TestExecutionListeners [%s] for declaring class [%s].".formatted( testExecutionListeners, declaringClass.getName())); } @@ -254,13 +254,11 @@ private MergedContextConfiguration buildDefaultMergedContextConfiguration(Class< ContextLoader contextLoader = resolveContextLoader(testClass, defaultConfigAttributesList); if (logger.isTraceEnabled()) { - logger.trace(String.format( - "Neither @ContextConfiguration nor @ContextHierarchy found for test class [%s]: using %s", + logger.trace("Neither @ContextConfiguration nor @ContextHierarchy found for test class [%s]: using %s".formatted( testClass.getName(), contextLoader.getClass().getName())); } else if (logger.isDebugEnabled()) { - logger.debug(String.format( - "Neither @ContextConfiguration nor @ContextHierarchy found for test class [%s]: using %s", + logger.debug("Neither @ContextConfiguration nor @ContextHierarchy found for test class [%s]: using %s".formatted( testClass.getSimpleName(), contextLoader.getClass().getSimpleName())); } return buildMergedContextConfiguration(testClass, defaultConfigAttributesList, null, @@ -307,7 +305,7 @@ private MergedContextConfiguration buildMergedContextConfiguration(Class test for (ContextConfigurationAttributes configAttributes : configAttributesList) { if (logger.isTraceEnabled()) { - logger.trace(String.format("Processing locations and classes for context configuration attributes %s", + logger.trace("Processing locations and classes for context configuration attributes %s".formatted( configAttributes)); } if (contextLoader instanceof SmartContextLoader smartContextLoader) { @@ -506,7 +504,7 @@ protected ContextLoader resolveContextLoader(Class testClass, contextLoaderClass = getDefaultContextLoaderClass(testClass); } if (logger.isTraceEnabled()) { - logger.trace(String.format("Using ContextLoader class [%s] for test class [%s]", + logger.trace("Using ContextLoader class [%s] for test class [%s]".formatted( contextLoaderClass.getName(), testClass.getName())); } return BeanUtils.instantiateClass(contextLoaderClass, ContextLoader.class); diff --git a/spring-test/src/main/java/org/springframework/test/context/support/ContextLoaderUtils.java b/spring-test/src/main/java/org/springframework/test/context/support/ContextLoaderUtils.java index ab7b5165e0ee..4b87c5538a20 100644 --- a/spring-test/src/main/java/org/springframework/test/context/support/ContextLoaderUtils.java +++ b/spring-test/src/main/java/org/springframework/test/context/support/ContextLoaderUtils.java @@ -104,9 +104,8 @@ static List> resolveContextHierarchyAttribu UntypedAnnotationDescriptor desc = findAnnotationDescriptorForTypes(testClass, contextConfigType, contextHierarchyType); - Assert.notNull(desc, () -> String.format( - "Could not find an 'annotation declaring class' for annotation type [%s] or [%s] and test class [%s]", - contextConfigType.getName(), contextHierarchyType.getName(), testClass.getName())); + Assert.notNull(desc, () -> "Could not find an 'annotation declaring class' for annotation type [%s] or [%s] and test class [%s]".formatted( + contextConfigType.getName(), contextHierarchyType.getName(), testClass.getName())); while (desc != null) { Class rootDeclaringClass = desc.getRootDeclaringClass(); @@ -238,9 +237,8 @@ static List resolveContextConfigurationAttribute Class annotationType = ContextConfiguration.class; AnnotationDescriptor descriptor = findAnnotationDescriptor(testClass, annotationType); - Assert.notNull(descriptor, () -> String.format( - "Could not find an 'annotation declaring class' for annotation type [%s] and class [%s]", - annotationType.getName(), testClass.getName())); + Assert.notNull(descriptor, () -> "Could not find an 'annotation declaring class' for annotation type [%s] and class [%s]".formatted( + annotationType.getName(), testClass.getName())); List attributesList = new ArrayList<>(); ContextConfiguration previousAnnotation = null; @@ -281,7 +279,7 @@ private static void convertContextConfigToConfigAttributesAndAddToList(ContextCo Class declaringClass, List attributesList) { if (logger.isTraceEnabled()) { - logger.trace(String.format("Retrieved @ContextConfiguration [%s] for declaring class [%s].", + logger.trace("Retrieved @ContextConfiguration [%s] for declaring class [%s].".formatted( contextConfiguration, declaringClass.getName())); } ContextConfigurationAttributes attributes = diff --git a/spring-test/src/main/java/org/springframework/test/context/support/DefaultActiveProfilesResolver.java b/spring-test/src/main/java/org/springframework/test/context/support/DefaultActiveProfilesResolver.java index 71a33b00b991..dc35bc7e02df 100644 --- a/spring-test/src/main/java/org/springframework/test/context/support/DefaultActiveProfilesResolver.java +++ b/spring-test/src/main/java/org/springframework/test/context/support/DefaultActiveProfilesResolver.java @@ -60,17 +60,16 @@ public String[] resolve(Class testClass) { if (descriptor == null) { if (logger.isTraceEnabled()) { - logger.trace(String.format( - "Could not find an 'annotation declaring class' for annotation type [%s] and class [%s]", - ActiveProfiles.class.getName(), testClass.getName())); + logger.trace("Could not find an 'annotation declaring class' for annotation type [%s] and class [%s]".formatted( + ActiveProfiles.class.getName(), testClass.getName())); } return EMPTY_STRING_ARRAY; } else { ActiveProfiles annotation = descriptor.getAnnotation(); if (logger.isTraceEnabled()) { - logger.trace(String.format("Retrieved @ActiveProfiles [%s] for declaring class [%s].", annotation, - descriptor.getDeclaringClass().getName())); + logger.trace("Retrieved @ActiveProfiles [%s] for declaring class [%s].".formatted(annotation, + descriptor.getDeclaringClass().getName())); } return annotation.profiles(); } diff --git a/spring-test/src/main/java/org/springframework/test/context/support/DefaultTestContext.java b/spring-test/src/main/java/org/springframework/test/context/support/DefaultTestContext.java index 850c752dac27..21edae6339e8 100644 --- a/spring-test/src/main/java/org/springframework/test/context/support/DefaultTestContext.java +++ b/spring-test/src/main/java/org/springframework/test/context/support/DefaultTestContext.java @@ -16,6 +16,7 @@ package org.springframework.test.context.support; +import java.io.Serial; import java.lang.reflect.Method; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -47,7 +48,7 @@ @SuppressWarnings("serial") public class DefaultTestContext implements TestContext { - private static final long serialVersionUID = -5827157174866681233L; + @Serial private static final long serialVersionUID = -5827157174866681233L; private final Map attributes = new ConcurrentHashMap<>(4); diff --git a/spring-test/src/main/java/org/springframework/test/context/support/TestPropertySourceAttributes.java b/spring-test/src/main/java/org/springframework/test/context/support/TestPropertySourceAttributes.java index ff4474555880..1a90baa2db7e 100644 --- a/spring-test/src/main/java/org/springframework/test/context/support/TestPropertySourceAttributes.java +++ b/spring-test/src/main/java/org/springframework/test/context/support/TestPropertySourceAttributes.java @@ -197,7 +197,7 @@ private String detectDefaultPropertiesFile(Class testClass) { } String prefixedResourcePath = ResourceUtils.CLASSPATH_URL_PREFIX + SLASH + resourcePath; if (logger.isDebugEnabled()) { - logger.debug(String.format("Detected default properties file \"%s\" for test class [%s]", + logger.debug("Detected default properties file \"%s\" for test class [%s]".formatted( prefixedResourcePath, testClass.getName())); } return prefixedResourcePath; diff --git a/spring-test/src/main/java/org/springframework/test/context/support/TestPropertySourceUtils.java b/spring-test/src/main/java/org/springframework/test/context/support/TestPropertySourceUtils.java index 3617e5c0d425..909e6890ccea 100644 --- a/spring-test/src/main/java/org/springframework/test/context/support/TestPropertySourceUtils.java +++ b/spring-test/src/main/java/org/springframework/test/context/support/TestPropertySourceUtils.java @@ -142,7 +142,7 @@ private static boolean duplicationDetected(TestPropertySourceAttributes currentA (currentAttributes.equals(previousAttributes) && !currentAttributes.isEmpty()); if (duplicationDetected && logger.isTraceEnabled()) { - logger.trace(String.format("Ignoring duplicate %s declaration on %s since it is also declared on %s", + logger.trace("Ignoring duplicate %s declaration on %s since it is also declared on %s".formatted( currentAttributes, currentAttributes.getDeclaringClass().getName(), previousAttributes.getDeclaringClass().getName())); } diff --git a/spring-test/src/main/java/org/springframework/test/context/transaction/TestContextTransactionUtils.java b/spring-test/src/main/java/org/springframework/test/context/transaction/TestContextTransactionUtils.java index 32cc36459219..9d5bb7d6d3cb 100644 --- a/spring-test/src/main/java/org/springframework/test/context/transaction/TestContextTransactionUtils.java +++ b/spring-test/src/main/java/org/springframework/test/context/transaction/TestContextTransactionUtils.java @@ -99,7 +99,7 @@ public abstract class TestContextTransactionUtils { } } catch (BeansException ex) { - logger.error(String.format("Failed to retrieve DataSource named '%s' for test context %s", + logger.error("Failed to retrieve DataSource named '%s' for test context %s".formatted( name, testContext), ex); throw ex; } @@ -170,7 +170,7 @@ public abstract class TestContextTransactionUtils { } } catch (BeansException ex) { - logger.error(String.format("Failed to retrieve transaction manager named '%s' for test context %s", + logger.error("Failed to retrieve transaction manager named '%s' for test context %s".formatted( name, testContext), ex); throw ex; } diff --git a/spring-test/src/main/java/org/springframework/test/context/transaction/TransactionalTestExecutionListener.java b/spring-test/src/main/java/org/springframework/test/context/transaction/TransactionalTestExecutionListener.java index 85a22cd8b1e3..1ed18a01a3b6 100644 --- a/spring-test/src/main/java/org/springframework/test/context/transaction/TransactionalTestExecutionListener.java +++ b/spring-test/src/main/java/org/springframework/test/context/transaction/TransactionalTestExecutionListener.java @@ -382,8 +382,7 @@ else if (logger.isDebugEnabled()) { } catch (RuntimeException ex) { if (logger.isWarnEnabled()) { - logger.warn(String.format( - "Caught exception while retrieving transaction manager with qualifier '%s' for test context %s", + logger.warn("Caught exception while retrieving transaction manager with qualifier '%s' for test context %s".formatted( qualifier, testContext), ex); } throw ex; @@ -431,7 +430,7 @@ protected final boolean isDefaultRollback(TestContext testContext) throws Except if (rollbackPresent) { boolean defaultRollback = rollback.value(); if (logger.isDebugEnabled()) { - logger.debug(String.format("Retrieved default @Rollback(%s) for test class [%s].", + logger.debug("Retrieved default @Rollback(%s) for test class [%s].".formatted( defaultRollback, testClass.getName())); } return defaultRollback; diff --git a/spring-test/src/main/java/org/springframework/test/context/web/WebMergedContextConfiguration.java b/spring-test/src/main/java/org/springframework/test/context/web/WebMergedContextConfiguration.java index cd8df132e89f..f6a34929f401 100644 --- a/spring-test/src/main/java/org/springframework/test/context/web/WebMergedContextConfiguration.java +++ b/spring-test/src/main/java/org/springframework/test/context/web/WebMergedContextConfiguration.java @@ -16,6 +16,7 @@ package org.springframework.test.context.web; +import java.io.Serial; import java.util.List; import java.util.Set; @@ -60,7 +61,7 @@ */ public class WebMergedContextConfiguration extends MergedContextConfiguration { - private static final long serialVersionUID = 7323361588604247458L; + @Serial private static final long serialVersionUID = 7323361588604247458L; private final String resourceBasePath; diff --git a/spring-test/src/main/java/org/springframework/test/util/JsonPathExpectationsHelper.java b/spring-test/src/main/java/org/springframework/test/util/JsonPathExpectationsHelper.java index b8acf914b8e9..45df27f07859 100644 --- a/spring-test/src/main/java/org/springframework/test/util/JsonPathExpectationsHelper.java +++ b/spring-test/src/main/java/org/springframework/test/util/JsonPathExpectationsHelper.java @@ -86,7 +86,7 @@ public JsonPathExpectationsHelper(String expression, @Nullable Configuration con * Construct a new {@code JsonPathExpectationsHelper}. * @param expression the {@link JsonPath} expression; never {@code null} or empty * @param args arguments to parameterize the {@code JsonPath} expression with, - * using formatting specifiers defined in {@link String#format(String, Object...)} + * using formatting specifiers defined in {@link String#formatted(Object...)} * @deprecated in favor of calling {@link String#formatted(Object...)} upfront */ @Deprecated(since = "6.2", forRemoval = true) diff --git a/spring-test/src/main/java/org/springframework/test/util/ReflectionTestUtils.java b/spring-test/src/main/java/org/springframework/test/util/ReflectionTestUtils.java index b21cc5a2de6f..b5e024554284 100644 --- a/spring-test/src/main/java/org/springframework/test/util/ReflectionTestUtils.java +++ b/spring-test/src/main/java/org/springframework/test/util/ReflectionTestUtils.java @@ -189,14 +189,12 @@ public static void setField(@Nullable Object targetObject, @Nullable Class ta Field field = ReflectionUtils.findField(targetClass, name, type); if (field == null) { - throw new IllegalArgumentException(String.format( - "Could not find field '%s' of type [%s] on %s or target class [%s]", name, type, + throw new IllegalArgumentException("Could not find field '%s' of type [%s] on %s or target class [%s]".formatted(name, type, safeToString(targetObject), targetClass)); } if (logger.isDebugEnabled()) { - logger.debug(String.format( - "Setting field '%s' of type [%s] on %s or target class [%s] to value [%s]", name, type, + logger.debug("Setting field '%s' of type [%s] on %s or target class [%s] to value [%s]".formatted(name, type, safeToString(targetObject), targetClass, value)); } ReflectionUtils.makeAccessible(field); @@ -272,12 +270,12 @@ public static void setField(@Nullable Object targetObject, @Nullable Class ta Field field = ReflectionUtils.findField(targetClass, name); if (field == null) { - throw new IllegalArgumentException(String.format("Could not find field '%s' on %s or target class [%s]", + throw new IllegalArgumentException("Could not find field '%s' on %s or target class [%s]".formatted( name, safeToString(targetObject), targetClass)); } if (logger.isDebugEnabled()) { - logger.debug(String.format("Getting field '%s' from %s or target class [%s]", name, + logger.debug("Getting field '%s' from %s or target class [%s]".formatted(name, safeToString(targetObject), targetClass)); } ReflectionUtils.makeAccessible(field); @@ -342,13 +340,12 @@ public static void invokeSetterMethod(Object target, String name, @Nullable Obje method = ReflectionUtils.findMethod(target.getClass(), setterMethodName, paramTypes); } if (method == null) { - throw new IllegalArgumentException(String.format( - "Could not find setter method '%s' on %s with parameter type [%s]", setterMethodName, + throw new IllegalArgumentException("Could not find setter method '%s' on %s with parameter type [%s]".formatted(setterMethodName, safeToString(target), type)); } if (logger.isDebugEnabled()) { - logger.debug(String.format("Invoking setter method '%s' on %s with value [%s]", setterMethodName, + logger.debug("Invoking setter method '%s' on %s with value [%s]".formatted(setterMethodName, safeToString(target), value)); } @@ -402,8 +399,7 @@ public static void invokeSetterMethod(Object target, String name, @Nullable Obje method = ReflectionUtils.findMethod(target.getClass(), getterMethodName); } if (method == null) { - throw new IllegalArgumentException(String.format( - "Could not find getter method '%s' on %s", getterMethodName, safeToString(target))); + throw new IllegalArgumentException("Could not find getter method '%s' on %s".formatted(getterMethodName, safeToString(target))); } if (SPRING_AOP_PRESENT) { @@ -415,7 +411,7 @@ public static void invokeSetterMethod(Object target, String name, @Nullable Obje } if (logger.isDebugEnabled()) { - logger.debug(String.format("Invoking getter method '%s' on %s", getterMethodName, safeToString(target))); + logger.debug("Invoking getter method '%s' on %s".formatted(getterMethodName, safeToString(target))); } ReflectionUtils.makeAccessible(method); return ReflectionUtils.invokeMethod(method, target); @@ -524,16 +520,16 @@ public static void invokeSetterMethod(Object target, String name, @Nullable Obje private static String safeToString(@Nullable Object target) { try { - return String.format("target object [%s]", target); + return "target object [%s]".formatted(target); } catch (Exception ex) { - return String.format("target of type [%s] whose toString() method threw [%s]", + return "target of type [%s] whose toString() method threw [%s]".formatted( (target != null ? target.getClass().getName() : "unknown"), ex); } } private static String safeToString(@Nullable Class clazz) { - return String.format("target class [%s]", (clazz != null ? clazz.getName() : null)); + return "target class [%s]".formatted((clazz != null ? clazz.getName() : null)); } /** diff --git a/spring-test/src/main/java/org/springframework/test/util/TestSocketUtils.java b/spring-test/src/main/java/org/springframework/test/util/TestSocketUtils.java index ff32da9bc507..4042c83968d6 100644 --- a/spring-test/src/main/java/org/springframework/test/util/TestSocketUtils.java +++ b/spring-test/src/main/java/org/springframework/test/util/TestSocketUtils.java @@ -109,8 +109,7 @@ int findAvailableTcpPortInternal() { int candidatePort; int searchCounter = 0; do { - Assert.state(++searchCounter <= MAX_ATTEMPTS, () -> String.format( - "Could not find an available TCP port in the range [%d, %d] after %d attempts", + Assert.state(++searchCounter <= MAX_ATTEMPTS, () -> "Could not find an available TCP port in the range [%d, %d] after %d attempts".formatted( PORT_RANGE_MIN, PORT_RANGE_MAX, MAX_ATTEMPTS)); candidatePort = PORT_RANGE_MIN + random.nextInt(PORT_RANGE_PLUS_ONE); } diff --git a/spring-test/src/main/java/org/springframework/test/util/XpathExpectationsHelper.java b/spring-test/src/main/java/org/springframework/test/util/XpathExpectationsHelper.java index 91915ea3e709..77163fa3c841 100644 --- a/spring-test/src/main/java/org/springframework/test/util/XpathExpectationsHelper.java +++ b/spring-test/src/main/java/org/springframework/test/util/XpathExpectationsHelper.java @@ -61,13 +61,13 @@ public class XpathExpectationsHelper { * @param expression the XPath expression * @param namespaces the XML namespaces referenced in the XPath expression, or {@code null} * @param args arguments to parameterize the XPath expression with using the - * formatting specifiers defined in {@link String#format(String, Object...)} + * formatting specifiers defined in {@link String#formatted(Object...)} * @throws XPathExpressionException if expression compilation failed */ public XpathExpectationsHelper(String expression, @Nullable Map namespaces, Object... args) throws XPathExpressionException { - this.expression = String.format(expression, args); + this.expression = expression.formatted(args); this.xpathExpression = compileXpathExpression(this.expression, namespaces); this.hasNamespaces = !CollectionUtils.isEmpty(namespaces); } diff --git a/spring-test/src/main/java/org/springframework/test/web/client/match/JsonPathRequestMatchers.java b/spring-test/src/main/java/org/springframework/test/web/client/match/JsonPathRequestMatchers.java index f841c3f6f7a0..3fef39611a11 100644 --- a/spring-test/src/main/java/org/springframework/test/web/client/match/JsonPathRequestMatchers.java +++ b/spring-test/src/main/java/org/springframework/test/web/client/match/JsonPathRequestMatchers.java @@ -51,7 +51,7 @@ public class JsonPathRequestMatchers { * {@link MockRestRequestMatchers#jsonPath(String, Object...)}. * @param expression the {@link JsonPath} expression; never {@code null} or empty * @param args arguments to parameterize the {@code JsonPath} expression with, - * using formatting specifiers defined in {@link String#format(String, Object...)} + * using formatting specifiers defined in {@link String#formatted(Object...)} */ protected JsonPathRequestMatchers(String expression, Object... args) { Assert.hasText(expression, "expression must not be null or empty"); diff --git a/spring-test/src/main/java/org/springframework/test/web/client/match/MockRestRequestMatchers.java b/spring-test/src/main/java/org/springframework/test/web/client/match/MockRestRequestMatchers.java index a0029405d60f..aa838fa95553 100644 --- a/spring-test/src/main/java/org/springframework/test/web/client/match/MockRestRequestMatchers.java +++ b/spring-test/src/main/java/org/springframework/test/web/client/match/MockRestRequestMatchers.java @@ -333,7 +333,7 @@ public static ContentRequestMatchers content() { * JsonPath expression to * inspect a specific subset of the body. The JSON path expression can be a * parameterized string using formatting specifiers as defined in - * {@link String#format(String, Object...)}. + * {@link String#formatted(Object...)}. * @param expression the JSON path optionally parameterized with arguments * @param args arguments to parameterize the JSON path expression with */ @@ -357,7 +357,7 @@ public static RequestMatcher jsonPath(String expression, Matcher * Access to request body matchers using an XPath to inspect a specific * subset of the body. The XPath expression can be a parameterized string * using formatting specifiers as defined in - * {@link String#format(String, Object...)}. + * {@link String#formatted(Object...)}. * @param expression the XPath optionally parameterized with arguments * @param args arguments to parameterize the XPath expression with */ @@ -369,7 +369,7 @@ public static XpathRequestMatchers xpath(String expression, Object... args) thro * Access to response body matchers using an XPath to inspect a specific * subset of the body. The XPath expression can be a parameterized string * using formatting specifiers as defined in - * {@link String#format(String, Object...)}. + * {@link String#formatted(Object...)}. * @param expression the XPath optionally parameterized with arguments * @param namespaces the namespaces referenced in the XPath expression * @param args arguments to parameterize the XPath expression with diff --git a/spring-test/src/main/java/org/springframework/test/web/client/match/XpathRequestMatchers.java b/spring-test/src/main/java/org/springframework/test/web/client/match/XpathRequestMatchers.java index 23ff77b4e313..8d17fc633f8a 100644 --- a/spring-test/src/main/java/org/springframework/test/web/client/match/XpathRequestMatchers.java +++ b/spring-test/src/main/java/org/springframework/test/web/client/match/XpathRequestMatchers.java @@ -55,7 +55,7 @@ public class XpathRequestMatchers { * @param expression the XPath expression * @param namespaces the XML namespaces referenced in the XPath expression, or {@code null} * @param args arguments to parameterize the XPath expression with, using the - * formatting specifiers defined in {@link String#format(String, Object...)} + * formatting specifiers defined in {@link String#formatted(Object...)} * @throws XPathExpressionException if expression compilation failed */ protected XpathRequestMatchers(String expression, @Nullable Map namespaces, Object... args) diff --git a/spring-test/src/main/java/org/springframework/test/web/servlet/result/JsonPathResultMatchers.java b/spring-test/src/main/java/org/springframework/test/web/servlet/result/JsonPathResultMatchers.java index 8e0ba72d881b..d0a91f5902ac 100644 --- a/spring-test/src/main/java/org/springframework/test/web/servlet/result/JsonPathResultMatchers.java +++ b/spring-test/src/main/java/org/springframework/test/web/servlet/result/JsonPathResultMatchers.java @@ -56,7 +56,7 @@ public class JsonPathResultMatchers { * {@link MockMvcResultMatchers#jsonPath(String, Matcher)}. * @param expression the {@link JsonPath} expression; never {@code null} or empty * @param args arguments to parameterize the {@code JsonPath} expression with, - * using formatting specifiers defined in {@link String#format(String, Object...)} + * using formatting specifiers defined in {@link String#formatted(Object...)} */ protected JsonPathResultMatchers(String expression, Object... args) { Assert.hasText(expression, "expression must not be null or empty"); diff --git a/spring-test/src/main/java/org/springframework/test/web/servlet/result/MockMvcResultHandlers.java b/spring-test/src/main/java/org/springframework/test/web/servlet/result/MockMvcResultHandlers.java index 4af0003db6c2..1bda20017967 100644 --- a/spring-test/src/main/java/org/springframework/test/web/servlet/result/MockMvcResultHandlers.java +++ b/spring-test/src/main/java/org/springframework/test/web/servlet/result/MockMvcResultHandlers.java @@ -102,14 +102,14 @@ public PrintWriterPrintingResultHandler(PrintWriter writer) { @Override public void printHeading(String heading) { writer.println(); - writer.println(String.format("%s:", heading)); + writer.println("%s:".formatted(heading)); } @Override public void printValue(String label, @Nullable Object value) { if (value != null && value.getClass().isArray()) { value = CollectionUtils.arrayToList(value); } - writer.println(String.format("%17s = %s", label, value)); + writer.println("%17s = %s".formatted(label, value)); } }); } diff --git a/spring-test/src/main/java/org/springframework/test/web/servlet/result/MockMvcResultMatchers.java b/spring-test/src/main/java/org/springframework/test/web/servlet/result/MockMvcResultMatchers.java index 601224528268..01cb780aa684 100644 --- a/spring-test/src/main/java/org/springframework/test/web/servlet/result/MockMvcResultMatchers.java +++ b/spring-test/src/main/java/org/springframework/test/web/servlet/result/MockMvcResultMatchers.java @@ -187,7 +187,7 @@ public static ContentResultMatchers content() { * to inspect a specific subset of the body. *

The JSON path expression can be a parameterized string using * formatting specifiers as defined in - * {@link String#format(String, Object...)}. + * {@link String#formatted(Object...)}. * @param expression the JSON path expression, optionally parameterized with arguments * @param args arguments to parameterize the JSON path expression with * @see #jsonPath(String, Matcher) @@ -232,7 +232,7 @@ public static ResultMatcher jsonPath(String expression, Matcher m * Access to response body assertions using an XPath expression to * inspect a specific subset of the body. *

The XPath expression can be a parameterized string using formatting - * specifiers as defined in {@link String#format(String, Object...)}. + * specifiers as defined in {@link String#formatted(Object...)}. * @param expression the XPath expression, optionally parameterized with arguments * @param args arguments to parameterize the XPath expression with */ @@ -244,7 +244,7 @@ public static XpathResultMatchers xpath(String expression, Object... args) throw * Access to response body assertions using an XPath expression to * inspect a specific subset of the body. *

The XPath expression can be a parameterized string using formatting - * specifiers as defined in {@link String#format(String, Object...)}. + * specifiers as defined in {@link String#formatted(Object...)}. * @param expression the XPath expression, optionally parameterized with arguments * @param namespaces the namespaces referenced in the XPath expression * @param args arguments to parameterize the XPath expression with diff --git a/spring-test/src/main/java/org/springframework/test/web/servlet/result/XpathResultMatchers.java b/spring-test/src/main/java/org/springframework/test/web/servlet/result/XpathResultMatchers.java index 628c555c1b4e..041047cedf9e 100644 --- a/spring-test/src/main/java/org/springframework/test/web/servlet/result/XpathResultMatchers.java +++ b/spring-test/src/main/java/org/springframework/test/web/servlet/result/XpathResultMatchers.java @@ -50,7 +50,7 @@ public class XpathResultMatchers { * @param expression the XPath expression * @param namespaces the XML namespaces referenced in the XPath expression, or {@code null} * @param args arguments to parameterize the XPath expression with using the - * formatting specifiers defined in {@link String#format(String, Object...)} + * formatting specifiers defined in {@link String#formatted(Object...)} */ protected XpathResultMatchers(String expression, @Nullable Map namespaces, Object... args) throws XPathExpressionException { diff --git a/spring-test/src/test/java/org/springframework/test/context/aot/AbstractAotTests.java b/spring-test/src/test/java/org/springframework/test/context/aot/AbstractAotTests.java index cdaf8da48286..e36eac177f66 100644 --- a/spring-test/src/test/java/org/springframework/test/context/aot/AbstractAotTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/aot/AbstractAotTests.java @@ -17,7 +17,6 @@ package org.springframework.test.context.aot; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Set; import java.util.stream.Stream; @@ -140,7 +139,7 @@ Set classpathRoots() { Path classpathRoot() { try { - return Paths.get(getClass().getProtectionDomain().getCodeSource().getLocation().toURI()); + return Path.of(getClass().getProtectionDomain().getCodeSource().getLocation().toURI()); } catch (Exception ex) { throw new RuntimeException(ex); @@ -149,7 +148,7 @@ Path classpathRoot() { Path classpathRoot(Class clazz) { try { - return Paths.get(clazz.getProtectionDomain().getCodeSource().getLocation().toURI()); + return Path.of(clazz.getProtectionDomain().getCodeSource().getLocation().toURI()); } catch (Exception ex) { throw new RuntimeException(ex); diff --git a/spring-test/src/test/java/org/springframework/test/context/aot/AotIntegrationTests.java b/spring-test/src/test/java/org/springframework/test/context/aot/AotIntegrationTests.java index 12ed85654041..b9b82fd91837 100644 --- a/spring-test/src/test/java/org/springframework/test/context/aot/AotIntegrationTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/aot/AotIntegrationTests.java @@ -18,7 +18,6 @@ import java.io.PrintWriter; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.List; import java.util.Optional; import java.util.Set; @@ -81,7 +80,7 @@ class AotIntegrationTests extends AbstractAotTests { // nested JUnit Platform launched by the CompileWithForkedClassLoaderExtension. static { try { - Path classpathRoot = Paths.get(AotIntegrationTests.class.getProtectionDomain().getCodeSource().getLocation().toURI()); + Path classpathRoot = Path.of(AotIntegrationTests.class.getProtectionDomain().getCodeSource().getLocation().toURI()); System.setProperty(CLASSPATH_ROOT, classpathRoot.toFile().getCanonicalPath()); } catch (Exception ex) { @@ -267,7 +266,7 @@ else if (source instanceof MethodSource methodSource) { private static TestClassScanner createTestClassScanner() { String classpathRoot = System.getProperty(CLASSPATH_ROOT); assertThat(classpathRoot).as(CLASSPATH_ROOT).isNotNull(); - Set classpathRoots = Set.of(Paths.get(classpathRoot)); + Set classpathRoots = Set.of(Path.of(classpathRoot)); return new TestClassScanner(classpathRoots); } diff --git a/spring-test/src/test/java/org/springframework/test/context/support/ContextLoaderUtilsContextHierarchyTests.java b/spring-test/src/test/java/org/springframework/test/context/support/ContextLoaderUtilsContextHierarchyTests.java index 879cc707386b..5c796d62d434 100644 --- a/spring-test/src/test/java/org/springframework/test/context/support/ContextLoaderUtilsContextHierarchyTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/support/ContextLoaderUtilsContextHierarchyTests.java @@ -313,8 +313,7 @@ void buildContextHierarchyMapForTestClassHierarchyWithMultiLevelContextHierarchi private void assertContextConfigEntriesAreNotUnique(Class testClass) { assertThatIllegalStateException().isThrownBy(() -> buildContextHierarchyMap(testClass)) - .withMessage(String.format( - "The @ContextConfiguration elements configured via @ContextHierarchy in test class [%s] and its superclasses must define unique contexts per hierarchy level.", testClass.getName())); + .withMessage("The @ContextConfiguration elements configured via @ContextHierarchy in test class [%s] and its superclasses must define unique contexts per hierarchy level.".formatted(testClass.getName())); } @Test diff --git a/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/JsonContentTests.java b/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/JsonContentTests.java index c2b552bf2fa0..e33556107580 100644 --- a/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/JsonContentTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/JsonContentTests.java @@ -146,7 +146,7 @@ Person getPerson(@PathVariable String firstName, @PathVariable String lastName) @PostMapping ResponseEntity savePerson(@RequestBody Person person) { - return ResponseEntity.created(URI.create(String.format("/persons/%s/%s", person.getFirstName(), person.getLastName()))).build(); + return ResponseEntity.created(URI.create("/persons/%s/%s".formatted(person.getFirstName(), person.getLastName()))).build(); } } diff --git a/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/XmlContentTests.java b/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/XmlContentTests.java index 6615821a3fcb..c42e1117c2af 100644 --- a/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/XmlContentTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/XmlContentTests.java @@ -163,7 +163,7 @@ Person getPerson(@PathVariable String name) { @PostMapping(consumes = MediaType.APPLICATION_XML_VALUE) ResponseEntity savepersons(@RequestBody Person person) { - URI location = URI.create(String.format("/persons/%s", person.getName())); + URI location = URI.create("/persons/%s".formatted(person.getName())); return ResponseEntity.created(location).build(); } } diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/client/samples/JsonContentTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/client/samples/JsonContentTests.java index efcf21d31631..f14c3c7592db 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/client/samples/JsonContentTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/client/samples/JsonContentTests.java @@ -144,7 +144,7 @@ Person getPerson(@PathVariable String firstName, @PathVariable String lastName) @PostMapping ResponseEntity savePerson(@RequestBody Person person) { - URI location = URI.create(String.format("/persons/%s/%s", person.getFirstName(), person.getLastName())); + URI location = URI.create("/persons/%s/%s".formatted(person.getFirstName(), person.getLastName())); return ResponseEntity.created(location).build(); } } diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/client/samples/XmlContentTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/client/samples/XmlContentTests.java index ee12416dc71a..19399f18106b 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/client/samples/XmlContentTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/client/samples/XmlContentTests.java @@ -190,7 +190,7 @@ Person getPerson(@PathVariable String name) { @PostMapping(consumes = MediaType.APPLICATION_XML_VALUE) ResponseEntity savepersons(@RequestBody Person person) { - URI location = URI.create(String.format("/persons/%s", person.getName())); + URI location = URI.create("/persons/%s".formatted(person.getName())); return ResponseEntity.created(location).build(); } } diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/result/XpathResultMatchersTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/result/XpathResultMatchersTests.java index 640184cd6b78..11c63339b271 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/result/XpathResultMatchersTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/result/XpathResultMatchersTests.java @@ -127,8 +127,9 @@ public void booleanValueNoMatch() { @Test public void stringEncodingDetection() throws Exception { - String content = "\n" + - "Jürgen"; + String content = """ + + Jürgen"""; byte[] bytes = content.getBytes(StandardCharsets.UTF_8); MockHttpServletResponse response = new MockHttpServletResponse(); response.addHeader("Content-Type", "application/xml"); diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/spr/FormContentTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/spr/FormContentTests.java index 1803b4da1aeb..cc876e6053e5 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/spr/FormContentTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/spr/FormContentTests.java @@ -52,7 +52,7 @@ private static class Spr15753Controller { @PutMapping("/") public String test(Data d) { - return String.format("d1:%s, d2:%s.", d.getD1(), d.getD2()); + return "d1:%s, d2:%s.".formatted(d.getD1(), d.getD2()); } } diff --git a/spring-web/spring-web.gradle b/spring-web/spring-web.gradle index 62a50956d608..a23d27933502 100644 --- a/spring-web/spring-web.gradle +++ b/spring-web/spring-web.gradle @@ -94,8 +94,7 @@ dependencies { testImplementation("org.xmlunit:xmlunit-assertj") testImplementation("org.xmlunit:xmlunit-matchers") testImplementation("tools.jackson.module:jackson-module-kotlin") - testRuntimeOnly("com.sun.xml.bind:jaxb-core") - testRuntimeOnly("com.sun.xml.bind:jaxb-impl") + testRuntimeOnly("org.glassfish.jaxb:jaxb-runtime") testRuntimeOnly("jakarta.json:jakarta.json-api") testRuntimeOnly("org.eclipse.angus:angus-mail") testRuntimeOnly("org.eclipse:yasson") diff --git a/spring-web/src/main/java/org/springframework/http/DefaultHttpStatusCode.java b/spring-web/src/main/java/org/springframework/http/DefaultHttpStatusCode.java index 64023eb19c7a..b702e420d7ce 100644 --- a/spring-web/src/main/java/org/springframework/http/DefaultHttpStatusCode.java +++ b/spring-web/src/main/java/org/springframework/http/DefaultHttpStatusCode.java @@ -16,6 +16,7 @@ package org.springframework.http; +import java.io.Serial; import java.io.Serializable; import org.jspecify.annotations.Nullable; @@ -28,7 +29,7 @@ */ final class DefaultHttpStatusCode implements HttpStatusCode, Comparable, Serializable { - private static final long serialVersionUID = 7017664779360718111L; + @Serial private static final long serialVersionUID = 7017664779360718111L; private final int value; diff --git a/spring-web/src/main/java/org/springframework/http/HttpHeaders.java b/spring-web/src/main/java/org/springframework/http/HttpHeaders.java index 581729453daf..b49f35030b60 100644 --- a/spring-web/src/main/java/org/springframework/http/HttpHeaders.java +++ b/spring-web/src/main/java/org/springframework/http/HttpHeaders.java @@ -16,6 +16,7 @@ package org.springframework.http; +import java.io.Serial; import java.io.Serializable; import java.net.InetSocketAddress; import java.net.URI; @@ -96,7 +97,7 @@ */ public class HttpHeaders implements Serializable { - private static final long serialVersionUID = -8578554704772377436L; + @Serial private static final long serialVersionUID = -8578554704772377436L; /** diff --git a/spring-web/src/main/java/org/springframework/http/HttpMethod.java b/spring-web/src/main/java/org/springframework/http/HttpMethod.java index 608d7d535a1c..159ffaa01b48 100644 --- a/spring-web/src/main/java/org/springframework/http/HttpMethod.java +++ b/spring-web/src/main/java/org/springframework/http/HttpMethod.java @@ -16,6 +16,7 @@ package org.springframework.http; +import java.io.Serial; import java.io.Serializable; import org.jspecify.annotations.Nullable; @@ -33,7 +34,7 @@ */ public final class HttpMethod implements Comparable, Serializable { - private static final long serialVersionUID = -70133475680645360L; + @Serial private static final long serialVersionUID = -70133475680645360L; /** * The HTTP method {@code GET}. diff --git a/spring-web/src/main/java/org/springframework/http/MediaType.java b/spring-web/src/main/java/org/springframework/http/MediaType.java index 0ae9fb797dcf..f283a91e1923 100644 --- a/spring-web/src/main/java/org/springframework/http/MediaType.java +++ b/spring-web/src/main/java/org/springframework/http/MediaType.java @@ -16,6 +16,7 @@ package org.springframework.http; +import java.io.Serial; import java.io.Serializable; import java.nio.charset.Charset; import java.util.ArrayList; @@ -55,7 +56,7 @@ */ public class MediaType extends MimeType implements Serializable { - private static final long serialVersionUID = 2069937152339670231L; + @Serial private static final long serialVersionUID = 2069937152339670231L; /** * Media type for "*/*", including all media ranges. diff --git a/spring-web/src/main/java/org/springframework/http/ProblemDetail.java b/spring-web/src/main/java/org/springframework/http/ProblemDetail.java index ffdfd89ad060..d761a335d517 100644 --- a/spring-web/src/main/java/org/springframework/http/ProblemDetail.java +++ b/spring-web/src/main/java/org/springframework/http/ProblemDetail.java @@ -16,6 +16,7 @@ package org.springframework.http; +import java.io.Serial; import java.io.Serializable; import java.net.URI; import java.util.LinkedHashMap; @@ -53,7 +54,7 @@ */ public class ProblemDetail implements Serializable { - private static final long serialVersionUID = 3307761915842206538L; + @Serial private static final long serialVersionUID = 3307761915842206538L; private @Nullable URI type; diff --git a/spring-web/src/main/java/org/springframework/http/ReadOnlyHttpHeaders.java b/spring-web/src/main/java/org/springframework/http/ReadOnlyHttpHeaders.java index 8eeabf1a63dd..83b55084fad9 100644 --- a/spring-web/src/main/java/org/springframework/http/ReadOnlyHttpHeaders.java +++ b/spring-web/src/main/java/org/springframework/http/ReadOnlyHttpHeaders.java @@ -16,6 +16,7 @@ package org.springframework.http; +import java.io.Serial; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.Collections; import java.util.LinkedHashSet; @@ -42,7 +43,7 @@ */ class ReadOnlyHttpHeaders extends HttpHeaders { - private static final long serialVersionUID = -8578554704772377436L; + @Serial private static final long serialVersionUID = -8578554704772377436L; private @Nullable MediaType cachedContentType; diff --git a/spring-web/src/main/java/org/springframework/web/accept/StandardApiVersionDeprecationHandler.java b/spring-web/src/main/java/org/springframework/web/accept/StandardApiVersionDeprecationHandler.java index e203e142c098..517228235d37 100644 --- a/spring-web/src/main/java/org/springframework/web/accept/StandardApiVersionDeprecationHandler.java +++ b/spring-web/src/main/java/org/springframework/web/accept/StandardApiVersionDeprecationHandler.java @@ -232,7 +232,7 @@ public VersionInfo withDeprecationDate(ZonedDateTime deprecationDate) { public VersionInfo withDeprecationLink(URI uri, MediaType mediaType) { return new VersionInfo(version(), requestPredicate(), - deprecationDate(), String.format("<%s>; rel=\"deprecation\"; type=\"%s\"", uri, mediaType), + deprecationDate(), "<%s>; rel=\"deprecation\"; type=\"%s\"".formatted(uri, mediaType), sunsetDate(), sunsetLink()); } @@ -245,7 +245,7 @@ public VersionInfo withSunsetDate(ZonedDateTime sunsetDate) { public VersionInfo withSunsetLink(URI uri, MediaType mediaType) { return new VersionInfo(version(), requestPredicate(), deprecationDate(), deprecationLink(), - sunsetDate(), String.format("<%s>; rel=\"sunset\"; type=\"%s\"", uri, mediaType)); + sunsetDate(), "<%s>; rel=\"sunset\"; type=\"%s\"".formatted(uri, mediaType)); } boolean match(Comparable requestVersion, HttpServletRequest request) { diff --git a/spring-web/src/main/java/org/springframework/web/util/InvalidUrlException.java b/spring-web/src/main/java/org/springframework/web/util/InvalidUrlException.java index aa5de96aa3cd..83881fee279b 100644 --- a/spring-web/src/main/java/org/springframework/web/util/InvalidUrlException.java +++ b/spring-web/src/main/java/org/springframework/web/util/InvalidUrlException.java @@ -16,6 +16,8 @@ package org.springframework.web.util; +import java.io.Serial; + /** * Thrown when a URL string cannot be parsed. * @@ -24,7 +26,7 @@ */ public class InvalidUrlException extends IllegalArgumentException { - private static final long serialVersionUID = 7409308391039105562L; + @Serial private static final long serialVersionUID = 7409308391039105562L; /** diff --git a/spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.java b/spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.java index 0202febd610e..9b1e6b03d111 100644 --- a/spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.java +++ b/spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.java @@ -17,6 +17,7 @@ package org.springframework.web.util; import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; import java.nio.charset.UnsupportedCharsetException; import java.util.Locale; import java.util.Map; @@ -554,7 +555,7 @@ private String decodeInternal(HttpServletRequest request, String source) { logger.debug("Could not decode request string [" + source + "] with encoding '" + enc + "': falling back to platform default encoding; exception message: " + ex.getMessage()); } - return URLDecoder.decode(source); + return URLDecoder.decode(source, StandardCharsets.UTF_8); } } diff --git a/spring-web/src/test/java/org/springframework/http/codec/ServerSentEventHttpMessageReaderTests.java b/spring-web/src/test/java/org/springframework/http/codec/ServerSentEventHttpMessageReaderTests.java index 3693bed3755d..3c2b00c23257 100644 --- a/spring-web/src/test/java/org/springframework/http/codec/ServerSentEventHttpMessageReaderTests.java +++ b/spring-web/src/test/java/org/springframework/http/codec/ServerSentEventHttpMessageReaderTests.java @@ -66,10 +66,25 @@ void canRead() { void readServerSentEvents() { MockServerHttpRequest request = MockServerHttpRequest.post("/") .body(Mono.just(stringBuffer( - "id:c42\nevent:foo\nretry:123\n:bla\n:bla bla\n:bla bla bla\ndata:bar\n\n" + - "id:c43\nevent:bar\nretry:456\ndata:baz\n\n" + - "data:\n\n" + - "data: \n\n"))); + """ + id:c42 + event:foo + retry:123 + :bla + :bla bla + :bla bla bla + data:bar + + id:c43 + event:bar + retry:456 + data:baz + + data: + + data:\s + + """))); Flux events = this.reader .read(ResolvableType.forClassWithGenerics(ServerSentEvent.class, String.class), diff --git a/spring-web/src/test/java/org/springframework/http/converter/json/Jackson2ObjectMapperBuilderTests.java b/spring-web/src/test/java/org/springframework/http/converter/json/Jackson2ObjectMapperBuilderTests.java index 83f7c82a640a..1d5c30314878 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/json/Jackson2ObjectMapperBuilderTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/json/Jackson2ObjectMapperBuilderTests.java @@ -19,7 +19,6 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Path; -import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.time.OffsetDateTime; import java.time.format.DateTimeParseException; @@ -284,7 +283,7 @@ int getY() { void wellKnownModules() throws JsonProcessingException { ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().build(); - Path file = Paths.get("foo"); + Path file = Path.of("foo"); assertThat(new String(objectMapper.writeValueAsBytes(file), StandardCharsets.UTF_8)) .endsWith("foo\""); diff --git a/spring-web/src/test/java/org/springframework/http/converter/json/JacksonJsonHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/json/JacksonJsonHttpMessageConverterTests.java index 1854381d1a90..62558c13e2fd 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/json/JacksonJsonHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/json/JacksonJsonHttpMessageConverterTests.java @@ -252,7 +252,7 @@ void readAndWriteGenerics() throws Exception { JacksonJsonHttpMessageConverter converter = new JacksonJsonHttpMessageConverter() { @Override protected JavaType getJavaType(Type type, @Nullable Class contextClass) { - if (type instanceof Class && List.class.isAssignableFrom((Class)type)) { + if (type instanceof Class class1 && List.class.isAssignableFrom(class1)) { return new ObjectMapper().getTypeFactory().constructCollectionType(ArrayList.class, MyBean.class); } else { diff --git a/spring-web/src/test/java/org/springframework/http/converter/json/MappingJackson2HttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/json/MappingJackson2HttpMessageConverterTests.java index 2d5703012789..d0737537916f 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/json/MappingJackson2HttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/json/MappingJackson2HttpMessageConverterTests.java @@ -250,7 +250,7 @@ void readAndWriteGenerics() throws Exception { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter() { @Override protected JavaType getJavaType(Type type, @Nullable Class contextClass) { - if (type instanceof Class && List.class.isAssignableFrom((Class)type)) { + if (type instanceof Class class1 && List.class.isAssignableFrom(class1)) { return new ObjectMapper().getTypeFactory().constructCollectionType(ArrayList.class, MyBean.class); } else { diff --git a/spring-web/src/test/java/org/springframework/protobuf/Msg.java b/spring-web/src/test/java/org/springframework/protobuf/Msg.java index e47b4738e7e7..c379ee97d868 100644 --- a/spring-web/src/test/java/org/springframework/protobuf/Msg.java +++ b/spring-web/src/test/java/org/springframework/protobuf/Msg.java @@ -62,8 +62,8 @@ public boolean hasFoo() { @java.lang.Override public java.lang.String getFoo() { java.lang.Object ref = foo_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; + if (ref instanceof java.lang.String string) { + return string; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; @@ -82,10 +82,10 @@ public java.lang.String getFoo() { public com.google.protobuf.ByteString getFooBytes() { java.lang.Object ref = foo_; - if (ref instanceof java.lang.String) { + if (ref instanceof java.lang.String string) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( - (java.lang.String) ref); + string); foo_ = b; return b; } else { @@ -391,8 +391,8 @@ private void buildPartial0(org.springframework.protobuf.Msg result) { @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof org.springframework.protobuf.Msg) { - return mergeFrom((org.springframework.protobuf.Msg)other); + if (other instanceof org.springframework.protobuf.Msg msg) { + return mergeFrom(msg); } else { super.mergeFrom(other); return this; @@ -497,10 +497,10 @@ public java.lang.String getFoo() { public com.google.protobuf.ByteString getFooBytes() { java.lang.Object ref = foo_; - if (ref instanceof String) { + if (ref instanceof java.lang.String string) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( - (java.lang.String) ref); + string); foo_ = b; return b; } else { diff --git a/spring-web/src/test/java/org/springframework/protobuf/OuterSample.java b/spring-web/src/test/java/org/springframework/protobuf/OuterSample.java index 26267b08e6c9..641c894365c4 100644 --- a/spring-web/src/test/java/org/springframework/protobuf/OuterSample.java +++ b/spring-web/src/test/java/org/springframework/protobuf/OuterSample.java @@ -44,10 +44,19 @@ public static void registerAllExtensions( descriptor; static { java.lang.String[] descriptorData = { - "\n\014sample.proto\",\n\003Msg\022\013\n\003foo\030\001 \001(\t\022\030\n\004bl" + - "ah\030\002 \001(\0132\n.SecondMsg\"\031\n\tSecondMsg\022\014\n\004bla" + - "h\030\001 \001(\005B-\n\034org.springframework.protobufB" + - "\013OuterSampleP\001" + """ + + sample.proto", + Msg + foo (  + bl\ + ah ( 2 + .SecondMsg" + SecondMsg + bla\ + h (B- + org.springframework.protobufB\ + OuterSampleP""" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, diff --git a/spring-web/src/test/java/org/springframework/protobuf/SecondMsg.java b/spring-web/src/test/java/org/springframework/protobuf/SecondMsg.java index 7f75718f23b9..0d95cb0625a9 100644 --- a/spring-web/src/test/java/org/springframework/protobuf/SecondMsg.java +++ b/spring-web/src/test/java/org/springframework/protobuf/SecondMsg.java @@ -302,8 +302,8 @@ private void buildPartial0(org.springframework.protobuf.SecondMsg result) { @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof org.springframework.protobuf.SecondMsg) { - return mergeFrom((org.springframework.protobuf.SecondMsg)other); + if (other instanceof org.springframework.protobuf.SecondMsg msg) { + return mergeFrom(msg); } else { super.mergeFrom(other); return this; diff --git a/spring-web/src/test/java/org/springframework/web/context/request/ServletWebRequestHttpMethodsTests.java b/spring-web/src/test/java/org/springframework/web/context/request/ServletWebRequestHttpMethodsTests.java index 787ccad785f2..7e0fabf31009 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/ServletWebRequestHttpMethodsTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/ServletWebRequestHttpMethodsTests.java @@ -177,7 +177,7 @@ void ifNoneMatchShouldNotFailForUnquotedETag(String method) { void ifNoneMatchShouldMatchPaddedETag(String method) { setUpRequest(method); String etag = "spring"; - String paddedEtag = String.format("\"%s\"", etag); + String paddedEtag = "\"%s\"".formatted(etag); servletRequest.addHeader(HttpHeaders.IF_NONE_MATCH, paddedEtag); assertThat(request.checkNotModified(etag)).isTrue(); assertNotModified(paddedEtag, null); diff --git a/spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTests.java b/spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTests.java index d38c3e73403c..beffca452161 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTests.java @@ -383,8 +383,8 @@ private static final class StubCallable implements Callable { @Override public Object call() throws Exception { - if (this.value instanceof Exception) { - throw ((Exception) this.value); + if (this.value instanceof Exception exception) { + throw exception; } return this.value; } diff --git a/spring-web/src/test/java/org/springframework/web/server/adapter/DefaultServerWebExchangeCheckNotModifiedTests.java b/spring-web/src/test/java/org/springframework/web/server/adapter/DefaultServerWebExchangeCheckNotModifiedTests.java index db6eb0fe7c37..fe4f30094b9c 100644 --- a/spring-web/src/test/java/org/springframework/web/server/adapter/DefaultServerWebExchangeCheckNotModifiedTests.java +++ b/spring-web/src/test/java/org/springframework/web/server/adapter/DefaultServerWebExchangeCheckNotModifiedTests.java @@ -144,7 +144,7 @@ void checkModifiedETag() { @Test void checkNotModifiedUnpaddedETag() { String eTag = "Foo"; - String paddedEtag = String.format("\"%s\"", eTag); + String paddedEtag = "\"%s\"".formatted(eTag); MockServerWebExchange exchange = MockServerWebExchange.from(get("/").ifNoneMatch(paddedEtag)); assertThat(exchange.checkNotModified(eTag)).isTrue(); @@ -162,7 +162,7 @@ void checkModifiedUnpaddedETag() { assertThat(exchange.checkNotModified(currentETag)).isFalse(); assertThat(exchange.getResponse().getStatusCode()).isNull(); - assertThat(exchange.getResponse().getHeaders().getETag()).isEqualTo(String.format("\"%s\"", currentETag)); + assertThat(exchange.getResponse().getHeaders().getETag()).isEqualTo("\"%s\"".formatted(currentETag)); } @Test @@ -224,7 +224,7 @@ void checkModifiedETagAndNotModifiedTimestamp() throws Exception { @Test void checkNotModifiedETagWeakStrong() { String eTag = "\"Foo\""; - String weakEtag = String.format("W/%s", eTag); + String weakEtag = "W/%s".formatted(eTag); MockServerWebExchange exchange = MockServerWebExchange.from(get("/").ifNoneMatch(eTag)); assertThat(exchange.checkNotModified(weakEtag)).isTrue(); @@ -236,7 +236,7 @@ void checkNotModifiedETagWeakStrong() { @Test void checkNotModifiedETagStrongWeak() { String eTag = "\"Foo\""; - MockServerHttpRequest request = get("/").ifNoneMatch(String.format("W/%s", eTag)).build(); + MockServerHttpRequest request = get("/").ifNoneMatch("W/%s".formatted(eTag)).build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); assertThat(exchange.checkNotModified(eTag)).isTrue(); @@ -248,7 +248,7 @@ void checkNotModifiedETagStrongWeak() { @Test void checkNotModifiedMultipleETags() { String eTag = "\"Bar\""; - String multipleETags = String.format("\"Foo\", %s", eTag); + String multipleETags = "\"Foo\", %s".formatted(eTag); MockServerWebExchange exchange = MockServerWebExchange.from(get("/").ifNoneMatch(multipleETags)); assertThat(exchange.checkNotModified(eTag)).isTrue(); diff --git a/spring-webflux/spring-webflux.gradle b/spring-webflux/spring-webflux.gradle index dad853c54300..8914467e3117 100644 --- a/spring-webflux/spring-webflux.gradle +++ b/spring-webflux/spring-webflux.gradle @@ -54,8 +54,7 @@ dependencies { testImplementation("org.eclipse.jetty:jetty-server") testImplementation("org.hibernate.validator:hibernate-validator") testImplementation("org.jetbrains.kotlinx:kotlinx-serialization-json") - testRuntimeOnly("com.sun.xml.bind:jaxb-core") - testRuntimeOnly("com.sun.xml.bind:jaxb-impl") + testRuntimeOnly("org.glassfish.jaxb:jaxb-runtime") testRuntimeOnly("com.sun.activation:jakarta.activation") testRuntimeOnly("org.glassfish:jakarta.el") testRuntimeOnly("org.jruby:jruby") diff --git a/spring-webflux/src/main/java/org/springframework/web/reactive/function/server/RequestPredicates.java b/spring-webflux/src/main/java/org/springframework/web/reactive/function/server/RequestPredicates.java index 2fd02b0a35ae..d4305fd66609 100644 --- a/spring-webflux/src/main/java/org/springframework/web/reactive/function/server/RequestPredicates.java +++ b/spring-webflux/src/main/java/org/springframework/web/reactive/function/server/RequestPredicates.java @@ -346,7 +346,7 @@ public static RequestPredicate queryParam(String name, Predicate predica private static void traceMatch(String prefix, Object desired, @Nullable Object actual, boolean match) { if (logger.isTraceEnabled()) { - logger.trace(String.format("%s \"%s\" %s against value \"%s\"", + logger.trace("%s \"%s\" %s against value \"%s\"".formatted( prefix, desired, match ? "matches" : "does not match", actual)); } } @@ -963,7 +963,7 @@ public void accept(Visitor visitor) { @Override public String toString() { - return String.format("*.%s", + return "*.%s".formatted( (this.extension != null) ? this.extension : this.extensionPredicate); @@ -1011,7 +1011,7 @@ public void accept(Visitor visitor) { @Override public String toString() { - return String.format("?%s %s", this.name, + return "?%s %s".formatted(this.name, (this.value != null) ? this.value : this.valuePredicate); @@ -1097,7 +1097,7 @@ public void changeParser(PathPatternParser parser) { @Override public String toString() { - return String.format("(%s && %s)", this.left, this.right); + return "(%s && %s)".formatted(this.left, this.right); } } @@ -1215,7 +1215,7 @@ public void changeParser(PathPatternParser parser) { @Override public String toString() { - return String.format("(%s || %s)", this.left, this.right); + return "(%s || %s)".formatted(this.left, this.right); } } diff --git a/spring-webflux/src/main/java/org/springframework/web/reactive/function/server/RouterFunctions.java b/spring-webflux/src/main/java/org/springframework/web/reactive/function/server/RouterFunctions.java index 834aeef8b5b0..28f4a15c74b2 100644 --- a/spring-webflux/src/main/java/org/springframework/web/reactive/function/server/RouterFunctions.java +++ b/spring-webflux/src/main/java/org/springframework/web/reactive/function/server/RouterFunctions.java @@ -1220,7 +1220,7 @@ public Mono> route(ServerRequest request) { if (this.predicate.test(request)) { if (logger.isTraceEnabled()) { String logPrefix = request.exchange().getLogPrefix(); - logger.trace(logPrefix + String.format("Matched %s", this.predicate)); + logger.trace(logPrefix + "Matched %s".formatted(this.predicate)); } return Mono.just(this.handlerFunction); } @@ -1256,7 +1256,7 @@ public Mono> route(ServerRequest serverRequest) { .map(nestedRequest -> { if (logger.isTraceEnabled()) { String logPrefix = serverRequest.exchange().getLogPrefix(); - logger.trace(logPrefix + String.format("Matched nested %s", this.predicate)); + logger.trace(logPrefix + "Matched nested %s".formatted(this.predicate)); } return this.routerFunction.route(nestedRequest) .doOnNext(match -> { diff --git a/spring-webflux/src/main/java/org/springframework/web/reactive/function/server/ToStringVisitor.java b/spring-webflux/src/main/java/org/springframework/web/reactive/function/server/ToStringVisitor.java index bd52b4c407bf..0221e1c3b831 100644 --- a/spring-webflux/src/main/java/org/springframework/web/reactive/function/server/ToStringVisitor.java +++ b/spring-webflux/src/main/java/org/springframework/web/reactive/function/server/ToStringVisitor.java @@ -106,22 +106,22 @@ public void path(String pattern) { @Deprecated(since = "7.0", forRemoval = true) @Override public void pathExtension(String extension) { - this.builder.append(String.format("*.%s", extension)); + this.builder.append("*.%s".formatted(extension)); } @Override public void header(String name, String value) { - this.builder.append(String.format("%s: %s", name, value)); + this.builder.append("%s: %s".formatted(name, value)); } @Override public void queryParam(String name, String value) { - this.builder.append(String.format("?%s == %s", name, value)); + this.builder.append("?%s == %s".formatted(name, value)); } @Override public void version(String version) { - this.builder.append(String.format("version: %s", version)); + this.builder.append("version: %s".formatted(version)); } @Override diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/MultipartRouterFunctionIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/MultipartRouterFunctionIntegrationTests.java index bc959ea2f542..ff3303944dd5 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/MultipartRouterFunctionIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/MultipartRouterFunctionIntegrationTests.java @@ -20,7 +20,6 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.time.Duration; import java.util.List; import java.util.Map; @@ -117,7 +116,7 @@ private void verifyTransferTo(HttpServer httpServer) throws Exception { .create(result) .consumeNextWith(location -> { try { - byte[] actualBytes = Files.readAllBytes(Paths.get(location)); + byte[] actualBytes = Files.readAllBytes(Path.of(location)); byte[] expectedBytes = FileCopyUtils.copyToByteArray(this.resource.getInputStream()); assertThat(actualBytes).isEqualTo(expectedBytes); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultServerRequestTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultServerRequestTests.java index 768e9fc2c066..bc029297f006 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultServerRequestTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultServerRequestTests.java @@ -590,7 +590,7 @@ void ifNoneMatchShouldNotMatchDifferentETag(String method) { @SafeHttpMethodsTest void ifNoneMatchShouldMatchPaddedETag(String method) { String eTag = "Foo"; - String paddedEtag = String.format("\"%s\"", eTag); + String paddedEtag = "\"%s\"".formatted(eTag); MockServerHttpRequest mockRequest = MockServerHttpRequest .method(HttpMethod.valueOf(method), "/") .ifNoneMatch(paddedEtag).build(); diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/protobuf/Msg.java b/spring-webflux/src/test/java/org/springframework/web/reactive/protobuf/Msg.java index 5c0b1b9d1d41..a6abcdd5a9bd 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/protobuf/Msg.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/protobuf/Msg.java @@ -62,8 +62,8 @@ public boolean hasFoo() { @java.lang.Override public java.lang.String getFoo() { java.lang.Object ref = foo_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; + if (ref instanceof java.lang.String string) { + return string; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; @@ -82,10 +82,10 @@ public java.lang.String getFoo() { public com.google.protobuf.ByteString getFooBytes() { java.lang.Object ref = foo_; - if (ref instanceof java.lang.String) { + if (ref instanceof java.lang.String string) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( - (java.lang.String) ref); + string); foo_ = b; return b; } else { @@ -391,8 +391,8 @@ private void buildPartial0(org.springframework.web.reactive.protobuf.Msg result) @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof org.springframework.web.reactive.protobuf.Msg) { - return mergeFrom((org.springframework.web.reactive.protobuf.Msg)other); + if (other instanceof org.springframework.web.reactive.protobuf.Msg msg) { + return mergeFrom(msg); } else { super.mergeFrom(other); return this; @@ -497,10 +497,10 @@ public java.lang.String getFoo() { public com.google.protobuf.ByteString getFooBytes() { java.lang.Object ref = foo_; - if (ref instanceof String) { + if (ref instanceof java.lang.String string) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( - (java.lang.String) ref); + string); foo_ = b; return b; } else { diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/protobuf/OuterSample.java b/spring-webflux/src/test/java/org/springframework/web/reactive/protobuf/OuterSample.java index be316c54b2e2..5d4bc6006335 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/protobuf/OuterSample.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/protobuf/OuterSample.java @@ -44,10 +44,19 @@ public static void registerAllExtensions( descriptor; static { java.lang.String[] descriptorData = { - "\n\014sample.proto\",\n\003Msg\022\013\n\003foo\030\001 \001(\t\022\030\n\004bl" + - "ah\030\002 \001(\0132\n.SecondMsg\"\031\n\tSecondMsg\022\014\n\004bla" + - "h\030\001 \001(\005B:\n)org.springframework.web.react" + - "ive.protobufB\013OuterSampleP\001" + """ + + sample.proto", + Msg + foo (  + bl\ + ah ( 2 + .SecondMsg" + SecondMsg + bla\ + h (B: + )org.springframework.web.react\ + ive.protobufB OuterSampleP""" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/protobuf/SecondMsg.java b/spring-webflux/src/test/java/org/springframework/web/reactive/protobuf/SecondMsg.java index a06b72b310fb..50c7524c0e86 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/protobuf/SecondMsg.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/protobuf/SecondMsg.java @@ -302,8 +302,8 @@ private void buildPartial0(org.springframework.web.reactive.protobuf.SecondMsg r @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof org.springframework.web.reactive.protobuf.SecondMsg) { - return mergeFrom((org.springframework.web.reactive.protobuf.SecondMsg)other); + if (other instanceof org.springframework.web.reactive.protobuf.SecondMsg msg) { + return mergeFrom(msg); } else { super.mergeFrom(other); return this; diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ContentBasedVersionStrategyTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ContentBasedVersionStrategyTests.java index af9834685173..22e2a5d36e92 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ContentBasedVersionStrategyTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ContentBasedVersionStrategyTests.java @@ -59,7 +59,7 @@ void removeVersion() { String hash = "7fbe76cdac6093784895bb4989203e5a"; String path = "font-awesome/css/font-awesome.min%s%s.css"; - assertThat(this.strategy.removeVersion(String.format(path, "-", hash), hash)).isEqualTo(String.format(path, "", "")); + assertThat(this.strategy.removeVersion(path.formatted("-", hash), hash)).isEqualTo(path.formatted("", "")); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/GzipSupport.java b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/GzipSupport.java index bbbfa3946072..491774bb4e74 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/GzipSupport.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/GzipSupport.java @@ -22,7 +22,6 @@ import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.HashSet; import java.util.Set; import java.util.zip.GZIPOutputStream; @@ -72,7 +71,7 @@ void create(String filePath) { Resource location = new ClassPathResource("test/", getClass()); Resource resource = new FileSystemResource(location.createRelative(filePath).getFile()); - Path gzFilePath = Paths.get(resource.getFile().getAbsolutePath() + ".gz"); + Path gzFilePath = Path.of(resource.getFile().getAbsolutePath() + ".gz"); Files.deleteIfExists(gzFilePath); File gzFile = Files.createFile(gzFilePath).toFile(); diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceWebHandlerTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceWebHandlerTests.java index 7aff83db6f0f..b70cfede7f3d 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceWebHandlerTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceWebHandlerTests.java @@ -17,7 +17,7 @@ package org.springframework.web.reactive.resource; import java.io.IOException; -import java.nio.file.Paths; +import java.nio.file.Path; import java.time.Duration; import java.util.Arrays; import java.util.Collections; @@ -800,7 +800,7 @@ void shouldNotServeDirectoryInJarFile() throws Exception { @Test void servesResourcesFromFileSystem() throws Exception { String packagePath = ClassUtils.classPackageAsResourcePath(getClass()); - String path = Paths.get("src/test/resources", packagePath).normalize() + "/"; + String path = Path.of("src/test/resources", packagePath).normalize() + "/"; this.handler.setLocations(List.of(new FileSystemResource(path))); this.handler.afterPropertiesSet(); diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MultipartWebClientIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MultipartWebClientIntegrationTests.java index 580f7c58d39f..2ba818a5f3d0 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MultipartWebClientIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MultipartWebClientIntegrationTests.java @@ -19,7 +19,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; @@ -176,8 +175,8 @@ void transferTo(HttpServer httpServer) throws Exception { .bodyToFlux(String.class); StepVerifier.create(result) - .consumeNextWith(filename -> verifyContents(Paths.get(filename), new ClassPathResource("foo.txt", MultipartHttpMessageReader.class))) - .consumeNextWith(filename -> verifyContents(Paths.get(filename), new ClassPathResource("logo.png", getClass()))) + .consumeNextWith(filename -> verifyContents(Path.of(filename), new ClassPathResource("foo.txt", MultipartHttpMessageReader.class))) + .consumeNextWith(filename -> verifyContents(Path.of(filename), new ClassPathResource("logo.png", getClass()))) .verifyComplete(); } diff --git a/spring-webmvc/spring-webmvc.gradle b/spring-webmvc/spring-webmvc.gradle index 760530e3c87d..4cdadc59ae63 100644 --- a/spring-webmvc/spring-webmvc.gradle +++ b/spring-webmvc/spring-webmvc.gradle @@ -74,8 +74,7 @@ dependencies { testImplementation("org.xmlunit:xmlunit-assertj") testImplementation("org.xmlunit:xmlunit-matchers") testRuntimeOnly("com.sun.activation:jakarta.activation") - testRuntimeOnly("com.sun.xml.bind:jaxb-core") - testRuntimeOnly("com.sun.xml.bind:jaxb-impl") + testRuntimeOnly("org.glassfish.jaxb:jaxb-runtime") testRuntimeOnly("org.apache.httpcomponents.client5:httpclient5") testRuntimeOnly("org.glassfish:jakarta.el") testRuntimeOnly("org.jruby:jruby") diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/function/RequestPredicates.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/function/RequestPredicates.java index 3cf40bd24ae5..9a376f690a23 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/function/RequestPredicates.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/function/RequestPredicates.java @@ -344,7 +344,7 @@ public static RequestPredicate param(String name, Predicate predicate) { private static void traceMatch(String prefix, Object desired, @Nullable Object actual, boolean match) { if (logger.isTraceEnabled()) { - logger.trace(String.format("%s \"%s\" %s against value \"%s\"", + logger.trace("%s \"%s\" %s against value \"%s\"".formatted( prefix, desired, match ? "matches" : "does not match", actual)); } } @@ -961,7 +961,7 @@ public void accept(Visitor visitor) { @Override public String toString() { - return String.format("*.%s", + return "*.%s".formatted( (this.extension != null) ? this.extension : this.extensionPredicate); @@ -1009,7 +1009,7 @@ public void accept(Visitor visitor) { @Override public String toString() { - return String.format("?%s %s", this.name, + return "?%s %s".formatted(this.name, (this.value != null) ? this.value : this.valuePredicate); @@ -1095,7 +1095,7 @@ public void changeParser(PathPatternParser parser) { @Override public String toString() { - return String.format("(%s && %s)", this.left, this.right); + return "(%s && %s)".formatted(this.left, this.right); } } @@ -1213,7 +1213,7 @@ public void changeParser(PathPatternParser parser) { @Override public String toString() { - return String.format("(%s || %s)", this.left, this.right); + return "(%s || %s)".formatted(this.left, this.right); } } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/function/RouterFunctions.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/function/RouterFunctions.java index 9c6739e91e4a..0c41dcb443e6 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/function/RouterFunctions.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/function/RouterFunctions.java @@ -1142,7 +1142,7 @@ public DefaultRouterFunction(RequestPredicate predicate, HandlerFunction hand public Optional> route(ServerRequest request) { if (this.predicate.test(request)) { if (logger.isTraceEnabled()) { - logger.trace(String.format("Predicate \"%s\" matches against \"%s\"", this.predicate, request)); + logger.trace("Predicate \"%s\" matches against \"%s\"".formatted(this.predicate, request)); } return Optional.of(this.handlerFunction); } @@ -1176,7 +1176,7 @@ public Optional> route(ServerRequest serverRequest) { return this.predicate.nest(serverRequest) .map(nestedRequest -> { if (logger.isTraceEnabled()) { - logger.trace(String.format("Nested predicate \"%s\" matches against \"%s\"", + logger.trace("Nested predicate \"%s\" matches against \"%s\"".formatted( this.predicate, serverRequest)); } Optional> result = this.routerFunction.route(nestedRequest); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/function/ToStringVisitor.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/function/ToStringVisitor.java index a0d3f9638eba..c46d9b59d5e1 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/function/ToStringVisitor.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/function/ToStringVisitor.java @@ -105,22 +105,22 @@ public void path(String pattern) { @Deprecated(since = "7.0", forRemoval = true) @Override public void pathExtension(String extension) { - this.builder.append(String.format("*.%s", extension)); + this.builder.append("*.%s".formatted(extension)); } @Override public void header(String name, String value) { - this.builder.append(String.format("%s: %s", name, value)); + this.builder.append("%s: %s".formatted(name, value)); } @Override public void param(String name, String value) { - this.builder.append(String.format("?%s == %s", name, value)); + this.builder.append("?%s == %s".formatted(name, value)); } @Override public void version(String version) { - this.builder.append(String.format("version: %s", version)); + this.builder.append("version: %s".formatted(version)); } @Override diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/HandlerMappingIntrospector.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/HandlerMappingIntrospector.java index 47d28d847e15..060772433ddc 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/HandlerMappingIntrospector.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/HandlerMappingIntrospector.java @@ -349,7 +349,7 @@ public void resetCache(ServletRequest request, @Nullable CachedResult cachedResu } private MatchableHandlerMapping createMatchableHandlerMapping(HandlerMapping mapping, HttpServletRequest request) { - if (mapping instanceof MatchableHandlerMapping) { + if (mapping instanceof MatchableHandlerMapping handlerMapping) { PathPatternMatchableHandlerMapping pathPatternMapping = this.pathPatternMappings.get(mapping); if (pathPatternMapping != null) { RequestPath requestPath = ServletRequestPathUtils.getParsedRequestPath(request); @@ -357,7 +357,7 @@ private MatchableHandlerMapping createMatchableHandlerMapping(HandlerMapping map } else { String lookupPath = (String) request.getAttribute(UrlPathHelper.PATH_ATTRIBUTE); - return new LookupPathMatchableHandlerMapping((MatchableHandlerMapping) mapping, lookupPath); + return new LookupPathMatchableHandlerMapping(handlerMapping, lookupPath); } } throw new IllegalStateException("HandlerMapping is not a MatchableHandlerMapping"); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilder.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilder.java index 708e888706cc..13959bdc9922 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilder.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilder.java @@ -583,8 +583,7 @@ private static Method getMethod(Class controllerType, final String methodName return methods.iterator().next(); } else if (methods.size() > 1) { - throw new IllegalArgumentException(String.format( - "Found two methods named '%s' accepting arguments %s in controller %s: [%s]", + throw new IllegalArgumentException("Found two methods named '%s' accepting arguments %s in controller %s: [%s]".formatted( methodName, Arrays.asList(args), controllerType.getName(), methods)); } else { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/ComplexWebApplicationContext.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/ComplexWebApplicationContext.java index e29ba91f95a8..536b63c0a297 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/ComplexWebApplicationContext.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/ComplexWebApplicationContext.java @@ -143,8 +143,9 @@ public void refresh() throws BeansException { pvs = new MutablePropertyValues(); pvs.add("order", "2"); pvs.add("exceptionMappings", - "java.lang.IllegalAccessException=failed2\n" + - "ServletRequestBindingException=failed3"); + """ + java.lang.IllegalAccessException=failed2 + ServletRequestBindingException=failed3"""); pvs.add("defaultErrorView", "failed0"); registerSingleton("exceptionResolver2", SimpleMappingExceptionResolver.class, pvs); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultServerRequestTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultServerRequestTests.java index 6de44eeef99e..34e240b057b0 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultServerRequestTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultServerRequestTests.java @@ -491,7 +491,7 @@ void checkModifiedETag(String method) { void checkNotModifiedUnpaddedETag(String method) { MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest(method, "/", true); String eTag = "Foo"; - String paddedEtag = String.format("\"%s\"", eTag); + String paddedEtag = "\"%s\"".formatted(eTag); servletRequest.addHeader(HttpHeaders.IF_NONE_MATCH, paddedEtag); DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ContentBasedVersionStrategyTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ContentBasedVersionStrategyTests.java index b0a9a4fb547a..5221b83e29bb 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ContentBasedVersionStrategyTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ContentBasedVersionStrategyTests.java @@ -60,7 +60,7 @@ void removeVersion() { String hash = "7fbe76cdac6093784895bb4989203e5a"; String file = "font-awesome/css/font-awesome.min%s%s.css"; - assertThat(this.versionStrategy.removeVersion(String.format(file, "-", hash), hash)).isEqualTo(String.format(file, "", "")); + assertThat(this.versionStrategy.removeVersion(file.formatted("-", hash), hash)).isEqualTo(file.formatted("", "")); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/GzipSupport.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/GzipSupport.java index 16e3e8062b3c..b4749fe12cd2 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/GzipSupport.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/GzipSupport.java @@ -22,7 +22,6 @@ import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.HashSet; import java.util.Set; import java.util.zip.GZIPOutputStream; @@ -72,7 +71,7 @@ void create(String filePath) { Resource location = new ClassPathResource("test/", getClass()); Resource resource = new FileSystemResource(location.createRelative(filePath).getFile()); - Path gzFilePath = Paths.get(resource.getFile().getAbsolutePath() + ".gz"); + Path gzFilePath = Path.of(resource.getFile().getAbsolutePath() + ".gz"); Files.deleteIfExists(gzFilePath); File gzFile = Files.createFile(gzFilePath).toFile(); diff --git a/spring-websocket/src/main/java/org/springframework/web/socket/CloseStatus.java b/spring-websocket/src/main/java/org/springframework/web/socket/CloseStatus.java index fa3f7dfd2100..ed813752f1fb 100644 --- a/spring-websocket/src/main/java/org/springframework/web/socket/CloseStatus.java +++ b/spring-websocket/src/main/java/org/springframework/web/socket/CloseStatus.java @@ -16,6 +16,7 @@ package org.springframework.web.socket; +import java.io.Serial; import java.io.Serializable; import java.util.Objects; @@ -36,7 +37,7 @@ */ public final class CloseStatus implements Serializable { - private static final long serialVersionUID = 5199057709285570947L; + @Serial private static final long serialVersionUID = 5199057709285570947L; /** diff --git a/spring-websocket/src/main/java/org/springframework/web/socket/handler/ConcurrentWebSocketSessionDecorator.java b/spring-websocket/src/main/java/org/springframework/web/socket/handler/ConcurrentWebSocketSessionDecorator.java index 0113f89b0bf6..598903335790 100644 --- a/spring-websocket/src/main/java/org/springframework/web/socket/handler/ConcurrentWebSocketSessionDecorator.java +++ b/spring-websocket/src/main/java/org/springframework/web/socket/handler/ConcurrentWebSocketSessionDecorator.java @@ -212,14 +212,14 @@ private void checkSessionLimits() { try { if (getTimeSinceSendStarted() > getSendTimeLimit()) { String format = "Send time %d (ms) for session '%s' exceeded the allowed limit %d"; - String reason = String.format(format, getTimeSinceSendStarted(), getId(), getSendTimeLimit()); + String reason = format.formatted(getTimeSinceSendStarted(), getId(), getSendTimeLimit()); limitExceeded(reason); } else if (getBufferSize() > getBufferSizeLimit()) { switch (this.overflowStrategy) { case TERMINATE -> { String format = "Buffer size %d bytes for session '%s' exceeds the allowed limit %d"; - String reason = String.format(format, getBufferSize(), getId(), getBufferSizeLimit()); + String reason = format.formatted(getBufferSize(), getId(), getBufferSizeLimit()); limitExceeded(reason); } case DROP -> { diff --git a/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/frame/DefaultSockJsFrameFormat.java b/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/frame/DefaultSockJsFrameFormat.java index 9e9948e26b86..05fab5f140d4 100644 --- a/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/frame/DefaultSockJsFrameFormat.java +++ b/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/frame/DefaultSockJsFrameFormat.java @@ -21,7 +21,7 @@ /** * A default implementation of * {@link org.springframework.web.socket.sockjs.frame.SockJsFrameFormat} that relies - * on {@link java.lang.String#format(String, Object...)}.. + * on {@link String#formatted(Object...)}.. * * @author Rossen Stoyanchev * @since 4.0 @@ -39,7 +39,7 @@ public DefaultSockJsFrameFormat(String format) { @Override public String format(SockJsFrame frame) { - return String.format(this.format, preProcessContent(frame.getContent())); + return this.format.formatted(preProcessContent(frame.getContent())); } protected String preProcessContent(String content) { diff --git a/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/support/AbstractSockJsService.java b/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/support/AbstractSockJsService.java index 54fc2610ae6b..75ee29dad784 100644 --- a/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/support/AbstractSockJsService.java +++ b/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/support/AbstractSockJsService.java @@ -593,8 +593,7 @@ public void handle(ServerHttpRequest request, ServerHttpResponse response) throw addNoCacheHeaders(response); if (checkOrigin(request, response)) { response.getHeaders().setContentType(new MediaType("application", "json", StandardCharsets.UTF_8)); - String content = String.format( - INFO_CONTENT, random.nextInt(), isSessionCookieNeeded(), isWebSocketEnabled()); + String content = INFO_CONTENT.formatted(random.nextInt(), isSessionCookieNeeded(), isWebSocketEnabled()); response.getBody().write(content.getBytes()); } @@ -640,7 +639,7 @@ public void handle(ServerHttpRequest request, ServerHttpResponse response) throw return; } - String content = String.format(IFRAME_CONTENT, getSockJsClientLibraryUrl()); + String content = IFRAME_CONTENT.formatted(getSockJsClientLibraryUrl()); byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8); StringBuilder builder = new StringBuilder("\"0"); DigestUtils.appendMd5DigestAsHex(contentBytes, builder); diff --git a/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/handler/HtmlFileTransportHandler.java b/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/handler/HtmlFileTransportHandler.java index 57a3be060886..949264f3425a 100644 --- a/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/handler/HtmlFileTransportHandler.java +++ b/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/handler/HtmlFileTransportHandler.java @@ -146,7 +146,7 @@ public HtmlFileStreamingSockJsSession(String sessionId, SockJsServiceConfig conf protected byte[] getPrelude(ServerHttpRequest request) { // We already validated the parameter above... String callback = getCallbackParam(request); - String html = String.format(PARTIAL_HTML_CONTENT, callback); + String html = PARTIAL_HTML_CONTENT.formatted(callback); return html.getBytes(StandardCharsets.UTF_8); } } diff --git a/spring-websocket/src/test/java/org/springframework/web/socket/handler/ConcurrentWebSocketSessionDecoratorTests.java b/spring-websocket/src/test/java/org/springframework/web/socket/handler/ConcurrentWebSocketSessionDecoratorTests.java index 85678fce779a..aa2cecd7727d 100644 --- a/spring-websocket/src/test/java/org/springframework/web/socket/handler/ConcurrentWebSocketSessionDecoratorTests.java +++ b/spring-websocket/src/test/java/org/springframework/web/socket/handler/ConcurrentWebSocketSessionDecoratorTests.java @@ -115,7 +115,7 @@ void sendBufferSizeExceeded() throws IOException, InterruptedException { sendBlockingMessage(decorator); - String msg = String.format("%1023s", "a"); + String msg = "%1023s".formatted("a"); TextMessage message = new TextMessage(msg); decorator.sendMessage(message); @@ -140,7 +140,7 @@ public void overflowStrategyDrop() throws IOException, InterruptedException { sendBlockingMessage(decorator); - String msg = String.format("%1023s", "a"); + String msg = "%1023s".formatted("a"); for (int i = 0; i < 5; i++) { TextMessage message = new TextMessage(msg);