XContentFactory.xContentType: allow for possible UTF-8 BOM for JSON XContentType

Fixes #14442
This commit is contained in:
Camilo Díaz Repka 2015-11-09 00:45:25 -03:00 committed by Daniel Mitterdorfer
parent 617c0c6a6d
commit d795ce3b6e
2 changed files with 21 additions and 1 deletions

View File

@ -329,8 +329,14 @@ public class XContentFactory {
return XContentType.CBOR;
}
int jsonStart = 0;
// JSON may be preceded by UTF-8 BOM
if (length > 3 && first == (byte) 0xEF && bytes.get(1) == (byte) 0xBB && bytes.get(2) == (byte) 0xBF) {
jsonStart = 3;
}
// a last chance for JSON
for (int i = 0; i < length; i++) {
for (int i = jsonStart; i < length; i++) {
byte b = bytes.get(i);
if (b == '{') {
return XContentType.JSON;

View File

@ -97,4 +97,18 @@ public class XContentFactoryTests extends ESTestCase {
is = new ByteArrayInputStream(new byte[] {(byte) 1});
assertNull(XContentFactory.xContentType(is));
}
public void testJsonFromBytesOptionallyPrecededByUtf8Bom() throws Exception {
byte[] bytes = new byte[] {(byte) '{', (byte) '}'};
assertThat(XContentFactory.xContentType(bytes), equalTo(XContentType.JSON));
bytes = new byte[] {(byte) 0x20, (byte) '{', (byte) '}'};
assertThat(XContentFactory.xContentType(bytes), equalTo(XContentType.JSON));
bytes = new byte[] {(byte) 0xef, (byte) 0xbb, (byte) 0xbf, (byte) '{', (byte) '}'};
assertThat(XContentFactory.xContentType(bytes), equalTo(XContentType.JSON));
bytes = new byte[] {(byte) 0xef, (byte) 0xbb, (byte) 0xbf, (byte) 0x20, (byte) '{', (byte) '}'};
assertThat(XContentFactory.xContentType(bytes), equalTo(XContentType.JSON));
}
}