Fix Protobuf support - HTTP headers already written

Prior to this commit, the `ProtobufHttpMessageConverter` would call
`outputMessage.getBody()` at the beginning of the `writeInternal`
method, thus writing HTTP headers. Since this method is trying to write
"x-protobuf" headers after that, protobuf support wasn't working
properly for the default "x-protobuf" media type.

Thanks Toshiaki Maki for the repro project!

Also fixed:
* improve `MockHttpOutputMessage` behavior to reproduce the read-only
state of HTTP headers once they've been written.

Issue: SPR-12229
This commit is contained in:
Brian Clozel
2014-09-22 14:02:35 +02:00
parent 2989fe4203
commit b9348bb89c
2 changed files with 12 additions and 7 deletions

View File

@@ -164,19 +164,18 @@ public class ProtobufHttpMessageConverter extends AbstractHttpMessageConverter<M
MediaType contentType = outputMessage.getHeaders().getContentType();
Charset charset = getCharset(contentType);
OutputStreamWriter writer = new OutputStreamWriter(outputMessage.getBody(), charset);
if (MediaType.TEXT_HTML.isCompatibleWith(contentType)) {
HtmlFormat.print(message, writer);
HtmlFormat.print(message, new OutputStreamWriter(outputMessage.getBody(), charset));
}
else if (MediaType.APPLICATION_JSON.isCompatibleWith(contentType)) {
JsonFormat.print(message, writer);
JsonFormat.print(message, new OutputStreamWriter(outputMessage.getBody(), charset));
}
else if (MediaType.TEXT_PLAIN.isCompatibleWith(contentType)) {
TextFormat.print(message, writer);
TextFormat.print(message, new OutputStreamWriter(outputMessage.getBody(), charset));
}
else if (MediaType.APPLICATION_XML.isCompatibleWith(contentType)) {
XmlFormat.print(message, writer);
XmlFormat.print(message, new OutputStreamWriter(outputMessage.getBody(), charset));
}
else if (PROTOBUF.isCompatibleWith(contentType)) {
setProtoHeader(outputMessage, message);
@@ -191,6 +190,8 @@ public class ProtobufHttpMessageConverter extends AbstractHttpMessageConverter<M
/**
* Set the "X-Protobuf-*" HTTP headers when responding with a message of
* content type "application/x-protobuf"
* <p><b>Note:</b> <code>outputMessage.getBody()</code> should not have been called
* before because it writes HTTP headers (making them read only).</p>
*/
private void setProtoHeader(HttpOutputMessage response, Message message) {
response.getHeaders().set(X_PROTOBUF_SCHEMA_HEADER, message.getDescriptorForType().getFile().getName());