From e9998bf7c6d7579a42b92006c5cfbd2f56bc92f6 Mon Sep 17 00:00:00 2001 From: Scott Leberknight <174812+sleberknight@users.noreply.github.com> Date: Thu, 9 Jan 2020 19:01:26 -0500 Subject: [PATCH] Fix NPE in DataFormatMatcher#getMatchedFormatName when no match exists (#591) Change DataFormatMatcher#getMatchedFormatName so it does what the Javadoc says to avoid NPE for non-match; add unit tests to verify. --- .../core/format/DataFormatMatcher.java | 2 +- .../core/format/DataFormatMatcherTest.java | 20 +++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/fasterxml/jackson/core/format/DataFormatMatcher.java b/src/main/java/com/fasterxml/jackson/core/format/DataFormatMatcher.java index 73586440f9..38a699b85c 100644 --- a/src/main/java/com/fasterxml/jackson/core/format/DataFormatMatcher.java +++ b/src/main/java/com/fasterxml/jackson/core/format/DataFormatMatcher.java @@ -91,7 +91,7 @@ public MatchStrength getMatchStrength() { * */ public String getMatchedFormatName() { - return _match.getFormatName(); + return hasMatch() ? getMatch().getFormatName() : null; } /* diff --git a/src/test/java/com/fasterxml/jackson/core/format/DataFormatMatcherTest.java b/src/test/java/com/fasterxml/jackson/core/format/DataFormatMatcherTest.java index 948d7803fa..479fd83f24 100644 --- a/src/test/java/com/fasterxml/jackson/core/format/DataFormatMatcherTest.java +++ b/src/test/java/com/fasterxml/jackson/core/format/DataFormatMatcherTest.java @@ -35,4 +35,24 @@ public void testCreatesDataFormatMatcherTwo() throws IOException { verifyException(e, "Illegal start/length"); } } + + public void testGetMatchedFormatNameReturnsNameWhenMatches() { + DataFormatMatcher dataFormatMatcher = new DataFormatMatcher(null, + new byte[2], + 1, + 0, + new JsonFactory(), + MatchStrength.SOLID_MATCH); + assertEquals(JsonFactory.FORMAT_NAME_JSON, dataFormatMatcher.getMatchedFormatName()); + } + + public void testGetMatchedFormatNameReturnsNullWhenNoMatch() { + DataFormatMatcher dataFormatMatcher = new DataFormatMatcher(null, + new byte[2], + 1, + 0, + null, + MatchStrength.NO_MATCH); + assertNull(dataFormatMatcher.getMatchedFormatName()); + } }