diff --git a/jetty-core/jetty-util/src/main/java/org/eclipse/jetty/util/Fields.java b/jetty-core/jetty-util/src/main/java/org/eclipse/jetty/util/Fields.java index e4ef26d45bda..d9e087dba071 100644 --- a/jetty-core/jetty-util/src/main/java/org/eclipse/jetty/util/Fields.java +++ b/jetty-core/jetty-util/src/main/java/org/eclipse/jetty/util/Fields.java @@ -190,8 +190,9 @@ public List getValuesOrEmpty(String name) */ public void put(String name, String value) { + String v = value == null ? "" : value; // Preserve the case for the field name - Field field = new Field(name, value); + Field field = new Field(name, v); fields.put(name, field); } @@ -218,13 +219,14 @@ public void put(Field field) */ public void add(String name, String value) { + String v = value == null ? "" : value; fields.compute(name, (k, f) -> { if (f == null) // Preserve the case for the field name - return new Field(name, value); + return new Field(name, v); else - return new Field(f.getName(), f.getValues(), value); + return new Field(f.getName(), f.getValues(), v); }); } @@ -246,13 +248,30 @@ public void add(String name, String... values) fields.compute(name, (k, f) -> { if (f == null) - return new Field(name, List.of(values)); + return new Field(name, toList(values)); else - return new Field(f.getName(), f.getValues(), List.of(values)); + return new Field(f.getName(), f.getValues(), toList(values)); }); } } + static List toList(String... strings) + { + try + { + return List.of(strings); + } + catch (NullPointerException e) + { + List result = new ArrayList<>(strings.length); + for (String s : strings) + { + result.add(s == null ? "" : s); + } + return Collections.unmodifiableList(result); + } + } + /** *

Adds the given field, storing it if none exists for the given name, * or adding all the values to the existing field with the given name.

diff --git a/jetty-core/jetty-util/src/test/java/org/eclipse/jetty/util/FieldsTest.java b/jetty-core/jetty-util/src/test/java/org/eclipse/jetty/util/FieldsTest.java index 33465d73acaf..9f16e78aafc2 100644 --- a/jetty-core/jetty-util/src/test/java/org/eclipse/jetty/util/FieldsTest.java +++ b/jetty-core/jetty-util/src/test/java/org/eclipse/jetty/util/FieldsTest.java @@ -82,4 +82,18 @@ public void testIterator() assertThat(set, containsInAnyOrder("x", "y", "z")); } + + @Test + public void testNullValues() + { + Fields fields = new Fields(); + fields.add("x", (String)null); + fields.add("y", "1", null, "2"); + fields.put("z", null); + + assertThat(fields.getSize(), equalTo(3)); + assertThat(fields.getValues("x"), contains("")); + assertThat(fields.getValues("y"), contains("1", "", "2")); + assertThat(fields.getValues("z"), contains("")); + } }