|
34 | 34 | import org.springframework.core.codec.Hints;
|
35 | 35 | import org.springframework.core.io.buffer.DataBuffer;
|
36 | 36 | import org.springframework.core.io.buffer.DataBufferFactory;
|
| 37 | +import org.springframework.core.io.buffer.DataBufferUtils; |
37 | 38 | import org.springframework.core.log.LogFormatUtils;
|
38 | 39 | import org.springframework.lang.Nullable;
|
39 | 40 | import org.springframework.util.ClassUtils;
|
@@ -78,27 +79,38 @@ public boolean canEncode(ResolvableType elementType, @Nullable MimeType mimeType
|
78 | 79 | @Override
|
79 | 80 | protected Flux<DataBuffer> encode(Object value, DataBufferFactory dataBufferFactory,
|
80 | 81 | ResolvableType type, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
|
| 82 | + |
| 83 | + if (!Hints.isLoggingSuppressed(hints)) { |
| 84 | + LogFormatUtils.traceDebug(logger, traceOn -> { |
| 85 | + String formatted = LogFormatUtils.formatValue(value, !traceOn); |
| 86 | + return Hints.getLogPrefix(hints) + "Encoding [" + formatted + "]"; |
| 87 | + }); |
| 88 | + } |
| 89 | + |
| 90 | + boolean release = true; |
| 91 | + DataBuffer buffer = dataBufferFactory.allocateBuffer(1024); |
| 92 | + OutputStream outputStream = buffer.asOutputStream(); |
| 93 | + Class<?> clazz = ClassUtils.getUserClass(value); |
| 94 | + |
81 | 95 | try {
|
82 |
| - if (!Hints.isLoggingSuppressed(hints)) { |
83 |
| - LogFormatUtils.traceDebug(logger, traceOn -> { |
84 |
| - String formatted = LogFormatUtils.formatValue(value, !traceOn); |
85 |
| - return Hints.getLogPrefix(hints) + "Encoding [" + formatted + "]"; |
86 |
| - }); |
87 |
| - } |
88 |
| - DataBuffer buffer = dataBufferFactory.allocateBuffer(1024); |
89 |
| - OutputStream outputStream = buffer.asOutputStream(); |
90 |
| - Class<?> clazz = ClassUtils.getUserClass(value); |
91 | 96 | Marshaller marshaller = this.jaxbContexts.createMarshaller(clazz);
|
92 | 97 | marshaller.setProperty(Marshaller.JAXB_ENCODING, StandardCharsets.UTF_8.name());
|
93 | 98 | marshaller.marshal(value, outputStream);
|
| 99 | + release = false; |
94 | 100 | return Flux.just(buffer);
|
95 | 101 | }
|
96 | 102 | catch (MarshalException ex) {
|
97 |
| - return Flux.error(new EncodingException("Could not marshal " + value.getClass() + " to XML", ex)); |
| 103 | + return Flux.error(new EncodingException( |
| 104 | + "Could not marshal " + value.getClass() + " to XML", ex)); |
98 | 105 | }
|
99 | 106 | catch (JAXBException ex) {
|
100 | 107 | return Flux.error(new CodecException("Invalid JAXB configuration", ex));
|
101 | 108 | }
|
| 109 | + finally { |
| 110 | + if (release) { |
| 111 | + DataBufferUtils.release(buffer); |
| 112 | + } |
| 113 | + } |
102 | 114 | }
|
103 | 115 |
|
104 | 116 | }
|
0 commit comments