1 package com.fasterxml.jackson.databind.node;
2 
3 import java.util.*;
4 
5 import com.fasterxml.jackson.databind.BaseMapTest;
6 import com.fasterxml.jackson.databind.JsonNode;
7 import com.fasterxml.jackson.databind.node.ObjectNode;
8 
9 public class TestFindMethods
10     extends BaseMapTest
11 {
testNonMatching()12     public void testNonMatching() throws Exception
13     {
14         JsonNode root = _buildTree();
15 
16         assertNull(root.findValue("boogaboo"));
17         assertNull(root.findParent("boogaboo"));
18         JsonNode n = root.findPath("boogaboo");
19         assertNotNull(n);
20         assertTrue(n.isMissingNode());
21 
22         assertTrue(root.findValues("boogaboo").isEmpty());
23         assertTrue(root.findParents("boogaboo").isEmpty());
24     }
25 
testMatchingSingle()26     public void testMatchingSingle() throws Exception
27     {
28         JsonNode root = _buildTree();
29 
30         JsonNode node = root.findValue("b");
31         assertNotNull(node);
32         assertEquals(3, node.intValue());
33         node = root.findParent("b");
34         assertNotNull(node);
35         assertTrue(node.isObject());
36         assertEquals(1, ((ObjectNode) node).size());
37         assertEquals(3, node.path("b").intValue());
38     }
39 
testMatchingMultiple()40     public void testMatchingMultiple() throws Exception
41     {
42         JsonNode root = _buildTree();
43 
44         List<JsonNode> nodes = root.findValues("value");
45         assertEquals(2, nodes.size());
46         // here we count on nodes being returned in order; true with Jackson:
47         assertEquals(3, nodes.get(0).intValue());
48         assertEquals(42, nodes.get(1).intValue());
49 
50         nodes = root.findParents("value");
51         assertEquals(2, nodes.size());
52         // should only return JSON Object nodes:
53         assertTrue(nodes.get(0).isObject());
54         assertTrue(nodes.get(1).isObject());
55         assertEquals(3, nodes.get(0).path("value").intValue());
56         assertEquals(42, nodes.get(1).path("value").intValue());
57 
58         // and finally, convenience conversion method
59         List<String> values = root.findValuesAsText("value");
60         assertEquals(2, values.size());
61         assertEquals("3", values.get(0));
62         assertEquals("42", values.get(1));
63     }
64 
_buildTree()65     private JsonNode _buildTree() throws Exception
66     {
67         final String SAMPLE = "{ \"a\" : { \"value\" : 3 },"
68             +"\"array\" : [ { \"b\" : 3 }, {\"value\" : 42}, { \"other\" : true } ]"
69             +"}";
70         return objectMapper().readTree(SAMPLE);
71     }
72 }
73