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.bna.ezrxlookup.service.OpenFdaService.java

/**
 * Retrieve set of <code>DrugLabel</code> from JSON response
 * @param response/*w  w  w .  j  a  v  a 2s.c o  m*/
 * @return TreeSet with DrugLabel objects
 */
public Set<DrugLabel> getDrugLabelResults(String jsonResponse) throws Exception {
    Set<DrugLabel> labelList = new TreeSet<DrugLabel>();

    if (StringUtils.isEmpty(jsonResponse))
        return labelList;

    try {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(jsonResponse);
        JsonNode resultsNodes = rootNode.path(RESULTS_TAG);
        LOG.debug("Results size : " + resultsNodes.size());

        Iterator<JsonNode> elements = resultsNodes.elements();

        while (elements.hasNext()) {
            JsonNode aResultsNode = elements.next(); // results node
            JsonNode openFdaNode = aResultsNode.get(OPENFDA_TAG);

            DrugLabel label = new DrugLabel();
            label.setId(aResultsNode.path(ID_TAG).asText());
            label.setVersion(aResultsNode.path(VERSION_TAG).asText());
            label.setBrandName(openFdaNode.get(BRAND_NAME_TAG).elements().next().asText());
            label.setManufactureName(openFdaNode.get(MFR_NAME_TAG).elements().next().asText());

            labelList.add(label);
        }
    } catch (IOException e) {
        LOG.error(e);
        throw e;
    }

    LOG.debug(labelList);
    return labelList;
}

From source file:org.opendaylight.nemo.renderer.cli.physicalnetwork.PhysicalResourceLoaderTest.java

@Test
public void testBuildLinks() throws Exception {
    List<PhysicalLink> list;
    Class<PhysicalResourceLoader> class1 = PhysicalResourceLoader.class;
    Method method = class1.getDeclaredMethod("buildLinks", new Class[] { JsonNode.class });
    method.setAccessible(true);//w w w  .  java2s .  com

    JsonNode linksRoot = mock(JsonNode.class);
    JsonNode links = mock(JsonNode.class);
    JsonNode link = mock(JsonNode.class);
    JsonNode link_temp_buildlink = mock(JsonNode.class);

    when(linksRoot.path(any(String.class))).thenReturn(links);
    when(links.size()).thenReturn(1);
    when(links.get(any(Integer.class))).thenReturn(link);
    //get into method "build link" args(link)
    when(link.get(any(String.class))).thenReturn(link_temp_buildlink);
    when(link_temp_buildlink.asText()).thenReturn(new String("1"))//new PhysicalLinkId(strLinkId)
            .thenReturn(new String("2"))//new PhysicalNodeId
            .thenReturn(new String("3"))//new PhysicalPortId
            .thenReturn(new String("4"))//new PhysicalNodeId
            .thenReturn(new String("5"))//new PhysicalPortId
            .thenReturn(new String(""));//linkNode.get("link-bandwidth").asText().equals("")
    when(link_temp_buildlink.asLong()).thenReturn((long) 1);

    list = (List<PhysicalLink>) method.invoke(physicalResourceLoader, linksRoot);
    Assert.assertTrue(list.size() == 1);
    verify(link_temp_buildlink, times(6)).asText();
}

From source file:org.activiti.rest.service.api.history.HistoricProcessInstanceCommentResourceTest.java

/**
 * Test getting all comments for a historic process instance. GET history/historic-process-instances/{processInstanceId}/comments
 *///from w ww.j  a  v a 2s.  c  o  m
@Deployment(resources = { "org/activiti/rest/service/api/repository/oneTaskProcess.bpmn20.xml" })
public void testGetComments() throws Exception {
    ProcessInstance pi = null;

    try {
        pi = runtimeService.startProcessInstanceByKey("oneTaskProcess");

        // Add a comment as "kermit"
        identityService.setAuthenticatedUserId("kermit");
        Comment comment = taskService.addComment(null, pi.getId(), "This is a comment...");
        identityService.setAuthenticatedUserId(null);

        CloseableHttpResponse response = executeRequest(
                new HttpGet(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(
                        RestUrls.URL_HISTORIC_PROCESS_INSTANCE_COMMENT_COLLECTION, pi.getId())),
                HttpStatus.SC_OK);

        assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());

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

        ObjectNode commentNode = (ObjectNode) responseNode.get(0);
        assertEquals("kermit", commentNode.get("author").textValue());
        assertEquals("This is a comment...", commentNode.get("message").textValue());
        assertEquals(comment.getId(), commentNode.get("id").textValue());
        assertTrue(
                commentNode.get("processInstanceUrl").textValue().endsWith(RestUrls.createRelativeResourceUrl(
                        RestUrls.URL_HISTORIC_PROCESS_INSTANCE_COMMENT, pi.getId(), comment.getId())));
        assertEquals(pi.getProcessInstanceId(), commentNode.get("processInstanceId").asText());
        assertTrue(commentNode.get("taskUrl").isNull());
        assertTrue(commentNode.get("taskId").isNull());

        // Test with unexisting task
        closeResponse(executeRequest(
                new HttpGet(SERVER_URL_PREFIX + RestUrls
                        .createRelativeResourceUrl(RestUrls.URL_TASK_COMMENT_COLLECTION, "unexistingtask")),
                HttpStatus.SC_NOT_FOUND));

    } finally {
        if (pi != null) {
            List<Comment> comments = taskService.getProcessInstanceComments(pi.getId());
            for (Comment c : comments) {
                taskService.deleteComment(c.getId());
            }
        }
    }
}

From source file:org.flowable.rest.service.api.history.HistoricProcessInstanceCommentResourceTest.java

/**
 * Test getting all comments for a historic process instance. GET history/historic-process-instances/{processInstanceId}/comments
 *///from   w w w. j  ava  2 s. c  o m
@Deployment(resources = { "org/flowable/rest/service/api/repository/oneTaskProcess.bpmn20.xml" })
public void testGetComments() throws Exception {
    ProcessInstance pi = null;

    try {
        pi = runtimeService.startProcessInstanceByKey("oneTaskProcess");

        // Add a comment as "kermit"
        identityService.setAuthenticatedUserId("kermit");
        Comment comment = taskService.addComment(null, pi.getId(), "This is a comment...");
        identityService.setAuthenticatedUserId(null);

        CloseableHttpResponse response = executeRequest(
                new HttpGet(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(
                        RestUrls.URL_HISTORIC_PROCESS_INSTANCE_COMMENT_COLLECTION, pi.getId())),
                HttpStatus.SC_OK);

        assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());

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

        ObjectNode commentNode = (ObjectNode) responseNode.get(0);
        assertEquals("kermit", commentNode.get("author").textValue());
        assertEquals("This is a comment...", commentNode.get("message").textValue());
        assertEquals(comment.getId(), commentNode.get("id").textValue());
        assertTrue(
                commentNode.get("processInstanceUrl").textValue().endsWith(RestUrls.createRelativeResourceUrl(
                        RestUrls.URL_HISTORIC_PROCESS_INSTANCE_COMMENT, pi.getId(), comment.getId())));
        assertEquals(pi.getProcessInstanceId(), commentNode.get("processInstanceId").asText());
        assertTrue(commentNode.get("taskUrl").isNull());
        assertTrue(commentNode.get("taskId").isNull());

        // Test with unexisting task
        closeResponse(executeRequest(
                new HttpGet(SERVER_URL_PREFIX + RestUrls
                        .createRelativeResourceUrl(RestUrls.URL_TASK_COMMENT_COLLECTION, "unexistingtask")),
                HttpStatus.SC_NOT_FOUND));

    } finally {
        if (pi != null) {
            List<Comment> comments = taskService.getProcessInstanceComments(pi.getId());
            for (Comment c : comments) {
                taskService.deleteComment(c.getId());
            }
        }
    }
}

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

/**
 * Test getting all identity links. GET runtime/tasks/{taskId}/identitylinks
 *//*from  w  ww .j  a  v a2s.  co  m*/
@Deployment
public void testGetIdentityLinks() throws Exception {

    // Test candidate user/groups links + manual added identityLink
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("identityLinkProcess");
    Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
    taskService.addUserIdentityLink(task.getId(), "john", "customType");

    assertEquals(3, taskService.getIdentityLinksForTask(task.getId()).size());

    // Execute the request
    HttpGet httpGet = new HttpGet(SERVER_URL_PREFIX
            + RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_IDENTITYLINKS_COLLECTION, task.getId()));
    CloseableHttpResponse response = executeRequest(httpGet, HttpStatus.SC_OK);
    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    assertNotNull(responseNode);
    assertTrue(responseNode.isArray());
    assertEquals(3, responseNode.size());

    boolean groupCandidateFound = false;
    boolean userCandidateFound = false;
    boolean customLinkFound = false;

    for (int i = 0; i < responseNode.size(); i++) {
        ObjectNode link = (ObjectNode) responseNode.get(i);
        assertNotNull(link);
        if (!link.get("user").isNull()) {
            if (link.get("user").textValue().equals("john")) {
                assertEquals("customType", link.get("type").textValue());
                assertTrue(link.get("group").isNull());
                assertTrue(link.get("url").textValue().endsWith(RestUrls.createRelativeResourceUrl(
                        RestUrls.URL_TASK_IDENTITYLINK, task.getId(), "users", "john", "customType")));
                customLinkFound = true;
            } else {
                assertEquals("kermit", link.get("user").textValue());
                assertEquals("candidate", link.get("type").textValue());
                assertTrue(link.get("group").isNull());
                assertTrue(link.get("url").textValue().endsWith(RestUrls.createRelativeResourceUrl(
                        RestUrls.URL_TASK_IDENTITYLINK, task.getId(), "users", "kermit", "candidate")));
                userCandidateFound = true;
            }
        } else if (!link.get("group").isNull()) {
            assertEquals("sales", link.get("group").textValue());
            assertEquals("candidate", link.get("type").textValue());
            assertTrue(link.get("user").isNull());
            assertTrue(link.get("url").textValue()
                    .endsWith(RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_IDENTITYLINK, task.getId(),
                            RestUrls.SEGMENT_IDENTITYLINKS_FAMILY_GROUPS, "sales", "candidate")));
            groupCandidateFound = true;
        }
    }
    assertTrue(groupCandidateFound);
    assertTrue(userCandidateFound);
    assertTrue(customLinkFound);
}

From source file:com.ikanow.aleph2.analytics.services.DeduplicationEnrichmentContext.java

/** Common emit logic
 * @param json/* ww  w  .j  a v a2  s. c o  m*/
 * @param supplier
 * @return
 */
public Validation<BasicMessageBean, JsonNode> emitObjectCommon(final JsonNode json,
        final Supplier<Validation<BasicMessageBean, JsonNode>> supplier) {
    return checkObjectLogic(json).bind(j -> {
        final boolean is_manual_delete = (1 == json.size());
        final JsonNode _id = (_delete_unhandled_duplicates || is_manual_delete) ? json.get(AnnotationBean._ID)
                : null;
        if (is_manual_delete && (null != _id)) {
            _mutable_state._manual_ids_to_delete.add(_id);
            return Validation.success(json);
        } else {
            if (_delete_unhandled_duplicates || (CustomPolicy.very_strict == _custom_policy))
                _mutable_state._id_set.remove(_id);
            _mutable_state._num_emitted++;
            return supplier.get();
        }
    });

}

From source file:de.raion.xmppbot.command.TrelloCommand.java

private TrelloConfig addCardInformations(String id, TrelloConfig config, Client client, ObjectMapper mapper) {

    WebResource boardResource = client.resource(config.getBoardBaseUrl()).path(id)
            .queryParam("key", config.getApplicationKey()).queryParam("token", config.getAccessToken())
            .queryParam("cards", "all");

    ClientResponse response = boardResource.get(ClientResponse.class);

    if (response.getClientResponseStatus() == Status.OK) {
        try {/*w w w .j  a  va  2s. c  om*/
            JsonNode rootNode = mapper.readValue(response.getEntityInputStream(), JsonNode.class);
            JsonNode cardsNode = rootNode.path("cards");

            HashMap<String, TrelloConfig.TrelloCard> map = new HashMap<String, TrelloConfig.TrelloCard>();

            int size = cardsNode.size();

            for (int i = 0; i < size; i++) {

                JsonNode json = cardsNode.get(i);
                TrelloConfig.TrelloCard card = new TrelloConfig.TrelloCard();

                card.setShortId(json.path("idShort").asText());
                card.setShortUrl(json.path("shortUrl").asText());
                card.setName(json.path("name").asText());

                map.put(card.getShortId(), card);
            }
            config.addCards(id, map);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        log.warn("couldn't GET card informations for board {}, status={}", id,
                response.getClientResponseStatus().getStatusCode());
    }

    return config;
}

From source file:org.n52.io.geojson.GeoJSONDecoder.java

protected GeometryCollection decodeGeometryCollection(JsonNode node, GeometryFactory fac)
        throws GeoJSONException {
    final JsonNode geometries = node.path(GEOMETRIES);
    if (!geometries.isArray()) {
        throw new GeoJSONException("expected 'geometries' array");
    }//from  w w  w .  j ava 2s . co  m
    Geometry[] geoms = new Geometry[geometries.size()];
    for (int i = 0; i < geometries.size(); ++i) {
        geoms[i] = decodeGeometry(geometries.get(i), fac);
    }
    return fac.createGeometryCollection(geoms);
}

From source file:org.activiti.rest.content.service.api.BaseSpringContentRestTestCase.java

/**
 * Checks if the returned "data" array (child-node of root-json node returned by invoking a GET on the given url) contains entries with the given ID's.
 *//*from w  w w . j a v a 2s.  c o m*/
protected void assertResultsPresentInDataResponse(String url, String... expectedResourceIds)
        throws JsonProcessingException, IOException {
    int numberOfResultsExpected = expectedResourceIds.length;

    // Do the actual call
    CloseableHttpResponse response = executeRequest(new HttpGet(SERVER_URL_PREFIX + url), HttpStatus.SC_OK);

    // Check status and size
    JsonNode dataNode = objectMapper.readTree(response.getEntity().getContent()).get("data");
    closeResponse(response);
    assertEquals(numberOfResultsExpected, dataNode.size());

    // Check presence of ID's
    List<String> toBeFound = new ArrayList<String>(Arrays.asList(expectedResourceIds));
    Iterator<JsonNode> it = dataNode.iterator();
    while (it.hasNext()) {
        String id = it.next().get("id").textValue();
        toBeFound.remove(id);
    }
    assertTrue("Not all expected ids have been found in result, missing: " + StringUtils.join(toBeFound, ", "),
            toBeFound.isEmpty());
}

From source file:com.github.fge.jsonschema.processors.validation.ArraySchemaDigester.java

@Override
public JsonNode digest(final JsonNode schema) {
    final ObjectNode ret = FACTORY.objectNode();
    ret.put("itemsSize", 0);
    ret.put("itemsIsArray", false);

    final JsonNode itemsNode = schema.path("items");
    final JsonNode additionalNode = schema.path("additionalItems");

    final boolean hasItems = !itemsNode.isMissingNode();
    final boolean hasAdditional = additionalNode.isObject();

    ret.put("hasItems", hasItems);
    ret.put("hasAdditional", hasAdditional);

    if (itemsNode.isArray()) {
        ret.put("itemsIsArray", true);
        ret.put("itemsSize", itemsNode.size());
    }/*w ww .  j a v a  2  s  .com*/

    return ret;
}