Perform NullAway build-time checks in more modules

This commit enables null-safety build-time checks in
all remaining modules except spring-test.

See gh-32475
This commit is contained in:
Sébastien Deleuze 2024-03-26 15:53:01 +01:00
parent 2fea3d7921
commit 8b51b36729
53 changed files with 93 additions and 31 deletions

View File

@ -117,12 +117,11 @@ tasks.withType(JavaCompile).configureEach {
options.errorprone { options.errorprone {
disableAllChecks = true disableAllChecks = true
option("NullAway:CustomContractAnnotations", "org.springframework.lang.Contract") option("NullAway:CustomContractAnnotations", "org.springframework.lang.Contract")
option("NullAway:AnnotatedPackages", "org.springframework.core,org.springframework.expression," + option("NullAway:AnnotatedPackages", "org.springframework")
"org.springframework.web,org.springframework.jms,org.springframework.messaging,org.springframework.jdbc," +
"org.springframework.r2dbc,org.springframework.orm,org.springframework.beans,org.springframework.aop")
option("NullAway:UnannotatedSubPackages", "org.springframework.instrument,org.springframework.context.index," + option("NullAway:UnannotatedSubPackages", "org.springframework.instrument,org.springframework.context.index," +
"org.springframework.asm,org.springframework.cglib,org.springframework.objenesis," + "org.springframework.asm,org.springframework.cglib,org.springframework.objenesis," +
"org.springframework.javapoet,org.springframework.aot.nativex.substitution,org.springframework.aot.nativex.feature") "org.springframework.javapoet,org.springframework.aot.nativex.substitution,org.springframework.aot.nativex.feature," +
"org.springframework.test,org.springframework.mock")
} }
} }
tasks.compileJava { tasks.compileJava {

View File

@ -101,7 +101,7 @@ class CacheResultInterceptor extends AbstractKeyCacheInterceptor<CacheResultOper
private Cache resolveExceptionCache(CacheOperationInvocationContext<CacheResultOperation> context) { private Cache resolveExceptionCache(CacheOperationInvocationContext<CacheResultOperation> context) {
CacheResolver exceptionCacheResolver = context.getOperation().getExceptionCacheResolver(); CacheResolver exceptionCacheResolver = context.getOperation().getExceptionCacheResolver();
if (exceptionCacheResolver != null) { if (exceptionCacheResolver != null) {
return extractFrom(context.getOperation().getExceptionCacheResolver().resolveCaches(context)); return extractFrom(exceptionCacheResolver.resolveCaches(context));
} }
return null; return null;
} }

View File

@ -188,6 +188,7 @@ public class DefaultJCacheOperationSource extends AnnotationJCacheOperationSourc
} }
} }
@SuppressWarnings("NullAway")
protected CacheManager getDefaultCacheManager() { protected CacheManager getDefaultCacheManager() {
if (getCacheManager() == null) { if (getCacheManager() == null) {
Assert.state(this.beanFactory != null, "BeanFactory required for default CacheManager resolution"); Assert.state(this.beanFactory != null, "BeanFactory required for default CacheManager resolution");
@ -207,6 +208,7 @@ public class DefaultJCacheOperationSource extends AnnotationJCacheOperationSourc
} }
@Override @Override
@SuppressWarnings("NullAway")
protected CacheResolver getDefaultCacheResolver() { protected CacheResolver getDefaultCacheResolver() {
if (getCacheResolver() == null) { if (getCacheResolver() == null) {
this.cacheResolver = SingletonSupplier.of(new SimpleCacheResolver(getDefaultCacheManager())); this.cacheResolver = SingletonSupplier.of(new SimpleCacheResolver(getDefaultCacheManager()));
@ -215,6 +217,7 @@ public class DefaultJCacheOperationSource extends AnnotationJCacheOperationSourc
} }
@Override @Override
@SuppressWarnings("NullAway")
protected CacheResolver getDefaultExceptionCacheResolver() { protected CacheResolver getDefaultExceptionCacheResolver() {
if (getExceptionCacheResolver() == null) { if (getExceptionCacheResolver() == null) {
this.exceptionCacheResolver = SingletonSupplier.of(new LazyCacheResolver()); this.exceptionCacheResolver = SingletonSupplier.of(new LazyCacheResolver());

View File

@ -90,6 +90,7 @@ public class LocalDataSourceJobStore extends JobStoreCMT {
@Override @Override
@SuppressWarnings("NullAway")
public void initialize(ClassLoadHelper loadHelper, SchedulerSignaler signaler) throws SchedulerConfigException { public void initialize(ClassLoadHelper loadHelper, SchedulerSignaler signaler) throws SchedulerConfigException {
// Absolutely needs thread-bound DataSource to initialize. // Absolutely needs thread-bound DataSource to initialize.
this.dataSource = SchedulerFactoryBean.getConfigTimeDataSource(); this.dataSource = SchedulerFactoryBean.getConfigTimeDataSource();

View File

@ -203,6 +203,7 @@ public abstract class SchedulerAccessor implements ResourceLoaderAware {
/** /**
* Register jobs and triggers (within a transaction, if possible). * Register jobs and triggers (within a transaction, if possible).
*/ */
@SuppressWarnings("NullAway")
protected void registerJobsAndTriggers() throws SchedulerException { protected void registerJobsAndTriggers() throws SchedulerException {
TransactionStatus transactionStatus = null; TransactionStatus transactionStatus = null;
if (this.transactionManager != null) { if (this.transactionManager != null) {

View File

@ -661,6 +661,7 @@ public class SchedulerFactoryBean extends SchedulerAccessor implements FactoryBe
* @see #afterPropertiesSet * @see #afterPropertiesSet
* @see org.quartz.SchedulerFactory#getScheduler * @see org.quartz.SchedulerFactory#getScheduler
*/ */
@SuppressWarnings("NullAway")
protected Scheduler createScheduler(SchedulerFactory schedulerFactory, @Nullable String schedulerName) protected Scheduler createScheduler(SchedulerFactory schedulerFactory, @Nullable String schedulerName)
throws SchedulerException { throws SchedulerException {

View File

@ -43,6 +43,7 @@ final class BeanMethod extends ConfigurationMethod {
@Override @Override
@SuppressWarnings("NullAway")
public void validate(ProblemReporter problemReporter) { public void validate(ProblemReporter problemReporter) {
if ("void".equals(getMetadata().getReturnTypeName())) { if ("void".equals(getMetadata().getReturnTypeName())) {
// declared as void: potential misuse of @Bean, maybe meant as init method instead? // declared as void: potential misuse of @Bean, maybe meant as init method instead?

View File

@ -40,6 +40,7 @@ import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.core.type.filter.RegexPatternTypeFilter; import org.springframework.core.type.filter.RegexPatternTypeFilter;
import org.springframework.core.type.filter.TypeFilter; import org.springframework.core.type.filter.TypeFilter;
import org.springframework.lang.Nullable; import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils; import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils; import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
@ -112,14 +113,18 @@ public class ComponentScanBeanDefinitionParser implements BeanDefinitionParser {
parseBeanNameGenerator(element, scanner); parseBeanNameGenerator(element, scanner);
} }
catch (Exception ex) { catch (Exception ex) {
parserContext.getReaderContext().error(ex.getMessage(), parserContext.extractSource(element), ex.getCause()); String message = ex.getMessage();
Assert.state(message != null, "Exception message must not be null");
parserContext.getReaderContext().error(message, parserContext.extractSource(element), ex.getCause());
} }
try { try {
parseScope(element, scanner); parseScope(element, scanner);
} }
catch (Exception ex) { catch (Exception ex) {
parserContext.getReaderContext().error(ex.getMessage(), parserContext.extractSource(element), ex.getCause()); String message = ex.getMessage();
Assert.state(message != null, "Exception message must not be null");
parserContext.getReaderContext().error(message, parserContext.extractSource(element), ex.getCause());
} }
parseTypeFilters(element, scanner, parserContext); parseTypeFilters(element, scanner, parserContext);
@ -214,8 +219,10 @@ public class ComponentScanBeanDefinitionParser implements BeanDefinitionParser {
"Ignoring non-present type filter class: " + ex, parserContext.extractSource(element)); "Ignoring non-present type filter class: " + ex, parserContext.extractSource(element));
} }
catch (Exception ex) { catch (Exception ex) {
String message = ex.getMessage();
Assert.state(message != null, "Exception message must not be null");
parserContext.getReaderContext().error( parserContext.getReaderContext().error(
ex.getMessage(), parserContext.extractSource(element), ex.getCause()); message, parserContext.extractSource(element), ex.getCause());
} }
} }
} }

View File

@ -219,6 +219,7 @@ final class ConfigurationClass {
return this.importBeanDefinitionRegistrars; return this.importBeanDefinitionRegistrars;
} }
@SuppressWarnings("NullAway")
void validate(ProblemReporter problemReporter) { void validate(ProblemReporter problemReporter) {
Map<String, Object> attributes = this.metadata.getAnnotationAttributes(Configuration.class.getName()); Map<String, Object> attributes = this.metadata.getAnnotationAttributes(Configuration.class.getName());

View File

@ -819,6 +819,7 @@ class ConfigurationClassParser {
deferredImport.getConfigurationClass()); deferredImport.getConfigurationClass());
} }
@SuppressWarnings("NullAway")
void processGroupImports() { void processGroupImports() {
for (DeferredImportSelectorGrouping grouping : this.groupings.values()) { for (DeferredImportSelectorGrouping grouping : this.groupings.values()) {
Predicate<String> filter = grouping.getCandidateFilter(); Predicate<String> filter = grouping.getCandidateFilter();

View File

@ -325,6 +325,7 @@ public class ConfigurationClassPostProcessor implements BeanDefinitionRegistryPo
@Override @Override
@Nullable @Nullable
@SuppressWarnings("NullAway")
public BeanFactoryInitializationAotContribution processAheadOfTime(ConfigurableListableBeanFactory beanFactory) { public BeanFactoryInitializationAotContribution processAheadOfTime(ConfigurableListableBeanFactory beanFactory) {
boolean hasPropertySourceDescriptors = !CollectionUtils.isEmpty(this.propertySourceDescriptors); boolean hasPropertySourceDescriptors = !CollectionUtils.isEmpty(this.propertySourceDescriptors);
boolean hasImportRegistry = beanFactory.containsBean(IMPORT_REGISTRY_BEAN_NAME); boolean hasImportRegistry = beanFactory.containsBean(IMPORT_REGISTRY_BEAN_NAME);
@ -556,6 +557,7 @@ public class ConfigurationClassPostProcessor implements BeanDefinitionRegistryPo
} }
@Override @Override
@Nullable
public PropertyValues postProcessProperties(@Nullable PropertyValues pvs, Object bean, String beanName) { public PropertyValues postProcessProperties(@Nullable PropertyValues pvs, Object bean, String beanName) {
// Inject the BeanFactory before AutowiredAnnotationBeanPostProcessor's // Inject the BeanFactory before AutowiredAnnotationBeanPostProcessor's
// postProcessProperties method attempts to autowire other configuration beans. // postProcessProperties method attempts to autowire other configuration beans.

View File

@ -98,6 +98,7 @@ public class ContextAnnotationAutowireCandidateResolver extends QualifierAnnotat
return descriptor.getDependencyType(); return descriptor.getDependencyType();
} }
@Override @Override
@SuppressWarnings("NullAway")
public Object getTarget() { public Object getTarget() {
Set<String> autowiredBeanNames = (beanName != null ? new LinkedHashSet<>(1) : null); Set<String> autowiredBeanNames = (beanName != null ? new LinkedHashSet<>(1) : null);
Object target = dlbf.doResolveDependency(descriptor, beanName, autowiredBeanNames, null); Object target = dlbf.doResolveDependency(descriptor, beanName, autowiredBeanNames, null);

View File

@ -31,6 +31,7 @@ import org.springframework.util.MultiValueMap;
class ProfileCondition implements Condition { class ProfileCondition implements Condition {
@Override @Override
@SuppressWarnings("NullAway")
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(Profile.class.getName()); MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(Profile.class.getName());
if (attrs != null) { if (attrs != null) {

View File

@ -40,6 +40,7 @@ import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.lang.Nullable; import org.springframework.lang.Nullable;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.ClassUtils; import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
/** /**
@ -229,6 +230,7 @@ public abstract class AbstractApplicationEventMulticaster
* @param retriever the ListenerRetriever, if supposed to populate one (for caching purposes) * @param retriever the ListenerRetriever, if supposed to populate one (for caching purposes)
* @return the pre-filtered list of application listeners for the given event and source type * @return the pre-filtered list of application listeners for the given event and source type
*/ */
@SuppressWarnings("NullAway")
private Collection<ApplicationListener<?>> retrieveApplicationListeners( private Collection<ApplicationListener<?>> retrieveApplicationListeners(
ResolvableType eventType, @Nullable Class<?> sourceType, @Nullable CachedListenerRetriever retriever) { ResolvableType eventType, @Nullable Class<?> sourceType, @Nullable CachedListenerRetriever retriever) {
@ -313,7 +315,7 @@ public abstract class AbstractApplicationEventMulticaster
AnnotationAwareOrderComparator.sort(allListeners); AnnotationAwareOrderComparator.sort(allListeners);
if (retriever != null) { if (retriever != null) {
if (filteredListenerBeans.isEmpty()) { if (CollectionUtils.isEmpty(filteredListenerBeans)) {
retriever.applicationListeners = new LinkedHashSet<>(allListeners); retriever.applicationListeners = new LinkedHashSet<>(allListeners);
retriever.applicationListenerBeans = filteredListenerBeans; retriever.applicationListenerBeans = filteredListenerBeans;
} }

View File

@ -460,6 +460,7 @@ public class ApplicationListenerMethodAdapter implements GenericApplicationListe
} }
} }
@SuppressWarnings("NullAway")
private String getInvocationErrorMessage(Object bean, @Nullable String message, @Nullable Object[] resolvedArgs) { private String getInvocationErrorMessage(Object bean, @Nullable String message, @Nullable Object[] resolvedArgs) {
StringBuilder sb = new StringBuilder(getDetailedErrorMessage(bean, message)); StringBuilder sb = new StringBuilder(getDetailedErrorMessage(bean, message));
sb.append("Resolved arguments: \n"); sb.append("Resolved arguments: \n");

View File

@ -111,7 +111,7 @@ public class EventListenerMethodProcessor
@Override @Override
public void afterSingletonsInstantiated() { public void afterSingletonsInstantiated() {
ConfigurableListableBeanFactory beanFactory = this.beanFactory; ConfigurableListableBeanFactory beanFactory = this.beanFactory;
Assert.state(this.beanFactory != null, "No ConfigurableListableBeanFactory set"); Assert.state(beanFactory != null, "No ConfigurableListableBeanFactory set");
String[] beanNames = beanFactory.getBeanNamesForType(Object.class); String[] beanNames = beanFactory.getBeanNamesForType(Object.class);
for (String beanName : beanNames) { for (String beanName : beanNames) {
if (!ScopedProxyUtils.isScopedTarget(beanName)) { if (!ScopedProxyUtils.isScopedTarget(beanName)) {

View File

@ -18,6 +18,8 @@ package org.springframework.context.i18n;
import io.micrometer.context.ThreadLocalAccessor; import io.micrometer.context.ThreadLocalAccessor;
import org.springframework.lang.Nullable;
/** /**
* Adapt {@link LocaleContextHolder} to the {@link ThreadLocalAccessor} contract * Adapt {@link LocaleContextHolder} to the {@link ThreadLocalAccessor} contract
* to assist the Micrometer Context Propagation library with {@link LocaleContext} * to assist the Micrometer Context Propagation library with {@link LocaleContext}
@ -40,6 +42,7 @@ public class LocaleContextThreadLocalAccessor implements ThreadLocalAccessor<Loc
} }
@Override @Override
@Nullable
public LocaleContext getValue() { public LocaleContext getValue() {
return LocaleContextHolder.getLocaleContext(); return LocaleContextHolder.getLocaleContext();
} }

View File

@ -51,6 +51,7 @@ import org.springframework.format.annotation.DateTimeFormat.ISO;
* @see org.springframework.format.FormatterRegistrar#registerFormatters * @see org.springframework.format.FormatterRegistrar#registerFormatters
* @see org.springframework.format.datetime.DateFormatterRegistrar * @see org.springframework.format.datetime.DateFormatterRegistrar
*/ */
@SuppressWarnings("NullAway")
public class DateTimeFormatterRegistrar implements FormatterRegistrar { public class DateTimeFormatterRegistrar implements FormatterRegistrar {
private enum Type {DATE, TIME, DATE_TIME} private enum Type {DATE, TIME, DATE_TIME}

View File

@ -993,6 +993,7 @@ public class MBeanExporter extends MBeanRegistrationSupport implements MBeanExpo
* Unregister the configured {@link NotificationListener NotificationListeners} * Unregister the configured {@link NotificationListener NotificationListeners}
* from the {@link MBeanServer}. * from the {@link MBeanServer}.
*/ */
@SuppressWarnings("NullAway")
private void unregisterNotificationListeners() { private void unregisterNotificationListeners() {
if (this.server != null) { if (this.server != null) {
this.registeredNotificationListeners.forEach((bean, mappedObjectNames) -> { this.registeredNotificationListeners.forEach((bean, mappedObjectNames) -> {

View File

@ -43,6 +43,7 @@ import org.springframework.core.annotation.RepeatableContainers;
import org.springframework.jmx.export.metadata.InvalidMetadataException; import org.springframework.jmx.export.metadata.InvalidMetadataException;
import org.springframework.jmx.export.metadata.JmxAttributeSource; import org.springframework.jmx.export.metadata.JmxAttributeSource;
import org.springframework.lang.Nullable; import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.util.StringValueResolver; import org.springframework.util.StringValueResolver;
/** /**
@ -117,7 +118,7 @@ public class AnnotationJmxAttributeSource implements JmxAttributeSource, BeanFac
pvs.removePropertyValue("defaultValue"); pvs.removePropertyValue("defaultValue");
PropertyAccessorFactory.forBeanPropertyAccess(bean).setPropertyValues(pvs); PropertyAccessorFactory.forBeanPropertyAccess(bean).setPropertyValues(pvs);
String defaultValue = (String) map.get("defaultValue"); String defaultValue = (String) map.get("defaultValue");
if (!defaultValue.isEmpty()) { if (StringUtils.hasLength(defaultValue)) {
bean.setDefaultValue(defaultValue); bean.setDefaultValue(defaultValue);
} }
return bean; return bean;

View File

@ -682,7 +682,8 @@ public class DataBinder implements PropertyEditorRegistry, TypeConverter {
} }
} }
private void assertValidators(Validator... validators) { @SuppressWarnings("NullAway")
private void assertValidators(@Nullable Validator... validators) {
Object target = getTarget(); Object target = getTarget();
for (Validator validator : validators) { for (Validator validator : validators) {
if (validator != null && (target != null && !validator.supports(target.getClass()))) { if (validator != null && (target != null && !validator.supports(target.getClass()))) {
@ -741,6 +742,7 @@ public class DataBinder implements PropertyEditorRegistry, TypeConverter {
* {@link #setExcludedValidators(Predicate) exclude predicate}. * {@link #setExcludedValidators(Predicate) exclude predicate}.
* @since 6.1 * @since 6.1
*/ */
@SuppressWarnings("NullAway")
public List<Validator> getValidatorsToApply() { public List<Validator> getValidatorsToApply() {
return (this.excludedValidators != null ? return (this.excludedValidators != null ?
this.validators.stream().filter(validator -> !this.excludedValidators.test(validator)).toList() : this.validators.stream().filter(validator -> !this.excludedValidators.test(validator)).toList() :
@ -1168,6 +1170,7 @@ public class DataBinder implements PropertyEditorRegistry, TypeConverter {
* @see #getBindingErrorProcessor * @see #getBindingErrorProcessor
* @see BindingErrorProcessor#processMissingFieldError * @see BindingErrorProcessor#processMissingFieldError
*/ */
@SuppressWarnings("NullAway")
protected void checkRequiredFields(MutablePropertyValues mpvs) { protected void checkRequiredFields(MutablePropertyValues mpvs) {
String[] requiredFields = getRequiredFields(); String[] requiredFields = getRequiredFields();
if (!ObjectUtils.isEmpty(requiredFields)) { if (!ObjectUtils.isEmpty(requiredFields)) {

View File

@ -242,7 +242,8 @@ public class DefaultMessageCodesResolver implements MessageCodesResolver, Serial
* {@link DefaultMessageCodesResolver#CODE_SEPARATOR}, skipping zero-length or * {@link DefaultMessageCodesResolver#CODE_SEPARATOR}, skipping zero-length or
* null elements altogether. * null elements altogether.
*/ */
public static String toDelimitedString(String... elements) { @SuppressWarnings("NullAway")
public static String toDelimitedString(@Nullable String... elements) {
StringJoiner rtn = new StringJoiner(CODE_SEPARATOR); StringJoiner rtn = new StringJoiner(CODE_SEPARATOR);
for (String element : elements) { for (String element : elements) {
if (StringUtils.hasLength(element)) { if (StringUtils.hasLength(element)) {

View File

@ -107,8 +107,7 @@ public class FieldError extends ObjectError {
if (!super.equals(other)) { if (!super.equals(other)) {
return false; return false;
} }
FieldError otherError = (FieldError) other; return (other instanceof FieldError otherError && getField().equals(otherError.getField()) &&
return (getField().equals(otherError.getField()) &&
ObjectUtils.nullSafeEquals(getRejectedValue(), otherError.getRejectedValue()) && ObjectUtils.nullSafeEquals(getRejectedValue(), otherError.getRejectedValue()) &&
isBindingFailure() == otherError.isBindingFailure()); isBindingFailure() == otherError.isBindingFailure());
} }

View File

@ -173,8 +173,8 @@ public class ParameterValidationResult {
if (!super.equals(other)) { if (!super.equals(other)) {
return false; return false;
} }
ParameterValidationResult otherResult = (ParameterValidationResult) other; return (other instanceof ParameterValidationResult otherResult &&
return (getMethodParameter().equals(otherResult.getMethodParameter()) && getMethodParameter().equals(otherResult.getMethodParameter()) &&
ObjectUtils.nullSafeEquals(getArgument(), otherResult.getArgument()) && ObjectUtils.nullSafeEquals(getArgument(), otherResult.getArgument()) &&
ObjectUtils.nullSafeEquals(getContainerIndex(), otherResult.getContainerIndex()) && ObjectUtils.nullSafeEquals(getContainerIndex(), otherResult.getContainerIndex()) &&
ObjectUtils.nullSafeEquals(getContainerKey(), otherResult.getContainerKey())); ObjectUtils.nullSafeEquals(getContainerKey(), otherResult.getContainerKey()));

View File

@ -63,6 +63,7 @@ public class BindingReflectionHintsRegistrar {
* @param hints the hints instance to use * @param hints the hints instance to use
* @param types the types to register * @param types the types to register
*/ */
@SuppressWarnings("NullAway")
public void registerReflectionHints(ReflectionHints hints, @Nullable Type... types) { public void registerReflectionHints(ReflectionHints hints, @Nullable Type... types) {
Set<Type> seen = new HashSet<>(); Set<Type> seen = new HashSet<>();
for (Type type : types) { for (Type type : types) {

View File

@ -108,7 +108,7 @@ public abstract class CoroutinesUtils {
* @throws IllegalArgumentException if {@code method} is not a suspending function * @throws IllegalArgumentException if {@code method} is not a suspending function
* @since 6.0 * @since 6.0
*/ */
@SuppressWarnings({"deprecation", "DataFlowIssue"}) @SuppressWarnings({"deprecation", "DataFlowIssue", "NullAway"})
public static Publisher<?> invokeSuspendingFunction( public static Publisher<?> invokeSuspendingFunction(
CoroutineContext context, Method method, @Nullable Object target, @Nullable Object... args) { CoroutineContext context, Method method, @Nullable Object target, @Nullable Object... args) {

View File

@ -322,6 +322,7 @@ final class PlaceholderParser {
} }
@Override @Override
@Nullable
public String resolvePlaceholder(String placeholderName) { public String resolvePlaceholder(String placeholderName) {
String value = this.resolver.resolvePlaceholder(placeholderName); String value = this.resolver.resolvePlaceholder(placeholderName);
if (value != null && logger.isTraceEnabled()) { if (value != null && logger.isTraceEnabled()) {
@ -358,6 +359,7 @@ final class PlaceholderParser {
} }
public void removePlaceholder(String placeholder) { public void removePlaceholder(String placeholder) {
Assert.state(this.visitedPlaceholders != null, "Visited placeholders must not be null");
this.visitedPlaceholders.remove(placeholder); this.visitedPlaceholders.remove(placeholder);
} }

View File

@ -25,6 +25,7 @@ import java.io.InputStreamReader;
import java.io.OutputStream; import java.io.OutputStream;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import org.springframework.lang.Contract;
import org.springframework.lang.Nullable; import org.springframework.lang.Nullable;
/** /**
@ -201,6 +202,7 @@ public abstract class StreamUtils {
* @throws IOException in case of I/O errors * @throws IOException in case of I/O errors
* @since 4.3 * @since 4.3
*/ */
@Contract("null -> fail")
public static int drain(@Nullable InputStream in) throws IOException { public static int drain(@Nullable InputStream in) throws IOException {
Assert.notNull(in, "No InputStream specified"); Assert.notNull(in, "No InputStream specified");
return (int) in.transferTo(OutputStream.nullOutputStream()); return (int) in.transferTo(OutputStream.nullOutputStream());

View File

@ -222,6 +222,7 @@ public class JmsResourceHolder extends ResourceHolderSupport {
* for the given connection, or {@code null} if none. * for the given connection, or {@code null} if none.
*/ */
@Nullable @Nullable
@SuppressWarnings("NullAway")
public <S extends Session> S getSession(Class<S> sessionType, @Nullable Connection connection) { public <S extends Session> S getSession(Class<S> sessionType, @Nullable Connection connection) {
Deque<Session> sessions = Deque<Session> sessions =
(connection != null ? this.sessionsPerConnection.get(connection) : this.sessions); (connection != null ? this.sessionsPerConnection.get(connection) : this.sessions);

View File

@ -344,6 +344,7 @@ public class SimpleMessageListenerContainer extends AbstractMessageListenerConta
* @see #executeListener * @see #executeListener
* @see #setExposeListenerSession * @see #setExposeListenerSession
*/ */
@SuppressWarnings("NullAway")
protected void processMessage(Message message, Session session) { protected void processMessage(Message message, Session session) {
ConnectionFactory connectionFactory = getConnectionFactory(); ConnectionFactory connectionFactory = getConnectionFactory();
boolean exposeResource = (connectionFactory != null && isExposeListenerSession()); boolean exposeResource = (connectionFactory != null && isExposeListenerSession());

View File

@ -92,6 +92,7 @@ final class RSocketServiceMethod {
} }
@Nullable @Nullable
@SuppressWarnings("NullAway")
private static String initRoute( private static String initRoute(
Method method, Class<?> containingClass, RSocketStrategies strategies, Method method, Class<?> containingClass, RSocketStrategies strategies,
@Nullable StringValueResolver embeddedValueResolver) { @Nullable StringValueResolver embeddedValueResolver) {

View File

@ -203,6 +203,7 @@ class PersistenceManagedTypesBeanRegistrationAotProcessor implements BeanRegistr
}); });
} }
@SuppressWarnings("NullAway")
private void registerInstantiatorForReflection(ReflectionHints reflection, @Nullable Annotation annotation) { private void registerInstantiatorForReflection(ReflectionHints reflection, @Nullable Annotation annotation) {
if (annotation == null) { if (annotation == null) {
return; return;

View File

@ -409,7 +409,9 @@ public abstract class TransactionAspectSupport implements BeanFactoryAware, Init
future.get(); future.get();
} }
catch (ExecutionException ex) { catch (ExecutionException ex) {
if (txAttr.rollbackOn(ex.getCause())) { Throwable cause = ex.getCause();
Assert.state(cause != null, "Cause must not be null");
if (txAttr.rollbackOn(cause)) {
status.setRollbackOnly(); status.setRollbackOnly();
} }
} }
@ -901,7 +903,9 @@ public abstract class TransactionAspectSupport implements BeanFactoryAware, Init
@Override @Override
public String toString() { public String toString() {
return getCause().toString(); Throwable cause = getCause();
Assert.state(cause != null, "Cause must not be null");
return cause.toString();
} }
} }

View File

@ -16,6 +16,7 @@
package org.springframework.http; package org.springframework.http;
import org.springframework.lang.Nullable;
import org.springframework.util.InvalidMimeTypeException; import org.springframework.util.InvalidMimeTypeException;
/** /**
@ -36,8 +37,8 @@ public class InvalidMediaTypeException extends IllegalArgumentException {
* @param mediaType the offending media type * @param mediaType the offending media type
* @param message a detail message indicating the invalid part * @param message a detail message indicating the invalid part
*/ */
public InvalidMediaTypeException(String mediaType, String message) { public InvalidMediaTypeException(String mediaType, @Nullable String message) {
super("Invalid media type \"" + mediaType + "\": " + message); super(message != null ? "Invalid media type \"" + mediaType + "\": " + message : "Invalid media type \"" + mediaType);
this.mediaType = mediaType; this.mediaType = mediaType;
} }

View File

@ -205,8 +205,8 @@ public class RequestEntity<T> extends HttpEntity<T> {
if (!super.equals(other)) { if (!super.equals(other)) {
return false; return false;
} }
RequestEntity<?> otherEntity = (RequestEntity<?>) other; return (other instanceof RequestEntity<?> otherEntity &&
return (ObjectUtils.nullSafeEquals(this.method, otherEntity.method) && ObjectUtils.nullSafeEquals(this.method, otherEntity.method) &&
ObjectUtils.nullSafeEquals(this.url, otherEntity.url)); ObjectUtils.nullSafeEquals(this.url, otherEntity.url));
} }
@ -736,8 +736,8 @@ public class RequestEntity<T> extends HttpEntity<T> {
if (!super.equals(other)) { if (!super.equals(other)) {
return false; return false;
} }
UriTemplateRequestEntity<?> otherEntity = (UriTemplateRequestEntity<?>) other; return (other instanceof UriTemplateRequestEntity<?> otherEntity &&
return (ObjectUtils.nullSafeEquals(this.uriTemplate, otherEntity.uriTemplate) && ObjectUtils.nullSafeEquals(this.uriTemplate, otherEntity.uriTemplate) &&
ObjectUtils.nullSafeEquals(this.uriVarsArray, otherEntity.uriVarsArray) && ObjectUtils.nullSafeEquals(this.uriVarsArray, otherEntity.uriVarsArray) &&
ObjectUtils.nullSafeEquals(this.uriVarsMap, otherEntity.uriVarsMap)); ObjectUtils.nullSafeEquals(this.uriVarsMap, otherEntity.uriVarsMap));
} }

View File

@ -162,8 +162,7 @@ public class ResponseEntity<T> extends HttpEntity<T> {
if (!super.equals(other)) { if (!super.equals(other)) {
return false; return false;
} }
ResponseEntity<?> otherEntity = (ResponseEntity<?>) other; return (other instanceof ResponseEntity<?> otherEntity && ObjectUtils.nullSafeEquals(this.status, otherEntity.status));
return ObjectUtils.nullSafeEquals(this.status, otherEntity.status);
} }
@Override @Override

View File

@ -63,6 +63,7 @@ abstract class AbstractStreamingClientHttpRequest extends AbstractClientHttpRequ
} }
@Override @Override
@SuppressWarnings("NullAway")
protected final ClientHttpResponse executeInternal(HttpHeaders headers) throws IOException { protected final ClientHttpResponse executeInternal(HttpHeaders headers) throws IOException {
if (this.body == null && this.bodyStream != null) { if (this.body == null && this.bodyStream != null) {
this.body = outputStream -> this.bodyStream.writeTo(outputStream); this.body = outputStream -> this.bodyStream.writeTo(outputStream);

View File

@ -90,6 +90,7 @@ class JdkClientHttpRequest extends AbstractStreamingClientHttpRequest {
@Override @Override
@SuppressWarnings("NullAway")
protected ClientHttpResponse executeInternal(HttpHeaders headers, @Nullable Body body) throws IOException { protected ClientHttpResponse executeInternal(HttpHeaders headers, @Nullable Body body) throws IOException {
try { try {
HttpRequest request = buildRequest(headers, body); HttpRequest request = buildRequest(headers, body);

View File

@ -69,6 +69,7 @@ class JettyClientHttpRequest extends AbstractStreamingClientHttpRequest {
} }
@Override @Override
@SuppressWarnings("NullAway")
protected ClientHttpResponse executeInternal(HttpHeaders headers, @Nullable Body body) throws IOException { protected ClientHttpResponse executeInternal(HttpHeaders headers, @Nullable Body body) throws IOException {
if (!headers.isEmpty()) { if (!headers.isEmpty()) {
this.request.headers(httpFields -> { this.request.headers(httpFields -> {

View File

@ -138,6 +138,7 @@ public class ServerSentEventHttpMessageReader implements HttpMessageReader<Objec
} }
@Nullable @Nullable
@SuppressWarnings("NullAway")
private Object buildEvent(List<String> lines, ResolvableType valueType, boolean shouldWrap, private Object buildEvent(List<String> lines, ResolvableType valueType, boolean shouldWrap,
Map<String, Object> hints) { Map<String, Object> hints) {

View File

@ -49,6 +49,7 @@ import org.springframework.lang.Nullable;
* @author Arjen Poutsma * @author Arjen Poutsma
* @since 5.3 * @since 5.3
*/ */
@SuppressWarnings("NullAway")
final class MultipartParser extends BaseSubscriber<DataBuffer> { final class MultipartParser extends BaseSubscriber<DataBuffer> {
private static final byte CR = '\r'; private static final byte CR = '\r';
@ -115,6 +116,7 @@ final class MultipartParser extends BaseSubscriber<DataBuffer> {
} }
@Override @Override
@SuppressWarnings("NullAway")
protected void hookOnNext(DataBuffer value) { protected void hookOnNext(DataBuffer value) {
this.requestOutstanding.set(false); this.requestOutstanding.set(false);
this.state.get().onNext(value); this.state.get().onNext(value);

View File

@ -57,6 +57,7 @@ import org.springframework.util.FastByteArrayOutputStream;
* @author Arjen Poutsma * @author Arjen Poutsma
* @since 5.3 * @since 5.3
*/ */
@SuppressWarnings("NullAway")
final class PartGenerator extends BaseSubscriber<MultipartParser.Token> { final class PartGenerator extends BaseSubscriber<MultipartParser.Token> {
private static final Log logger = LogFactory.getLog(PartGenerator.class); private static final Log logger = LogFactory.getLog(PartGenerator.class);

View File

@ -167,6 +167,7 @@ public class ResourceRegionHttpMessageConverter extends AbstractGenericHttpMessa
} }
} }
@SuppressWarnings("NullAway")
private void writeResourceRegionCollection(Collection<ResourceRegion> resourceRegions, private void writeResourceRegionCollection(Collection<ResourceRegion> resourceRegions,
HttpOutputMessage outputMessage) throws IOException { HttpOutputMessage outputMessage) throws IOException {

View File

@ -329,7 +329,8 @@ public abstract class AbstractJackson2HttpMessageConverter extends AbstractGener
} }
// Do not log warning for serializer not found (note: different message wording on Jackson 2.9) // Do not log warning for serializer not found (note: different message wording on Jackson 2.9)
boolean debugLevel = (cause instanceof JsonMappingException && cause.getMessage().startsWith("Cannot find")); boolean debugLevel = (cause instanceof JsonMappingException && cause.getMessage() != null &&
cause.getMessage().startsWith("Cannot find"));
if (debugLevel ? logger.isDebugEnabled() : logger.isWarnEnabled()) { if (debugLevel ? logger.isDebugEnabled() : logger.isWarnEnabled()) {
String msg = "Failed to evaluate Jackson " + (type instanceof JavaType ? "de" : "") + String msg = "Failed to evaluate Jackson " + (type instanceof JavaType ? "de" : "") +

View File

@ -47,6 +47,7 @@ import org.springframework.util.Assert;
* @since 5.0 * @since 5.0
* @param <T> the type of element signaled * @param <T> the type of element signaled
*/ */
@SuppressWarnings("NullAway")
public abstract class AbstractListenerReadPublisher<T> implements Publisher<T> { public abstract class AbstractListenerReadPublisher<T> implements Publisher<T> {
/** /**

View File

@ -40,6 +40,7 @@ import org.springframework.util.Assert;
* @since 5.0 * @since 5.0
* @param <T> the type of element signaled to the {@link Subscriber} * @param <T> the type of element signaled to the {@link Subscriber}
*/ */
@SuppressWarnings("NullAway")
public abstract class AbstractListenerWriteFlushProcessor<T> implements Processor<Publisher<? extends T>, Void> { public abstract class AbstractListenerWriteFlushProcessor<T> implements Processor<Publisher<? extends T>, Void> {
/** /**

View File

@ -43,6 +43,7 @@ import org.springframework.util.StringUtils;
* @since 5.0 * @since 5.0
* @param <T> the type of element signaled to the {@link Subscriber} * @param <T> the type of element signaled to the {@link Subscriber}
*/ */
@SuppressWarnings("NullAway")
public abstract class AbstractListenerWriteProcessor<T> implements Processor<T, Void> { public abstract class AbstractListenerWriteProcessor<T> implements Processor<T, Void> {
/** /**

View File

@ -131,6 +131,7 @@ class ServletServerHttpRequest extends AbstractServerHttpRequest {
return new URI(url.toString()); return new URI(url.toString());
} }
@SuppressWarnings("NullAway")
private static MultiValueMap<String, String> initHeaders( private static MultiValueMap<String, String> initHeaders(
MultiValueMap<String, String> headerValues, HttpServletRequest request) { MultiValueMap<String, String> headerValues, HttpServletRequest request) {

View File

@ -36,6 +36,7 @@ import org.springframework.util.Assert;
* @author Rossen Stoyanchev * @author Rossen Stoyanchev
* @since 5.0 * @since 5.0
*/ */
@SuppressWarnings("NullAway")
class WriteResultPublisher implements Publisher<Void> { class WriteResultPublisher implements Publisher<Void> {
/** /**

View File

@ -489,7 +489,9 @@ final class HttpServiceMethod {
return request -> client.exchangeForEntityFlux(request, bodyType) return request -> client.exchangeForEntityFlux(request, bodyType)
.map(entity -> { .map(entity -> {
Object body = reactiveAdapter.fromPublisher(entity.getBody()); Flux<?> entityBody = entity.getBody();
Assert.state(entityBody != null, "Entity body must not be null");
Object body = reactiveAdapter.fromPublisher(entityBody);
return new ResponseEntity<>(body, entity.getHeaders(), entity.getStatusCode()); return new ResponseEntity<>(body, entity.getHeaders(), entity.getStatusCode());
}); });
} }

View File

@ -177,6 +177,7 @@ public class RequestMappingHandlerMapping extends RequestMappingInfoHandlerMappi
if (this.embeddedValueResolver != null) { if (this.embeddedValueResolver != null) {
prefix = this.embeddedValueResolver.resolveStringValue(prefix); prefix = this.embeddedValueResolver.resolveStringValue(prefix);
} }
Assert.state(prefix != null, "Prefix must not be null");
info = RequestMappingInfo.paths(prefix).options(this.config).build().combine(info); info = RequestMappingInfo.paths(prefix).options(this.config).build().combine(info);
break; break;
} }

View File

@ -141,7 +141,7 @@ public abstract class AbstractMessageConverterMethodArgumentResolver implements
* @throws HttpMediaTypeNotSupportedException if no suitable message converter is found * @throws HttpMediaTypeNotSupportedException if no suitable message converter is found
*/ */
@Nullable @Nullable
@SuppressWarnings({"rawtypes", "unchecked"}) @SuppressWarnings({"rawtypes", "unchecked", "NullAway"})
protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage, MethodParameter parameter, protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage, MethodParameter parameter,
Type targetType) throws IOException, HttpMediaTypeNotSupportedException, HttpMessageNotReadableException { Type targetType) throws IOException, HttpMediaTypeNotSupportedException, HttpMessageNotReadableException {

View File

@ -306,6 +306,7 @@ public class MessageTag extends HtmlEscapingAwareTag implements ArgumentAware {
* Resolve the specified message into a concrete message String. * Resolve the specified message into a concrete message String.
* The returned message String should be unescaped. * The returned message String should be unescaped.
*/ */
@SuppressWarnings("NullAway")
protected String resolveMessage() throws JspException, NoSuchMessageException { protected String resolveMessage() throws JspException, NoSuchMessageException {
MessageSource messageSource = getMessageSource(); MessageSource messageSource = getMessageSource();