List of usage examples for com.fasterxml.jackson.databind JsonNode size
public int size()
From source file:com.infinities.keystone4j.admin.v3.group.GroupResourceTest.java
@Test public void testListGroups() throws JsonProcessingException, IOException { final List<Group> groups = new ArrayList<Group>(); groups.add(group);/*from w ww . jav a 2s . c om*/ Response response = target("/v3/groups").register(JacksonFeature.class).register(ObjectMapperResolver.class) .request() .header("X-Auth-Token", Config.Instance.getOpt(Config.Type.DEFAULT, "admin_token").asText()).get(); assertEquals(200, response.getStatus()); JsonNode node = JsonUtils.convertToJsonNode(response.readEntity(String.class)); JsonNode groupsJ = node.get("groups"); assertEquals(1, groupsJ.size()); JsonNode groupJ = groupsJ.get(0); assertEquals(group.getId(), groupJ.get("id").asText()); assertEquals(group.getName(), groupJ.get("name").asText()); assertEquals(group.getDescription(), groupJ.get("description").asText()); assertEquals(group.getDomain().getId(), groupJ.get("domain_id").asText()); assertNotNull(groupJ.get("links")); assertNotNull(groupJ.get("links").get("self").asText()); }
From source file:com.ikanow.aleph2.v1.document_db.utils.TestJsonNodeBsonUtils.java
@Test public void test_mapWritableWrapper() { final ObjectMapper mapper = BeanTemplateUtils.configureMapper(Optional.empty()); final BasicDBObject m1 = new BasicDBObject(); m1.put("test1", true); final BasicDBObject m2 = new BasicDBObject(); m2.put("nested", m1); m2.put("test2", "test2"); final BasicDBList a1 = new BasicDBList(); a1.add(4);//from www .ja v a2 s. com a1.add(5); final BasicDBList a2 = new BasicDBList(); a2.add(m1); a2.add(m1); m2.put("array", a2); m1.put("array", a1); final JsonNode j2 = JsonNodeBsonUtils.from(m2); assertEquals(3, j2.size()); // Check j's contents assertEquals(Stream.of("nested", "test2", "array").sorted().collect(Collectors.toList()), Optionals.streamOf(j2.fieldNames(), false).sorted().collect(Collectors.toList())); assertEquals("test2", j2.get("test2").asText()); final JsonNode j1 = j2.get("nested"); assertEquals(2, j1.size()); final JsonNode j1b = JsonNodeBsonUtils.from(m1); assertTrue("entrySet wrong: " + j1b.toString(), "{\"test1\":true,\"array\":[4,5]}".equals(j1b.toString()) || "{\"array\":[4,5],\"test1\":true}".equals(j1b.toString())); //(tests entrySet) final ArrayNode an = mapper.createArrayNode(); an.add(mapper.convertValue(4, JsonNode.class)); an.add(mapper.convertValue(5, JsonNode.class)); assertEquals(Arrays.asList(mapper.convertValue(true, JsonNode.class), an), Optionals.streamOf(((ObjectNode) j1).elements(), false).collect(Collectors.toList())); // OK, now test adding: assertEquals(2, j1.size()); final ObjectNode o1 = (ObjectNode) j1; o1.put("added", "added_this"); final ObjectNodeWrapper o1c = (ObjectNodeWrapper) o1; assertFalse(o1c.containsKey("not_present")); assertTrue(o1c.containsKey("added")); assertTrue(o1c.containsKey("test1")); assertEquals(Stream.of("test1", "array", "added").sorted().collect(Collectors.toList()), Optionals.streamOf(j1.fieldNames(), false).sorted().collect(Collectors.toList())); assertEquals( Arrays.asList(mapper.convertValue(true, JsonNode.class), an, mapper.convertValue("added_this", JsonNode.class)), Optionals.streamOf(((ObjectNode) j1).elements(), false).collect(Collectors.toList())); assertTrue(j1.toString().contains("added_this")); assertTrue(j1.toString().contains("4,5")); assertEquals(mapper.convertValue("added_this", JsonNode.class), j1.get("added")); assertEquals(3, j1.size()); // OK now test removing: assertEquals(null, o1.remove("not_present")); assertEquals(mapper.convertValue(true, JsonNode.class), o1.remove("test1")); assertEquals(2, o1.size()); ObjectNode o1b = o1.remove(Arrays.asList("added", "array")); assertEquals(0, o1.size()); assertEquals(0, o1b.size()); o1.setAll(JsonNodeBsonUtils.from(m1)); // will be minus one object assertEquals(2, o1.size()); assertTrue(o1c.containsValue(mapper.convertValue(true, JsonNode.class))); assertFalse(o1c.containsValue("banana")); final ObjectNodeWrapper o2 = (ObjectNodeWrapper) JsonNodeBsonUtils.from(m2); assertFalse(o2.isEmpty()); assertTrue(o2.containsKey("array")); assertFalse(o2.containsValue("array")); assertTrue(o2.containsValue(mapper.convertValue("test2", JsonNode.class))); assertEquals(TextNode.class, o2.remove("test2").getClass()); assertEquals(2, o2.size()); o2.removeAll(); assertEquals(0, o2.size()); }
From source file:com.redhat.lightblue.eval.ArrayAddExpressionEvaluatorTest.java
@Test public void object_array_append() throws Exception { UpdateExpression expr = EvalTestContext.updateExpressionFromJson( " [ {'$append' : { 'field7' : {} } }, {'$set': {'field7.-1.elemf1':'value'}} ]"); Updater updater = Updater.getInstance(JSON_NODE_FACTORY, md, expr); updater.update(doc, md.getFieldTreeRoot(), new Path()); JsonNode f7 = doc.get(new Path("field7")); Assert.assertEquals(5, f7.size()); Assert.assertEquals("value", f7.get(4).get("elemf1").asText()); }
From source file:cat.calidos.morfeu.model.injection.ContentSaverParserIntTest.java
@Test public void testSaveToYAML() throws Exception { String outputPath = temporaryOutputFilePath() + ".yaml"; URI outputURI = new URI("file://" + outputPath); FileSaver saver = DaggerContentSaverParserComponent.builder().from(content).to(outputURI).having(contentURI) .model(modelURI).withModelFetchedFrom(modelFetchableURI).build().saver().get(); saver.save();//from w w w . ja v a2 s . c om File savedFile = new File(outputPath); assertTrue("Saver component did not create a file", savedFile.exists()); savedFile.deleteOnExit(); String writtenContent = FileUtils.readFileToString(savedFile, Config.DEFAULT_CHARSET); YAMLMapper mapper = new YAMLMapper(); JsonNode yaml = mapper.readTree(writtenContent); assertNotNull(yaml); assertTrue(yaml.isObject()); assertTrue(yaml.has("rows")); JsonNode rows = yaml.get("rows"); //rows assertNotNull(rows); assertTrue(rows.isArray()); assertEquals(1, rows.size()); }
From source file:com.crushpaper.DbJsonBackupForUserTest.java
@Test public void test4() throws IOException { final TestEntrySet before = new TestEntrySet(new TestEntry[] { new TestEntry("1", new TestEntry[] { new TestEntry("2", 2), new TestEntry("3", 3) }) }); final ObjectMapper mapper = new ObjectMapper(); final JsonNode node1 = mapper .readTree("{\n" + "\"note\": \"3\",\n" + "\"modTime\": 3,\n" + "\"createTime\": 3,\n" + "\"id\": \"S5\",\n" + "\"type\": \"note\",\n" + "\"parentId\": \"S3\"\n" + "}"); final JsonNode node2 = mapper.readTree("{\n" + "\"note\": \"2\",\n" + "\"modTime\": 2,\n" + "\"createTime\": 2,\n" + "\"id\": \"S4\",\n" + "\"type\": \"note\",\n" + "\"parentId\": \"S3\",\n" + "\"nextSiblingId\": \"S5\"\n" + "}"); final JsonNode node3 = mapper.readTree("{\n" + "\"note\": \"1\",\n" + "\"modTime\": 1,\n" + "\"createTime\": 1,\n" + "\"id\": \"S3\",\n" + "\"type\": \"root\"\n" + "}\n"); final Errors errors = new Errors(); try {/*from w ww . j av a 2 s. c o m*/ final User user = dbLogic.getOrCreateUser("user"); assertTrue(dbLogic.addEntries(before, user, createTime, errors)); dbLogic.commit(); final StringBuilder result = new StringBuilder(); dbLogic.backupJsonForUser(user, result); final JsonNode resultNode = mapper.readTree(result.toString()); assertTrue(resultNode.isObject()); final JsonNode entriesNodes = resultNode.get("entries"); assertTrue(entriesNodes.isArray()); assertEquals(3, entriesNodes.size()); boolean matched1 = false, matched2 = false, matched3 = false; for (int i = 0; i < 3; ++i) { final JsonNode obj = entriesNodes.get(i); if (obj.equals(node1)) { matched1 = true; } else if (obj.equals(node2)) { matched2 = true; } else if (obj.equals(node3)) { matched3 = true; } } assertTrue(matched1); assertTrue(matched2); assertTrue(matched3); } catch (final IOException e) { assertTrue(false); } }
From source file:com.arpnetworking.test.junitbenchmarks.JsonBenchmarkConsumerTest.java
@Test public void testNormalBenchmarkCase() throws IOException { final Path path = Paths.get("target/tmp/test/testConsumer.json"); path.toFile().deleteOnExit();/*from w w w .ja va2s . c o m*/ Files.deleteIfExists(path); final JsonBenchmarkConsumer consumer = new JsonBenchmarkConsumer(path); final Result result = DataCreator.createResult(); consumer.accept(result); consumer.close(); // Read the file back in as json final ObjectMapper mapper = ObjectMapperFactory.getInstance(); final JsonNode resultsArray = mapper.readTree(path.toFile()); Assert.assertEquals(1, resultsArray.size()); final JsonNode augmentedResultNode = resultsArray.get(0); Assert.assertTrue(augmentedResultNode.isObject()); final JsonNode resultNode = augmentedResultNode.get("result"); Assert.assertTrue(resultNode.isObject()); Assert.assertEquals("com.arpnetworking.test.junitbenchmarks.JsonBenchmarkConsumerTest", resultNode.get("testClassName").asText()); Assert.assertEquals("testNormalBenchmarkCase", resultNode.get("testMethodName").asText()); Assert.assertEquals(result.benchmarkRounds, resultNode.get("benchmarkRounds").asInt()); Assert.assertEquals(result.warmupRounds, resultNode.get("warmupRounds").asInt()); Assert.assertEquals(result.warmupTime, resultNode.get("warmupTime").asInt()); Assert.assertEquals(result.benchmarkTime, resultNode.get("benchmarkTime").asInt()); Assert.assertTrue(resultNode.get("roundAverage").isObject()); final ObjectNode roundAverageNode = (ObjectNode) resultNode.get("roundAverage"); Assert.assertEquals(result.roundAverage.avg, roundAverageNode.get("avg").asDouble(), 0.0001d); Assert.assertEquals(result.roundAverage.stddev, roundAverageNode.get("stddev").asDouble(), 0.0001d); Assert.assertTrue(resultNode.get("blockedAverage").isObject()); final ObjectNode blockedAverageNode = (ObjectNode) resultNode.get("blockedAverage"); Assert.assertEquals(result.blockedAverage.avg, blockedAverageNode.get("avg").asDouble(), 0.0001d); Assert.assertEquals(result.blockedAverage.stddev, blockedAverageNode.get("stddev").asDouble(), 0.0001d); Assert.assertTrue(resultNode.get("gcAverage").isObject()); final ObjectNode gcAverageNode = (ObjectNode) resultNode.get("gcAverage"); Assert.assertEquals(result.gcAverage.avg, gcAverageNode.get("avg").asDouble(), 0.0001d); Assert.assertEquals(result.gcAverage.stddev, gcAverageNode.get("stddev").asDouble(), 0.0001d); Assert.assertTrue(resultNode.get("gcInfo").isObject()); final ObjectNode gcInfoNode = (ObjectNode) resultNode.get("gcInfo"); Assert.assertEquals(result.gcInfo.accumulatedInvocations(), gcInfoNode.get("accumulatedInvocations").asInt()); Assert.assertEquals(result.gcInfo.accumulatedTime(), gcInfoNode.get("accumulatedTime").asInt()); Assert.assertEquals(result.getThreadCount(), resultNode.get("threadCount").asInt()); }
From source file:org.jboss.aerogear.sync.diffmatchpatch.JsonMapperTest.java
@Test public void asJsonNode() { final String json = "{\"content\": [\"one\", \"two\"]}"; final JsonNode jsonNode = JsonMapper.asJsonNode(json); final JsonNode contentNode = jsonNode.get("content"); assertThat(contentNode.isArray(), is(true)); assertThat(contentNode.size(), is(2)); final Iterator<JsonNode> elements = contentNode.elements(); assertThat(elements.next().asText(), equalTo("one")); assertThat(elements.next().asText(), equalTo("two")); }
From source file:ac.ucy.cs.spdx.service.Compatibility.java
@POST @Path("/edge/") @Consumes(MediaType.TEXT_PLAIN)/*from ww w. j a va 2s. co m*/ @Produces(MediaType.APPLICATION_JSON) public String addEdge(String jsonString) { ObjectMapper mapper = new ObjectMapper(); JsonNode licenseEdge = null; try { licenseEdge = mapper.readTree(jsonString); } catch (JsonProcessingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } ArrayList<String> licenseNodes = new ArrayList<String>(); String nodeIdentifier = licenseEdge.get("nodeIdentifier").toString(); nodeIdentifier = nodeIdentifier.substring(1, nodeIdentifier.length() - 1); String transitivity = licenseEdge.get("transitivity").toString(); transitivity = transitivity.substring(1, transitivity.length() - 1); Boolean isTransitive = Boolean.parseBoolean(transitivity); JsonNode nodesJSON = licenseEdge.get("nodeIdentifiers"); for (int i = 0; i < nodesJSON.size(); i++) { String node = nodesJSON.get(i).get("identifier").toString(); node = node.substring(1, node.length() - 1); licenseNodes.add(node); } try { LicenseGraph.connectNode(isTransitive, nodeIdentifier, licenseNodes.toArray(new String[licenseNodes.size()])); } catch (LicenseEdgeAlreadyExistsException e) { e.printStackTrace(); return "{\"status\":\"failure\",\"message\":\"" + e.getMessage() + "\"}"; } LicenseGraph.exportGraph(); return "{\"status\":\"success\",\"message\":\"" + nodeIdentifier + " -> " + licenseNodes.toString() + " added in the system.\"}";// {"nodeIdentifier":"Caldera","transitivity":"true","nodeIdentifiers":[{"identifier":"Apache-2.0"}]} }
From source file:com.ikanow.aleph2.search_service.elasticsearch.utils.TestJsonNodeWritableUtils.java
@SuppressWarnings("deprecation") @Test// ww w . ja v a 2s . c o m public void test_mapWritableWrapper() { final ObjectMapper mapper = BeanTemplateUtils.configureMapper(Optional.empty()); final MapWritable m1 = new MapWritable(); m1.put(new Text("test1"), new BooleanWritable(true)); final MapWritable m2 = new MapWritable(); m2.put(new Text("nested"), m1); m2.put(new Text("test2"), new Text("test2")); final ArrayWritable a1 = new ArrayWritable(IntWritable.class); a1.set(new Writable[] { new IntWritable(4), new IntWritable(5) }); final ArrayWritable a2 = new ArrayWritable(MapWritable.class); a2.set(new Writable[] { m1, m1 }); m2.put(new Text("array"), a2); m1.put(new Text("array"), a1); final JsonNode j2 = JsonNodeWritableUtils.from(m2); assertEquals(3, j2.size()); // Check j's contents assertEquals(Stream.of("nested", "test2", "array").sorted().collect(Collectors.toList()), Optionals.streamOf(j2.fieldNames(), false).sorted().collect(Collectors.toList())); assertEquals("test2", j2.get("test2").asText()); final JsonNode j1 = j2.get("nested"); assertEquals(2, j1.size()); final JsonNode j1b = JsonNodeWritableUtils.from(m1); assertTrue("{\"test1\":true,\"array\":[4,5]}".equals(j1b.toString()) || "{\"array\":[4,5],\"test1\":true}".equals(j1b.toString())); //(tests entrySet) final ArrayNode an = mapper.createArrayNode(); an.add(mapper.convertValue(4, JsonNode.class)); an.add(mapper.convertValue(5, JsonNode.class)); assertEquals(Arrays.asList(mapper.convertValue(true, JsonNode.class), an), Optionals.streamOf(((ObjectNode) j1).elements(), false).collect(Collectors.toList())); // OK, now test adding: assertEquals(2, j1.size()); final ObjectNode o1 = (ObjectNode) j1; o1.put("added", "added_this"); final ObjectNodeWrapper o1c = (ObjectNodeWrapper) o1; assertFalse(o1c.containsKey("not_present")); assertTrue(o1c.containsKey("added")); assertTrue(o1c.containsKey("test1")); assertEquals(Stream.of("test1", "array", "added").sorted().collect(Collectors.toList()), Optionals.streamOf(j1.fieldNames(), false).sorted().collect(Collectors.toList())); assertEquals( Arrays.asList(mapper.convertValue(true, JsonNode.class), an, mapper.convertValue("added_this", JsonNode.class)), Optionals.streamOf(((ObjectNode) j1).elements(), false).collect(Collectors.toList())); assertTrue(j1.toString().contains("added_this")); assertTrue(j1.toString().contains("4,5")); assertEquals(mapper.convertValue("added_this", JsonNode.class), j1.get("added")); assertEquals(3, j1.size()); // OK now test removing: assertEquals(null, o1.remove("not_present")); assertEquals(mapper.convertValue(true, JsonNode.class), o1.remove("test1")); assertEquals(2, o1.size()); ObjectNode o1b = o1.remove(Arrays.asList("added", "array")); assertEquals(0, o1.size()); assertEquals(0, o1b.size()); o1.putAll(JsonNodeWritableUtils.from(m1)); // will be minus one object assertEquals(2, o1.size()); assertTrue(o1c.containsValue(mapper.convertValue(true, JsonNode.class))); assertFalse(o1c.containsValue("banana")); final ObjectNodeWrapper o2 = (ObjectNodeWrapper) JsonNodeWritableUtils.from(m2); assertFalse(o2.isEmpty()); assertTrue(o2.containsKey("array")); assertFalse(o2.containsValue("array")); assertTrue(o2.containsValue(mapper.convertValue("test2", JsonNode.class))); assertEquals(TextNode.class, o2.remove("test2").getClass()); assertEquals(2, o2.size()); o2.removeAll(); assertEquals(0, o2.size()); }
From source file:org.jboss.aerogear.sync.diffmatchpatch.JsonMapperTest.java
@Test public void serializeEdits() { final String documentId = "1234"; final String clientId = "client1"; final PatchMessage<DiffMatchPatchEdit> patchMessage = patchMessage(documentId, clientId, DiffMatchPatchEdit.withChecksum("bogus") .diff(new DiffMatchPatchDiff(Operation.UNCHANGED, "version")) .diff(new DiffMatchPatchDiff(Operation.DELETE, "1")) .diff(new DiffMatchPatchDiff(Operation.ADD, "2")).build()); final String json = JsonMapper.toJson(patchMessage); final JsonNode jsonNode = JsonMapper.asJsonNode(json); assertThat(jsonNode.get("msgType").asText(), equalTo("patch")); assertThat(jsonNode.get("id").asText(), equalTo(documentId)); assertThat(jsonNode.get("clientId").asText(), equalTo(clientId)); final JsonNode editsNode = jsonNode.get("edits"); assertThat(editsNode.isArray(), is(true)); assertThat(editsNode.size(), is(1)); final JsonNode edit = editsNode.iterator().next(); assertThat(edit.get("serverVersion").asText(), equalTo("0")); assertThat(edit.get("clientVersion").asText(), equalTo("0")); final JsonNode diffs = edit.get("diffs"); assertThat(diffs.isArray(), is(true)); assertThat(diffs.size(), is(3));/* ww w . j a v a 2 s .c o m*/ }