prevent NPE when calling GetResponse#getSourceAsBytesRef
This commit checks for a null BytesReference as the value for `source` in GetResult#sourceRef and simply returns null. Previously this would have resulted in a NPE. While this does seem internal at first glance, it can affect user code as a GetResponse could trigger this when the document is missing. Additionally, the CompressorFactory#uncompressIfNeeded now requires a non-null argument.
This commit is contained in:
parent
f4884e0726
commit
b04f8fe159
|
@ -28,6 +28,7 @@ import org.elasticsearch.common.xcontent.XContentFactory;
|
|||
import org.elasticsearch.common.xcontent.XContentType;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Objects;
|
||||
|
||||
public class CompressorFactory {
|
||||
|
||||
|
@ -68,9 +69,10 @@ public class CompressorFactory {
|
|||
|
||||
/**
|
||||
* Uncompress the provided data, data can be detected as compressed using {@link #isCompressed(BytesReference)}.
|
||||
* @throws NullPointerException a NullPointerException will be thrown when bytes is null
|
||||
*/
|
||||
public static BytesReference uncompressIfNeeded(BytesReference bytes) throws IOException {
|
||||
Compressor compressor = compressor(bytes);
|
||||
Compressor compressor = compressor(Objects.requireNonNull(bytes, "the BytesReference must not be null"));
|
||||
BytesReference uncompressed;
|
||||
if (compressor != null) {
|
||||
uncompressed = uncompress(bytes, compressor);
|
||||
|
|
|
@ -54,7 +54,7 @@ public class GetResult implements Streamable, Iterable<GetField>, ToXContentObje
|
|||
private static final String _VERSION = "_version";
|
||||
private static final String FOUND = "found";
|
||||
private static final String FIELDS = "fields";
|
||||
|
||||
|
||||
private String index;
|
||||
private String type;
|
||||
private String id;
|
||||
|
@ -135,6 +135,10 @@ public class GetResult implements Streamable, Iterable<GetField>, ToXContentObje
|
|||
* Returns bytes reference, also un compress the source if needed.
|
||||
*/
|
||||
public BytesReference sourceRef() {
|
||||
if (source == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
this.source = CompressorFactory.uncompressIfNeeded(this.source);
|
||||
return this.source;
|
||||
|
|
|
@ -79,6 +79,17 @@ public class GetResultTests extends ESTestCase {
|
|||
}
|
||||
}
|
||||
|
||||
public void testGetSourceAsBytes() {
|
||||
XContentType xContentType = randomFrom(XContentType.values());
|
||||
Tuple<GetResult, GetResult> tuple = randomGetResult(xContentType);
|
||||
GetResult getResult = tuple.v1();
|
||||
if (getResult.isExists()) {
|
||||
assertNotNull(getResult.sourceRef());
|
||||
} else {
|
||||
assertNull(getResult.sourceRef());
|
||||
}
|
||||
}
|
||||
|
||||
public void testEqualsAndHashcode() {
|
||||
checkEqualsAndHashCode(randomGetResult(XContentType.JSON).v1(), GetResultTests::copyGetResult, GetResultTests::mutateGetResult);
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue