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

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

Introduction

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

Prototype

default void forEach(Consumer<? super T> action) 

Source Link

Document

Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

Usage

From source file:org.obiba.mica.micaConfig.service.EntityConfigService.java

private JsonNode mergeDefinition(JsonNode customDefinition, JsonNode mandatoryDefinition) {

    customDefinition.forEach(((ArrayNode) mandatoryDefinition)::add);

    return mandatoryDefinition;
}

From source file:org.lendingclub.mercator.dynect.DynectScanner.java

private void scanAllRecordsByZone(List<String> zones) {

    Instant startTime = Instant.now();

    logger.info("Scanning all records in each available zones");

    for (String zone : zones) {
        logger.debug("Scanning all records in Dynect zone {} ", zone);

        ObjectNode response = getDynectClient().get("REST/AllRecord/" + zone);

        JsonNode recordsData = response.path("data");

        if (recordsData.isArray()) {
            recordsData.forEach(record -> {
                String recordFullName = record.asText();

                logger.debug("Scanning {} record for more information in {} zone", recordFullName, zone);
                ObjectNode recordResponse = getDynectClient().get(recordFullName);

                ObjectNode data = toRecordJson(recordResponse.get("data"));
                String recordId = Splitter.on("/").splitToList(recordFullName).get(5);

                String cypher = "MATCH (z:DynHostedZone {zoneName:{zone}})"
                        + "MERGE (m:DynHostedZoneRecord {recordId:{recordId}}) "
                        + "ON CREATE SET  m+={props}, m.createTs = timestamp(), m.updateTs=timestamp() "
                        + "ON MATCH SET m+={props}, m.updateTs=timestamp() " + "MERGE (z)-[:CONTAINS]->(m);";
                getProjector().getNeoRxClient().execCypher(cypher, "recordId", recordId, "props", data, "zone",
                        zone);/*from ww  w  .jav a  2 s  .  co m*/
            });
        }
    }

    Instant endTime = Instant.now();
    logger.info("Updating neo4j with the latest information of all records from zones in Dynect took {} secs",
            Duration.between(startTime, endTime).getSeconds());
}

From source file:org.fcrepo.importexport.common.BagProfile.java

private void loadOtherTags(final JsonNode json) {
    final JsonNode arrayTags = json.get("Other-Info");
    if (arrayTags != null && arrayTags.isArray()) {
        arrayTags.forEach(tag -> tag.fieldNames().forEachRemaining(sections::add));
        final Iterator<JsonNode> arrayEntries = arrayTags.elements();
        while (arrayEntries.hasNext()) {
            final JsonNode entries = arrayEntries.next();
            final Iterator<String> tagNames = entries.fieldNames();
            while (tagNames.hasNext()) {
                final String tagName = tagNames.next();
                metadataFields.put(tagName, metadataFields(entries, tagName));
            }/* www . j  a v a 2  s .  c o m*/
        }
    }
    logger.debug("tagFiles is {}", sections);
    logger.debug("metadataFields is {}", metadataFields);
}

From source file:org.lendingclub.mercator.dynect.DynectScanner.java

private List<String> scanZones() {

    Instant startTime = Instant.now();

    logger.info("Scanning all zones in Dynect");
    ObjectNode response = getDynectClient().get("REST/Zone/");

    JsonNode zoneData = response.path("data");
    List<String> zonesList = new ArrayList<String>();

    if (zoneData.isArray()) {
        zoneData.forEach(zone -> {

            String zoneNode = zone.asText();
            String zoneName = Splitter.on("/").splitToList(zoneNode).get(3);
            zonesList.add(zoneName);/*from   w  w  w.j ava  2s . c o  m*/
        });
    }

    logger.info("Scanning {} zones in Dynect to get more details", zonesList.size());

    for (String zone : zonesList) {
        response = getDynectClient().get("REST/Zone/" + zone);
        logger.debug("Scanning {} zone", zone);

        ObjectNode n = toZoneJson(response.get("data"));
        Preconditions.checkNotNull(getProjector().getNeoRxClient(), "neorx client must be set");
        String cypher = "MERGE (m:DynHostedZone {zoneName:{zone}}) "
                + "ON CREATE SET  m+={props}, m.createTs = timestamp(), m.updateTs=timestamp() "
                + "ON MATCH SET m+={props}, m.updateTs=timestamp();";
        getProjector().getNeoRxClient().execCypher(cypher, "zone", zone, "props", n);
    }

    Instant endTime = Instant.now();
    logger.info("Updating neo4j with the latest information of all {} zones from Dynect took {} secs",
            zonesList.size(), Duration.between(startTime, endTime).getSeconds());

    return zonesList;
}

From source file:org.onosproject.sdxl3.config.SdxParticipantsConfig.java

/**
 * Gets the set of configured BGP peers.
 *
 * @return BGP peers/*  www .j a  v a  2s.  c om*/
 */
public Set<PeerConfig> bgpPeers() {
    Set<PeerConfig> peers = Sets.newHashSet();

    JsonNode peersNode = object.get(PEERS);

    if (peersNode == null) {
        return peers;
    }
    peersNode.forEach(jsonNode -> {
        Optional<String> name;
        if (jsonNode.get(NAME) == null) {
            name = Optional.empty();
        } else {
            name = Optional.of(jsonNode.get(NAME).asText());
        }

        peers.add(new PeerConfig(name, IpAddress.valueOf(jsonNode.path(IP).asText()),
                ConnectPoint.deviceConnectPoint(jsonNode.path(CONN_POINT).asText()),
                jsonNode.path(INTF_NAME).asText()));
    });

    return peers;
}

From source file:org.lendingclub.mercator.docker.SwarmScanner.java

public void scanTasksForSwarm(String swarmClusterId) {

    logger.info("scanning tasks for swarm: {}", swarmClusterId);

    AtomicLong earlistUpdate = new AtomicLong(Long.MAX_VALUE);
    AtomicBoolean error = new AtomicBoolean(false);
    JsonNode response = getRestClient().getTasks();
    response.forEach(it -> {
        try {//from w w w .java  2s.  co m
            earlistUpdate.set(Math.min(earlistUpdate.get(), saveTask(it)));

        } catch (Exception e) {
            logger.warn("problem updating task", e);
            error.set(true);
        }
    });

    if (error.get() == false) {
        if (earlistUpdate.get() < System.currentTimeMillis()) {
            dockerScanner.getNeoRxClient().execCypher(
                    "match (x:DockerTask) where x.swarmClusterId={swarmClusterId} and x.updateTs<{cutoff} detach delete x",
                    "cutoff", earlistUpdate.get(), "swarmClusterId", swarmClusterId);
        }
    }

}

From source file:org.lendingclub.mercator.docker.SwarmScanner.java

public void scanServicesForSwarm(String swarmClusterId) {

    JsonNode response = getRestClient().getServices();

    AtomicLong earlistUpdate = new AtomicLong(Long.MAX_VALUE);
    AtomicBoolean error = new AtomicBoolean(false);
    response.forEach(it -> {
        try {//from   ww  w .  ja v a 2s  .c o  m
            ObjectNode n = flattenService(it);
            n.put("swarmClusterId", swarmClusterId);
            dockerScanner.getNeoRxClient().execCypher(
                    "merge (x:DockerService {serviceId:{serviceId}}) set x+={props}, x.updateTs=timestamp() return x",
                    "serviceId", n.get("serviceId").asText(), "props", n).forEach(svc -> {
                        removeDockerLabels("DockerService", "serviceId", n.get("serviceId").asText(), n, svc);
                        earlistUpdate.set(
                                Math.min(earlistUpdate.get(), svc.path("updateTs").asLong(Long.MAX_VALUE)));
                    });
            dockerScanner.getNeoRxClient().execCypher(
                    "match (swarm:DockerSwarm {swarmClusterId:{swarmClusterId}}),(service:DockerService{serviceId:{serviceId}}) merge (swarm)-[x:CONTAINS]->(service) set x.updateTs=timestamp()",
                    "swarmClusterId", swarmClusterId, "serviceId", n.path("serviceId").asText());

        } catch (Exception e) {
            logger.warn("problem updating service", e);
            error.set(true);
        }
    });
    if (error.get() == false) {
        if (earlistUpdate.get() < System.currentTimeMillis()) {
            dockerScanner.getNeoRxClient().execCypher(
                    "match (x:DockerService) where x.swarmClusterId={swarmClusterId} and x.updateTs<{cutoff} detach delete x",
                    "cutoff", earlistUpdate.get(), "swarmClusterId", swarmClusterId);
        }
    }

}

From source file:cc.arduino.packages.discoverers.PluggableDiscovery.java

private void processJsonNode(ObjectMapper mapper, JsonNode node) {
    JsonNode eventTypeNode = node.get("eventType");
    if (eventTypeNode == null) {
        System.err.println(format("{0}: Invalid message, missing eventType", discoveryName));
        return;/*from   w  w  w  . j av a2  s  .  co m*/
    }

    switch (eventTypeNode.asText()) {
    case "error":
        try {
            PluggableDiscoveryMessage msg = mapper.treeToValue(node, PluggableDiscoveryMessage.class);
            debug("error: " + msg.getMessage());
            if (msg.getMessage().contains("START_SYNC")) {
                startPolling();
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return;

    case "list":
        JsonNode portsNode = node.get("ports");
        if (portsNode == null) {
            System.err.println(format("{0}: Invalid message, missing ports list", discoveryName));
            return;
        }
        if (!portsNode.isArray()) {
            System.err.println(format("{0}: Invalid message, ports list should be an array", discoveryName));
            return;
        }

        synchronized (portList) {
            portList.clear();
        }
        portsNode.forEach(portNode -> {
            BoardPort port = mapJsonNodeToBoardPort(mapper, node);
            if (port != null) {
                addOrUpdate(port);
            }
        });
        return;

    // Messages for SYNC updates

    case "add":
        BoardPort addedPort = mapJsonNodeToBoardPort(mapper, node);
        if (addedPort != null) {
            addOrUpdate(addedPort);
        }
        return;

    case "remove":
        BoardPort removedPort = mapJsonNodeToBoardPort(mapper, node);
        if (removedPort != null) {
            remove(removedPort);
        }
        return;

    default:
        debug("Invalid event: " + eventTypeNode.asText());
        return;
    }
}

From source file:org.talend.dataprep.transformation.service.TransformationServiceTest.java

/**
 * see https://jira.talendforge.org/browse/TDP-3126
 *///from   ww w.  ja v  a  2 s  .c  om
@Test
public void shouldGetPreparationColumnTypesWhenDomainIsForced() throws Exception {

    // given
    final String dataSetId = createDataset("first_interactions_400.csv", "first interactions", "text/csv");
    final String preparationId = createEmptyPreparationFromDataset(dataSetId, "first interactions");
    // (force the domain to gender to replace all the 'F' by 'France')
    applyActionFromFile(preparationId, "change_domain.json");
    applyActionFromFile(preparationId, "replace_value.json");

    // when
    final Response response = when().get("/preparations/{preparationId}/columns/{columnId}/types",
            preparationId, "0005");

    // then
    assertEquals(200, response.getStatusCode());
    final JsonNode rootNode = mapper.readTree(response.asInputStream());
    assertEquals(5, rootNode.size());
    final List<String> actual = new ArrayList<>(5);
    rootNode.forEach(n -> actual.add(n.get("id").textValue().toUpperCase()));
    final List<String> expected = Arrays.asList("COUNTRY", "CIVILITY", "GENDER", "LAST_NAME", "FIRST_NAME");

    assertTrue(expected.containsAll(actual));
}

From source file:org.thingsboard.demo.loader.data.DemoData.java

private void readData(String email, byte[] pluginsContent, byte[] rulesContent, byte[] customersContent,
        byte[] devicesContent, List<byte[]> dashboardsContent) throws Exception {
    Map<String, String> pluginTokenMap = new HashMap<>();
    if (pluginsContent != null) {
        JsonNode pluginsJson = objectMapper.readTree(pluginsContent);
        JsonNode pluginsArray = pluginsJson.get("plugins");
        String hash = DigestUtils.md5DigestAsHex(email.getBytes()).substring(0, 10);
        pluginsArray.forEach(jsonNode -> {
            try {
                PluginMetaData plugin = objectMapper.treeToValue(jsonNode, PluginMetaData.class);
                String pluginToken = plugin.getApiToken();
                String newPluginToken = pluginToken + "_" + hash;
                pluginTokenMap.put(pluginToken, newPluginToken);
                plugin.setApiToken(newPluginToken);
                if (plugin.getState() == ComponentLifecycleState.ACTIVE) {
                    plugin.setState(ComponentLifecycleState.SUSPENDED);
                }/* w  ww.  j  a va2s  .  c  om*/
                this.plugins.add(plugin);
            } catch (Exception e) {
                log.error("Unable to load plugins from json!");
                log.error("Cause:", e);
                System.exit(-1);
            }
        });
    }

    if (rulesContent != null) {
        JsonNode rulesJson = objectMapper.readTree(rulesContent);
        JsonNode rulesArray = rulesJson.get("rules");
        rulesArray.forEach(jsonNode -> {
            try {
                String jsonBody = objectMapper.writeValueAsString(jsonNode);
                jsonBody = jsonBody.replaceAll("\\$EMAIL", email);
                RuleMetaData rule = objectMapper.treeToValue(objectMapper.readTree(jsonBody),
                        RuleMetaData.class);
                String newPluginToken;
                // Need to be able to reference system plugins.
                if (pluginTokenMap.containsKey(rule.getPluginToken())) {
                    newPluginToken = pluginTokenMap.get(rule.getPluginToken());
                } else {
                    newPluginToken = rule.getPluginToken();
                }
                if (newPluginToken != null) {
                    rule.setPluginToken(newPluginToken);
                }
                if (rule.getState() == ComponentLifecycleState.ACTIVE) {
                    rule.setState(ComponentLifecycleState.SUSPENDED);
                }
                this.rules.add(rule);
            } catch (Exception e) {
                log.error("Unable to load rule from json!");
                log.error("Cause:", e);
            }
        });
    }

    if (customersContent != null) {
        JsonNode customersJson = objectMapper.readTree(customersContent);
        JsonNode customersArray = customersJson.get("customers");
        Map<String, CustomerId> customerIdMap = new HashMap<>();
        customersArray.forEach(jsonNode -> {
            try {
                Customer customer = objectMapper.treeToValue(jsonNode, Customer.class);
                this.customers.add(customer);
            } catch (Exception e) {
                log.error("Unable to load customer from json!");
                log.error("Cause:", e);
            }
        });
    }

    if (devicesContent != null) {
        JsonNode devicesJson = objectMapper.readTree(devicesContent);
        JsonNode devicesArray = devicesJson.get("devices");
        devicesArray.forEach(jsonNode -> {
            try {
                Device device = objectMapper.treeToValue(jsonNode, Device.class);
                this.devices.add(device);
            } catch (Exception e) {
                log.error("Unable to load device from json!");
                log.error("Cause:", e);
            }
        });
        JsonNode customerDevicesJson = devicesJson.get("customerDevices");
        customerDevicesJson.forEach(jsonNode -> {
            String deviceName = jsonNode.get("deviceName").asText();
            String customerTitle = jsonNode.get("customerTitle").asText();
            customerDevices.put(deviceName, customerTitle);
        });

        JsonNode deviceAttributesJson = devicesJson.get("deviceAttributes");
        deviceAttributesJson.forEach(jsonNode -> {
            String deviceName = jsonNode.get("deviceName").asText();
            Map<String, JsonNode> attributesMap = new HashMap<>();
            if (jsonNode.has("server")) {
                JsonNode serverAttributes = jsonNode.get("server");
                attributesMap.put(DataConstants.SERVER_SCOPE, serverAttributes);
            }
            if (jsonNode.has("shared")) {
                JsonNode sharedAttributes = jsonNode.get("shared");
                attributesMap.put(DataConstants.SHARED_SCOPE, sharedAttributes);
            }
            devicesAttributes.put(deviceName, attributesMap);
        });

    }
    dashboardsContent.forEach(dashboardContent -> {
        try {
            JsonNode dashboardJson = objectMapper.readTree(dashboardContent);
            Dashboard dashboard = objectMapper.treeToValue(dashboardJson, Dashboard.class);
            this.dashboards.add(dashboard);
        } catch (Exception e) {
            log.error("Unable to load dashboard from json!");
            log.error("Cause:", e);
        }
    });
}