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:com.auditbucket.test.functional.TestWebServiceIntegration.java

public void jsonReadFiles() throws Exception {
    SecurityContextHolder.getContext().setAuthentication(authA);
    ObjectMapper mapper = new ObjectMapper();
    String filename = "//tmp/new-trainprofiles.json";
    InputStream is = new FileInputStream(filename);
    JsonNode node = mapper.readTree(is);

    System.out.println("node Count = " + node.size());
    HttpClient httpclient = new DefaultHttpClient();
    String url = "http://localhost:8080/ab-engine/track/header/new";
    for (JsonNode profile : node.elements().next()) {
        HttpPost auditPost = new HttpPost(url);
        auditPost.addHeader("content-type", "application/json");
        auditPost.addHeader("Authorization", "Basic bWlrZToxMjM=");
        MetaInputBean inputBean = new MetaInputBean("capacity", "system", "TrainProfile", DateTime.now(),
                profile.get("profileID").asText());
        LogInputBean log = new LogInputBean("moira", null, profile.toString());
        inputBean.setLog(log);//ww w . j a  v a 2  s. co m
        log.setForceReindex(true);
        StringEntity json = new StringEntity(mapper.writeValueAsString(inputBean));
        auditPost.setEntity(json);
        HttpResponse response = httpclient.execute(auditPost);

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }
    }
}

From source file:com.spankingrpgs.scarletmoon.characters.CrimsonGameCharacter.java

private void loadEquipment(JsonNode equipmentNames) {
    Iterator<JsonNode> equipmentNodes = equipmentNames.elements();
    while (equipmentNodes.hasNext()) {
        equip((Equipment) GameState.getInstance().getItem(equipmentNodes.next().asText().trim()));
    }//from   w w  w.j  a  v a2 s .c  om
}

From source file:gov.pnnl.cloud.KinesisRecordProcessor.java

/** Process records performing retries as needed. Skip "poison pill" records.
 * @param records//from  w w w . ja  va  2s .  c  o m
 */
private void processRecordsWithRetries(List<Record> records) {

    // list of messages to put into Kafka
    List<KeyedMessage<String, String>> list = new ArrayList<KeyedMessage<String, String>>();

    // iterate through the Kinesis records, and make a Kafka record for each

    for (Record record : records) {
        stats.increment(Key.KINESIS_MESSAGE_READ);
        String data = null;
        byte[] recordBytes = record.getData().array();

        Coordinate c = null;

        try {
            // For this app, we interpret the payload as UTF-8 chars.

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

            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
            stats.increment(Key.JSON_PARSE_ERROR);
        }

        String topic = "nocoords";
        if (c != null) {
            topic = "coords";
        }
        KeyedMessage<String, String> message = null;

        message = new KeyedMessage<String, String>(topic, new String(recordBytes));
        list.add(message);

    }

    boolean processedSuccessfully = false;

    for (int i = 0; i < NUM_RETRIES; i++) {
        try {
            producer.send(list);
            stats.increment(Key.KAFKA_MESSAGE_PUT);

            processedSuccessfully = true;
            break;
        } catch (Throwable t) {
            LOG.warn("Caught throwable while processing batch of " + list.size() + " records", 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 batch of " + list.size() + "records.  What to do now?");
        stats.increment(Key.KAFKA_WRITE_ERROR);

    }
}

From source file:org.jboss.aerogear.sync.diffmatchpatch.JsonMapperTest.java

@Test
public void asJsonNode() {
    final String json = "{\"content\": [\"one\", \"two\"]}";
    final JsonNode jsonNode = JsonMapper.asJsonNode(json);
    final JsonNode contentNode = jsonNode.get("content");
    assertThat(contentNode.isArray(), is(true));
    assertThat(contentNode.size(), is(2));
    final Iterator<JsonNode> elements = contentNode.elements();
    assertThat(elements.next().asText(), equalTo("one"));
    assertThat(elements.next().asText(), equalTo("two"));
}

From source file:managers.nodes.RHSManager.java

private Promise<List<String>> findInOutputStrings(JsonNode properties, JsonNode strings) {
    List<Promise<? extends String>> stringsNotFound = new ArrayList<Promise<? extends String>>();
    Iterator<JsonNode> stringIter = strings.elements();
    while (stringIter.hasNext()) {
        final JsonNode string = stringIter.next();
        Promise<Boolean> stringFound = has(properties, string);
        stringsNotFound.add(stringFound.map(new Function<Boolean, String>() {
            public String apply(Boolean stringFound) {
                if (stringFound) {
                    return "";
                }/*from   w  w w . j av  a2  s.  c  om*/
                return string.get("content").asText();
            }
        }));
    }
    return Promise.sequence(stringsNotFound).map(new Function<List<String>, List<String>>() {
        public List<String> apply(List<String> stringsNotFound) {
            List<String> strings = new ArrayList<String>();
            for (String str : stringsNotFound) {
                if (!str.equals("")) {
                    strings.add(str);
                }
            }
            return strings;
        }
    });

}

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

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

    Rule rule = new Rule();

    node.fieldNames().forEachRemaining(field -> {
        JsonNode subNode = node.findValue(field);

        switch (field) {
        case "methods":
            if (subNode != null && subNode.isArray()) {
                HttpMethod[] methods = new HttpMethod[subNode.size()];

                final int[] idx = { 0 };
                subNode.elements().forEachRemaining(jsonNode -> {
                    methods[idx[0]++] = HttpMethod.valueOf(jsonNode.asText().toUpperCase());
                });/*from  w  ww. j  av  a 2s  .  c om*/

                rule.getMethods().addAll(Arrays.asList(methods));
            }
            break;
        case "description":
            if (subNode != null) {
                rule.setDescription(subNode.asText());
            }
            break;
        case "enabled":
            if (subNode != null) {
                rule.setEnabled(subNode.asBoolean(true));
            }
            break;
        default:
            // We are in the case of a policy
            Policy policy = new Policy();

            policy.setName(field);
            policy.setConfiguration(subNode.toString());

            rule.setPolicy(policy);

            break;
        }
    });

    if (rule.getMethods().isEmpty()) {
        rule.getMethods()
                .addAll(Arrays.asList(HttpMethod.CONNECT, HttpMethod.DELETE, HttpMethod.GET, HttpMethod.HEAD,
                        HttpMethod.OPTIONS, HttpMethod.PATCH, HttpMethod.POST, HttpMethod.PUT,
                        HttpMethod.TRACE));
    }

    return rule;
}

From source file:com.redhat.lightblue.config.ldap.LdapDataSourceConfiguration.java

private Map<String, Integer> parseServers(JsonNode node) {
    JsonNode serversNode = parseJsonNode(node, "servers", true);
    Map<String, Integer> hostPortMap = new HashMap<String, Integer>();
    if (serversNode.isArray()) {
        Iterator<JsonNode> serversIterator = serversNode.elements();
        while (serversIterator.hasNext()) {
            JsonNode serverNode = serversIterator.next();
            hostPortMap.put(parseJsonNode(serverNode, LDAP_SERVER_CONFIG_HOST, true).asText(),
                    parseJsonNode(serverNode, LDAP_SERVER_CONFIG_PORT, true).asInt());
        }/* ww w .j  a  va  2 s.co  m*/
    } else {
        throw new IllegalArgumentException("Unable to parse 'servers' for ldap database " + databaseName
                + ". Must be an instance of an array and must contain at least one entry with a host and port.");
    }

    if (hostPortMap.isEmpty()) {
        throw new IllegalArgumentException(
                "At least 1 server must be provided for ldap database " + databaseName);
    }

    return hostPortMap;
}

From source file:com.unboundid.scim2.common.utils.JsonDiff.java

/**
 * Removes any fields with the {@code null} value or an empty array.
 *
 * @param node The node with {@code null} and empty array values removed.
 *//*  w ww  . j  ava  2 s  .c o m*/
private void removeNullAndEmptyValues(final JsonNode node) {
    Iterator<JsonNode> si = node.elements();
    while (si.hasNext()) {
        JsonNode field = si.next();
        if (field.isNull() || field.isArray() && field.size() == 0) {
            si.remove();
        } else if (field.isContainerNode()) {
            removeNullAndEmptyValues(field);
        }
    }
}

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));
            }//from   w  w  w  .j av a2 s . c o m
        }
    }
    logger.debug("tagFiles is {}", sections);
    logger.debug("metadataFields is {}", metadataFields);
}