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:org.schedoscope.export.kafka.avro.HCatToAvroRecordConverter.java

private List<Object> convertArray(JsonNode json, Schema schema) throws IOException {

    List<Object> res = new ArrayList<>();
    Iterator<JsonNode> it = json.elements();

    while (it.hasNext()) {

        JsonNode n = it.next();/*  w ww.  java 2  s.com*/
        if (!n.isNull()) {
            for (Schema s : schema.getElementType().getTypes()) {
                if (s.getType().equals(Schema.Type.STRING)) {
                    res.add(n.asText());
                } else if (s.getType().equals(Schema.Type.INT)) {
                    res.add(n.asInt());
                } else if (s.getType().equals(Schema.Type.LONG)) {
                    res.add(n.asLong());
                } else if (s.getType().equals(Schema.Type.BOOLEAN)) {
                    res.add(n.asBoolean());
                } else if (s.getType().equals(Schema.Type.DOUBLE)) {
                    res.add(n.asDouble());
                } else if (s.getType().equals(Schema.Type.FLOAT)) {
                    res.add(n.asDouble());
                } else if (s.getType().equals(Schema.Type.RECORD)) {
                    res.add(convertRecord(n, s));
                } else if (s.getType().equals(Schema.Type.ARRAY)) {
                    res.addAll(convertArray(n, s));
                } else if (s.getType().equals(Schema.Type.MAP)) {
                    res.add(convertMap(n, s));
                }
            }
        }
    }
    return res;
}

From source file:io.gravitee.definition.jackson.datatype.api.deser.ApiDeserializer.java

@Override
public Api deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    JsonNode node = jp.getCodec().readTree(jp);

    Api api = new Api();

    JsonNode idNode = node.get("id");
    if (idNode == null) {
        throw ctxt.mappingException("ID property is required");
    } else {// www . j a v a2 s  . c o m
        api.setId(idNode.asText());
    }

    JsonNode nameNode = node.get("name");
    if (nameNode == null) {
        throw ctxt.mappingException("Name property is required");
    } else {
        api.setName(nameNode.asText());
    }

    JsonNode versionNode = node.get("version");
    if (versionNode == null) {
        api.setVersion("undefined");
    } else {
        api.setVersion(versionNode.asText());
    }

    JsonNode proxyNode = node.get("proxy");
    if (proxyNode != null) {
        api.setProxy(proxyNode.traverse(jp.getCodec()).readValueAs(Proxy.class));
    } else {
        logger.error("A proxy property is required for {}", api.getName());
        throw ctxt.mappingException("A proxy property is required for " + api.getName());
    }

    JsonNode servicesNode = node.get("services");
    if (servicesNode != null) {
        Services services = servicesNode.traverse(jp.getCodec()).readValueAs(Services.class);
        api.getServices().set(services.getAll());
    }

    JsonNode resourcesNode = node.get("resources");
    if (resourcesNode != null && resourcesNode.isArray()) {
        resourcesNode.elements().forEachRemaining(resourceNode -> {
            try {
                Resource resource = resourceNode.traverse(jp.getCodec()).readValueAs(Resource.class);
                if (!api.getResources().contains(resource)) {
                    api.getResources().add(resource);
                } else {
                    logger.error("A resource already exists with name {}", resource.getName());
                    throw ctxt.mappingException("A resource already exists with name " + resource.getName());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    JsonNode pathsNode = node.get("paths");
    if (pathsNode != null) {
        final Map<String, Path> paths = new TreeMap<>(
                (Comparator<String>) (path1, path2) -> path2.compareTo(path1));
        pathsNode.fields().forEachRemaining(jsonNode -> {
            try {
                Path path = jsonNode.getValue().traverse(jp.getCodec()).readValueAs(Path.class);
                path.setPath(jsonNode.getKey());
                paths.put(jsonNode.getKey(), path);
            } catch (IOException e) {
                logger.error("Path {} can not be de-serialized", jsonNode.getKey());
            }
        });

        api.setPaths(paths);
    }

    JsonNode propertiesNode = node.get("properties");
    if (propertiesNode != null) {
        Map<String, String> properties = new TemplatedValueHashMap();
        propertiesNode.fields().forEachRemaining(
                jsonNode -> properties.put(jsonNode.getKey(), jsonNode.getValue().textValue()));

        api.setProperties(properties);
    }

    JsonNode tagsNode = node.get("tags");

    if (tagsNode != null && tagsNode.isArray()) {
        tagsNode.elements().forEachRemaining(jsonNode -> api.getTags().add(jsonNode.asText()));
    }

    return api;
}

From source file:io.gravitee.definition.jackson.datatype.services.core.deser.ServiceDeserializer.java

@Override
public Service deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    JsonNode node = jp.getCodec().readTree(jp);
    String serviceName = node.fieldNames().next();

    Class<? extends Service> serviceClass = registeredServices.get(serviceName);
    if (serviceClass == null) {
        return null;
    }//from  ww  w .  j  a  v a2 s .  co  m

    return node.elements().next().traverse(jp.getCodec()).readValueAs(new TypeReference<Service>() {
        @Override
        public Type getType() {
            return serviceClass;
        }
    });
}

From source file:com.netflix.zeno.json.JsonFrameworkDeserializer.java

private <T> void deserializeCollection(JsonNode nodes, NFTypeSerializer<T> itemSerializer,
        Collection<T> elements) {
    try {/* ww  w  .j  a  v a2  s.com*/
        for (Iterator<JsonNode> it = nodes.elements(); it.hasNext();) {
            JsonNode node = it.next();
            T element = itemSerializer
                    .deserialize(new JsonReadGenericRecord(itemSerializer.getFastBlobSchema(), node));
            elements.add(element);
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.netflix.zeno.json.JsonFrameworkDeserializer.java

private <K, V, M extends Map<K, V>> M deserializeIntoMap(JsonReadGenericRecord rec, String fieldName,
        NFTypeSerializer<K> keySerializer, NFTypeSerializer<V> valueSerializer, M map) {
    JsonNode node = getJsonNode(rec, fieldName);
    if (node == null) {
        return null;
    }/*  w ww . j ava2  s .  co  m*/
    for (Iterator<JsonNode> it = node.elements(); it.hasNext();) {
        JsonNode element = it.next();
        K key = keySerializer
                .deserialize(new JsonReadGenericRecord(keySerializer.getFastBlobSchema(), element.get("key")));
        V value = valueSerializer.deserialize(
                new JsonReadGenericRecord(valueSerializer.getFastBlobSchema(), element.get("value")));
        map.put(key, value);
    }
    return map;
}

From source file:org.obiba.mica.core.upgrade.Mica220Upgrade.java

private boolean replacePropertyInDefinition(JsonNode definitionNode) {
    Iterator<JsonNode> itemsLvl0 = definitionNode.elements();
    while (itemsLvl0.hasNext()) {
        JsonNode itemLvl0 = itemsLvl0.next();
        if (itemLvl0.has("items")) {
            Iterator<JsonNode> itemsLvl1 = itemLvl0.get("items").elements();
            while (itemsLvl1.hasNext()) {
                JsonNode itemLvl1 = itemsLvl1.next();
                if (itemLvl1.has("items")) {
                    Iterator<JsonNode> itemsLvl2 = itemLvl1.get("items").elements();
                    while (itemsLvl2.hasNext()) {
                        JsonNode itemLvl2 = itemsLvl2.next();
                        if (itemLvl2.has("titleMap")) {
                            Iterator<JsonNode> titleMaps = itemLvl2.get("titleMap").elements();
                            while (titleMaps.hasNext()) {
                                JsonNode titleMap = titleMaps.next();
                                if (titleMap.has("value")
                                        && titleMap.get("value").textValue().equals("biosamples")) {
                                    ((ObjectNode) titleMap).put("value", "bio_samples");
                                    return true;
                                }//  w w w . ja  va 2 s  .  c  om
                            }
                        }
                    }
                }
            }
        }
    }
    return false;
}

From source file:com.amazonaws.kinesis.dataviz.kinesisclient.KinesisRecordProcessor.java

/** Process records performing retries as needed. Skip "poison pill" records.
 * @param records/*www .ja v a 2s .  c  om*/
 */
private void processRecordsWithRetries(List<Record> records) {
    for (Record record : records) {
        boolean processedSuccessfully = false;
        String data = null;
        for (int i = 0; i < NUM_RETRIES; i++) {
            try {

                Coordinate c = null;

                try {
                    // For this app, we interpret the payload as UTF-8 chars.
                    data = decoder.decode(record.getData()).toString();

                    // use the ObjectMapper to read the json string and create a tree
                    JsonNode node = mapper.readTree(data);

                    JsonNode geo = node.findValue("geo");
                    JsonNode coords = geo.findValue("coordinates");

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

                    double lat = elements.next().asDouble();
                    double lng = elements.next().asDouble();

                    c = new Coordinate(lat, lng);

                } catch (Exception e) {
                    // if we get here, its bad data, ignore and move on to next record
                }

                if (c != null) {
                    String jsonCoords = mapper.writeValueAsString(c);
                    jedis.publish("loc", jsonCoords);
                }

                processedSuccessfully = true;
                break;
            } catch (Throwable t) {
                LOG.warn("Caught throwable while processing record " + record, t);
            }

            // backoff if we encounter an exception.
            try {
                Thread.sleep(BACKOFF_TIME_IN_MILLIS);
            } catch (InterruptedException e) {
                LOG.debug("Interrupted sleep", e);
            }
        }

        if (!processedSuccessfully) {
            LOG.error("Couldn't process record " + record + ". Skipping the record.");
        }
    }
}

From source file:com.redhat.lightblue.config.rdbms.RDBMSDataSourceConfiguration.java

@Override
public void initializeFromJson(JsonNode node) {
    if (node != null) {
        JsonNode x = node.get("metadataDataStoreParser");
        try {/*from w  w  w  .  j  av a 2 s  .c om*/
            if (x != null) {
                metadataDataStoreParser = Class.forName(x.asText());
            }
        } catch (Exception e) {
            throw new IllegalArgumentException(node.toString() + ":" + e);
        }
        x = node.get("database");
        if (x != null) {
            databaseName = x.asText();
        }
        JsonNode jsonNodeServers = node.get("connections");
        if (jsonNodeServers != null && jsonNodeServers.isArray()) {
            Iterator<JsonNode> elements = jsonNodeServers.elements();
            while (elements.hasNext()) {
                JsonNode next = elements.next();
                String datasourceName;
                String JNDI;
                x = next.get("datasourceName");
                if (x != null) {
                    datasourceName = x.asText();
                } else {
                    throw new IllegalStateException("No datasourceName was found: " + node.toString());
                }

                x = next.get("JNDI");
                if (x != null) {
                    JNDI = x.asText();
                } else {
                    throw new IllegalStateException("No JNDI was found: " + node.toString());
                }
                dataSourceJDNIMap.put(datasourceName, JNDI);
            }
        } else {
            throw new IllegalStateException("No connection was found: " + node.toString());
        }
    }
}

From source file:com.easarrive.aws.plugins.common.service.impl.TestSNSService.java

@Test
public void aaa() {
    // String message =
    // "{\"Records\":[{\"eventVersion\":\"2.0\",\"eventSource\":\"aws:s3\",\"awsRegion\":\"us-west-2\",\"eventTime\":\"2016-06-28T12:59:55.700Z\",\"eventName\":\"ObjectCreated:Put\",\"userIdentity\":{\"principalId\":\"AFRDGXV7XRMK5\"},\"requestParameters\":{\"sourceIPAddress\":\"124.205.19.130\"},\"responseElements\":{\"x-amz-request-id\":\"CA17C6B0CA3B9D5B\",\"x-amz-id-2\":\"8OnEzpN3a49R+oHXc+BXDRGEaLRjgM9sygcuNhg+G2g6FNWxK9CkE1vaxJhc+WiW\"},\"s3\":{\"s3SchemaVersion\":\"1.0\",\"configurationId\":\"test\",\"bucket\":{\"name\":\"etago-app-dev\",\"ownerIdentity\":{\"principalId\":\"AFRDGXV7XRMK5\"},\"arn\":\"arn:aws:s3:::etago-app-dev\"},\"object\":{\"key\":\"users/image/22.jpg\",\"size\":4006886,\"eTag\":\"229f0eddc267a22e02d938e294ebd7e5\",\"sequencer\":\"00577274CB93A5D229\"}}}]}";
    String message = "{\"Service\":\"Amazon S3\",\"Event\":\"s3:TestEvent\",\"Time\":\"2016-06-29T09:35:00.087Z\",\"Bucket\":\"etago-app-dev\",\"RequestId\":\"3AFC2B9075E9D4F1\",\"HostId\":\"aNL0geUz8N1uvZwQZ9mEdphu3wOYpvYCt9FiHIDTKzAEUjF6xXuOzybqRItfVtLc\"}";
    ObjectMapper mapper = JsonUtil.getInstance();
    try {//from w w w  .  j  av a2  s . c o  m
        if (StringUtil.isEmpty(message)) {
            return;
        }
        JsonNode jsonNode = mapper.readTree(message);
        if (jsonNode == null) {
            return;
        }
        JsonNode recordsJsonNode = jsonNode.get("Records");
        if (recordsJsonNode == null) {
            return;
        }
        Iterator<JsonNode> recordsJsonNodeI = recordsJsonNode.elements();
        if (recordsJsonNodeI == null) {
            return;
        }
        while (recordsJsonNodeI.hasNext()) {
            JsonNode recordJsonNode = recordsJsonNodeI.next();
            if (recordJsonNode == null) {
                continue;
            }
            JsonNode eventVersion = recordJsonNode.get("eventVersion");
            System.out.println(eventVersion.asText());
            JsonNode eventSource = recordJsonNode.get("eventSource");
            System.out.println(eventSource.asText());
            JsonNode eventName = recordJsonNode.get("eventName");
            System.out.println(eventName.asText());

        }
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.neo4j.ogm.drivers.http.driver.HttpDriver.java

public CloseableHttpResponse executeHttpRequest(HttpRequestBase request) throws HttpRequestException {

    try (CloseableHttpResponse response = HttpRequest.execute(httpClient(), request,
            configuration.getCredentials())) {
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            JsonNode responseNode = mapper.readTree(EntityUtils.toString(responseEntity));
            LOGGER.debug("Response: {}", responseNode);
            JsonNode errors = responseNode.findValue("errors");
            if (errors.elements().hasNext()) {
                JsonNode errorNode = errors.elements().next();
                throw new CypherException("Error executing Cypher", errorNode.findValue("code").asText(),
                        errorNode.findValue("message").asText());
            }/*from w w  w .ja v a  2 s  .c  o m*/
        }
        return response;
    } catch (IOException ioe) {
        throw new HttpRequestException(request, ioe);
    } finally {
        request.releaseConnection();
        LOGGER.debug("Thread: {}, Connection released", Thread.currentThread().getId());
    }
}