From 2530efd1c7fc241a9ba24ca4b83aefbbad186402 Mon Sep 17 00:00:00 2001 From: rstoyanchev Date: Wed, 20 Sep 2023 17:52:52 +0100 Subject: [PATCH] SseEmitter support for multiline String Closes gh-30965 --- .../web/servlet/mvc/method/annotation/SseEmitter.java | 3 +++ .../servlet/mvc/method/annotation/SseEmitterTests.java | 10 ++++++++++ 2 files changed, 13 insertions(+) diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/SseEmitter.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/SseEmitter.java index 836e1d2b23..a9cda6ce6f 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/SseEmitter.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/SseEmitter.java @@ -237,6 +237,9 @@ public class SseEmitter extends ResponseBodyEmitter { public SseEventBuilder data(Object object, @Nullable MediaType mediaType) { append("data:"); saveAppendedText(); + if (object instanceof String text) { + object = StringUtils.replace(text, "\n", "\ndata:"); + } this.dataToSend.add(new DataWithMediaType(object, mediaType)); append('\n'); return this; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/SseEmitterTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/SseEmitterTests.java index 570986e056..5ea4b498ad 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/SseEmitterTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/SseEmitterTests.java @@ -104,6 +104,16 @@ public class SseEmitterTests { this.handler.assertWriteCount(1); } + @Test + public void sendEventWithMultiline() throws Exception { + this.emitter.send(event().data("foo\nbar\nbaz")); + this.handler.assertSentObjectCount(3); + this.handler.assertObject(0, "data:", TEXT_PLAIN_UTF8); + this.handler.assertObject(1, "foo\ndata:bar\ndata:baz"); + this.handler.assertObject(2, "\n\n", TEXT_PLAIN_UTF8); + this.handler.assertWriteCount(1); + } + @Test public void sendEventFull() throws Exception { this.emitter.send(event().comment("blah").name("test").reconnectTime(5000L).id("1").data("foo"));