Forbid null converters in RestTemplate & HttpMessageConverterExtractor

Prior to this commit, RestTemplate and HttpMessageConverterExtractor did
not validate that the supplied HttpMessageConverter list contained no
null elements, which can lead to a NullPointerException when the
converters are accessed.

This commit improves the user experience by failing immediately if the
supplied HttpMessageConverter list contains a null element. This applies
to constructors for RestTemplate and HttpMessageConverterExtractor as
well as to RestTemplate#setMessageConverters().

Note, however, that RestTemplate#getMessageConverters() returns a mutable
list. Thus, if a user modifies that list so that it contains null values,
that will still lead to a NullPointerException when the converters are
accessed.

This commit also introduces noNullElements() variants for collections in
org.springframework.util.Assert.

Closes gh-23151
This commit is contained in:
Sam Brannen
2019-06-18 15:56:50 +03:00
parent 8ceac9c015
commit 4000b244ff
5 changed files with 102 additions and 61 deletions

View File

@@ -495,6 +495,47 @@ public abstract class Assert {
"[Assertion failed] - this collection must not be empty: it must contain at least 1 element");
}
/**
* Assert that a collection contains no {@code null} elements.
* <p>Note: Does not complain if the collection is empty!
* <pre class="code">Assert.noNullElements(collection, "Collection must contain non-null elements");</pre>
* @param collection the collection to check
* @param message the exception message to use if the assertion fails
* @throws IllegalArgumentException if the collection contains a {@code null} element
* @since 5.2
*/
public static void noNullElements(@Nullable Collection<?> collection, String message) {
if (collection != null) {
for (Object element : collection) {
if (element == null) {
throw new IllegalArgumentException(message);
}
}
}
}
/**
* Assert that a collection contains no {@code null} elements.
* <p>Note: Does not complain if the collection is empty!
* <pre class="code">
* Assert.noNullElements(collection, () -&gt; "Collection " + collectionName + " must contain non-null elements");
* </pre>
* @param collection the collection to check
* @param messageSupplier a supplier for the exception message to use if the
* assertion fails
* @throws IllegalArgumentException if the collection contains a {@code null} element
* @since 5.2
*/
public static void noNullElements(@Nullable Collection<?> collection, Supplier<String> messageSupplier) {
if (collection != null) {
for (Object element : collection) {
if (element == null) {
throw new IllegalArgumentException(nullSafeGet(messageSupplier));
}
}
}
}
/**
* Assert that a Map contains entries; that is, it must not be {@code null}
* and must contain at least one entry.