Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix ignoring trailing content in JsonUtils #12862

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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')");
}
}