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

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

Introduction

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

Prototype

public Iterator<JsonNode> elements() 

Source Link

Usage

From source file:dao.AdvSearchDAO.java

public static ObjectNode elasticSearchFlowJobs(JsonNode searchOpt, int page, int size) {
    ObjectNode resultNode = Json.newObject();
    Long count = 0L;//from   w w  w.  j  a v a2s.  co  m
    List<FlowJob> pagedFlows = new ArrayList<>();
    ObjectNode queryNode = Json.newObject();
    queryNode.put("from", (page - 1) * size);
    queryNode.put("size", size);

    JsonNode searchNode = utils.Search.generateFlowJobAdvSearchQueryString(searchOpt);

    if (searchNode != null && searchNode.isContainerNode()) {
        queryNode.set("query", searchNode);
    }

    Promise<WSResponse> responsePromise = WS
            .url(Play.application().configuration().getString(SearchDAO.ELASTICSEARCH_FLOW_URL_KEY))
            .post(queryNode);
    JsonNode responseNode = responsePromise.get(1000).asJson();

    resultNode.put("page", page);
    resultNode.put("category", "Flows");
    resultNode.put("isFlowJob", true);
    resultNode.put("itemsPerPage", size);

    if (responseNode != null && responseNode.isContainerNode() && responseNode.has("hits")) {
        JsonNode hitsNode = responseNode.get("hits");
        if (hitsNode != null) {
            if (hitsNode.has("total")) {
                count = hitsNode.get("total").asLong();
            }
            if (hitsNode.has("hits")) {
                JsonNode dataNode = hitsNode.get("hits");
                if (dataNode != null && dataNode.isArray()) {
                    Iterator<JsonNode> arrayIterator = dataNode.elements();
                    if (arrayIterator != null) {
                        while (arrayIterator.hasNext()) {
                            JsonNode node = arrayIterator.next();
                            if (node.isContainerNode() && node.has("_id")) {
                                FlowJob flowJob = new FlowJob();
                                if (node.has("_source")) {
                                    JsonNode sourceNode = node.get("_source");
                                    if (sourceNode != null) {
                                        if (sourceNode.has("app_code")) {
                                            flowJob.appCode = sourceNode.get("app_code").asText();
                                        }
                                        if (sourceNode.has("app_id")) {
                                            flowJob.appId = sourceNode.get("app_id").asInt();
                                        }
                                        if (sourceNode.has("flow_id")) {
                                            flowJob.flowId = sourceNode.get("flow_id").asLong();
                                        }
                                        if (sourceNode.has("flow_name")) {
                                            flowJob.flowName = sourceNode.get("flow_name").asText();
                                            flowJob.displayName = flowJob.flowName;
                                        }
                                        if (sourceNode.has("flow_path")) {
                                            flowJob.flowPath = sourceNode.get("flow_path").asText();
                                        }
                                        if (sourceNode.has("flow_group")) {
                                            flowJob.flowGroup = sourceNode.get("flow_group").asText();
                                        }
                                        flowJob.link = "#/flows/name/" + flowJob.appCode + "/"
                                                + Long.toString(flowJob.flowId) + "/page/1?urn="
                                                + flowJob.flowGroup;
                                        flowJob.path = flowJob.appCode + "/" + flowJob.flowPath;

                                        flowJob.schema = sourceNode.toString();
                                    }
                                }
                                pagedFlows.add(flowJob);
                            }
                        }
                    }
                }
            }
        }
    }
    resultNode.put("count", count);
    resultNode.put("totalPages", (int) Math.ceil(count / ((double) size)));
    resultNode.set("data", Json.toJson(pagedFlows));
    return resultNode;
}

From source file:dao.AdvSearchDAO.java

public static ObjectNode elasticSearchMetric(JsonNode searchOpt, int page, int size) {
    ObjectNode resultNode = Json.newObject();
    Long count = 0L;//  w  w  w  .j  a  v a  2 s .  co  m
    List<Metric> pagedMetrics = new ArrayList<>();
    ObjectNode queryNode = Json.newObject();
    queryNode.put("from", (page - 1) * size);
    queryNode.put("size", size);

    JsonNode searchNode = utils.Search.generateMetricAdvSearchQueryString(searchOpt);

    if (searchNode != null && searchNode.isContainerNode()) {
        queryNode.set("query", searchNode);
    }

    Promise<WSResponse> responsePromise = WS
            .url(Play.application().configuration().getString(SearchDAO.ELASTICSEARCH_METRIC_URL_KEY))
            .post(queryNode);
    JsonNode responseNode = responsePromise.get(1000).asJson();

    resultNode.put("page", page);
    resultNode.put("category", "Metrics");
    resultNode.put("isMetrics", true);
    resultNode.put("itemsPerPage", size);

    if (responseNode != null && responseNode.isContainerNode() && responseNode.has("hits")) {
        JsonNode hitsNode = responseNode.get("hits");
        if (hitsNode != null) {
            if (hitsNode.has("total")) {
                count = hitsNode.get("total").asLong();
            }
            if (hitsNode.has("hits")) {
                JsonNode dataNode = hitsNode.get("hits");
                if (dataNode != null && dataNode.isArray()) {
                    Iterator<JsonNode> arrayIterator = dataNode.elements();
                    if (arrayIterator != null) {
                        while (arrayIterator.hasNext()) {
                            JsonNode node = arrayIterator.next();
                            if (node.isContainerNode() && node.has("_id")) {
                                Metric metric = new Metric();
                                metric.id = node.get("_id").asInt();
                                if (node.has("_source")) {
                                    JsonNode sourceNode = node.get("_source");
                                    if (sourceNode != null) {
                                        if (sourceNode.has("metric_name")) {
                                            metric.name = sourceNode.get("metric_name").asText();
                                        }
                                        if (sourceNode.has("metric_description")) {
                                            metric.description = sourceNode.get("metric_description").asText();
                                        }
                                        if (sourceNode.has("dashboard_name")) {
                                            metric.dashboardName = sourceNode.get("dashboard_name").asText();
                                        }
                                        if (sourceNode.has("metric_group")) {
                                            metric.group = sourceNode.get("metric_group").asText();
                                        }
                                        if (sourceNode.has("metric_category")) {
                                            metric.category = sourceNode.get("metric_category").asText();
                                        }
                                        if (sourceNode.has("urn")) {
                                            metric.urn = sourceNode.get("urn").asText();
                                        }
                                        if (sourceNode.has("metric_source")) {
                                            metric.source = sourceNode.get("metric_source").asText();
                                            if (StringUtils.isBlank(metric.source)) {
                                                metric.source = null;
                                            }
                                        }
                                        metric.schema = sourceNode.toString();
                                    }
                                }
                                pagedMetrics.add(metric);
                            }
                        }
                    }
                }
            }
        }
    }
    resultNode.put("count", count);
    resultNode.put("totalPages", (int) Math.ceil(count / ((double) size)));
    resultNode.set("data", Json.toJson(pagedMetrics));
    return resultNode;
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.external.RouterTest.java

@Before
public void before() throws Exception {
    ObjectMapper objectMapper = new ObjectMapper(new JsonFactory());

    String resourcePath = "internal/api/1.3/steering.json";
    InputStream inputStream = getClass().getClassLoader().getResourceAsStream(resourcePath);

    if (inputStream == null) {
        fail("Could not find file '" + resourcePath
                + "' needed for test from the current classpath as a resource!");
    }//  w w w  .j  av  a2  s .  c om

    Set<String> steeringDeliveryServices = new HashSet<String>();
    JsonNode steeringData = objectMapper.readTree(inputStream).get("response");
    Iterator<JsonNode> elements = steeringData.elements();

    while (elements.hasNext()) {
        JsonNode ds = elements.next();
        String dsId = ds.get("deliveryService").asText();
        steeringDeliveryServices.add(dsId);
    }

    resourcePath = "publish/CrConfig.json";
    inputStream = getClass().getClassLoader().getResourceAsStream(resourcePath);
    if (inputStream == null) {
        fail("Could not find file '" + resourcePath
                + "' needed for test from the current classpath as a resource!");
    }

    JsonNode jsonNode = objectMapper.readTree(inputStream);

    deliveryServiceId = null;

    Iterator<String> deliveryServices = jsonNode.get("deliveryServices").fieldNames();
    while (deliveryServices.hasNext()) {
        String dsId = deliveryServices.next();

        if (steeringDeliveryServices.contains(dsId)) {
            continue;
        }

        JsonNode deliveryServiceNode = jsonNode.get("deliveryServices").get(dsId);
        Iterator<JsonNode> matchsets = deliveryServiceNode.get("matchsets").iterator();

        while (matchsets.hasNext() && deliveryServiceId == null) {
            if ("HTTP".equals(matchsets.next().get("protocol").asText())) {
                final boolean sslEnabled = JsonUtils.optBoolean(deliveryServiceNode, "sslEnabled");
                if (!sslEnabled) {
                    deliveryServiceId = dsId;
                    deliveryServiceDomain = deliveryServiceNode.get("domains").get(0).asText();
                }
            }
        }
    }

    assertThat(deliveryServiceId, not(nullValue()));
    assertThat(deliveryServiceDomain, not(nullValue()));
    assertThat(httpsOnlyId, not(nullValue()));
    assertThat(httpsOnlyDomain, not(nullValue()));

    Iterator<String> cacheIds = jsonNode.get("contentServers").fieldNames();
    while (cacheIds.hasNext()) {
        String cacheId = cacheIds.next();
        JsonNode cacheNode = jsonNode.get("contentServers").get(cacheId);

        if (!cacheNode.has("deliveryServices")) {
            continue;
        }

        if (cacheNode.get("deliveryServices").has(deliveryServiceId)) {
            int port = cacheNode.get("port").asInt();
            String portText = (port == 80) ? "" : ":" + port;
            validLocations.add("http://" + cacheId + "." + deliveryServiceDomain + portText
                    + "/stuff?fakeClientIpAddress=12.34.56.78");
            validLocations.add("http://" + cacheId + "." + deliveryServiceDomain + portText
                    + "/stuff?fakeClientIpAddress=12.34.56.78&format=json");
        }

        if (cacheNode.get("deliveryServices").has(httpsOnlyId)) {
            int port = cacheNode.has("httpsPort") ? cacheNode.get("httpsPort").asInt(443) : 443;

            String portText = (port == 443) ? "" : ":" + port;
            httpsOnlyLocations.add("https://" + cacheId + "." + httpsOnlyDomain + portText
                    + "/stuff?fakeClientIpAddress=12.34.56.78");
        }

        if (cacheNode.get("deliveryServices").has(httpsNoCertsId)) {
            int port = cacheNode.has("httpsPort") ? cacheNode.get("httpsPort").asInt(443) : 443;

            String portText = (port == 443) ? "" : ":" + port;
            httpsNoCertsLocations.add("https://" + cacheId + "." + httpsNoCertsDomain + portText
                    + "/stuff?fakeClientIpAddress=12.34.56.78");
        }

        if (cacheNode.get("deliveryServices").has(httpAndHttpsId)) {
            int port = cacheNode.has("httpsPort") ? cacheNode.get("httpsPort").asInt(443) : 443;

            String portText = (port == 443) ? "" : ":" + port;
            httpAndHttpsLocations.add("https://" + cacheId + "." + httpAndHttpsDomain + portText
                    + "/stuff?fakeClientIpAddress=12.34.56.78");

            port = cacheNode.has("port") ? cacheNode.get("port").asInt(80) : 80;
            portText = (port == 80) ? "" : ":" + port;
            httpAndHttpsLocations.add("http://" + cacheId + "." + httpAndHttpsDomain + portText
                    + "/stuff?fakeClientIpAddress=12.34.56.78");
        }

        if (cacheNode.get("deliveryServices").has(httpToHttpsId)) {
            int port = cacheNode.has("httpsPort") ? cacheNode.get("httpsPort").asInt(443) : 443;

            String portText = (port == 443) ? "" : ":" + port;
            httpToHttpsLocations.add("https://" + cacheId + "." + httpToHttpsDomain + portText
                    + "/stuff?fakeClientIpAddress=12.34.56.78");
        }

        if (cacheNode.get("deliveryServices").has(httpOnlyId)) {
            int port = cacheNode.has("port") ? cacheNode.get("port").asInt(80) : 80;

            String portText = (port == 80) ? "" : ":" + port;
            httpOnlyLocations.add("http://" + cacheId + "." + httpOnlyDomain + portText
                    + "/stuff?fakeClientIpAddress=12.34.56.78");
        }
    }

    assertThat(validLocations.isEmpty(), equalTo(false));
    assertThat(httpsOnlyLocations.isEmpty(), equalTo(false));

    trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream keystoreStream = getClass().getClassLoader().getResourceAsStream("keystore.jks");
    trustStore.load(keystoreStream, "changeit".toCharArray());
    TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()).init(trustStore);

    httpClient = HttpClientBuilder.create()
            .setSSLSocketFactory(new ClientSslSocketFactory("tr.https-only-test.thecdn.example.com"))
            .setSSLHostnameVerifier(new TestHostnameVerifier()).disableRedirectHandling().build();

}

From source file:com.sitewhere.wso2.identity.scim.Wso2ScimAssetModule.java

/**
 * Make remote call to list all user assets, then parse and cache them.
 * //from w  w w .  ja  v a  2s .com
 * @throws SiteWhereException
 */
protected ICommandResponse cacheAssetData() throws SiteWhereException {
    assetCache.clear();

    LOGGER.info("Caching search data.");
    int totalAssets = 0;
    long startTime = System.currentTimeMillis();
    JsonNode json = doGet(getScimUsersUrl(), JsonNode.class);
    try {
        JsonNode resources = json.get(IScimFields.RESOURCES);
        if (resources == null) {
            String message = "SCIM JSON response did not contain a 'resources' section.";
            LOGGER.info(message);
            return new CommandResponse(CommandResult.Failed, message);
        }
        Iterator<JsonNode> it = resources.elements();
        while (it.hasNext()) {
            JsonNode resource = it.next();
            PersonAsset asset = parse(resource);
            assetCache.put(asset.getId(), asset);
            totalAssets++;
        }
    } catch (IOException e) {
        throw new SiteWhereException("Unable to read asset response.", e);
    }
    long totalTime = System.currentTimeMillis() - startTime;
    String message = "Cached " + totalAssets + " assets in " + totalTime + "ms.";
    LOGGER.info(message);
    return new CommandResponse(CommandResult.Successful, message);
}

From source file:kz.nurlan.kaspandr.KaspandrWindow.java

private String checkLessonCountByGroup(String lessons)
        throws JsonParseException, JsonMappingException, IOException {
    String resultString = "";

    ObjectNode rootNode1 = mapper.readValue("{\"lessons\":[" + lessons + "]}", ObjectNode.class);
    JsonNode lessonsNode1 = rootNode1.get("lessons");

    HashMap<String, Integer> groupMap = new HashMap<String, Integer>();
    HashMap<String, String> groupNameMap = new HashMap<String, String>();
    ValueComparator bvc = new ValueComparator(groupNameMap);
    TreeMap<String, String> sortedGroupNameMap = new TreeMap<String, String>(bvc);

    groupMap.put("all", 0);

    if (lessonsNode1 != null && lessonsNode1.isArray()) {
        Iterator<JsonNode> it = lessonsNode1.elements();

        while (it.hasNext()) {
            JsonNode lesson = it.next();

            if (lesson.get("id") != null && !lesson.get("status").textValue().equalsIgnoreCase("deleted")
                    && lesson.get("group") != null && !lesson.get("group").textValue().isEmpty()) {
                if (groupMap.containsKey(lesson.get("group").textValue()))
                    groupMap.put(lesson.get("group").textValue(),
                            groupMap.get(lesson.get("group").textValue()) + 1);
                else
                    groupMap.put(lesson.get("group").textValue(), 1);

                groupNameMap.put(lesson.get("group").textValue(), lesson.get("groupName").textValue());
            }//from w w  w  . ja  v a 2 s.  co  m

            groupMap.put("all", groupMap.get("all") + 1);
        }
    }
    sortedGroupNameMap.putAll(groupNameMap);

    int count = 0;
    for (String group : groupMap.keySet()) {
        if (!group.equals("all")) {
            count += groupMap.get(group);
        }
    }

    for (String group : sortedGroupNameMap.keySet()) {
        if (!resultString.isEmpty())
            resultString += ", ";

        resultString += groupNameMap.get(group) + "(" + groupMap.get(group) + ")";
    }
    resultString = "Lessons(" + count + "/" + groupMap.get("all") + "); " + resultString;

    return resultString;
}

From source file:com.jaspersoft.studio.data.querydesigner.json.JsonDataManager.java

private List<JsonSupportNode> getChildrenJsonNodes(JsonNode jsonNode) {
    List<JsonSupportNode> children = new ArrayList<JsonSupportNode>();
    if (jsonNode.isArray() && jsonNode.equals(jsonRoot)) {
        // Assumption: consider the first element as a template
        jsonNode = jsonNode.get(0);//from  ww w.  j  ava2s  .  com
    }
    Iterator<String> fieldNames = jsonNode.fieldNames();
    while (fieldNames.hasNext()) {
        String name = fieldNames.next();
        JsonNode tmpNode = jsonNode.get(name);
        if (tmpNode.isObject()) {
            JsonSupportNode child = new JsonSupportNode();
            child.setNodeText(name);
            List<JsonSupportNode> innerChildren = getChildrenJsonNodes(tmpNode);
            for (JsonSupportNode innerChild : innerChildren) {
                innerChild.setParent(child, -1);
            }
            getJsonNodesMap().put(child, tmpNode);
            children.add(child);
        } else if (tmpNode.isArray()) {
            Iterator<JsonNode> elements = tmpNode.elements();
            while (elements.hasNext()) {
                JsonNode el = elements.next();
                JsonSupportNode child = new JsonSupportNode();
                child.setNodeText(name);
                List<JsonSupportNode> innerChildren = getChildrenJsonNodes(el);
                for (JsonSupportNode innerChild : innerChildren) {
                    innerChild.setParent(child, -1);
                }
                getJsonNodesMap().put(child, el);
                children.add(child);
            }
        } else if (tmpNode.isValueNode()) {
            JsonSupportNode child = new JsonSupportNode();
            child.setNodeText(name);
            getJsonNodesMap().put(child, tmpNode);
            children.add(child);
        }
    }
    return children;
}

From source file:com.spankingrpgs.model.GameState.java

private void loadKeywords(JsonNode keywords) {
    Iterator<JsonNode> keywordsIterator = keywords.elements();
    this.keywords.clear();
    while (keywordsIterator.hasNext()) {
        this.keywords.add(keywordsIterator.next().asText().trim());
    }// w  ww . j  a va  2s. co  m
}

From source file:com.appdynamics.extensions.elasticsearch.QueryMonitorTask.java

private Map<String, Double> processResponeForMetrics(String responseString, ElasticSearchRequest esRequest)
        throws JsonParseException, JsonMappingException, IOException {
    Map<String, Double> queryMetrics = Maps.newHashMap();
    if (esRequest.getQueryDisplayName() != null) {
        String queryName = esRequest.getQueryDisplayName();
        for (Metric metric : esRequest.getMetrics()) {
            if (metric.getJsonPathInResponse() != null) {
                String[] paths = metric.getJsonPathInResponse().trim().split(">");
                JsonNode jsonNode = new ObjectMapper().readValue(responseString.getBytes(), JsonNode.class);
                for (int i = 0; i < paths.length; i++) {
                    jsonNode = jsonNode.path(paths[i].trim());
                }/*from www .j a va 2s  .  c om*/
                if (jsonNode.isNumber()) {
                    Double metricValue = jsonNode.asDouble();
                    StringBuilder sb = new StringBuilder(queryName).append(METRIC_SEPARATOR)
                            .append(buildMetricDisplayName(metric));
                    String metricName = sb.toString();
                    queryMetrics.put(metricName, metricValue);
                } else if (jsonNode.isArray()) {
                    int i = 0;
                    Iterator<JsonNode> elements = jsonNode.elements();
                    while (elements.hasNext()) {
                        JsonNode elementNode = elements.next();
                        Iterator<Entry<String, JsonNode>> fields = elementNode.fields();
                        while (fields.hasNext()) {
                            Entry<String, JsonNode> entry = fields.next();
                            if (entry.getValue().isNumber()) {
                                StringBuilder sb = new StringBuilder(queryName).append(METRIC_SEPARATOR)
                                        .append(buildMetricDisplayName(metric));
                                String metricName = sb.append(METRIC_SEPARATOR).toString() + i
                                        + METRIC_SEPARATOR + entry.getKey();
                                Double metricValue = entry.getValue().asDouble();
                                queryMetrics.put(metricName, metricValue);
                            }
                        }
                        i++;
                    }
                }
            }
        }
    } else {
        logger.error("queryDisplayName cannot be null for " + esRequest.getQuery());
    }
    return queryMetrics;
}

From source file:com.marklogic.jena.functionaltests.ConnectedRESTQA.java

public static void setDatabaseFieldProperties(String dbName, String field_name, String propName,
        ObjectNode objNode) throws IOException {
    InputStream jsonstream = null;
    try {//from  ww  w.j a  va2  s .c  o m
        DefaultHttpClient client = new DefaultHttpClient();
        client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002),
                new UsernamePasswordCredentials("admin", "admin"));
        HttpGet getrequest = new HttpGet(
                "http://localhost:8002" + "/manage/v2/databases/" + dbName + "/properties?format=json");
        HttpResponse response1 = client.execute(getrequest);
        jsonstream = response1.getEntity().getContent();
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jnode = mapper.readTree(jsonstream);
        if (!jnode.isNull() && jnode.has("field")) {
            JsonNode fieldNode = jnode.withArray("field");
            Iterator<JsonNode> fnode = fieldNode.elements();
            while (fnode.hasNext()) {
                JsonNode fnchild = fnode.next();
                if ((fnchild.path("field-name").asText()).equals(field_name)) {
                    //                     System.out.println("Hurray" +fnchild.has(propName));
                    if (!fnchild.has(propName)) {
                        ((ObjectNode) fnchild).putArray(propName).addAll(objNode.withArray(propName));
                        //                     System.out.println("Adding child array include node" + jnode.toString());
                    } else {
                        JsonNode member = fnchild.withArray(propName);
                        ((ArrayNode) member).addAll(objNode.withArray(propName));
                    }

                }
            }

            HttpPut put = new HttpPut(
                    "http://localhost:8002" + "/manage/v2/databases/" + dbName + "/properties?format=json");
            put.addHeader("Content-type", "application/json");
            put.setEntity(new StringEntity(jnode.toString()));

            HttpResponse response2 = client.execute(put);
            HttpEntity respEntity = response2.getEntity();
            if (respEntity != null) {
                String content = EntityUtils.toString(respEntity);
                System.out.println(content);
            }
        } else {
            System.out.println("REST call for database properties returned NULL \n" + jnode.toString() + "\n"
                    + response1.getStatusLine().getStatusCode());
        }
    } catch (Exception e) {
        // writing error to Log
        e.printStackTrace();
    } finally {
        if (jsonstream == null) {
        } else {
            jsonstream.close();
        }
    }
}