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

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

Introduction

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

Prototype

public final Iterator<JsonNode> iterator() 

Source Link

Usage

From source file:net.solarnetwork.node.support.JsonHttpClientSupport.java

/**
 * Parse a standard {@code Response} HTTP response and return the
 * {@code data} object as the provided type.
 * //from w  w  w .  j  av a2s  .c om
 * @param in
 *        the InputStream to read, which will be closed before returning
 *        from this method
 * @param dataType
 *        the type of object to extract from the response
 * @return the extracted object, or <em>null</em>
 * @throws RemoteServiceException
 *         if the response does not include the success flag
 * @throws IOException
 *         if any IO error occurs
 * @since 1.1
 */
protected <T> Collection<T> extractCollectionResponseData(InputStream in, Class<T> dataType)
        throws RemoteServiceException, IOException {
    try {
        JsonNode root = getObjectMapper().readTree(in);
        if (root.isObject()) {
            JsonNode child = root.get("success");
            if (child != null && child.asBoolean()) {
                child = root.get("data");
                if (child != null && child.isArray()) {
                    Iterator<JsonNode> children = child.iterator();
                    List<T> result = new ArrayList<T>();
                    while (children.hasNext()) {
                        child = children.next();
                        result.add(objectMapper.treeToValue(child, dataType));
                    }
                    return result;
                }
                log.debug("Server returned no data for request.");
                return null;
            }
        }
        throw new RemoteServiceException(
                "Server response not successful: " + root.get("message") == null ? "(no message)"
                        : root.get("message").asText());
    } finally {
        if (in != null) {
            in.close();
        }
    }
}

From source file:com.amazonaws.samples.SamplesGenerator.java

private void getAssignmentValue(final StringBuilder sb, final JsonNode node, MemberModel memberModel) {
    if (memberModel.isSimple()) {
        sb.append(formatPrimitiveValue(memberModel.getSetterModel().getSimpleType(), node.asText()));
    } else if (memberModel.isList()) {
        ListModel listModel = memberModel.getListModel();
        Iterator<JsonNode> iter = node.iterator();

        while (iter.hasNext()) {
            JsonNode entry = iter.next();

            if (listModel.getListMemberModel() == null) {
                sb.append(formatPrimitiveValue(listModel.getMemberType(), entry.asText()));
            } else {
                getAssignmentValue(sb, entry, listModel.getListMemberModel());
            }/*from w w  w . java  2  s  . co m*/

            if (iter.hasNext()) {
                sb.append(", ");
            }
        }
    } else if (memberModel.isMap()) {
        MapModel mapModel = memberModel.getMapModel();
        Iterator<Entry<String, JsonNode>> iter = node.fields();

        while (iter.hasNext()) {
            Entry<String, JsonNode> field = iter.next();
            JsonNode curNode = field.getValue();
            sb.append(String.format(".add%sEntry(", firstCharToUpper(memberModel.getC2jName())));

            sb.append(formatPrimitiveValue(mapModel.getKeyType(), field.getKey()));
            sb.append(", ");

            if (mapModel.getValueModel() == null) {
                sb.append(formatPrimitiveValue(mapModel.getValueType(), curNode.asText()));
            } else {
                getAssignmentValue(sb, curNode, mapModel.getValueModel());
            }

            sb.append(")");
        }
    } else {
        sb.append(String.format("new %s()", memberModel.getC2jShape()));

        Iterator<Entry<String, JsonNode>> iter = node.fields();
        ShapeModel memberShape = model.getShapes().get(memberModel.getC2jShape());

        while (iter.hasNext()) {
            Entry<String, JsonNode> field = iter.next();
            MemberModel fieldMemberModel = memberShape.getMemberByC2jName(field.getKey());

            if (fieldMemberModel.isMap()) {
                getAssignmentValue(sb, field.getValue(), fieldMemberModel);
            } else {
                sb.append(String.format(".with%s(", firstCharToUpper(field.getKey())));
                getAssignmentValue(sb, field.getValue(), fieldMemberModel);
                sb.append(")");
            }
        }
    }
}

From source file:org.eclipse.winery.bpmn2bpel.parser.Bpmn4JsonParser.java

protected Set<String> extractNodeTargetIds(JsonNode node) {
    Set<String> linkTargetIds = new HashSet<String>();
    /* Look for the 'connections' element within the node or its children */
    JsonNode connectionsNode = node.findValue(JsonKeys.CONNECTIONS);
    /*/* w ww .j a v  a  2s  . co m*/
     * The connection node hosts an array of all outgoing connections to
     * other nodes
     */
    if (connectionsNode != null && connectionsNode.isArray()) {
        Iterator<JsonNode> iter = connectionsNode.iterator();
        while (iter.hasNext()) {
            JsonNode connectionEntry = (JsonNode) iter.next();
            /*
             * Should always be true as the connection entry is the id of
             * the target node
             */
            if (connectionEntry.isTextual()) {
                linkTargetIds.add(connectionEntry.asText());
            } else {
                // TODO warn
            }

        }
    } else {
        log.debug("Node with id '" + node.get(JsonKeys.ID) + "' has no connections to other nodes");
        return null;
    }
    return linkTargetIds;
}

From source file:de.hbz.lobid.helper.CompareJsonMaps.java

/**
 * Construct a map with json paths as keys with aggregated values form json
 * nodes.//from  w  w  w .  j a v  a 2  s . c om
 * 
 * @param jnode the JsonNode which should be transformed into a map
 * @param map the map constructed out of the JsonNode
 */
public void extractFlatMapFromJsonNode(final JsonNode jnode, final HashMap<String, String> map) {
    if (jnode.getNodeType().equals(JsonNodeType.OBJECT)) {
        final Iterator<Map.Entry<String, JsonNode>> it = jnode.fields();
        while (it.hasNext()) {
            final Map.Entry<String, JsonNode> entry = it.next();
            stack.push(entry.getKey());
            extractFlatMapFromJsonNode(entry.getValue(), map);
            stack.pop();
        }
    } else if (jnode.isArray()) {
        final Iterator<JsonNode> it = jnode.iterator();
        while (it.hasNext()) {
            extractFlatMapFromJsonNode(it.next(), map);
        }
    } else if (jnode.isValueNode()) {
        String value = jnode.toString();
        if (map.containsKey(stack.toString()))
            value = map.get(stack.toString()).concat("," + jnode.toString());
        map.put(stack.toString(), value);
        CompareJsonMaps.logger.trace("Stored this path as key into map:" + stack.toString(), value);
    }
}

From source file:org.agatom.springatom.cmp.action.DefaultActionsModelReader.java

private ActionRole resolveSecurityRoles(final JsonNode roles, final ActionRoleMap.Connector[] connectors) {
    if (JsonNodeType.STRING.equals(roles.getNodeType())) {
        return new DefaultActionRole().appendRole(roles.asText());
    }// www  .  j  a v  a  2  s  .c  om
    final Iterator<JsonNode> iterator = roles.iterator();
    ActionRole actionRole = null;

    while (iterator.hasNext()) {
        final JsonNode node = iterator.next();
        final JsonNodeType type = node.getNodeType();
        if (JsonNodeType.STRING.equals(type)) {
            actionRole = new DefaultActionRole().appendRole(node.asText());
        } else if (JsonNodeType.ARRAY.equals(type)) {

            final ArrayNode arrayNode = (ArrayNode) node;
            final DefaultActionRole role = new DefaultActionRole();
            for (JsonNode textRoleNode : arrayNode) {
                role.appendRole(textRoleNode.asText());
            }
            actionRole = role;

        } else if (JsonNodeType.OBJECT.equals(type)) {

            final ActionRoleMap actionRoleMap = new ActionRoleMap();
            final Map<ActionRoleMap.Connector, DefaultActionRole> map = Maps
                    .newHashMapWithExpectedSize(node.size());
            String strConnector;
            for (final ActionRoleMap.Connector connector : connectors) {
                strConnector = connector.toString().toLowerCase();
                if (node.has(strConnector)) {
                    final DefaultActionRole role = new DefaultActionRole();
                    for (JsonNode textRoleNode : node.get(strConnector)) {
                        role.appendRole(textRoleNode.asText());
                    }
                    map.put(connector, role);
                }
            }
            actionRoleMap.setRoles(map);
            actionRole = actionRoleMap;

        }
    }

    return actionRole;
}

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   ww  w.jav a  2  s  . 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());
}