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:org.activiti.rest.content.service.api.BaseSpringContentRestTestCase.java

protected void assertResultsPresentInPostDataResponseWithStatusCheck(String url, ObjectNode body,
        int expectedStatusCode, String... expectedResourceIds) throws JsonProcessingException, IOException {
    int numberOfResultsExpected = 0;
    if (expectedResourceIds != null) {
        numberOfResultsExpected = expectedResourceIds.length;
    }/*from   w ww.  jav  a2s. c  o  m*/

    // Do the actual call
    HttpPost post = new HttpPost(SERVER_URL_PREFIX + url);
    post.setEntity(new StringEntity(body.toString()));
    CloseableHttpResponse response = executeRequest(post, expectedStatusCode);

    if (expectedStatusCode == HttpStatus.SC_OK) {
        // Check status and size
        JsonNode rootNode = objectMapper.readTree(response.getEntity().getContent());
        JsonNode dataNode = rootNode.get("data");
        assertEquals(numberOfResultsExpected, dataNode.size());

        // Check presence of ID's
        if (expectedResourceIds != null) {
            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 entries have been found in result, missing: " + StringUtils.join(toBeFound, ", "),
                    toBeFound.isEmpty());
        }
    }

    closeResponse(response);
}

From source file:com.yahoo.elide.graphql.GraphQLEndpoint.java

/**
 * Create handler.//from   w  ww .  ja  v  a 2 s  . c  o m
 *
 * @param securityContext security context
 * @param graphQLDocument post data as jsonapi document
 * @return response
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response post(@Context SecurityContext securityContext, String graphQLDocument) {
    ObjectMapper mapper = elide.getMapper().getObjectMapper();

    JsonNode topLevel;

    try {
        topLevel = mapper.readTree(graphQLDocument);
    } catch (IOException e) {
        log.debug("Invalid json body provided to GraphQL", e);
        // NOTE: Can't get at isVerbose setting here for hardcoding to false. If necessary, we can refactor
        // so this can be set appropriately.
        return buildErrorResponse(new InvalidEntityBodyException(graphQLDocument), false);
    }

    Function<JsonNode, Response> executeRequest = (node) -> executeGraphQLRequest(mapper, securityContext,
            graphQLDocument, node);

    if (topLevel.isArray()) {
        Iterator<JsonNode> nodeIterator = topLevel.iterator();
        Iterable<JsonNode> nodeIterable = () -> nodeIterator;
        // NOTE: Create a non-parallel stream
        // It's unclear whether or not the expectations of the caller would be that requests are intended
        // to run serially even outside of a single transaction. We should revisit this.
        Stream<JsonNode> nodeStream = StreamSupport.stream(nodeIterable.spliterator(), false);
        ArrayNode result = nodeStream.map(executeRequest).map(response -> {
            try {
                return mapper.readTree((String) response.getEntity());
            } catch (IOException e) {
                log.debug("Caught an IO exception while trying to read response body");
                return JsonNodeFactory.instance.objectNode();
            }
        }).reduce(JsonNodeFactory.instance.arrayNode(), (arrayNode, node) -> arrayNode.add(node),
                (left, right) -> left.addAll(right));
        try {
            return Response.ok(mapper.writeValueAsString(result)).build();
        } catch (IOException e) {
            log.error("An unexpected error occurred trying to serialize array response.", e);
            return Response.serverError().build();
        }
    }

    return executeRequest.apply(topLevel);
}

From source file:edu.usc.ir.visualization.NLTKandCoreNLP.java

private void countNER(String memexUrl, String username, String password)
        throws JsonParseException, JsonMappingException, IOException {

    JsonNode node;/*from  w w  w  .j  a  v  a 2s .c  o m*/
    JsonNode dataset = null;
    String url;
    String response;

    for (int c = 0; c < 101; c += 100) {

        url = memexUrl + "/select?q=gunsamerica&start=" + c
                + "&rows=100&fl=content%2Corganizations%2Cpersons%2Cdates%2Clocations&wt=json&indent=true";
        response = WebClient.create(url, username, password, null).accept(MediaType.APPLICATION_JSON).get()
                .readEntity(String.class);

        try {
            node = mapper.readTree(response);
            dataset = node.get("response").get("docs");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Iterator<JsonNode> datasetElements = dataset.iterator();

        while (datasetElements.hasNext()) {
            datasetElement = datasetElements.next();
            String content = datasetElement.get("content").asText();
            md = new Metadata();
            try (InputStream stream = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8))) {
                tika.parse(stream, md);
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (datasetElement.has("locations")) {
                extract("locations");
            }

            if (datasetElement.has("dates")) {
                extract("organizations");
            }

            if (datasetElement.has("organizations")) {
                extract("organizations");
            }

            if (datasetElement.has("persons")) {
                extract("persons");
            }

            if (md.getValues("NER_NAMES").length > 0) {
                for (String ner_name : Arrays.asList(md.getValues("NER_NAMES"))) {
                    if (!freq.contains(ner_name)) {
                        freq.add(ner_name);
                    }
                    if (nltk.containsKey(ner_name)) {
                        nltk.put(ner_name, nltk.get(ner_name) + 1);
                    } else {
                        nltk.put(ner_name, 1);
                    }
                }
            }
        }
    }
}

From source file:com.jaspersoft.jasperserver.war.action.DataSourceAction.java

/**
 * Bind sub-datasources for virtual datasource
 *
 * @param context/*  w w  w .ja v  a 2 s  .c  om*/
 * @return
 * @throws Exception
 */
public Event bindSubDatasources(RequestContext context) throws Exception {
    ReportDataSourceWrapper formObject = (ReportDataSourceWrapper) getFormObject(context);
    VirtualReportDataSource vds = (VirtualReportDataSource) formObject.getReportDataSource();
    String subDsJSON = (String) formObject.getNamedProperties().get(SUB_DATASOURCES_JSON_KEY);
    vds.getDataSourceUriMap().clear();
    if (isEmpty(subDsJSON)) {
        return success();
    }
    JsonNode subDsList = jsonMapper.readTree(subDsJSON);
    for (Iterator<JsonNode> i = subDsList.iterator(); i.hasNext();) {
        JsonNode subDs = i.next();
        String id = subDs.get(SUB_DATASOURCE_ID_KEY).asText();
        String uri = subDs.get(SUB_DATASOURCE_URI_KEY).asText();
        vds.getDataSourceUriMap().put(id, new ResourceReference(uri));
    }
    return success();
}

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

@Override
public ManagementFlow parse(URI jsonFileUrl) throws ParseException {

    try {/*w w w.  ja v  a 2s  .  c  o  m*/
        // general method, same as with data binding
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        // (note: can also use more specific type, like ArrayNode or
        // ObjectNode!)
        JsonNode rootNode = mapper.readValue(jsonFileUrl.toURL(), JsonNode.class);

        String prettyPrintedJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode);
        log.debug("Creating management flow from following Json model:" + prettyPrintedJson);

        ManagementFlow managementFlow = new ManagementFlow();
        /* Contains the ids (values) of the target nodes of a certain node
         * (key is node id of this node) */
        Map<String, Set<String>> nodeWithTargetsMap = new HashMap<String, Set<String>>();

        /* Create model objects from Json nodes */
        log.debug("Creating node models...");
        Iterator<JsonNode> iter = rootNode.iterator();
        while (iter.hasNext()) {
            JsonNode jsonNode = (JsonNode) iter.next();

            /*
             * As top level elements just start events, end events and
             * management tasks expected which are transformed to tasks in
             * our management model
             */
            Task task = createTaskFromJson(jsonNode);
            /*
             * Task may be null if it could not be created due to missing or
             * incorrect fields/values in the Json node
             */
            if (task != null) {
                managementFlow.addVertex(task);

                // TODO GATEWAAAAYYYYSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS
                // !!!!!!!!!!!!!!!!!!

                /*
                 * To create the links later, relate the id of the created
                 * node with its direct successor nodes
                 */
                nodeWithTargetsMap.put(task.getId(), extractNodeTargetIds(jsonNode));
            } else {
                String ignoredJsonNode = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode);
                log.warn(
                        "No model element could be created from following node due to missing or invalid keys/values :"
                                + ignoredJsonNode);
            }
        }

        /*
         * Now since all node models are created they can be linked with each other in the management flow
         */
        log.debug("Building management flow by relating node models...");
        Iterator<Map.Entry<String, Set<String>>> nodeWithTargetsMapIter = nodeWithTargetsMap.entrySet()
                .iterator();
        while (nodeWithTargetsMapIter.hasNext()) {
            Map.Entry<String, Set<String>> inputParamEntry = (Map.Entry<String, Set<String>>) nodeWithTargetsMapIter
                    .next();
            String srcNodeId = inputParamEntry.getKey();
            Node srcNode = managementFlow.getNode(srcNodeId);
            if (srcNode == null) {
                throw new Exception(
                        "Node with id '" + srcNodeId + "' could not be found in the management flow.");
            }

            /* Relate the source node with its link targets */
            Iterator<String> nodeTargetIdsIter = inputParamEntry.getValue().iterator();
            while (nodeTargetIdsIter.hasNext()) {
                String targetNodeId = (String) nodeTargetIdsIter.next();
                Node targetNode = managementFlow.getNode(targetNodeId);
                if (targetNode == null) {
                    throw new Exception(
                            "Node with id '" + targetNodeId + "' could not be found in the management flow.");
                }

                log.debug("Creating link between node with id '" + srcNodeId + "' and target node with id '"
                        + targetNodeId + "'");
                managementFlow.addEdge(srcNode, targetNode);
            }
        }

        return managementFlow;

    } catch (Exception e) {
        log.error("Error while creating management flow : " + e.getMessage());
        throw new ParseException(e);
    }

}

From source file:org.walkmod.conf.providers.yml.AddConfigurationParameterYMLAction.java

@Override
public void doAction(JsonNode node) throws Exception {

    List<JsonNode> elementsToModify = new LinkedList<JsonNode>();

    if (node.has("chains")) {
        JsonNode aux = node.get("chains");
        if (aux.isArray()) {
            ArrayNode chainsList = (ArrayNode) node.get("chains");
            Iterator<JsonNode> it = chainsList.iterator();

            while (it.hasNext()) {
                JsonNode next = it.next();
                JsonNode walkerNode = null;
                JsonNode transformationsNode = null;
                if (chain == null || chain.equals(next.get("name").asText())) {
                    if (category != null) {
                        if (node.has(category)) { // reader, walker,
                            // writer
                            JsonNode categoryNode = node.get(category);
                            analyzeNode(categoryNode, type, name, elementsToModify);
                        } else {
                            if (category.equals("transformation")) {
                                if (node.has("transformations")) {
                                    transformationsNode = node.get("transformations");
                                }//from  ww w  .ja v a  2s.  c  o  m
                            }
                            if (node.has("walker")) {
                                walkerNode = node.get("walker");
                            }
                        }
                    } else {
                        Iterator<JsonNode> it2 = next.iterator();
                        while (it2.hasNext()) {
                            analyzeNode(it2.next(), type, name, elementsToModify);
                        }
                        if (next.has("walker")) {
                            walkerNode = next.get("walker");

                        } else if (next.has("transformations")) {
                            transformationsNode = next.get("transformations");
                        }
                    }
                }
                if (walkerNode != null) {
                    if (category != null) {

                        if (walkerNode.has(category)) {
                            JsonNode categoryNode = node.get(category);
                            analyzeNode(categoryNode, type, name, elementsToModify);
                        }
                    } else if (walkerNode.has("transformations")) {
                        transformationsNode = walkerNode.get("transformations");

                    }

                }
                if (transformationsNode != null) {
                    if (transformationsNode.isArray()) {
                        ArrayNode transformationsArray = (ArrayNode) transformationsNode;
                        Iterator<JsonNode> it2 = transformationsArray.iterator();

                        while (it2.hasNext()) {
                            JsonNode current = it2.next();

                            analyzeNode(current, type, name, elementsToModify);
                        }
                    }
                }
            }
        }
    } else if (node.has("transformations") && (category == null || "transformation".equals(category))) {

        JsonNode transformationsNode = node.get("transformations");
        if (transformationsNode.isArray()) {
            ArrayNode transformationsArray = (ArrayNode) transformationsNode;
            Iterator<JsonNode> it = transformationsArray.iterator();

            while (it.hasNext()) {
                JsonNode current = it.next();
                analyzeNode(current, type, name, elementsToModify);
            }
        }

    }

    Iterator<JsonNode> it = elementsToModify.iterator();
    while (it.hasNext()) {
        JsonNode current = it.next();
        if (current.isObject()) {
            JsonNode params = null;
            if (current.has("params")) {
                params = current.get("params");
                if (params.isObject()) {
                    ((ObjectNode) params).set(param, new TextNode(value));
                }
            } else {
                Map<String, Object> paramToAdd = new HashMap<String, Object>();
                paramToAdd.put(param, value);
                populateParams((ObjectNode) current, paramToAdd);
            }
        }
    }

    if (!elementsToModify.isEmpty()) {
        provider.write(node);
    }

}