Skip to content

Commit 4c382be

Browse files
committed
Handle empty inputs for JSON better
We now return `null` instead of throwing an exception if we attempt to read from an inputstream that doesn't have any JSON content.
1 parent 960e168 commit 4c382be

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

java/client/src/org/openqa/selenium/json/JsonInput.java

+7
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,13 @@ public void skipValue() {
286286
}
287287

288288
public <T> T read(Type type) {
289+
skipWhitespace(input);
290+
291+
// Guard against reading an empty stream
292+
if (input.peek() == Input.EOF) {
293+
return null;
294+
}
295+
289296
return coercer.coerce(this, type, setter);
290297
}
291298

java/client/test/org/openqa/selenium/json/JsonInputTest.java

+31
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
package org.openqa.selenium.json;
1919

20+
import static java.nio.charset.StandardCharsets.UTF_8;
2021
import static org.assertj.core.api.Assertions.assertThat;
2122
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
2223
import static org.openqa.selenium.json.Json.MAP_TYPE;
@@ -35,7 +36,13 @@
3536
import org.junit.experimental.categories.Category;
3637
import org.openqa.selenium.testing.UnitTests;
3738

39+
import java.io.ByteArrayInputStream;
40+
import java.io.IOException;
41+
import java.io.InputStream;
42+
import java.io.InputStreamReader;
43+
import java.io.Reader;
3844
import java.io.StringReader;
45+
import java.nio.charset.StandardCharsets;
3946
import java.util.Map;
4047
import java.util.Random;
4148
import java.util.stream.Collectors;
@@ -258,6 +265,30 @@ public void shouldBeAbleToReadNonWellFormedDataLongerThanReadBuffer() {
258265
raw, raw.substring(raw.length() - 128)));
259266
}
260267

268+
@Test
269+
public void nullInputsShouldCoerceAsNullValues() throws IOException {
270+
try (InputStream is = new ByteArrayInputStream(new byte[0]);
271+
Reader reader = new InputStreamReader(is, UTF_8);
272+
JsonInput input = new Json().newInput(reader)) {
273+
274+
Object value = input.read(MAP_TYPE);
275+
276+
assertThat(value).isNull();
277+
}
278+
}
279+
280+
@Test
281+
public void emptyStringsWithNoJsonValuesComeBackAsNull() throws IOException {
282+
try (InputStream is = new ByteArrayInputStream(" ".getBytes(UTF_8));
283+
Reader reader = new InputStreamReader(is, UTF_8);
284+
JsonInput input = new Json().newInput(reader)) {
285+
286+
Object value = input.read(String.class);
287+
288+
assertThat(value).isNull();
289+
}
290+
}
291+
261292
private JsonInput newInput(String raw) {
262293
StringReader reader = new StringReader(raw);
263294
return new JsonInput(reader, new JsonTypeCoercer(), BY_NAME);

0 commit comments

Comments
 (0)