Example usage for com.fasterxml.jackson.databind ObjectMapper readTree

List of usage examples for com.fasterxml.jackson.databind ObjectMapper readTree

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper readTree.

Prototype

public JsonNode readTree(URL source) throws IOException, JsonProcessingException 

Source Link

Document

Method to deserialize JSON content as tree expressed using set of JsonNode instances.

Usage

From source file:de.qaware.cloud.deployer.commons.config.util.ContentTreeUtil.java

/**
 * Parses the content and creates a object tree.
 *
 * @param contentType The type of the content (json, yaml, ...)
 * @param content     The content./* w  w  w .j  a  va2s.  co m*/
 * @return The object tree.
 * @throws ResourceConfigException If the content type isn't supported or an error during parsing occurs.
 */
public static JsonNode createObjectTree(ContentType contentType, String content)
        throws ResourceConfigException {
    if (content == null || content.isEmpty()) {
        throw new ResourceConfigException(
                COMMONS_MESSAGE_BUNDLE.getMessage("DEPLOYER_COMMONS_ERROR_EMPTY_CONTENT"));
    }
    try {
        ObjectMapper objectMapper = retrieveObjectMapper(contentType);
        return objectMapper.readTree(content);
    } catch (IOException ex) {
        throw new ResourceConfigException(
                COMMONS_MESSAGE_BUNDLE.getMessage("DEPLOYER_COMMONS_ERROR_DURING_CONTENT_PARSING"), ex);
    }
}

From source file:com.wegas.log.neo4j.Neo4jUtils.java

/**
 * Extracts from the JSON result of a query the potential error message.
 * If no message is found null is returned.
 *
 * @param result the result of the query
 * @return the error message if an error occurred, null otherwise
 */// w  ww.j av  a 2  s . c  om
protected static String extractErrorData(String result) {
    ObjectMapper om = new ObjectMapper();
    try {
        JsonNode jn = om.readTree(result);
        JsonNode jnErr = jn.path("errors");
        Iterator<JsonNode> ite1 = jnErr.elements();
        String err = "";
        while (ite1.hasNext()) {
            JsonNode jn1 = ite1.next();
            err += ", " + jn1.path("message").asText();
        }
        if ("".equals(err))
            return null;
        return err.substring(2);
    } catch (IOException ioe) {
        logger.debug("Error in extractErrorData: " + ioe.getMessage());
    }
    return null;
}

From source file:org.apache.calcite.adapter.elasticsearch.ElasticsearchTable.java

/**
 * Detects current Elastic Search version by connecting to a existing instance.
 * It is a {@code GET} request to {@code /}. Returned JSON has server information
 * (including version).//from w ww . ja va2s .  co m
 *
 * @param client low-level rest client connected to ES instance
 * @param mapper Jackson mapper instance used to parse responses
 * @return parsed version from ES, or {@link ElasticsearchVersion#UNKNOWN}
 * @throws IOException if couldn't connect to ES
 */
private static ElasticsearchVersion detectVersion(RestClient client, ObjectMapper mapper) throws IOException {
    HttpEntity entity = client.performRequest("GET", "/").getEntity();
    JsonNode node = mapper.readTree(EntityUtils.toString(entity));
    return ElasticsearchVersion.fromString(node.get("version").get("number").asText());
}

From source file:com.wegas.log.neo4j.Neo4jUtils.java

/**
 * Extracts the data part from the JSON result of a query. The data is
 * returned as a list of string(s). If no data was found, an empty list is
 * returned./*from   w ww .  j ava 2  s. co  m*/
 *
 * @param result the result of a query
 * @return the data list as a Json object
 */
protected static ArrayNode extractListData(String result) {
    ArrayNode on = objectMapper.createArrayNode();
    ObjectMapper om = new ObjectMapper();
    try {
        JsonNode jn = om.readTree(result);
        JsonNode jnRes = jn.path("results");
        Iterator<JsonNode> ite1 = jnRes.elements();
        while (ite1.hasNext()) {
            JsonNode jn1 = ite1.next();
            JsonNode jnDat = jn1.path("data");
            Iterator<JsonNode> ite2 = jnDat.elements();
            while (ite2.hasNext()) {
                JsonNode jn2 = ite2.next();
                JsonNode jnRow = jn2.path("row");
                Iterator<JsonNode> ite3 = jnRow.elements();
                while (ite3.hasNext()) {
                    JsonNode jn3 = ite3.next();
                    on.add(jn3);
                }
            }
        }
    } catch (IOException ioe) {
        logger.debug("Error in extractListData: " + ioe.getMessage());
    }
    return on;
}

From source file:com.redhat.smonkey.Monkey.java

public static JsonNode json(String s) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true);
    return mapper.readTree(s);
}

From source file:com.github.dockerjava.test.serdes.JSONTestHelper.java

/**
 * Performs roundtrip test for the specified class.
 * /* w w  w.ja v a2s  .  co m*/
 * @param <TClass>
 *            Item class
 * @param item
 *            Item to be checked
 * @param asclass
 *            Class to be used during conversions
 * @return Deserialized object after the roundtrip
 * @throws IOException
 *             JSON Conversion error
 * @throws AssertionError
 *             Validation error
 */
public static <TClass> TClass testRoundTrip(TClass item, Class<TClass> asclass)
        throws IOException, AssertionError {
    ObjectMapper mapper = new ObjectMapper();

    String serialized1 = mapper.writeValueAsString(item);
    JsonNode json1 = mapper.readTree(serialized1);
    TClass deserialized1 = mapper.readValue(serialized1, asclass);
    String serialized2 = mapper.writeValueAsString(deserialized1);
    JsonNode json2 = mapper.readTree(serialized2);
    TClass deserialized2 = mapper.readValue(serialized2, asclass);

    assertEquals(json2, json1, "JSONs must be equal after the second roundtrip");
    return deserialized2;
}

From source file:org.hbz.oerworldmap.NtToEs.java

static String findParent(String jsonLd) {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode value = null;/*from  w w w  . java2s .c  o m*/
    try {
        value = mapper.readTree(jsonLd).findValue("addressCountry");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return value != null && value.isArray() /* else in context */
            ? value.get(0).asText().trim()
            : "http://sws.geonames.org/";
}

From source file:org.fcrepo.camel.indexing.triplestore.integration.TestUtils.java

/**
 * get a count of the items in the triplestore, corresponding to a given subject.
 *///from  w w w  .j a va 2  s  . c o  m
public static Callable<Integer> triplestoreCount(final String fusekiBase, final String subject)
        throws Exception {
    final String query = "SELECT (COUNT(*) AS ?n) WHERE { <" + subject + "> ?o ?p . }";
    final String url = fusekiBase + "/query?query=" + URLEncoder.encode(query, "UTF-8") + "&output=json";
    final ObjectMapper mapper = new ObjectMapper();
    return new Callable<Integer>() {
        public Integer call() throws Exception {
            return Integer.valueOf(mapper.readTree(httpGet(url)).get("results").get("bindings").get(0).get("n")
                    .get("value").asText(), 10);
        }
    };
}

From source file:net.udidb.server.driver.EventsSocket.java

public static void passMessageToWampListener(String message, ObjectMapper objectMapper,
        IWampConnectionListener connectionListener) {
    try {/*from   w ww . j ava2s.  co m*/
        JsonNode jsonNode = objectMapper.readTree(message);
        if (jsonNode.isArray()) {
            WampMessage wampMessage = WampMessages.WampMessage.fromObjectArray((ArrayNode) jsonNode);
            if (wampMessage == null) {
                logger.warn("Encountered unknown WAMP message, ignoring: '{}'", message);
            } else {
                connectionListener.messageReceived(wampMessage);
            }
        } else {
            throw new IOException("Invalid format of message, JSON array expected");
        }
    } catch (IOException | WampError e) {
        // TODO more robust handling of this may be required in the future
        throw new IllegalArgumentException("Failed to parse or process incoming message", e);
    }
}

From source file:org.hbz.oerworldmap.NtToEs.java

private static String withGeo(Map<String, Object> compact) throws JsonGenerationException, IOException {

    ObjectMapper mapper = new ObjectMapper();
    JsonNode lat = null;// ww  w.j  a  va2 s  .  c  o  m
    JsonNode lon = null;

    lat = mapper.readTree(JsonUtils.toString(compact)).findValue("latitude");
    lon = mapper.readTree(JsonUtils.toString(compact)).findValue("longitude");
    if (lat != null && lon != null && lat instanceof ArrayNode && lon instanceof ArrayNode)
        compact.put("location",
                ((ArrayNode) lat).get(0).textValue() + ", " + ((ArrayNode) lon).get(0).textValue());
    System.out.println(JsonUtils.toPrettyString(compact));
    return JsonUtils.toString(compact);
}