diff --git a/spring-web/src/main/java/org/springframework/http/codec/ServerSentEvent.java b/spring-web/src/main/java/org/springframework/http/codec/ServerSentEvent.java index 1daf5607cca..dc90690e711 100644 --- a/spring-web/src/main/java/org/springframework/http/codec/ServerSentEvent.java +++ b/spring-web/src/main/java/org/springframework/http/codec/ServerSentEvent.java @@ -267,8 +267,10 @@ public final class ServerSentEvent { } private static void checkEvent(String content) { - Assert.isTrue(content.indexOf('\n') == -1 && content.indexOf('\r') == -1, - "illegal character '\\n' or '\\r' in event content"); + if (content != null) { + Assert.isTrue(content.indexOf('\n') == -1 && content.indexOf('\r') == -1, + "illegal character '\\n' or '\\r' in event content"); + } } @Override diff --git a/spring-web/src/test/java/org/springframework/http/codec/ServerSentEventTests.java b/spring-web/src/test/java/org/springframework/http/codec/ServerSentEventTests.java index a106ea07337..7d6f1b4d9a5 100644 --- a/spring-web/src/test/java/org/springframework/http/codec/ServerSentEventTests.java +++ b/spring-web/src/test/java/org/springframework/http/codec/ServerSentEventTests.java @@ -18,10 +18,12 @@ package org.springframework.http.codec; import java.util.stream.Stream; +import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** @@ -44,6 +46,18 @@ class ServerSentEventTests { ServerSentEvent.builder().event("first" + newLine + "second").build()); } + @Test // gh-36634 + void allowsNullId() { + ServerSentEvent event = ServerSentEvent.builder().id(null).event("first").build(); + assertThat(event.format()).contains("event:first").doesNotContain("id"); + } + + @Test // gh-36634 + void allowsNullEvent() { + ServerSentEvent event = ServerSentEvent.builder().id("42").event(null).build(); + assertThat(event.format()).contains("id:42").doesNotContain("event"); + } + private static Stream newLineCharacters() { return Stream.of( Arguments.of("\n", "LF"),