Skip to content

Commit 01827fd

Browse files
committed
Ensure response not closed by MappingJackson2HttpMessageConverter
Closes gh-25987
1 parent af1d721 commit 01827fd

File tree

2 files changed

+9
-2
lines changed

2 files changed

+9
-2
lines changed

spring-web/src/main/java/org/springframework/http/converter/json/AbstractJackson2HttpMessageConverter.java

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818

1919
import java.io.IOException;
2020
import java.io.InputStreamReader;
21+
import java.io.OutputStream;
2122
import java.io.Reader;
2223
import java.lang.reflect.Type;
2324
import java.nio.charset.Charset;
@@ -55,6 +56,8 @@
5556
import org.springframework.http.converter.HttpMessageNotWritableException;
5657
import org.springframework.lang.Nullable;
5758
import org.springframework.util.Assert;
59+
import org.springframework.util.CollectionUtils;
60+
import org.springframework.util.StreamUtils;
5861
import org.springframework.util.TypeUtils;
5962

6063
/**
@@ -308,7 +311,8 @@ protected void writeInternal(Object object, @Nullable Type type, HttpOutputMessa
308311
MediaType contentType = outputMessage.getHeaders().getContentType();
309312
JsonEncoding encoding = getJsonEncoding(contentType);
310313

311-
try (JsonGenerator generator = this.objectMapper.getFactory().createGenerator(outputMessage.getBody(), encoding)) {
314+
OutputStream outputStream = StreamUtils.nonClosing(outputMessage.getBody());
315+
try (JsonGenerator generator = this.objectMapper.getFactory().createGenerator(outputStream, encoding)) {
312316
writePrefix(generator, object);
313317

314318
Object value = object;

spring-web/src/test/java/org/springframework/http/converter/json/MappingJackson2HttpMessageConverterTests.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2019 the original author or authors.
2+
* Copyright 2002-2020 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -47,6 +47,8 @@
4747
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
4848
import static org.assertj.core.api.Assertions.entry;
4949
import static org.assertj.core.api.Assertions.within;
50+
import static org.mockito.Mockito.never;
51+
import static org.mockito.Mockito.verify;
5052

5153
/**
5254
* Jackson 2.x converter tests.
@@ -149,6 +151,7 @@ public void write() throws IOException {
149151
assertThat(result.contains("\"bool\":true")).isTrue();
150152
assertThat(result.contains("\"bytes\":\"AQI=\"")).isTrue();
151153
assertThat(outputMessage.getHeaders().getContentType()).as("Invalid content-type").isEqualTo(MediaType.APPLICATION_JSON);
154+
verify(outputMessage.getBody(), never()).close();
152155
}
153156

154157
@Test

0 commit comments

Comments
 (0)