From 3438c47744097a964966f01314d473966bd54ee5 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Tue, 8 Nov 2022 11:33:57 +0100 Subject: [PATCH] Polishing --- ...BeanFactoryAwareAspectInstanceFactory.java | 4 +- .../aop/framework/AdvisedSupport.java | 6 +- .../aop/framework/ProxyCreatorSupport.java | 4 +- .../aop/support/MethodMatchers.java | 6 +- .../BeanFactoryRefreshableTargetSource.java | 4 +- .../org/springframework/beans/BeanUtils.java | 2 +- .../beans/factory/InjectionPoint.java | 4 +- .../aot/AutowiredArgumentsCodeGenerator.java | 13 +-- .../aot/AutowiredFieldValueResolver.java | 4 +- .../aot/AutowiredMethodArgumentsResolver.java | 9 +- .../factory/aot/BeanInstanceSupplier.java | 102 ++++++++---------- ...eanRegistrationCodeFragmentsDecorator.java | 12 +-- .../factory/support/InstanceSupplier.java | 13 ++- ...AutowiredMethodArgumentsResolverTests.java | 9 +- .../support/InstanceSupplierTests.java | 2 +- .../org/springframework/core/Constants.java | 4 +- .../org/springframework/core/Conventions.java | 7 +- .../core/ReactiveTypeDescriptor.java | 4 +- .../core/io/buffer/DefaultDataBuffer.java | 2 +- .../core/io/buffer/Netty5DataBuffer.java | 9 +- .../AbstractMethodMessageHandler.java | 4 +- .../reactive/ArgumentResolverConfigurer.java | 10 +- .../rsocket/DefaultRSocketRequester.java | 8 +- .../messaging/rsocket/MetadataEncoder.java | 16 +-- .../jpa/support/InjectionCodeGenerator.java | 28 ++--- .../AbstractRoutingConnectionFactory.java | 2 +- .../reactive/MockServerHttpRequest.java | 3 +- .../mock/web/MockHttpServletRequest.java | 51 ++++----- .../mock/web/MockHttpServletResponse.java | 2 +- .../test/annotation/ProfileValueUtils.java | 4 +- .../web/reactive/server/WiretapConnector.java | 6 +- .../DefaultPartHttpMessageReader.java | 2 +- .../server/ServletServerHttpResponse.java | 4 +- .../servlet/MockHttpServletRequest.java | 51 ++++----- .../web/reactive/function/BodyInserters.java | 5 +- .../client/DefaultClientResponseBuilder.java | 2 +- 36 files changed, 190 insertions(+), 228 deletions(-) diff --git a/spring-aop/src/main/java/org/springframework/aop/config/SimpleBeanFactoryAwareAspectInstanceFactory.java b/spring-aop/src/main/java/org/springframework/aop/config/SimpleBeanFactoryAwareAspectInstanceFactory.java index 3d89993cadd..34a180a2c84 100644 --- a/spring-aop/src/main/java/org/springframework/aop/config/SimpleBeanFactoryAwareAspectInstanceFactory.java +++ b/spring-aop/src/main/java/org/springframework/aop/config/SimpleBeanFactoryAwareAspectInstanceFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,7 +58,7 @@ public class SimpleBeanFactoryAwareAspectInstanceFactory implements AspectInstan /** - * Look up the aspect bean from the {@link BeanFactory} and returns it. + * Look up the aspect bean from the {@link BeanFactory} and return it. * @see #setAspectBeanName */ @Override 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 3862d464086..b6e192e7d35 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -334,8 +334,8 @@ public class AdvisedSupport extends ProxyConfig implements Advised { } if (!CollectionUtils.isEmpty(advisors)) { for (Advisor advisor : advisors) { - if (advisor instanceof IntroductionAdvisor) { - validateIntroductionAdvisor((IntroductionAdvisor) advisor); + if (advisor instanceof IntroductionAdvisor introductionAdvisor) { + validateIntroductionAdvisor(introductionAdvisor); } Assert.notNull(advisor, "Advisor must not be null"); this.advisors.add(advisor); diff --git a/spring-aop/src/main/java/org/springframework/aop/framework/ProxyCreatorSupport.java b/spring-aop/src/main/java/org/springframework/aop/framework/ProxyCreatorSupport.java index 9fa04a33e92..096294321f8 100644 --- a/spring-aop/src/main/java/org/springframework/aop/framework/ProxyCreatorSupport.java +++ b/spring-aop/src/main/java/org/springframework/aop/framework/ProxyCreatorSupport.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -86,7 +86,7 @@ public class ProxyCreatorSupport extends AdvisedSupport { /** * Remove the given AdvisedSupportListener from this proxy configuration. - * @param listener the listener to deregister + * @param listener the listener to remove */ public void removeListener(AdvisedSupportListener listener) { Assert.notNull(listener, "AdvisedSupportListener must not be null"); diff --git a/spring-aop/src/main/java/org/springframework/aop/support/MethodMatchers.java b/spring-aop/src/main/java/org/springframework/aop/support/MethodMatchers.java index 416697ef245..19bf5adbb07 100644 --- a/spring-aop/src/main/java/org/springframework/aop/support/MethodMatchers.java +++ b/spring-aop/src/main/java/org/springframework/aop/support/MethodMatchers.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -94,8 +94,8 @@ public abstract class MethodMatchers { */ public static boolean matches(MethodMatcher mm, Method method, Class targetClass, boolean hasIntroductions) { Assert.notNull(mm, "MethodMatcher must not be null"); - return (mm instanceof IntroductionAwareMethodMatcher ? - ((IntroductionAwareMethodMatcher) mm).matches(method, targetClass, hasIntroductions) : + return (mm instanceof IntroductionAwareMethodMatcher iamm ? + iamm.matches(method, targetClass, hasIntroductions) : mm.matches(method, targetClass)); } diff --git a/spring-aop/src/main/java/org/springframework/aop/target/dynamic/BeanFactoryRefreshableTargetSource.java b/spring-aop/src/main/java/org/springframework/aop/target/dynamic/BeanFactoryRefreshableTargetSource.java index 66f84a1c986..0d5988f6b52 100644 --- a/spring-aop/src/main/java/org/springframework/aop/target/dynamic/BeanFactoryRefreshableTargetSource.java +++ b/spring-aop/src/main/java/org/springframework/aop/target/dynamic/BeanFactoryRefreshableTargetSource.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,7 +63,7 @@ public class BeanFactoryRefreshableTargetSource extends AbstractRefreshableTarge */ @Override protected final Object freshTarget() { - return this.obtainFreshBean(this.beanFactory, this.beanName); + return obtainFreshBean(this.beanFactory, this.beanName); } /** diff --git a/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java b/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java index c306b6b899b..e71fc723b62 100644 --- a/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java +++ b/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java @@ -882,7 +882,7 @@ public abstract class BeanUtils { List parameters = kotlinConstructor.getParameters(); Assert.isTrue(args.length <= parameters.size(), - "Number of provided arguments should be less of equals than number of constructor parameters"); + "Number of provided arguments must be less than or equal to the number of constructor parameters"); if (parameters.isEmpty()) { return kotlinConstructor.call(); } diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/InjectionPoint.java b/spring-beans/src/main/java/org/springframework/beans/factory/InjectionPoint.java index 13e765893dc..eed896e1b4f 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/InjectionPoint.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/InjectionPoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -112,7 +112,7 @@ public class InjectionPoint { * @since 5.0 */ protected final MethodParameter obtainMethodParameter() { - Assert.state(this.methodParameter != null, "Neither Field nor MethodParameter"); + Assert.state(this.methodParameter != null, "MethodParameter is not available"); return this.methodParameter; } diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/aot/AutowiredArgumentsCodeGenerator.java b/spring-beans/src/main/java/org/springframework/beans/factory/aot/AutowiredArgumentsCodeGenerator.java index ab6b6a85a2e..8a8f152cd7c 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/aot/AutowiredArgumentsCodeGenerator.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/aot/AutowiredArgumentsCodeGenerator.java @@ -28,14 +28,11 @@ import org.springframework.util.ReflectionUtils; /** * Code generator to apply {@link AutowiredArguments}. - *

- * Generates code in the form:

{@code
- * args.get(0), args.get(1)
- * }
or
{@code
- * args.get(0, String.class), args.get(1, Integer.class)
- * }
- *

- * The simpler form is only used if the target method or constructor is + * + *

Generates code in the form: {@code args.get(0), args.get(1)} or + * {@code args.get(0, String.class), args.get(1, Integer.class)} + * + *

The simpler form is only used if the target method or constructor is * unambiguous. * * @author Phillip Webb diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/aot/AutowiredFieldValueResolver.java b/spring-beans/src/main/java/org/springframework/beans/factory/aot/AutowiredFieldValueResolver.java index cd329aa9f13..8237ccab4ed 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/aot/AutowiredFieldValueResolver.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/aot/AutowiredFieldValueResolver.java @@ -39,8 +39,8 @@ import org.springframework.util.function.ThrowingConsumer; * AOT-processed applications as a targeted alternative to the * {@link org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor * AutowiredAnnotationBeanPostProcessor}. - *

- * When resolving arguments in a native image, the {@link Field} being used must + * + *

When resolving arguments in a native image, the {@link Field} being used must * be marked with an {@link ExecutableMode#INTROSPECT introspection} hint so * that field annotations can be read. Full {@link ExecutableMode#INVOKE * invocation} hints are only required if the diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/aot/AutowiredMethodArgumentsResolver.java b/spring-beans/src/main/java/org/springframework/beans/factory/aot/AutowiredMethodArgumentsResolver.java index dea4d192267..7b878e6fc8f 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/aot/AutowiredMethodArgumentsResolver.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/aot/AutowiredMethodArgumentsResolver.java @@ -42,8 +42,8 @@ import org.springframework.util.function.ThrowingConsumer; * AOT-processed applications as a targeted alternative to the * {@link org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor * AutowiredAnnotationBeanPostProcessor}. - *

- * When resolving arguments in a native image, the {@link Method} being used + * + *

When resolving arguments in a native image, the {@link Method} being used * must be marked with an {@link ExecutableMode#INTROSPECT introspection} hint * so that field annotations can be read. Full {@link ExecutableMode#INVOKE * invocation} hints are only required if the @@ -205,9 +205,8 @@ public final class AutowiredMethodArgumentsResolver extends AutowiredElementReso private Method getMethod(RegisteredBean registeredBean) { Method method = ReflectionUtils.findMethod(registeredBean.getBeanClass(), this.methodName, this.parameterTypes); - Assert.notNull(method, - () -> String.format( - "Method '%s' with parameter types [%s] declared on %s", + Assert.notNull(method, () -> + "Method '%s' with parameter types [%s] declared on %s could not be found.".formatted( this.methodName, toCommaSeparatedNames(this.parameterTypes), registeredBean.getBeanClass().getName())); return method; diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanInstanceSupplier.java b/spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanInstanceSupplier.java index dd4d4867a3d..939f753bae7 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanInstanceSupplier.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanInstanceSupplier.java @@ -61,8 +61,8 @@ import org.springframework.util.function.ThrowingSupplier; * handles resolution of {@link AutowiredArguments} if necessary. Typically used * in AOT-processed applications as a targeted alternative to the reflection * based injection. - *

- * If no {@code generator} is provided, reflection is used to instantiate the + * + *

If no {@code generator} is provided, reflection is used to instantiate the * bean instance, and full {@link ExecutableMode#INVOKE invocation} hints are * contributed. Multiple generator callback styles are supported: *

* Generator callbacks handle checked exceptions so that the caller does not - * have to deal with it. + * have to deal with them. * * @author Phillip Webb * @author Stephane Nicoll @@ -113,10 +113,8 @@ public final class BeanInstanceSupplier extends AutowiredElementResolver impl Class... parameterTypes) { Assert.notNull(parameterTypes, "'parameterTypes' must not be null"); - Assert.noNullElements(parameterTypes, - "'parameterTypes' must not contain null elements"); - return new BeanInstanceSupplier<>( - new ConstructorLookup(parameterTypes), null, null); + Assert.noNullElements(parameterTypes, "'parameterTypes' must not contain null elements"); + return new BeanInstanceSupplier<>(new ConstructorLookup(parameterTypes), null, null); } /** @@ -134,8 +132,7 @@ public final class BeanInstanceSupplier extends AutowiredElementResolver impl Assert.notNull(declaringClass, "'declaringClass' must not be null"); Assert.hasText(methodName, "'methodName' must not be empty"); Assert.notNull(parameterTypes, "'parameterTypes' must not be null"); - Assert.noNullElements(parameterTypes, - "'parameterTypes' must not contain null elements"); + Assert.noNullElements(parameterTypes, "'parameterTypes' must not contain null elements"); return new BeanInstanceSupplier<>( new FactoryMethodLookup(declaringClass, methodName, parameterTypes), null, null); @@ -172,8 +169,8 @@ public final class BeanInstanceSupplier extends AutowiredElementResolver impl public BeanInstanceSupplier withGenerator( ThrowingFunction generator) { Assert.notNull(generator, "'generator' must not be null"); - return new BeanInstanceSupplier<>(this.lookup, (registeredBean, args) -> - generator.apply(registeredBean), this.shortcuts); + return new BeanInstanceSupplier<>(this.lookup, + (registeredBean, args) -> generator.apply(registeredBean), this.shortcuts); } /** @@ -186,8 +183,8 @@ public final class BeanInstanceSupplier extends AutowiredElementResolver impl */ public BeanInstanceSupplier withGenerator(ThrowingSupplier generator) { Assert.notNull(generator, "'generator' must not be null"); - return new BeanInstanceSupplier<>(this.lookup, (registeredBean, args) -> - generator.get(), this.shortcuts); + return new BeanInstanceSupplier<>(this.lookup, + (registeredBean, args) -> generator.get(), this.shortcuts); } /** @@ -208,11 +205,10 @@ public final class BeanInstanceSupplier extends AutowiredElementResolver impl Executable executable = this.lookup.get(registeredBean); AutowiredArguments arguments = resolveArguments(registeredBean, executable); if (this.generator != null) { - return invokeBeanSupplier(executable, () -> - this.generator.apply(registeredBean, arguments)); + return invokeBeanSupplier(executable, () -> this.generator.apply(registeredBean, arguments)); } - return invokeBeanSupplier(executable, () -> - instantiate(registeredBean.getBeanFactory(), executable, arguments.toArray())); + return invokeBeanSupplier(executable, + () -> instantiate(registeredBean.getBeanFactory(), executable, arguments.toArray())); } private T invokeBeanSupplier(Executable executable, ThrowingSupplier beanSupplier) { @@ -247,19 +243,15 @@ public final class BeanInstanceSupplier extends AutowiredElementResolver impl return resolveArguments(registeredBean, this.lookup.get(registeredBean)); } - private AutowiredArguments resolveArguments(RegisteredBean registeredBean, - Executable executable) { - - Assert.isInstanceOf(AbstractAutowireCapableBeanFactory.class, - registeredBean.getBeanFactory()); + private AutowiredArguments resolveArguments(RegisteredBean registeredBean,Executable executable) { + Assert.isInstanceOf(AbstractAutowireCapableBeanFactory.class, registeredBean.getBeanFactory()); String beanName = registeredBean.getBeanName(); Class beanClass = registeredBean.getBeanClass(); - AbstractAutowireCapableBeanFactory beanFactory = (AbstractAutowireCapableBeanFactory) registeredBean - .getBeanFactory(); - RootBeanDefinition mergedBeanDefinition = registeredBean - .getMergedBeanDefinition(); - int startIndex = (executable instanceof Constructor constructor - && ClassUtils.isInnerClass(constructor.getDeclaringClass())) ? 1 : 0; + AbstractAutowireCapableBeanFactory beanFactory = + (AbstractAutowireCapableBeanFactory) registeredBean.getBeanFactory(); + RootBeanDefinition mergedBeanDefinition = registeredBean.getMergedBeanDefinition(); + int startIndex = (executable instanceof Constructor constructor && + ClassUtils.isInnerClass(constructor.getDeclaringClass())) ? 1 : 0; int parameterCount = executable.getParameterCount(); Object[] resolved = new Object[parameterCount - startIndex]; Assert.isTrue(this.shortcuts == null || this.shortcuts.length == resolved.length, @@ -269,10 +261,8 @@ public final class BeanInstanceSupplier extends AutowiredElementResolver impl beanName, mergedBeanDefinition); for (int i = startIndex; i < parameterCount; i++) { MethodParameter parameter = getMethodParameter(executable, i); - DependencyDescriptor dependencyDescriptor = new DependencyDescriptor( - parameter, true); - String shortcut = (this.shortcuts != null) ? this.shortcuts[i - startIndex] - : null; + DependencyDescriptor dependencyDescriptor = new DependencyDescriptor(parameter, true); + String shortcut = (this.shortcuts != null) ? this.shortcuts[i - startIndex] : null; if (shortcut != null) { dependencyDescriptor = new ShortcutDependencyDescriptor( dependencyDescriptor, shortcut, beanClass); @@ -303,13 +293,10 @@ public final class BeanInstanceSupplier extends AutowiredElementResolver impl ConstructorArgumentValues resolved = new ConstructorArgumentValues(); if (mergedBeanDefinition.hasConstructorArgumentValues()) { BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver( - beanFactory, beanName, mergedBeanDefinition, - beanFactory.getTypeConverter()); - ConstructorArgumentValues values = mergedBeanDefinition - .getConstructorArgumentValues(); + beanFactory, beanName, mergedBeanDefinition, beanFactory.getTypeConverter()); + ConstructorArgumentValues values = mergedBeanDefinition.getConstructorArgumentValues(); values.getIndexedArgumentValues().forEach((index, valueHolder) -> { - ValueHolder resolvedValue = resolveArgumentValue(valueResolver, - valueHolder); + ValueHolder resolvedValue = resolveArgumentValue(valueResolver, valueHolder); resolved.addIndexedArgumentValue(index, resolvedValue); }); } @@ -333,15 +320,14 @@ public final class BeanInstanceSupplier extends AutowiredElementResolver impl @Nullable private Object resolveArgument(AbstractAutowireCapableBeanFactory beanFactory, String beanName, Set autowiredBeans, MethodParameter parameter, - DependencyDescriptor dependencyDescriptor, - @Nullable ValueHolder argumentValue) { + DependencyDescriptor dependencyDescriptor, @Nullable ValueHolder argumentValue) { TypeConverter typeConverter = beanFactory.getTypeConverter(); Class parameterType = parameter.getParameterType(); if (argumentValue != null) { - return (!argumentValue.isConverted()) ? typeConverter - .convertIfNecessary(argumentValue.getValue(), parameterType) - : argumentValue.getConvertedValue(); + return (!argumentValue.isConverted()) ? + typeConverter.convertIfNecessary(argumentValue.getValue(), parameterType) : + argumentValue.getConvertedValue(); } try { try { @@ -387,9 +373,7 @@ public final class BeanInstanceSupplier extends AutowiredElementResolver impl "Unsupported executable " + executable.getClass().getName()); } - private Object instantiate(Constructor constructor, Object[] arguments) - throws Exception { - + private Object instantiate(Constructor constructor, Object[] arguments) throws Exception { Class declaringClass = constructor.getDeclaringClass(); if (ClassUtils.isInnerClass(declaringClass)) { Object enclosingInstance = createInstance(declaringClass.getEnclosingClass()); @@ -428,6 +412,10 @@ public final class BeanInstanceSupplier extends AutowiredElementResolver impl } + private static String toCommaSeparatedNames(Class... parameterTypes) { + return Arrays.stream(parameterTypes).map(Class::getName).collect(Collectors.joining(", ")); + } + /** * Performs lookup of the {@link Executable}. */ @@ -435,11 +423,6 @@ public final class BeanInstanceSupplier extends AutowiredElementResolver impl abstract Executable get(RegisteredBean registeredBean); - final String toCommaSeparatedNames(Class... parameterTypes) { - return Arrays.stream(parameterTypes).map(Class::getName) - .collect(Collectors.joining(", ")); - } - } @@ -460,20 +443,20 @@ public final class BeanInstanceSupplier extends AutowiredElementResolver impl public Executable get(RegisteredBean registeredBean) { Class beanClass = registeredBean.getBeanClass(); try { - Class[] actualParameterTypes = (!ClassUtils.isInnerClass(beanClass)) - ? this.parameterTypes : ObjectUtils.addObjectToArray( - this.parameterTypes, beanClass.getEnclosingClass(), 0); + Class[] actualParameterTypes = (!ClassUtils.isInnerClass(beanClass)) ? + this.parameterTypes : ObjectUtils.addObjectToArray( + this.parameterTypes, beanClass.getEnclosingClass(), 0); return beanClass.getDeclaredConstructor(actualParameterTypes); } catch (NoSuchMethodException ex) { - throw new IllegalArgumentException(String.format( - "%s cannot be found on %s", this, beanClass.getName()), ex); + throw new IllegalArgumentException( + "%s cannot be found on %s".formatted(this, beanClass.getName()), ex); } } @Override public String toString() { - return String.format("Constructor with parameter types [%s]", + return "Constructor with parameter types [%s]".formatted( toCommaSeparatedNames(this.parameterTypes)); } @@ -508,14 +491,13 @@ public final class BeanInstanceSupplier extends AutowiredElementResolver impl Method get() { Method method = ReflectionUtils.findMethod(this.declaringClass, this.methodName, this.parameterTypes); - Assert.notNull(method, () -> String.format("%s cannot be found", this)); + Assert.notNull(method, () -> "%s cannot be found".formatted(this)); return method; } @Override public String toString() { - return String.format( - "Factory method '%s' with parameter types [%s] declared on %s", + return "Factory method '%s' with parameter types [%s] declared on %s".formatted( this.methodName, toCommaSeparatedNames(this.parameterTypes), this.declaringClass); } diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanRegistrationCodeFragmentsDecorator.java b/spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanRegistrationCodeFragmentsDecorator.java index 8351f9ce4ba..69cae124b8f 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanRegistrationCodeFragmentsDecorator.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanRegistrationCodeFragmentsDecorator.java @@ -33,7 +33,7 @@ import org.springframework.util.Assert; /** * A {@link BeanRegistrationCodeFragments} decorator implementation. Typically * used when part of the default code fragments have to customized, by extending - * this class and use it as part of + * this class and using it as part of * {@link BeanRegistrationAotContribution#withCustomCodeFragments(UnaryOperator)}. * * @author Phillip Webb @@ -42,7 +42,6 @@ import org.springframework.util.Assert; */ public class BeanRegistrationCodeFragmentsDecorator implements BeanRegistrationCodeFragments { - private final BeanRegistrationCodeFragments delegate; @@ -52,9 +51,7 @@ public class BeanRegistrationCodeFragmentsDecorator implements BeanRegistrationC } @Override - public ClassName getTarget(RegisteredBean registeredBean, - Executable constructorOrFactoryMethod) { - + public ClassName getTarget(RegisteredBean registeredBean, Executable constructorOrFactoryMethod) { return this.delegate.getTarget(registeredBean, constructorOrFactoryMethod); } @@ -64,7 +61,6 @@ public class BeanRegistrationCodeFragmentsDecorator implements BeanRegistrationC return this.delegate.generateNewBeanDefinitionCode(generationContext, beanType, beanRegistrationCode); - } @Override @@ -75,7 +71,6 @@ public class BeanRegistrationCodeFragmentsDecorator implements BeanRegistrationC return this.delegate.generateSetBeanDefinitionPropertiesCode( generationContext, beanRegistrationCode, beanDefinition, attributeFilter); - } @Override @@ -101,8 +96,7 @@ public class BeanRegistrationCodeFragmentsDecorator implements BeanRegistrationC public CodeBlock generateReturnCode(GenerationContext generationContext, BeanRegistrationCode beanRegistrationCode) { - return this.delegate.generateReturnCode(generationContext, - beanRegistrationCode); + return this.delegate.generateReturnCode(generationContext, beanRegistrationCode); } } diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/support/InstanceSupplier.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/InstanceSupplier.java index cd41026d6c7..4938c0e4155 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/support/InstanceSupplier.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/support/InstanceSupplier.java @@ -45,7 +45,7 @@ public interface InstanceSupplier extends ThrowingSupplier { } /** - * Gets the supplied instance. + * Get the supplied instance. * @param registeredBean the registered bean requesting the instance * @return the supplied instance * @throws Exception on error @@ -55,7 +55,7 @@ public interface InstanceSupplier extends ThrowingSupplier { /** * Return the factory method that this supplier uses to create the * instance, or {@code null} if it is not known or this supplier uses - * another mean. + * another means. * @return the factory method used to create the instance, or {@code null} */ @Nullable @@ -65,7 +65,7 @@ public interface InstanceSupplier extends ThrowingSupplier { /** * Return a composed instance supplier that first obtains the instance from - * this supplier, and then applied the {@code after} function to obtain the + * this supplier and then applies the {@code after} function to obtain the * result. * @param the type of output of the {@code after} function, and of the * composed function @@ -74,7 +74,7 @@ public interface InstanceSupplier extends ThrowingSupplier { */ default InstanceSupplier andThen( ThrowingBiFunction after) { - Assert.notNull(after, "After must not be null"); + Assert.notNull(after, "'after' function must not be null"); return new InstanceSupplier() { @Override @@ -135,10 +135,9 @@ public interface InstanceSupplier extends ThrowingSupplier { } /** - * Lambda friendly method that can be used to create a + * Lambda friendly method that can be used to create an * {@link InstanceSupplier} and add post processors in a single call. For - * example: {@code - * InstanceSupplier.of(registeredBean -> ...).andThen(...)}. + * example: {@code InstanceSupplier.of(registeredBean -> ...).andThen(...)}. * @param the type of instance supplied by this supplier * @param instanceSupplier the source instance supplier * @return a new {@link InstanceSupplier} diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/aot/AutowiredMethodArgumentsResolverTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/aot/AutowiredMethodArgumentsResolverTests.java index e1ec79c3546..857592f4323 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/aot/AutowiredMethodArgumentsResolverTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/aot/AutowiredMethodArgumentsResolverTests.java @@ -74,12 +74,11 @@ class AutowiredMethodArgumentsResolverTests { @Test void resolveWhenMethodIsMissingThrowsException() { RegisteredBean registeredBean = registerTestBean(this.beanFactory); + AutowiredMethodArgumentsResolver resolver = AutowiredMethodArgumentsResolver.forMethod("missing", InputStream.class); assertThatIllegalArgumentException() - .isThrownBy(() -> AutowiredMethodArgumentsResolver - .forMethod("missing", InputStream.class).resolve(registeredBean)) - .withMessage( - "Method 'missing' with parameter types [java.io.InputStream] declared on " - + TestBean.class.getName()); + .isThrownBy(() -> resolver.resolve(registeredBean)) + .withMessage("Method 'missing' with parameter types [java.io.InputStream] declared on %s could not be found.", + TestBean.class.getName()); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/InstanceSupplierTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/InstanceSupplierTests.java index 5cb43d26199..c66a897b3ba 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/InstanceSupplierTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/InstanceSupplierTests.java @@ -61,7 +61,7 @@ class InstanceSupplierTests { InstanceSupplier supplier = registeredBean -> "test"; ThrowingBiFunction after = null; assertThatIllegalArgumentException().isThrownBy(() -> supplier.andThen(after)) - .withMessage("After must not be null"); + .withMessage("'after' function must not be null"); } @Test diff --git a/spring-core/src/main/java/org/springframework/core/Constants.java b/spring-core/src/main/java/org/springframework/core/Constants.java index f94b1842bb6..9cb3e7af715 100644 --- a/spring-core/src/main/java/org/springframework/core/Constants.java +++ b/spring-core/src/main/java/org/springframework/core/Constants.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -132,7 +132,7 @@ public class Constants { /** * Parse the given String (upper or lower case accepted) and return * the appropriate value if it's the name of a constant field in the - * class that we're analysing. + * class that we're analyzing. * @param code the name of the field (never {@code null}) * @return the Object value * @throws ConstantException if there's no such field diff --git a/spring-core/src/main/java/org/springframework/core/Conventions.java b/spring-core/src/main/java/org/springframework/core/Conventions.java index be3abc598a9..7eac92ca0d1 100644 --- a/spring-core/src/main/java/org/springframework/core/Conventions.java +++ b/spring-core/src/main/java/org/springframework/core/Conventions.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -169,10 +169,7 @@ public final class Conventions { Assert.notNull(method, "Method must not be null"); if (Object.class == resolvedType) { - if (value == null) { - throw new IllegalArgumentException( - "Cannot generate variable name for an Object return type with null value"); - } + Assert.notNull(value, "Cannot generate variable name for an Object return type with null value"); return getVariableName(value); } diff --git a/spring-core/src/main/java/org/springframework/core/ReactiveTypeDescriptor.java b/spring-core/src/main/java/org/springframework/core/ReactiveTypeDescriptor.java index f1d76c330e2..fe56c512b1c 100644 --- a/spring-core/src/main/java/org/springframework/core/ReactiveTypeDescriptor.java +++ b/spring-core/src/main/java/org/springframework/core/ReactiveTypeDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -94,7 +94,7 @@ public final class ReactiveTypeDescriptor { /** * Return an empty-value instance for the underlying reactive or async type. - * Use of this type implies {@link #supportsEmpty()} is {@code true}. + *

Use of this type implies {@link #supportsEmpty()} is {@code true}. */ public Object getEmptyValue() { Assert.state(this.emptyValueSupplier != null, "Empty values not supported"); 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 2d3645cc86f..23bdbd0cf8e 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 @@ -425,7 +425,7 @@ public class DefaultDataBuffer implements DataBuffer { * @see io.netty.buffer.AbstractByteBufAllocator#calculateNewCapacity(int, int) */ private int calculateCapacity(int neededCapacity) { - Assert.isTrue(neededCapacity >= 0, "'neededCapacity' must >= 0"); + Assert.isTrue(neededCapacity >= 0, "'neededCapacity' must be >= 0"); if (neededCapacity == CAPACITY_THRESHOLD) { return CAPACITY_THRESHOLD; diff --git a/spring-core/src/main/java/org/springframework/core/io/buffer/Netty5DataBuffer.java b/spring-core/src/main/java/org/springframework/core/io/buffer/Netty5DataBuffer.java index 64b78042557..6d79ef16674 100644 --- a/spring-core/src/main/java/org/springframework/core/io/buffer/Netty5DataBuffer.java +++ b/spring-core/src/main/java/org/springframework/core/io/buffer/Netty5DataBuffer.java @@ -28,7 +28,6 @@ import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; - /** * Implementation of the {@code DataBuffer} interface that wraps a Netty 5 * {@link Buffer}. Typically constructed with {@link Netty5DataBufferFactory}. @@ -37,8 +36,7 @@ import org.springframework.util.ObjectUtils; * @author Arjen Poutsma * @since 6.0 */ -public final class Netty5DataBuffer implements CloseableDataBuffer, - TouchableDataBuffer { +public final class Netty5DataBuffer implements CloseableDataBuffer, TouchableDataBuffer { private final Buffer buffer; @@ -51,7 +49,7 @@ public final class Netty5DataBuffer implements CloseableDataBuffer, */ Netty5DataBuffer(Buffer buffer, Netty5DataBufferFactory dataBufferFactory) { Assert.notNull(buffer, "Buffer must not be null"); - Assert.notNull(dataBufferFactory, "NettyDataBufferFactory must not be null"); + Assert.notNull(dataBufferFactory, "Netty5DataBufferFactory must not be null"); this.buffer = buffer; this.dataBufferFactory = dataBufferFactory; } @@ -150,7 +148,7 @@ public final class Netty5DataBuffer implements CloseableDataBuffer, @Override public DataBuffer ensureWritable(int capacity) { - Assert.isTrue(capacity >= 0, "Capacity must be larger than 0"); + Assert.isTrue(capacity >= 0, "Capacity must be >= 0"); this.buffer.ensureWritable(capacity); return this; } @@ -328,6 +326,7 @@ public final class Netty5DataBuffer implements CloseableDataBuffer, } + @Override public boolean equals(@Nullable Object other) { return (this == other || (other instanceof Netty5DataBuffer dataBuffer && this.buffer.equals(dataBuffer.buffer))); diff --git a/spring-messaging/src/main/java/org/springframework/messaging/handler/invocation/reactive/AbstractMethodMessageHandler.java b/spring-messaging/src/main/java/org/springframework/messaging/handler/invocation/reactive/AbstractMethodMessageHandler.java index 4e731cda82a..0ce87e47b17 100644 --- a/spring-messaging/src/main/java/org/springframework/messaging/handler/invocation/reactive/AbstractMethodMessageHandler.java +++ b/spring-messaging/src/main/java/org/springframework/messaging/handler/invocation/reactive/AbstractMethodMessageHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -146,7 +146,7 @@ public abstract class AbstractMethodMessageHandler * Configure custom resolvers for handler method arguments. */ public void setArgumentResolverConfigurer(ArgumentResolverConfigurer configurer) { - Assert.notNull(configurer, "HandlerMethodArgumentResolver is required"); + Assert.notNull(configurer, "ArgumentResolverConfigurer is required"); this.argumentResolverConfigurer = configurer; } diff --git a/spring-messaging/src/main/java/org/springframework/messaging/handler/invocation/reactive/ArgumentResolverConfigurer.java b/spring-messaging/src/main/java/org/springframework/messaging/handler/invocation/reactive/ArgumentResolverConfigurer.java index 9b6d71d84bb..6c1b8de2f38 100644 --- a/spring-messaging/src/main/java/org/springframework/messaging/handler/invocation/reactive/ArgumentResolverConfigurer.java +++ b/spring-messaging/src/main/java/org/springframework/messaging/handler/invocation/reactive/ArgumentResolverConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,11 +36,11 @@ public class ArgumentResolverConfigurer { /** * Configure resolvers for custom handler method arguments. - * @param resolver the resolvers to add + * @param resolvers the resolvers to add */ - public void addCustomResolver(HandlerMethodArgumentResolver... resolver) { - Assert.notNull(resolver, "'resolvers' must not be null"); - this.customResolvers.addAll(Arrays.asList(resolver)); + public void addCustomResolver(HandlerMethodArgumentResolver... resolvers) { + Assert.notNull(resolvers, "'resolvers' must not be null"); + this.customResolvers.addAll(Arrays.asList(resolvers)); } diff --git a/spring-messaging/src/main/java/org/springframework/messaging/rsocket/DefaultRSocketRequester.java b/spring-messaging/src/main/java/org/springframework/messaging/rsocket/DefaultRSocketRequester.java index 1762536eec1..d8403afc979 100644 --- a/spring-messaging/src/main/java/org/springframework/messaging/rsocket/DefaultRSocketRequester.java +++ b/spring-messaging/src/main/java/org/springframework/messaging/rsocket/DefaultRSocketRequester.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -171,7 +171,8 @@ final class DefaultRSocketRequester implements RSocketRequester { Assert.notNull(producer, "'producer' must not be null"); Assert.notNull(elementClass, "'elementClass' must not be null"); ReactiveAdapter adapter = getAdapter(producer.getClass()); - Assert.notNull(adapter, "'producer' type is unknown to ReactiveAdapterRegistry"); + Assert.notNull(adapter, () -> "'producer' type is unknown to ReactiveAdapterRegistry: " + + producer.getClass().getName()); createPayload(adapter.toPublisher(producer), ResolvableType.forClass(elementClass)); return this; } @@ -186,7 +187,8 @@ final class DefaultRSocketRequester implements RSocketRequester { Assert.notNull(producer, "'producer' must not be null"); Assert.notNull(elementTypeRef, "'elementTypeRef' must not be null"); ReactiveAdapter adapter = getAdapter(producer.getClass()); - Assert.notNull(adapter, "'producer' type is unknown to ReactiveAdapterRegistry"); + Assert.notNull(adapter, () -> "'producer' type is unknown to ReactiveAdapterRegistry: " + + producer.getClass().getName()); createPayload(adapter.toPublisher(producer), ResolvableType.forType(elementTypeRef)); return this; } diff --git a/spring-messaging/src/main/java/org/springframework/messaging/rsocket/MetadataEncoder.java b/spring-messaging/src/main/java/org/springframework/messaging/rsocket/MetadataEncoder.java index 3e54088ccb5..507745c7e12 100644 --- a/spring-messaging/src/main/java/org/springframework/messaging/rsocket/MetadataEncoder.java +++ b/spring-messaging/src/main/java/org/springframework/messaging/rsocket/MetadataEncoder.java @@ -78,8 +78,8 @@ final class MetadataEncoder { this.strategies = strategies; this.isComposite = this.metadataMimeType.toString().equals( WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString()); - this.allocator = bufferFactory() instanceof NettyDataBufferFactory ? - ((NettyDataBufferFactory) bufferFactory()).getByteBufAllocator() : ByteBufAllocator.DEFAULT; + this.allocator = bufferFactory() instanceof NettyDataBufferFactory nettyDBF ? + nettyDBF.getByteBufAllocator() : ByteBufAllocator.DEFAULT; } @@ -193,7 +193,7 @@ final class MetadataEncoder { Object value = entry.value(); io.rsocket.metadata.CompositeMetadataCodec.encodeAndAddMetadata( composite, this.allocator, entry.mimeType().toString(), - value instanceof ByteBuf ? (ByteBuf) value : PayloadUtils.asByteBuf(encodeEntry(entry))); + value instanceof ByteBuf byteBuf ? byteBuf : PayloadUtils.asByteBuf(encodeEntry(entry))); }); return asDataBuffer(composite); } @@ -232,8 +232,8 @@ final class MetadataEncoder { @SuppressWarnings("unchecked") private DataBuffer encodeEntry(Object value, MimeType mimeType) { - if (value instanceof ByteBuf) { - return asDataBuffer((ByteBuf) value); + if (value instanceof ByteBuf byteBuf) { + return asDataBuffer(byteBuf); } ResolvableType type = ResolvableType.forInstance(value); Encoder encoder = this.strategies.encoder(type, mimeType); @@ -242,8 +242,8 @@ final class MetadataEncoder { } private DataBuffer asDataBuffer(ByteBuf byteBuf) { - if (bufferFactory() instanceof NettyDataBufferFactory) { - return ((NettyDataBufferFactory) bufferFactory()).wrap(byteBuf); + if (bufferFactory() instanceof NettyDataBufferFactory nettyDBF) { + return nettyDBF.wrap(byteBuf); } else { DataBuffer buffer = bufferFactory().wrap(byteBuf.nioBuffer()); @@ -257,7 +257,7 @@ final class MetadataEncoder { List> valueMonos = new ArrayList<>(); this.metadataEntries.forEach(entry -> { Object v = entry.value(); - valueMonos.add(v instanceof Mono ? (Mono) v : Mono.just(v)); + valueMonos.add(v instanceof Mono mono ? mono : Mono.just(v)); }); return Mono.zip(valueMonos, values -> { List result = new ArrayList<>(values.length); diff --git a/spring-orm/src/main/java/org/springframework/orm/jpa/support/InjectionCodeGenerator.java b/spring-orm/src/main/java/org/springframework/orm/jpa/support/InjectionCodeGenerator.java index f1fb64cb0f4..27083992c32 100644 --- a/spring-orm/src/main/java/org/springframework/orm/jpa/support/InjectionCodeGenerator.java +++ b/spring-orm/src/main/java/org/springframework/orm/jpa/support/InjectionCodeGenerator.java @@ -31,14 +31,15 @@ import org.springframework.util.ReflectionUtils; /** * Internal code generator that can inject a value into a field or single-arg * method. - *

- * Generates code in the form:

{@code
+ *
+ * 

Generates code in the form: + *

{@code
  * instance.age = value;
  * }
or
{@code
  * instance.setAge(value);
  * }
- *

- * Will also generate reflection based injection and register hints if the + * + *

Will also generate reflection based injection and register hints if the * member is not visible. * * @author Phillip Webb @@ -59,18 +60,14 @@ class InjectionCodeGenerator { } - CodeBlock generateInjectionCode(Member member, String instanceVariable, - CodeBlock resourceToInject) { - + CodeBlock generateInjectionCode(Member member, String instanceVariable, CodeBlock resourceToInject) { if (member instanceof Field field) { return generateFieldInjectionCode(field, instanceVariable, resourceToInject); } if (member instanceof Method method) { - return generateMethodInjectionCode(method, instanceVariable, - resourceToInject); + return generateMethodInjectionCode(method, instanceVariable, resourceToInject); } - throw new IllegalStateException( - "Unsupported member type " + member.getClass().getName()); + throw new IllegalStateException("Unsupported member type " + member.getClass().getName()); } private CodeBlock generateFieldInjectionCode(Field field, String instanceVariable, @@ -87,8 +84,7 @@ class InjectionCodeGenerator { "field", instanceVariable, resourceToInject); } else { - code.addStatement("$L.$L = $L", instanceVariable, field.getName(), - resourceToInject); + code.addStatement("$L.$L = $L", instanceVariable, field.getName(), resourceToInject); } return code.build(); } @@ -105,14 +101,12 @@ class InjectionCodeGenerator { code.addStatement("$T method = $T.findMethod($T.class, $S, $T.class)", Method.class, ReflectionUtils.class, method.getDeclaringClass(), method.getName(), method.getParameterTypes()[0]); - code.addStatement("$T.makeAccessible($L)", ReflectionUtils.class, - "method"); + code.addStatement("$T.makeAccessible($L)", ReflectionUtils.class, "method"); code.addStatement("$T.invokeMethod($L, $L, $L)", ReflectionUtils.class, "method", instanceVariable, resourceToInject); } else { - code.addStatement("$L.$L($L)", instanceVariable, method.getName(), - resourceToInject); + code.addStatement("$L.$L($L)", instanceVariable, method.getName(), resourceToInject); } return code.build(); } 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 c02cc563731..b3808539e3c 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 @@ -200,7 +200,7 @@ public abstract class AbstractRoutingConnectionFactory implements ConnectionFact * in the {@link #setTargetConnectionFactories targetConnectionFactories} map, * falls back to the specified {@link #setDefaultTargetConnectionFactory default * target ConnectionFactory} if necessary. - * @return {@link Mono} emitting the current {@link ConnectionFactory} as + * @return {@link Mono} that emits the current {@link ConnectionFactory} as * per {@link #determineCurrentLookupKey()} * @see #determineCurrentLookupKey() */ diff --git a/spring-test/src/main/java/org/springframework/mock/http/server/reactive/MockServerHttpRequest.java b/spring-test/src/main/java/org/springframework/mock/http/server/reactive/MockServerHttpRequest.java index 7bf5a693ca1..1e018ed6c3b 100644 --- a/spring-test/src/main/java/org/springframework/mock/http/server/reactive/MockServerHttpRequest.java +++ b/spring-test/src/main/java/org/springframework/mock/http/server/reactive/MockServerHttpRequest.java @@ -43,7 +43,6 @@ import org.springframework.util.Assert; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MimeType; import org.springframework.util.MultiValueMap; -import org.springframework.util.StringUtils; import org.springframework.web.util.UriComponentsBuilder; /** @@ -236,7 +235,7 @@ public final class MockServerHttpRequest extends AbstractServerHttpRequest { */ @Deprecated(since = "6.0") public static BodyBuilder method(String httpMethod, String uri, Object... vars) { - Assert.isTrue(StringUtils.hasText(httpMethod), "HTTP method is required."); + Assert.hasText(httpMethod, "HTTP method is required."); return new DefaultBodyBuilder(HttpMethod.valueOf(httpMethod), toUri(uri, vars)); } diff --git a/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletRequest.java b/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletRequest.java index ad730966f0d..c0121180795 100644 --- a/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletRequest.java +++ b/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletRequest.java @@ -549,11 +549,11 @@ public class MockHttpServletRequest implements HttpServletRequest { public void setParameters(Map params) { Assert.notNull(params, "Parameter map must not be null"); params.forEach((key, value) -> { - if (value instanceof String) { - setParameter(key, (String) value); + if (value instanceof String str) { + setParameter(key, str); } - else if (value instanceof String[]) { - setParameter(key, (String[]) value); + else if (value instanceof String[] strings) { + setParameter(key, strings); } else { throw new IllegalArgumentException( @@ -598,11 +598,11 @@ public class MockHttpServletRequest implements HttpServletRequest { public void addParameters(Map params) { Assert.notNull(params, "Parameter map must not be null"); params.forEach((key, value) -> { - if (value instanceof String) { - addParameter(key, (String) value); + if (value instanceof String str) { + addParameter(key, str); } - else if (value instanceof String[]) { - addParameter(key, (String[]) value); + else if (value instanceof String[] strings) { + addParameter(key, strings); } else { throw new IllegalArgumentException("Parameter map value must be single value " + @@ -1083,8 +1083,8 @@ public class MockHttpServletRequest implements HttpServletRequest { header = new HeaderValueHolder(); this.headers.put(name, header); } - if (value instanceof Collection) { - header.addValues((Collection) value); + if (value instanceof Collection collection) { + header.addValues(collection); } else if (value.getClass().isArray()) { header.addValueArray(value); @@ -1119,14 +1119,14 @@ public class MockHttpServletRequest implements HttpServletRequest { public long getDateHeader(String name) { HeaderValueHolder header = this.headers.get(name); Object value = (header != null ? header.getValue() : null); - if (value instanceof Date) { - return ((Date) value).getTime(); + if (value instanceof Date date) { + return date.getTime(); } - else if (value instanceof Number) { - return ((Number) value).longValue(); + else if (value instanceof Number number) { + return number.longValue(); } - else if (value instanceof String) { - return parseDateHeader(name, (String) value); + else if (value instanceof String str) { + return parseDateHeader(name, str); } else if (value != null) { throw new IllegalArgumentException( @@ -1173,11 +1173,11 @@ public class MockHttpServletRequest implements HttpServletRequest { public int getIntHeader(String name) { HeaderValueHolder header = this.headers.get(name); Object value = (header != null ? header.getValue() : null); - if (value instanceof Number) { - return ((Number) value).intValue(); + if (value instanceof Number number) { + return number.intValue(); } - else if (value instanceof String) { - return Integer.parseInt((String) value); + else if (value instanceof String str) { + return Integer.parseInt(str); } else if (value != null) { throw new NumberFormatException("Value for header '" + name + "' is not a Number: " + value); @@ -1248,8 +1248,9 @@ public class MockHttpServletRequest implements HttpServletRequest { @Override public boolean isUserInRole(String role) { - return (this.userRoles.contains(role) || (this.servletContext instanceof MockServletContext && - ((MockServletContext) this.servletContext).getDeclaredRoles().contains(role))); + return (this.userRoles.contains(role) || + (this.servletContext instanceof MockServletContext mockContext && + mockContext.getDeclaredRoles().contains(role))); } public void setUserPrincipal(@Nullable Principal userPrincipal) { @@ -1321,7 +1322,7 @@ public class MockHttpServletRequest implements HttpServletRequest { public HttpSession getSession(boolean create) { checkActive(); // Reset session if invalidated. - if (this.session instanceof MockHttpSession && ((MockHttpSession) this.session).isInvalid()) { + if (this.session instanceof MockHttpSession mockSession && mockSession.isInvalid()) { this.session = null; } // Create new session if necessary. @@ -1346,8 +1347,8 @@ public class MockHttpServletRequest implements HttpServletRequest { @Override public String changeSessionId() { Assert.isTrue(this.session != null, "The request does not have a session"); - if (this.session instanceof MockHttpSession) { - return ((MockHttpSession) this.session).changeSessionId(); + if (this.session instanceof MockHttpSession mockSession) { + return mockSession.changeSessionId(); } return this.session.getId(); } diff --git a/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java b/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java index 88af4672bfb..65995e95610 100644 --- a/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java +++ b/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java @@ -424,7 +424,7 @@ public class MockHttpServletResponse implements HttpServletResponse { buf.append("; Domain=").append(cookie.getDomain()); } int maxAge = cookie.getMaxAge(); - ZonedDateTime expires = (cookie instanceof MockCookie mockCookie? mockCookie.getExpires() : null); + ZonedDateTime expires = (cookie instanceof MockCookie mockCookie ? mockCookie.getExpires() : null); if (maxAge >= 0) { buf.append("; Max-Age=").append(maxAge); buf.append("; Expires="); diff --git a/spring-test/src/main/java/org/springframework/test/annotation/ProfileValueUtils.java b/spring-test/src/main/java/org/springframework/test/annotation/ProfileValueUtils.java index cf3614ee931..26957c49f25 100644 --- a/spring-test/src/main/java/org/springframework/test/annotation/ProfileValueUtils.java +++ b/spring-test/src/main/java/org/springframework/test/annotation/ProfileValueUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -187,7 +187,7 @@ public abstract class ProfileValueUtils { String environmentValue = profileValueSource.get(ifProfileValue.name()); String[] annotatedValues = ifProfileValue.values(); if (StringUtils.hasLength(ifProfileValue.value())) { - Assert.isTrue(annotatedValues.length == 0, () -> "Setting both the 'value' and 'values' attributes " + + Assert.isTrue(annotatedValues.length == 0, "Setting both the 'value' and 'values' attributes " + "of @IfProfileValue is not allowed: choose one or the other."); annotatedValues = new String[] { ifProfileValue.value() }; } diff --git a/spring-test/src/main/java/org/springframework/test/web/reactive/server/WiretapConnector.java b/spring-test/src/main/java/org/springframework/test/web/reactive/server/WiretapConnector.java index f0120d3a676..528d098c9e5 100644 --- a/spring-test/src/main/java/org/springframework/test/web/reactive/server/WiretapConnector.java +++ b/spring-test/src/main/java/org/springframework/test/web/reactive/server/WiretapConnector.java @@ -89,10 +89,8 @@ class WiretapConnector implements ClientHttpConnector { */ ExchangeResult getExchangeResult(String requestId, @Nullable String uriTemplate, Duration timeout) { ClientExchangeInfo clientInfo = this.exchanges.remove(requestId); - Assert.state(clientInfo != null, () -> { - String header = WebTestClient.WEBTESTCLIENT_REQUEST_ID; - return "No match for " + header + "=" + requestId; - }); + Assert.state(clientInfo != null, () -> "No match for %s=%s".formatted( + WebTestClient.WEBTESTCLIENT_REQUEST_ID, requestId)); return new ExchangeResult(clientInfo.getRequest(), clientInfo.getResponse(), clientInfo.getRequest().getRecorder().getContent(), clientInfo.getResponse().getRecorder().getContent(), diff --git a/spring-web/src/main/java/org/springframework/http/codec/multipart/DefaultPartHttpMessageReader.java b/spring-web/src/main/java/org/springframework/http/codec/multipart/DefaultPartHttpMessageReader.java index a694e43437a..35b77dbf7e2 100644 --- a/spring-web/src/main/java/org/springframework/http/codec/multipart/DefaultPartHttpMessageReader.java +++ b/spring-web/src/main/java/org/springframework/http/codec/multipart/DefaultPartHttpMessageReader.java @@ -154,7 +154,7 @@ public class DefaultPartHttpMessageReader extends LoggingCodecSupport implements * @see Schedulers#newBoundedElastic */ public void setBlockingOperationScheduler(Scheduler blockingOperationScheduler) { - Assert.notNull(blockingOperationScheduler, "FileCreationScheduler must not be null"); + Assert.notNull(blockingOperationScheduler, "'blockingOperationScheduler' must not be null"); this.blockingOperationScheduler = blockingOperationScheduler; } diff --git a/spring-web/src/main/java/org/springframework/http/server/ServletServerHttpResponse.java b/spring-web/src/main/java/org/springframework/http/server/ServletServerHttpResponse.java index 15ae6540933..ca28b8e0580 100644 --- a/spring-web/src/main/java/org/springframework/http/server/ServletServerHttpResponse.java +++ b/spring-web/src/main/java/org/springframework/http/server/ServletServerHttpResponse.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,7 +72,7 @@ public class ServletServerHttpResponse implements ServerHttpResponse { @Override public void setStatusCode(HttpStatusCode status) { - Assert.notNull(status, "HttpStatus must not be null"); + Assert.notNull(status, "HttpStatusCode must not be null"); this.servletResponse.setStatus(status.value()); } diff --git a/spring-web/src/testFixtures/java/org/springframework/web/testfixture/servlet/MockHttpServletRequest.java b/spring-web/src/testFixtures/java/org/springframework/web/testfixture/servlet/MockHttpServletRequest.java index 44174534e42..9c269278af0 100644 --- a/spring-web/src/testFixtures/java/org/springframework/web/testfixture/servlet/MockHttpServletRequest.java +++ b/spring-web/src/testFixtures/java/org/springframework/web/testfixture/servlet/MockHttpServletRequest.java @@ -549,11 +549,11 @@ public class MockHttpServletRequest implements HttpServletRequest { public void setParameters(Map params) { Assert.notNull(params, "Parameter map must not be null"); params.forEach((key, value) -> { - if (value instanceof String) { - setParameter(key, (String) value); + if (value instanceof String str) { + setParameter(key, str); } - else if (value instanceof String[]) { - setParameter(key, (String[]) value); + else if (value instanceof String[] strings) { + setParameter(key, strings); } else { throw new IllegalArgumentException( @@ -598,11 +598,11 @@ public class MockHttpServletRequest implements HttpServletRequest { public void addParameters(Map params) { Assert.notNull(params, "Parameter map must not be null"); params.forEach((key, value) -> { - if (value instanceof String) { - addParameter(key, (String) value); + if (value instanceof String str) { + addParameter(key, str); } - else if (value instanceof String[]) { - addParameter(key, (String[]) value); + else if (value instanceof String[] strings) { + addParameter(key, strings); } else { throw new IllegalArgumentException("Parameter map value must be single value " + @@ -1083,8 +1083,8 @@ public class MockHttpServletRequest implements HttpServletRequest { header = new HeaderValueHolder(); this.headers.put(name, header); } - if (value instanceof Collection) { - header.addValues((Collection) value); + if (value instanceof Collection collection) { + header.addValues(collection); } else if (value.getClass().isArray()) { header.addValueArray(value); @@ -1119,14 +1119,14 @@ public class MockHttpServletRequest implements HttpServletRequest { public long getDateHeader(String name) { HeaderValueHolder header = this.headers.get(name); Object value = (header != null ? header.getValue() : null); - if (value instanceof Date) { - return ((Date) value).getTime(); + if (value instanceof Date date) { + return date.getTime(); } - else if (value instanceof Number) { - return ((Number) value).longValue(); + else if (value instanceof Number number) { + return number.longValue(); } - else if (value instanceof String) { - return parseDateHeader(name, (String) value); + else if (value instanceof String str) { + return parseDateHeader(name, str); } else if (value != null) { throw new IllegalArgumentException( @@ -1173,11 +1173,11 @@ public class MockHttpServletRequest implements HttpServletRequest { public int getIntHeader(String name) { HeaderValueHolder header = this.headers.get(name); Object value = (header != null ? header.getValue() : null); - if (value instanceof Number) { - return ((Number) value).intValue(); + if (value instanceof Number number) { + return number.intValue(); } - else if (value instanceof String) { - return Integer.parseInt((String) value); + else if (value instanceof String str) { + return Integer.parseInt(str); } else if (value != null) { throw new NumberFormatException("Value for header '" + name + "' is not a Number: " + value); @@ -1248,8 +1248,9 @@ public class MockHttpServletRequest implements HttpServletRequest { @Override public boolean isUserInRole(String role) { - return (this.userRoles.contains(role) || (this.servletContext instanceof MockServletContext && - ((MockServletContext) this.servletContext).getDeclaredRoles().contains(role))); + return (this.userRoles.contains(role) || + (this.servletContext instanceof MockServletContext mockContext && + mockContext.getDeclaredRoles().contains(role))); } public void setUserPrincipal(@Nullable Principal userPrincipal) { @@ -1321,7 +1322,7 @@ public class MockHttpServletRequest implements HttpServletRequest { public HttpSession getSession(boolean create) { checkActive(); // Reset session if invalidated. - if (this.session instanceof MockHttpSession && ((MockHttpSession) this.session).isInvalid()) { + if (this.session instanceof MockHttpSession mockSession && mockSession.isInvalid()) { this.session = null; } // Create new session if necessary. @@ -1346,8 +1347,8 @@ public class MockHttpServletRequest implements HttpServletRequest { @Override public String changeSessionId() { Assert.isTrue(this.session != null, "The request does not have a session"); - if (this.session instanceof MockHttpSession) { - return ((MockHttpSession) this.session).changeSessionId(); + if (this.session instanceof MockHttpSession mockSession) { + return mockSession.changeSessionId(); } return this.session.getId(); } diff --git a/spring-webflux/src/main/java/org/springframework/web/reactive/function/BodyInserters.java b/spring-webflux/src/main/java/org/springframework/web/reactive/function/BodyInserters.java index ff94b50f418..5afeba0f8aa 100644 --- a/spring-webflux/src/main/java/org/springframework/web/reactive/function/BodyInserters.java +++ b/spring-webflux/src/main/java/org/springframework/web/reactive/function/BodyInserters.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -92,7 +92,8 @@ public abstract class BodyInserters { */ public static BodyInserter fromValue(T body) { Assert.notNull(body, "'body' must not be null"); - Assert.isNull(registry.getAdapter(body.getClass()), "'body' should be an object, for reactive types use a variant specifying a publisher/producer and its related element type"); + Assert.isNull(registry.getAdapter(body.getClass()), + "'body' should be an object, for reactive types use a variant specifying a publisher/producer and its related element type"); return (message, context) -> writeWithMessageWriters(message, context, Mono.just(body), ResolvableType.forInstance(body), null); } diff --git a/spring-webflux/src/main/java/org/springframework/web/reactive/function/client/DefaultClientResponseBuilder.java b/spring-webflux/src/main/java/org/springframework/web/reactive/function/client/DefaultClientResponseBuilder.java index ef68d4f8cda..62eb576cf12 100644 --- a/spring-webflux/src/main/java/org/springframework/web/reactive/function/client/DefaultClientResponseBuilder.java +++ b/spring-webflux/src/main/java/org/springframework/web/reactive/function/client/DefaultClientResponseBuilder.java @@ -113,7 +113,7 @@ final class DefaultClientResponseBuilder implements ClientResponse.Builder { @Override public DefaultClientResponseBuilder statusCode(HttpStatusCode statusCode) { - Assert.notNull(statusCode, "StatusCode must not be null"); + Assert.notNull(statusCode, "HttpStatusCode must not be null"); this.statusCode = statusCode; return this; }