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.springframework.data.repository.init.Jackson2ResourceReader.java

public Object readFrom(Resource resource, ClassLoader classLoader) throws Exception {

    InputStream stream = resource.getInputStream();
    JsonNode node = mapper.readerFor(JsonNode.class).readTree(stream);

    if (node.isArray()) {

        Iterator<JsonNode> elements = node.elements();
        List<Object> result = new ArrayList<>();

        while (elements.hasNext()) {
            JsonNode element = elements.next();
            result.add(readSingle(element, classLoader));
        }/*from   w  ww  . ja  v a2 s .  c  om*/

        return result;
    }

    return readSingle(node, classLoader);
}

From source file:org.graylog.plugins.pipelineprocessor.functions.json.SelectJsonPath.java

private Object unwrapJsonNode(Object value) {
    if (!(value instanceof JsonNode)) {
        return value;
    }//from w ww.  j ava 2  s  .  c  o  m
    JsonNode read = ((JsonNode) value);
    switch (read.getNodeType()) {
    case ARRAY:
        return ImmutableList.copyOf(read.elements());
    case BINARY:
        try {
            return read.binaryValue();
        } catch (IOException e) {
            return null;
        }
    case BOOLEAN:
        return read.booleanValue();
    case MISSING:
    case NULL:
        return null;
    case NUMBER:
        return read.numberValue();
    case OBJECT:
        return read;
    case POJO:
        return read;
    case STRING:
        return read.textValue();
    }
    return read;
}

From source file:com.strategicgains.hyperexpress.serialization.jackson.HalResourceDeserializer.java

/**
 * @param resource//from w  w w  .  j ava2s  .  c  o m
 * @param field
 */
private void addAllLinks(HalResource resource, Entry<String, JsonNode> field) {
    LinkBuilder lb = new LinkBuilder();
    lb.rel(field.getKey());
    Iterator<JsonNode> values = field.getValue().elements();

    while (values.hasNext()) {
        JsonNode value = values.next();
        Iterator<JsonNode> elements = value.elements();

        while (elements.hasNext()) {
            JsonNode element = elements.next();
            lb.set(element.asText(), element.textValue());
        }

        resource.addLink(lb.build());
        lb.clearAttributes();
    }
}

From source file:org.jsonschema2pojo.rules.RequiredArrayRule.java

@Override
public JDefinedClass apply(String nodeName, JsonNode node, JDefinedClass jclass, Schema schema) {
    List<String> requiredFieldMethods = new ArrayList<String>();

    for (Iterator iterator = node.elements(); iterator.hasNext();) {
        String fieldName = ruleFactory.getNameHelper().getPropertyName(((JsonNode) iterator.next()).asText());
        JFieldVar field = jclass.fields().get(fieldName);

        if (field == null) {
            continue;
        }//from w w w  .  j a  v a 2  s  . com

        addJavaDoc(field);

        if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations()) {
            addNotNullAnnotation(field);
        }

        requiredFieldMethods.add(getGetterName(fieldName, field.type()));
        requiredFieldMethods.add(getSetterName(fieldName));
    }

    updateGetterSetterJavaDoc(jclass, requiredFieldMethods);

    return jclass;
}

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

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

    Proxy proxy = new Proxy();
    final JsonNode contextPath = node.get("context_path");
    if (contextPath != null) {
        String sContextPath = formatContextPath(contextPath.asText());
        proxy.setContextPath(sContextPath);
    } else {/*from ww w  .  ja  v  a  2  s . com*/
        throw ctxt.mappingException("[api] API must have a valid context path");
    }

    final JsonNode nodeEndpoints = node.get("endpoints");

    if (nodeEndpoints != null && nodeEndpoints.isArray()) {
        nodeEndpoints.elements().forEachRemaining(jsonNode -> {
            try {
                Endpoint endpoint = jsonNode.traverse(jp.getCodec()).readValueAs(Endpoint.class);
                proxy.getEndpoints().add(endpoint);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    JsonNode stripContextNode = node.get("strip_context_path");
    if (stripContextNode != null) {
        proxy.setStripContextPath(stripContextNode.asBoolean(false));
    }

    JsonNode loadBalancingNode = node.get("load_balancing");
    if (loadBalancingNode != null) {
        LoadBalancer loadBalancer = loadBalancingNode.traverse(jp.getCodec()).readValueAs(LoadBalancer.class);
        proxy.setLoadBalancer(loadBalancer);
    }

    JsonNode failoverNode = node.get("failover");
    if (failoverNode != null) {
        Failover failover = failoverNode.traverse(jp.getCodec()).readValueAs(Failover.class);
        proxy.setFailover(failover);
    }

    JsonNode dumpRequestNode = node.get("dumpRequest");
    if (dumpRequestNode != null) {
        boolean dumpRequest = dumpRequestNode.asBoolean(Proxy.DEFAULT_DUMP_REQUEST);
        proxy.setDumpRequest(dumpRequest);
    } else {
        proxy.setDumpRequest(Proxy.DEFAULT_DUMP_REQUEST);
    }

    return proxy;
}

From source file:org.hawkular.component.availcreator.MetricReceiver.java

@Override
public void onMessage(Message message) {

    try {/* www. j  a  v a 2s  .  c o m*/
        String payload = ((TextMessage) message).getText();
        JsonNode rootNode = objectMapper.readTree(payload);

        JsonNode metricData = rootNode.get("metricData");
        // Get <rid>.status.code  metrics
        String tenant = metricData.get("tenantId").textValue();
        JsonNode data = metricData.get("data");
        List<SingleAvail> outer = new ArrayList<>();

        Iterator<JsonNode> items = data.elements();
        while (items.hasNext()) {
            JsonNode item = items.next();

            String source = item.get("source").textValue();
            if (source.endsWith(".status.code")) {
                int code = item.get("value").intValue();

                String id = source.substring(0, source.indexOf("."));
                long timestamp = item.get("timestamp").longValue();

                String avail = computeAvail(code);

                SingleAvail ar = new SingleAvail(tenant, id, timestamp, avail);
                outer.add(ar);
            }
        }
        if (!outer.isEmpty()) {
            availPublisher.publish(outer);
        }

    } catch (Exception e) {
        Log.LOG.eCouldNotHandleBusMessage(e);
    }

}

From source file:net.troja.eve.producersaid.utils.EveCentral.java

private Map<Integer, EveCentralPrice> parsePrices(final String content) {
    final Map<Integer, EveCentralPrice> map = new ConcurrentHashMap<>();
    try {//from ww w . j a  va 2s  .  c om
        final JsonNode node = objectMapper.readTree(content);
        final Iterator<JsonNode> iter = node.elements();
        while (iter.hasNext()) {
            final EveCentralPrice price = convertToObject(iter.next());
            map.put(price.getTypeId(), price);
        }

    } catch (final IOException e) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("Could not parse data", e);
        }
    }
    return map;
}

From source file:org.apache.nifi.registry.client.impl.BucketItemDeserializer.java

@Override
public BucketItem[] deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
        throws IOException, JsonProcessingException {
    final JsonNode arrayNode = jsonParser.getCodec().readTree(jsonParser);

    final List<BucketItem> bucketItems = new ArrayList<>();

    final Iterator<JsonNode> nodeIter = arrayNode.elements();
    while (nodeIter.hasNext()) {
        final JsonNode node = nodeIter.next();

        final String type = node.get("type").asText();
        if (StringUtils.isBlank(type)) {
            throw new IllegalStateException("BucketItem type cannot be null or blank");
        }/*from w  w w.j  av a 2s .  com*/

        final BucketItemType bucketItemType;
        try {
            bucketItemType = BucketItemType.valueOf(type);
        } catch (Exception e) {
            throw new IllegalStateException("Unknown type for BucketItem: " + type, e);
        }

        switch (bucketItemType) {
        case Flow:
            final VersionedFlow versionedFlow = jsonParser.getCodec().treeToValue(node, VersionedFlow.class);
            bucketItems.add(versionedFlow);
            break;
        case Extension_Bundle:
            final ExtensionBundle extensionBundle = jsonParser.getCodec().treeToValue(node,
                    ExtensionBundle.class);
            bucketItems.add(extensionBundle);
            break;
        default:
            throw new IllegalStateException("Unknown type for BucketItem: " + bucketItemType);
        }
    }

    return bucketItems.toArray(new BucketItem[bucketItems.size()]);
}

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

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

    Failover failover = new Failover();

    final JsonNode casesNode = node.get("cases");
    if (casesNode != null) {
        if (casesNode.isArray()) {
            List<FailoverCase> cases = new ArrayList<>();

            casesNode.elements().forEachRemaining(
                    jsonNode -> cases.add(FailoverCase.valueOf(jsonNode.asText().toUpperCase())));

            failover.setCases(cases.toArray(new FailoverCase[cases.size()]));
        } else {/* w  w  w  .ja  va  2  s .c o m*/
            failover.setCases(new FailoverCase[] { FailoverCase.valueOf(casesNode.asText().toUpperCase()) });
        }
    }

    JsonNode maxAttemptsNode = node.get("maxAttempts");
    if (maxAttemptsNode != null) {
        int maxAttempts = maxAttemptsNode.asInt(Failover.DEFAULT_MAX_ATTEMPTS);
        failover.setMaxAttempts(maxAttempts);
    } else {
        failover.setMaxAttempts(Failover.DEFAULT_MAX_ATTEMPTS);
    }

    JsonNode retryTimeoutNode = node.get("retryTimeout");
    if (retryTimeoutNode != null) {
        long retryTimeout = retryTimeoutNode.asLong(Failover.DEFAULT_RETRY_TIMEOUT);
        failover.setRetryTimeout(retryTimeout);
    } else {
        failover.setRetryTimeout(Failover.DEFAULT_RETRY_TIMEOUT);
    }

    return failover;
}

From source file:com.enitalk.controllers.bots.EniWordController.java

@RabbitListener(queues = "eniwords")
public void consume(Message msg) {
    try {//from ww  w .j  a va2 s . c o  m
        JsonNode user = jackson.readTree(msg.getBody());
        logger.info("Sending eniword to student {}", user);

        Integer lastWord = user.at("/eniword/wc").asInt(0) + 1;
        HashMap word = mongo.findOne(Query.query(Criteria.where("i").gt(lastWord)), HashMap.class, "words");
        if (word == null) {
            return;
        }

        ObjectNode wToSend = jackson.convertValue(word, ObjectNode.class);

        String text = "0x1f4d8 <b>EniWord</b>\n";
        text += "0x1f4e2 Word: <b>" + wToSend.path("word").asText() + "</b>\n";
        text += "0x1f4cb Part of speech: <b>" + parts.get(wToSend.path("type").asInt()) + "</b>\n";
        text += "0x1f6a9 <b>Usage:</b>\n";
        JsonNode exs = wToSend.at("/def/examples");
        Iterator<JsonNode> els = exs.elements();
        int i = 1;
        while (els.hasNext() && i < 2) {
            text += i++ + ". " + els.next().path("text").asText() + "\n";
        }

        text += "---------\nWe will send you another awesome word in 40 minutes.\nPress /recommend to get back to the menu and browse teachers.";

        logger.info("Text to send {}", text);

        ArrayNode tg = jackson.createArrayNode();
        ObjectNode o = tg.addObject();
        o.set("dest", user.path("dest"));
        ObjectNode message = jackson.createObjectNode();
        o.set("message", message);
        message.put("text", text);

        //make unsubscribe button
        ArrayNode a = jackson.createArrayNode();
        //            String buttonUrl = env.getProperty("self.url") + "/eniword/cancel/" + user.at("/dest/sendTo").asLong();
        //            logger.info("Button url {}", buttonUrl);

        //            makeButtonHref(a, "Stop sending words", buttonUrl);
        message.set("buttons", a);

        rate.acquire();
        sendMessages(tg);

        mongo.updateFirst(Query.query(Criteria.where("dest.sendTo").is(user.at("/dest/sendTo").asLong())),
                new Update().set("eniword.wc", wToSend.path("i").asLong()).inc("eniword.points", -1), "leads");

    } catch (Exception e) {
        logger.error(ExceptionUtils.getFullStackTrace(e));
    }
}