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:com.marklogic.client.test.SPARQLManagerTest.java

@Test
public void testPagination() throws Exception {
    SPARQLQueryDefinition qdef1 = smgr//from   ww  w. ja  v a2s .c  o  m
            .newQueryDefinition("SELECT ?s ?p ?o FROM <" + graphUri + "> { ?s ?p ?o }");
    qdef1.setIncludeDefaultRulesets(false);
    qdef1.setCollections(graphUri);
    long start = 1;
    smgr.setPageLength(1);
    JacksonHandle handle = new JacksonHandle();
    handle.setMimetype(SPARQLMimeTypes.SPARQL_JSON);
    JsonNode results = smgr.executeSelect(qdef1, handle, start).get();
    JsonNode bindings = results.path("results").path("bindings");
    // because we set pageLength to 1 we should only get one result
    assertEquals(1, bindings.size());
    String uri1 = bindings.get(0).get("s").get("value").asText();

    smgr.setPageLength(2);
    results = smgr.executeSelect(qdef1, new JacksonHandle(), start).get();
    // because we set pageLength to 2 we should get two results
    assertEquals(2, results.path("results").path("bindings").size());

    start = 2;
    results = smgr.executeSelect(qdef1, new JacksonHandle(), start).get();
    bindings = results.path("results").path("bindings");
    // because we skipped the first result (by setting start=2) there are not enough 
    // results for a full page, so size() only returns 1
    assertEquals(1, bindings.size());
    String uri2 = bindings.get(0).get("s").get("value").asText();
    assertNotEquals(uri1, uri2);
}

From source file:org.modeshape.web.jcr.rest.handler.ItemHandlerImpl.java

protected List<JSONChild> getChildren(JsonNode jsonNode) {
    List<JSONChild> children;
    JsonNode childrenNode = jsonNode.get(CHILD_NODE_HOLDER);
    if (childrenNode instanceof ObjectNode) {
        ObjectNode childrenObject = (ObjectNode) childrenNode;
        children = new ArrayList<>(childrenObject.size());
        for (Iterator<?> iterator = childrenObject.fields(); iterator.hasNext();) {
            String childName = iterator.next().toString();
            //it is not possible to have SNS in the object form, so the index will always be 1
            children.add(new JSONChild(childName, childrenObject.get(childName), 1));
        }/*ww w. j ava2  s.  c om*/
        return children;
    } else {
        ArrayNode childrenArray = (ArrayNode) childrenNode;
        children = new ArrayList<>(childrenArray.size());
        Map<String, Integer> visitedNames = new HashMap<>(childrenArray.size());

        for (int i = 0; i < childrenArray.size(); i++) {
            JsonNode child = childrenArray.get(i);
            if (child.size() == 0) {
                continue;
            }
            if (child.size() > 1) {
                logger.warn(
                        "The child object {0} has more than 1 elements, only the first one will be taken into account",
                        child);
            }
            String childName = child.fields().next().toString();
            int sns = visitedNames.containsKey(childName) ? visitedNames.get(childName) + 1 : 1;
            visitedNames.put(childName, sns);

            children.add(new JSONChild(childName, child.get(childName), sns));
        }
        return children;
    }
}

From source file:com.infinities.keystone4j.intergrated.v3.Keystone4jV3IT.java

private void listGrantByGroup(String newGroupId, String newProjectId, String newRoleId)
        throws JsonProcessingException, IOException {
    Response response = target("/v3/projects").path(newProjectId).path("groups").path(newGroupId).path("roles")
            .register(JacksonFeature.class).register(ObjectMapperResolver.class).request()
            .header("X-Auth-Token", getAdminToken()).get();
    assertEquals(200, response.getStatus());
    String ret = response.readEntity(String.class);
    JsonNode node = JsonUtils.convertToJsonNode(ret);
    JsonNode roleList = node.get("roles");
    assertEquals(1, roleList.size());
    JsonNode roleJ = roleList.get(0);//from   ww  w. ja v  a 2s.  c  om
    assertEquals(newRoleId, roleJ.get("id").asText());
}

From source file:com.infinities.keystone4j.intergrated.v3.Keystone4jV3IT.java

private void listGrantByUser(String newUserId, String newProjectId, String newRoleId)
        throws JsonProcessingException, IOException {
    Response response = target("/v3/projects").path(newProjectId).path("users").path(newUserId).path("roles")
            .register(JacksonFeature.class).register(ObjectMapperResolver.class).request()
            .header("X-Auth-Token", getAdminToken()).get();
    assertEquals(200, response.getStatus());
    String ret = response.readEntity(String.class);
    JsonNode node = JsonUtils.convertToJsonNode(ret);
    JsonNode roleList = node.get("roles");
    assertEquals(1, roleList.size());
    JsonNode roleJ = roleList.get(0);//from  ww w  . j a  va 2  s.  c  o m
    assertEquals(newRoleId, roleJ.get("id").asText());
}

From source file:com.infinities.keystone4j.intergrated.v3.Keystone4jV3IT.java

private void listUserProject(String newUserId, String newProjectId, String tokenid)
        throws JsonProcessingException, IOException {
    Response response = target("/v3/users").path(newUserId).path("projects").register(JacksonFeature.class)
            .register(ObjectMapperResolver.class).request().header("X-Auth-Token", tokenid).get();
    assertEquals(200, response.getStatus());
    JsonNode node = JsonUtils.convertToJsonNode(response.readEntity(String.class));
    JsonNode projectsJ = node.get("projects");
    assertEquals(1, projectsJ.size());
    JsonNode projectJ = projectsJ.get(0);
    assertEquals(newProjectId, projectJ.get("id").asText());
}

From source file:com.marklogic.client.test.SPARQLManagerTest.java

@Test
public void testSPARQLWithTwoResults() throws Exception {
    SPARQLQueryDefinition qdef2 = smgr.newQueryDefinition("select ?s ?p ?o { ?s ?p ?o } limit 100");
    qdef2.setIncludeDefaultRulesets(false);
    qdef2.setCollections(graphUri);//  w  ww .  java 2s .c o  m
    JsonNode jsonResults = smgr.executeSelect(qdef2, new JacksonHandle()).get();
    JsonNode tuples = jsonResults.path("results").path("bindings");
    // loop through the "bindings" array (we would call each row a tuple)
    for (int i = 0; i < tuples.size(); i++) {
        JsonNode tuple = tuples.get(i);
        String s = tuple.path("s").path("value").asText();
        String p = tuple.path("p").path("value").asText();
        String o = tuple.path("o").path("value").asText();
        if ("http://example.org/s1".equals(s)) {
            assertEquals("http://example.org/p1", p);
            assertEquals("http://example.org/o1", o);
        } else if ("http://example.org/s2".equals(s)) {
            assertEquals("http://example.org/p2", p);
            assertEquals("http://example.org/o2", o);
        } else {
            fail("Unexpected value for s:[" + s + "]");
        }
    }
}

From source file:org.activiti.rest.service.api.identity.UserInfoResourceTest.java

/**
 * Test getting the collection of info for a user.
 *///from   w  w w .  jav a  2s.  c  o  m
public void testGetUserInfoCollection() throws Exception {
    User savedUser = null;
    try {
        User newUser = identityService.newUser("testuser");
        newUser.setFirstName("Fred");
        newUser.setLastName("McDonald");
        newUser.setEmail("no-reply@activiti.org");
        identityService.saveUser(newUser);
        savedUser = newUser;

        identityService.setUserInfo(newUser.getId(), "key1", "Value 1");
        identityService.setUserInfo(newUser.getId(), "key2", "Value 2");

        CloseableHttpResponse response = executeRequest(
                new HttpGet(SERVER_URL_PREFIX + RestUrls
                        .createRelativeResourceUrl(RestUrls.URL_USER_INFO_COLLECTION, newUser.getId())),
                HttpStatus.SC_OK);
        JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
        closeResponse(response);
        assertNotNull(responseNode);
        assertTrue(responseNode.isArray());
        assertEquals(2, responseNode.size());

        boolean foundFirst = false;
        boolean foundSecond = false;

        for (int i = 0; i < responseNode.size(); i++) {
            ObjectNode info = (ObjectNode) responseNode.get(i);
            assertNotNull(info.get("key").textValue());
            assertNotNull(info.get("url").textValue());

            if (info.get("key").textValue().equals("key1")) {
                foundFirst = true;
                assertTrue(info.get("url").textValue().endsWith(
                        RestUrls.createRelativeResourceUrl(RestUrls.URL_USER_INFO, newUser.getId(), "key1")));
            } else if (info.get("key").textValue().equals("key2")) {
                assertTrue(info.get("url").textValue().endsWith(
                        RestUrls.createRelativeResourceUrl(RestUrls.URL_USER_INFO, newUser.getId(), "key2")));
                foundSecond = true;
            }
        }
        assertTrue(foundFirst);
        assertTrue(foundSecond);

    } finally {

        // Delete user after test passes or fails
        if (savedUser != null) {
            identityService.deleteUser(savedUser.getId());
        }
    }
}

From source file:org.activiti.rest.service.api.runtime.ProcessInstanceVariablesCollectionResourceTest.java

/**
 * Test getting all process variables. GET runtime/process-instances/{processInstanceId}/variables
 *//*from   w  w w  .  j a v a  2s  .c o m*/
@Deployment(resources = {
        "org/activiti/rest/service/api/runtime/ProcessInstanceVariablesCollectionResourceTest.testProcess.bpmn20.xml" })
public void testGetProcessVariables() throws Exception {

    Calendar cal = Calendar.getInstance();

    // Start process with all types of variables
    Map<String, Object> processVariables = new HashMap<String, Object>();
    processVariables.put("stringProcVar", "This is a ProcVariable");
    processVariables.put("intProcVar", 123);
    processVariables.put("longProcVar", 1234L);
    processVariables.put("shortProcVar", (short) 123);
    processVariables.put("doubleProcVar", 99.99);
    processVariables.put("booleanProcVar", Boolean.TRUE);
    processVariables.put("dateProcVar", cal.getTime());
    processVariables.put("byteArrayProcVar", "Some raw bytes".getBytes());
    processVariables.put("overlappingVariable", "process-value");

    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess",
            processVariables);

    // Request all variables (no scope provides) which include global an
    // local
    CloseableHttpResponse response = executeRequest(
            new HttpGet(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(
                    RestUrls.URL_PROCESS_INSTANCE_VARIABLE_COLLECTION, processInstance.getId())),
            HttpStatus.SC_OK);

    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    assertNotNull(responseNode);
    assertTrue(responseNode.isArray());
    assertEquals(9, responseNode.size());
}

From source file:org.flowable.rest.service.api.runtime.ProcessInstanceVariablesCollectionResourceTest.java

/**
 * Test getting all process variables. GET runtime/process-instances/{processInstanceId}/variables
 *///from   w w  w .j ava  2  s.c o m
@Deployment(resources = {
        "org/flowable/rest/service/api/runtime/ProcessInstanceVariablesCollectionResourceTest.testProcess.bpmn20.xml" })
public void testGetProcessVariables() throws Exception {

    Calendar cal = Calendar.getInstance();

    // Start process with all types of variables
    Map<String, Object> processVariables = new HashMap<String, Object>();
    processVariables.put("stringProcVar", "This is a ProcVariable");
    processVariables.put("intProcVar", 123);
    processVariables.put("longProcVar", 1234L);
    processVariables.put("shortProcVar", (short) 123);
    processVariables.put("doubleProcVar", 99.99);
    processVariables.put("booleanProcVar", Boolean.TRUE);
    processVariables.put("dateProcVar", cal.getTime());
    processVariables.put("byteArrayProcVar", "Some raw bytes".getBytes());
    processVariables.put("overlappingVariable", "process-value");

    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess",
            processVariables);

    // Request all variables (no scope provides) which include global an
    // local
    CloseableHttpResponse response = executeRequest(
            new HttpGet(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(
                    RestUrls.URL_PROCESS_INSTANCE_VARIABLE_COLLECTION, processInstance.getId())),
            HttpStatus.SC_OK);

    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    assertNotNull(responseNode);
    assertTrue(responseNode.isArray());
    assertEquals(9, responseNode.size());
}

From source file:org.teavm.flavour.json.test.SerializerTest.java

@Test
public void generatesIds() {
    GraphNode a = new GraphNode();
    GraphNode b = new GraphNode();
    a.successors.add(a);/*from  ww  w.  java 2 s  . c om*/
    a.successors.add(b);
    b.successors.add(a);
    JsonNode node = JSONRunner.serialize(a);

    assertTrue("Should have `@id' property", node.has("@id"));
    int aId = node.get("@id").intValue();

    JsonNode successors = node.get("successors");
    assertEquals(2, successors.size());

    JsonNode firstSuccessor = successors.get(0);
    assertTrue("`successors[0].successors' should be integer", firstSuccessor.isInt());
    assertEquals(aId, firstSuccessor.asInt());

    JsonNode secondSuccessor = successors.get(1);
    assertTrue("Should have `successors[1].successors'", secondSuccessor.has("successors"));
    assertNotEquals(aId, secondSuccessor.get("@id").asInt());

    successors = secondSuccessor.get("successors");
    assertEquals(1, successors.size());

    firstSuccessor = successors.get(0);
    assertTrue("`successors[1].successors[0]' should be integer", firstSuccessor.isInt());
    assertEquals(aId, firstSuccessor.asInt());
}