Skip to content

Commit 1807e05

Browse files
committed
Merge pull request #7 from lopopolo/add-op-class-cast-exception
Ensure JsonNodes are ContainerNodes in AddOperation The existing code only checked the parent node of the target path but failed to account for the node itself not being a container node.
2 parents b4f5480 + 1ec9bbb commit 1807e05

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

src/main/java/com/github/fge/jsonpatch/AddOperation.java

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -91,9 +91,13 @@ public JsonNode apply(final JsonNode node)
9191
if (parentNode.isMissingNode())
9292
throw new JsonPatchException(BUNDLE.getMessage(
9393
"jsonPatch.noSuchParent"));
94-
return parentNode.isArray()
95-
? addToArray(path, node)
96-
: addToObject(path, node);
94+
if (parentNode.isArray())
95+
return addToArray(path, node);
96+
else if (parentNode.isObject())
97+
return addToObject(path, node);
98+
else
99+
throw new JsonPatchException(BUNDLE.getMessage(
100+
"jsonPatch.noSuchPath"));
97101
}
98102

99103
private JsonNode addToArray(final JsonPointer path, final JsonNode node)

src/test/java/com/github/fge/jsonpatch/AddOperationTest.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,13 @@
1818

1919
package com.github.fge.jsonpatch;
2020

21+
import com.fasterxml.jackson.databind.node.ObjectNode;
22+
import com.fasterxml.jackson.databind.node.TextNode;
23+
import com.github.fge.jackson.JacksonUtils;
24+
import com.github.fge.jackson.jsonpointer.JsonPointer;
25+
import com.github.fge.jackson.jsonpointer.JsonPointerException;
26+
import org.testng.annotations.Test;
27+
2128
import java.io.IOException;
2229

2330
public final class AddOperationTest
@@ -28,4 +35,16 @@ public AddOperationTest()
2835
{
2936
super("add");
3037
}
38+
39+
@Test(expectedExceptions = JsonPatchException.class, expectedExceptionsMessageRegExp = "no such path in target JSON document")
40+
public void addingToANonContainerNodeThrowsException()
41+
throws JsonPatchException, JsonPointerException
42+
{
43+
final ObjectNode node = JacksonUtils.nodeFactory().objectNode();
44+
final TextNode textNode = JacksonUtils.nodeFactory().textNode("bar");
45+
node.put("foo", textNode);
46+
final JsonPointer p = new JsonPointer("/foo/f");
47+
final JsonPatchOperation op = new AddOperation(p, JacksonUtils.nodeFactory().nullNode());
48+
op.apply(node);
49+
}
3150
}

0 commit comments

Comments
 (0)