XContentFactory.xContentType: allow for possible UTF-8 BOM for JSON XContentType
Fixes #14442
This commit is contained in:
parent
617c0c6a6d
commit
d795ce3b6e
|
@ -329,8 +329,14 @@ public class XContentFactory {
|
||||||
return XContentType.CBOR;
|
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
|
// a last chance for JSON
|
||||||
for (int i = 0; i < length; i++) {
|
for (int i = jsonStart; i < length; i++) {
|
||||||
byte b = bytes.get(i);
|
byte b = bytes.get(i);
|
||||||
if (b == '{') {
|
if (b == '{') {
|
||||||
return XContentType.JSON;
|
return XContentType.JSON;
|
||||||
|
|
|
@ -97,4 +97,18 @@ public class XContentFactoryTests extends ESTestCase {
|
||||||
is = new ByteArrayInputStream(new byte[] {(byte) 1});
|
is = new ByteArrayInputStream(new byte[] {(byte) 1});
|
||||||
assertNull(XContentFactory.xContentType(is));
|
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));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue