Example usage for com.fasterxml.jackson.databind JsonNode size

List of usage examples for com.fasterxml.jackson.databind JsonNode size

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind JsonNode size.

Prototype

public int size() 

Source Link

Usage

From source file:org.apache.solr.kelvin.testcases.SimpleCondition.java

public List<ConditionFailureTestEvent> verifyConditions(ITestCase testCase, Properties queryParams,
        Map<String, Object> decodedResponses, Object testSpecificArgument) {
    List<ConditionFailureTestEvent> ret = new ArrayList<ConditionFailureTestEvent>();
    ArrayNode results = new ArrayNode(null);
    if (decodedResponses.containsKey(XmlDoclistExtractorResponseAnalyzer.DOC_LIST)) {
        results = (ArrayNode) decodedResponses.get(XmlDoclistExtractorResponseAnalyzer.DOC_LIST);
    }/*from  w  w w  . ja v a  2s .co  m*/
    int lengthToCheck = getLengthToCheck(results);
    for (int i = 0; i < lengthToCheck; i++) {
        if (results.size() <= i) {
            ret.add(new MissingResultTestEvent(testCase, queryParams, "result set too short", i));
        } else {
            JsonNode row = results.get(i);
            boolean allFields = true;
            for (String field : this.fields) {
                if (!hasField(row, field)) {
                    ret.add(new MissingFieldTestEvent(testCase, queryParams,
                            "missing field from result - " + field, i));
                    allFields = false;
                }
            }
            if (allFields) {
                String allText = "";
                for (String field : fields) {
                    JsonNode fieldValue = getField(row, field);
                    if (fieldValue.isArray()) {
                        for (int j = 0; j < fieldValue.size(); j++) {
                            allText = allText + " " + fieldValue.get(j);
                        }
                        //checkAllWords(testCase, queryParams, ret, i,
                        //      allText);

                    } else {
                        String stringFieldValue = fieldValue.asText();
                        allText = allText + " " + stringFieldValue;
                    }
                }
                checkAllWords(testCase, queryParams, ret, i, allText);
            }
        }
    }
    return ret;
}

From source file:org.n52.tamis.core.test.serialize.ExecuteInputBodySerializer_Test.java

@Test
public void testExecuteBodySerialization() {

    try {// w w w.  j  a v a2s  . com
        String execBodyJsonOutput = mapper.writeValueAsString(executeBody);
        System.out.println(execBodyJsonOutput);

        JsonNode parsedJsonExecBody = mapper.readTree(execBodyJsonOutput);
        JsonNode executeNode = parsedJsonExecBody.get("Execute");

        /*
         * the expected structure of the parsed JSON node looks like:
         * 
         * { "Execute": { "Identifier":
         * "org.n52.wps.server.algorithm.test.EchoProcess", "Input": [ {
         * "Reference": { "_mimeType": "text/xml", "_href":
         * "http://geoprocessing.demo.52north.org:8080/geoserver/wfs?SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&TYPENAME=topp:tasmania_roads&SRS=EPSG:4326&OUTPUTFORMAT=GML3"
         * }, "_id": "complexInput" } ], "output":[{ "_mimeType":
         * "text/xml", "_id": "complexOutput", "_transmission": "reference"
         * }], "_service": "WPS", "_version": "2.0.0"} }
         * 
         */

        Assert.assertTrue(executeNode.has("Identifier"));
        Assert.assertTrue(executeNode.has("Input"));
        Assert.assertTrue(executeNode.has("output"));
        Assert.assertTrue(executeNode.has("_service"));
        Assert.assertTrue(executeNode.has("_version"));

        Assert.assertEquals("example.processId", executeNode.get("Identifier").asText());
        Assert.assertEquals("WPS", executeNode.get("_service").asText());

        JsonNode inputs = executeNode.get("Input");

        Assert.assertTrue(inputs.isArray());
        Assert.assertTrue(inputs.size() == 2);
        /*
         * the actual structure of Input content is tested in a different
         * JUnit test case (ExecuteInputSerialier_Test)
         */

        /*
         * test output
         */
        JsonNode outputs = executeNode.get("output");
        Assert.assertTrue(outputs.isArray());

        JsonNode singleOutput = outputs.get(0);
        Assert.assertEquals("application/json", singleOutput.get("_mimeType").asText());
        Assert.assertEquals("executeOutputID", singleOutput.get("_id").asText());

    } catch (JsonProcessingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:ac.ucy.cs.spdx.service.Compatibility.java

@POST
@Path("/node/")
@Consumes(MediaType.TEXT_PLAIN)//w w w  .ja  v  a2s.  c  om
@Produces(MediaType.APPLICATION_JSON)
public String addNode(String jsonString) {

    ObjectMapper mapper = new ObjectMapper();
    JsonNode licenseNode = null;
    try {
        licenseNode = mapper.readTree(jsonString);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    ArrayList<String> licenses = new ArrayList<String>();
    String nodeIdentifier = licenseNode.get("nodeIdentifier").toString();
    nodeIdentifier = nodeIdentifier.substring(1, nodeIdentifier.length() - 1);

    String nodeCategory = licenseNode.get("nodeCategory").toString();
    nodeCategory = nodeCategory.substring(1, nodeCategory.length() - 1);
    Category category = Category.UNCATEGORIZED;

    if (nodeCategory == "PERMISSIVE") {
        category = Category.PERMISSIVE;
    } else if (nodeCategory == "WEAK_COPYLEFT") {
        category = Category.WEAK_COPYLEFT;
    } else if (nodeCategory == "STRONG_COPYLEFT") {
        category = Category.STRONG_COPYLEFT;
    } else {
        category = Category.UNCATEGORIZED;
    }

    JsonNode licensesJSON = licenseNode.get("nodelicenses");

    for (int i = 0; i < licensesJSON.size(); i++) {
        String licenseId = licensesJSON.get(i).get("identifier").toString();
        licenseId = licenseId.substring(1, licenseId.length() - 1);
        licenses.add(licenseId);
    }

    try {
        LicenseGraph.addLicenseNode(nodeIdentifier, category, licenses.toArray(new String[licenses.size()]));
    } catch (LicenseNodeAlreadyExistsException e) {
        e.printStackTrace();
        return "{\"status\":\"failure\",\"message\":\"" + e.getMessage() + "\"}";
    }

    LicenseGraph.exportGraph();

    return "{\"status\":\"success\",\"message\":\"" + nodeIdentifier + " added in the system.\"}";// {"nodeIdentifier":"Caldera","nodeCategory":"PERMISSIVE","nodelicenses":[{"identifier":"Caldera"}]}
}

From source file:org.flowable.rest.api.runtime.TaskSubTaskCollectionResourceTest.java

/**
 * Test getting all sub tasks. GET runtime/tasks/{taskId}/subtasks
 *///w ww .  j ava  2  s  .c  o  m
public void testGetSubTasks() throws Exception {

    Task parentTask = taskService.newTask();
    parentTask.setName("parent task");
    taskService.saveTask(parentTask);

    Task subTask = taskService.newTask();
    subTask.setName("sub task 1");
    subTask.setParentTaskId(parentTask.getId());
    taskService.saveTask(subTask);

    Task subTask2 = taskService.newTask();
    subTask2.setName("sub task 2");
    subTask2.setParentTaskId(parentTask.getId());
    taskService.saveTask(subTask2);

    // Request all sub tasks
    CloseableHttpResponse response = executeRequest(
            new HttpGet(SERVER_URL_PREFIX + RestUrls
                    .createRelativeResourceUrl(RestUrls.URL_TASK_SUBTASKS_COLLECTION, parentTask.getId())),
            HttpStatus.SC_OK);
    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    assertNotNull(responseNode);
    assertTrue(responseNode.isArray());
    assertEquals(2, responseNode.size());

    boolean foundSubtask1 = false;
    boolean foundSubtask2 = false;
    for (int i = 0; i < responseNode.size(); i++) {
        JsonNode var = responseNode.get(i);
        if ("sub task 1".equals(var.get("name").asText())) {
            foundSubtask1 = true;
            assertEquals(subTask.getId(), var.get("id").asText());
        } else if ("sub task 2".equals(var.get("name").asText())) {
            foundSubtask2 = true;
            assertEquals(subTask2.getId(), var.get("id").asText());
        }
    }
    assertTrue(foundSubtask1);
    assertTrue(foundSubtask2);

    taskService.deleteTask(parentTask.getId());
    taskService.deleteTask(subTask.getId());
    taskService.deleteTask(subTask2.getId());

    historyService.deleteHistoricTaskInstance(parentTask.getId());
    historyService.deleteHistoricTaskInstance(subTask.getId());
    historyService.deleteHistoricTaskInstance(subTask2.getId());
}

From source file:com.github.fge.jackson.JsonNumEquals.java

private boolean arrayEquals(final JsonNode a, final JsonNode b) {
    /*/*w  w  w  .  j a v a  2s .  co m*/
     * We are guaranteed here that arrays are the same size.
     */
    final int size = a.size();

    for (int i = 0; i < size; i++)
        if (!doEquivalent(a.get(i), b.get(i)))
            return false;

    return true;
}

From source file:org.jboss.aerogear.sync.diffmatchpatch.JsonMapperTest.java

@Test
public void serializeEditsWithArray() {
    final String documentId = "1234";
    final String clientId = "client1";
    final PatchMessage<DiffMatchPatchEdit> patchMessage = patchMessage(documentId, clientId,
            DiffMatchPatchEdit.withChecksum("bogus")
                    .diff(new DiffMatchPatchDiff(Operation.UNCHANGED, "{\"content\": [\"one\", \""))
                    .diff(new DiffMatchPatchDiff(Operation.ADD, "tw"))
                    .diff(new DiffMatchPatchDiff(Operation.UNCHANGED, "o"))
                    .diff(new DiffMatchPatchDiff(Operation.DELETE, "ne"))
                    .diff(new DiffMatchPatchDiff(Operation.UNCHANGED, "\"]}")).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(5));//from   w  w w  .j av a2  s .c o m
    assertThat(diffs.get(0).get("operation").asText(), equalTo("UNCHANGED"));
    assertThat(diffs.get(0).get("text").asText(), equalTo("{\"content\": [\"one\", \""));
    assertThat(diffs.get(1).get("operation").asText(), equalTo("ADD"));
    assertThat(diffs.get(1).get("text").asText(), equalTo("tw"));
    assertThat(diffs.get(2).get("operation").asText(), equalTo("UNCHANGED"));
    assertThat(diffs.get(2).get("text").asText(), equalTo("o"));
    assertThat(diffs.get(3).get("operation").asText(), equalTo("DELETE"));
    assertThat(diffs.get(3).get("text").asText(), equalTo("ne"));
    assertThat(diffs.get(4).get("operation").asText(), equalTo("UNCHANGED"));
    assertThat(diffs.get(4).get("text").asText(), equalTo("\"]}"));
}

From source file:org.jboss.aerogear.sync.diffmatchpatch.JsonMapperTest.java

@Test
public void serializeEditsWithArrayToJsonAndBack() {
    final String documentId = "1234";
    final String clientId = "client1";
    final PatchMessage<DiffMatchPatchEdit> patchMessage = patchMessage(documentId, clientId,
            DiffMatchPatchEdit.withChecksum("bogus")
                    .diff(new DiffMatchPatchDiff(Operation.UNCHANGED, "{\"content\": [\"one\", \""))
                    .diff(new DiffMatchPatchDiff(Operation.ADD, "tw"))
                    .diff(new DiffMatchPatchDiff(Operation.UNCHANGED, "o"))
                    .diff(new DiffMatchPatchDiff(Operation.DELETE, "ne"))
                    .diff(new DiffMatchPatchDiff(Operation.UNCHANGED, "\"]}")).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(5));/*www.  jav a 2s  .  c  o  m*/
    assertThat(diffs.get(0).get("operation").asText(), equalTo("UNCHANGED"));
    assertThat(diffs.get(0).get("text").asText(), equalTo("{\"content\": [\"one\", \""));
    assertThat(diffs.get(1).get("operation").asText(), equalTo("ADD"));
    assertThat(diffs.get(1).get("text").asText(), equalTo("tw"));
    assertThat(diffs.get(2).get("operation").asText(), equalTo("UNCHANGED"));
    assertThat(diffs.get(2).get("text").asText(), equalTo("o"));
    assertThat(diffs.get(3).get("operation").asText(), equalTo("DELETE"));
    assertThat(diffs.get(3).get("text").asText(), equalTo("ne"));
    assertThat(diffs.get(4).get("operation").asText(), equalTo("UNCHANGED"));
    assertThat(diffs.get(4).get("text").asText(), equalTo("\"]}"));
}

From source file:io.gravitee.definition.jackson.datatype.api.deser.RuleDeserializer.java

@Override
public Rule deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    JsonNode node = jp.getCodec().readTree(jp);

    Rule rule = new Rule();

    node.fieldNames().forEachRemaining(field -> {
        JsonNode subNode = node.findValue(field);

        switch (field) {
        case "methods":
            if (subNode != null && subNode.isArray()) {
                HttpMethod[] methods = new HttpMethod[subNode.size()];

                final int[] idx = { 0 };
                subNode.elements().forEachRemaining(jsonNode -> {
                    methods[idx[0]++] = HttpMethod.valueOf(jsonNode.asText().toUpperCase());
                });/* w  w  w  .j a  v  a2s . co  m*/

                rule.getMethods().addAll(Arrays.asList(methods));
            }
            break;
        case "description":
            if (subNode != null) {
                rule.setDescription(subNode.asText());
            }
            break;
        case "enabled":
            if (subNode != null) {
                rule.setEnabled(subNode.asBoolean(true));
            }
            break;
        default:
            // We are in the case of a policy
            Policy policy = new Policy();

            policy.setName(field);
            policy.setConfiguration(subNode.toString());

            rule.setPolicy(policy);

            break;
        }
    });

    if (rule.getMethods().isEmpty()) {
        rule.getMethods()
                .addAll(Arrays.asList(HttpMethod.CONNECT, HttpMethod.DELETE, HttpMethod.GET, HttpMethod.HEAD,
                        HttpMethod.OPTIONS, HttpMethod.PATCH, HttpMethod.POST, HttpMethod.PUT,
                        HttpMethod.TRACE));
    }

    return rule;
}

From source file:com.infinities.keystone4j.admin.v3.user.UserV3ResourceTest.java

@Test
public void testListGroupsForUser() throws JsonProcessingException, IOException {
    final List<Group> groups = new ArrayList<Group>();
    groups.add(group);/*from www  .java2s.co  m*/

    Response response = target("/v3/users").path("e7912c2225e84ac5905d8cf0b5040a6f").path("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());
    String ret = response.readEntity(String.class);
    System.err.println(ret);
    JsonNode node = JsonUtils.convertToJsonNode(ret);
    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.getDomain().getId(), groupJ.get("domain_id").asText());
}

From source file:com.infinities.keystone4j.admin.v3.domain.DomainResourceTest.java

@Test
public void testListGrantByUser() throws JsonProcessingException, IOException {
    final List<Role> roles = new ArrayList<Role>();
    roles.add(role1);//from w ww . j  a  v a2s. com
    Response response = target("/v3/domains").path(domain.getId()).path("users").path(user.getId())
            .path("roles").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());
    String ret = response.readEntity(String.class);
    System.err.println(ret);
    JsonNode node = JsonUtils.convertToJsonNode(ret);
    JsonNode roleJ = node.get("roles");
    assertEquals(1, roleJ.size());
}