Skip to content

Commit

Permalink
Fix ignoring trailing content in JsonUtils
Browse files Browse the repository at this point in the history
Similar to commit a7bc2ba, but in
plugin toolkit's `JsonUtils`.
  • Loading branch information
findepi committed Jun 20, 2022
1 parent d515f33 commit 88ced23
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
*/
package io.trino.plugin.base.util;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
Expand Down Expand Up @@ -81,6 +82,10 @@ public static <T> T jsonTreeToValue(JsonNode treeNode, Class<T> javaType)
static <T> T parseJson(byte[] jsonBytes, Class<T> javaType)
throws IOException
{
return OBJECT_MAPPER.readValue(jsonBytes, javaType);
try (JsonParser parser = OBJECT_MAPPER.createParser(jsonBytes)) {
T value = OBJECT_MAPPER.readValue(parser, javaType);
checkArgument(parser.nextToken() == null, "Found characters after the expected end of input");
return value;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
package io.trino.plugin.base.util;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParseException;
import org.testng.annotations.Test;

import java.io.IOException;
Expand All @@ -22,6 +23,7 @@
import static io.trino.plugin.base.util.TestJsonUtils.TestEnum.OPTION_A;
import static java.nio.charset.StandardCharsets.US_ASCII;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

public class TestJsonUtils
{
Expand All @@ -44,4 +46,17 @@ public void testLowercaseEnum()
TestObject parsed = parseJson("{\"testEnum\": \"option_a\"}".getBytes(US_ASCII), TestObject.class);
assertThat(parsed.testEnum).isEqualTo(OPTION_A);
}

@Test
public void testTrailingContent()
throws IOException
{
assertThatThrownBy(() -> parseJson("{} {}}".getBytes(US_ASCII), TestObject.class))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Found characters after the expected end of input");

assertThatThrownBy(() -> parseJson("{} not even a JSON here".getBytes(US_ASCII), TestObject.class))
.isInstanceOf(JsonParseException.class)
.hasMessageStartingWith("Unrecognized token 'not': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')");
}
}

0 comments on commit 88ced23

Please sign in to comment.