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

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

Introduction

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

Prototype

public abstract String toString();

Source Link

Usage

From source file:com.discover.cls.processors.cls.JSONToAttributes.java

private void addKeys(final String currentPath, final JsonNode jsonNode, final String separator,
        final boolean preserveType, final boolean flattenArrays, final Map<String, String> map) {
    if (jsonNode.isObject()) {
        ObjectNode objectNode = (ObjectNode) jsonNode;
        Iterator<Map.Entry<String, JsonNode>> iter = objectNode.fields();
        String pathPrefix = currentPath.isEmpty() ? "" : currentPath + separator;

        while (iter.hasNext()) {
            Map.Entry<String, JsonNode> entry = iter.next();
            addKeys(pathPrefix + entry.getKey(), entry.getValue(), separator, preserveType, flattenArrays, map);
        }/*from   w  w w  .ja  v  a2 s . c o m*/
    } else if (jsonNode.isArray()) {
        if (flattenArrays) {
            ArrayNode arrayNode = (ArrayNode) jsonNode;
            for (int i = 0; i < arrayNode.size(); i++) {
                addKeys(currentPath + "[" + i + "]", arrayNode.get(i), separator, preserveType, flattenArrays,
                        map);
            }
        } else {
            map.put(currentPath, jsonNode.toString());
        }
    } else if (jsonNode.isValueNode()) {
        ValueNode valueNode = (ValueNode) jsonNode;
        map.put(currentPath,
                valueNode.isTextual() && preserveType ? valueNode.toString() : valueNode.textValue());
    }
}

From source file:com.ning.metrics.action.hdfs.data.JsonNodeComparable.java

@Override
public int compareTo(Object o) {
    JsonNode thing = (JsonNode) o;

    if (isMissingNode() && !thing.isMissingNode()) {
        return -1;
    } else if (!isMissingNode() && thing.isMissingNode()) {
        return 1;
    }//from  ww w.ja  v a2  s .c  om

    int mySize = 0;
    Iterator<JsonNode> myIterator = elements();
    while (myIterator.hasNext()) {
        mySize++;
    }

    int hisSize = 0;
    Iterator<JsonNode> hisIterator = thing.elements();
    while (hisIterator.hasNext()) {
        hisSize++;
    }

    if (mySize != 0 || hisSize != 0) {
        if (mySize > hisSize) {
            return 1;
        } else if (mySize < hisSize) {
            return -1;
        }
    }

    // Looks like both nodes don't have children
    if (isValueNode() && thing.isValueNode()) {
        return textValue().compareTo(thing.textValue());
    } else {
        if (equals(thing)) {
            return 0;
        } else {
            // Weak. When do we come here?
            return toString().compareTo(thing.toString());
        }
    }
}

From source file:controllers.AnyplaceMapping.java

/**
 * Uploads a floor plan file and stores it at the server system.
 * If another floorplan exists for this floor we overwrite it.
 * <p>/*  w  w  w .  ja  v  a 2s  .  c om*/
 * Needs a field:
 * floorplan: the floor plan file
 * json: The json document
 *
 * @return
 */
public static Result floorPlanUpload() {
    OAuth2Request anyReq = new OAuth2Request(request(), response());

    Http.MultipartFormData body = anyReq.getMultipartFormData();
    if (body == null) {
        return AnyResponseHelper.bad_request("Invalid request type - Not Multipart!");
    }

    Http.MultipartFormData.FilePart floorplan;
    floorplan = body.getFile("floorplan");
    if (floorplan == null) {
        return AnyResponseHelper.bad_request("Cannot find the floor plan file in your request!");
    }

    Map<String, String[]> urlenc = body.asFormUrlEncoded();
    String json_str = urlenc.get("json")[0];
    //System.out.println("json: " + json_str);

    if (json_str == null) {
        return AnyResponseHelper.bad_request("Cannot find json in the request!");
    }

    JsonNode json = null;
    try {
        json = JsonUtils.getJsonTree(json_str);
    } catch (IOException e) {
        return AnyResponseHelper.bad_request("Cannot parse json in the request!");
    }
    LPLogger.info("Floorplan Request[json]: " + json.toString());
    LPLogger.info("Floorplan Request[floorplan]: " + floorplan.getFile().getAbsolutePath());

    //// Request has the required parts so now process the json data
    List<String> requiredMissing = JsonUtils.requirePropertiesInJson(json, "buid", "floor_number",
            "bottom_left_lat", "bottom_left_lng", "top_right_lat", "top_right_lng");
    if (!requiredMissing.isEmpty()) {
        return AnyResponseHelper.requiredFieldsMissing(requiredMissing);
    }

    String buid = json.path("buid").textValue();
    String floor_number = json.path("floor_number").textValue();

    String bottom_left_lat = json.path("bottom_left_lat").textValue();
    String bottom_left_lng = json.path("bottom_left_lng").textValue();
    String top_right_lat = json.path("top_right_lat").textValue();
    String top_right_lng = json.path("top_right_lng").textValue();

    String fuid = Floor.getId(buid, floor_number);
    try {
        ObjectNode stored_floor = (ObjectNode) ProxyDataSource.getIDatasource().getFromKeyAsJson(fuid);
        if (stored_floor == null) {
            return AnyResponseHelper.bad_request("Floor does not exist or could not be retrieved!");
        }

        // update the Floor document in couchbase to include the floor plan's coordinates
        stored_floor.put("bottom_left_lat", bottom_left_lat);
        stored_floor.put("bottom_left_lng", bottom_left_lng);
        stored_floor.put("top_right_lat", top_right_lat);
        stored_floor.put("top_right_lng", top_right_lng);

        if (!ProxyDataSource.getIDatasource().replaceJsonDocument(fuid, 0, stored_floor.toString())) {
            return AnyResponseHelper.bad_request("Floor plan could not be updated in the database!");
        }
    } catch (DatasourceException e) {
        return AnyResponseHelper.internal_server_error("Error while reading from our backend service!");
    }

    /////////////////////////////////////////////////////////////////////////////////////////////
    // store the new floor plan on the server
    File floor_file;
    try {
        floor_file = AnyPlaceTilerHelper.storeFloorPlanToServer(buid, floor_number, floorplan.getFile());
    } catch (AnyPlaceException e) {
        // TODO - I should put the old couchbase object in the database
        return AnyResponseHelper.bad_request("Cannot save floor plan on the server!");
    }

    /////////////////////////////////////////////////////////////////////////////////////////////
    // Now we should start the tiling process in order to create the tiles for the floor plan
    String top_left_lat = top_right_lat;
    String top_left_lng = bottom_left_lng;
    try {
        AnyPlaceTilerHelper.tileImage(floor_file, top_left_lat, top_left_lng);
    } catch (AnyPlaceException e) {
        // TODO - I should put the old couchbase object in the database
        return AnyResponseHelper.bad_request("Could not create floor plan tiles on the server!");
    }

    LPLogger.info("Successfully tiled [" + floor_file.toString() + "]");
    return AnyResponseHelper.ok("Successfully updated floor plan!");
}

From source file:com.redhat.lightblue.config.DataSourcesConfiguration.java

@Override
public final void initializeFromJson(JsonNode node) {
    // Node must be an object node
    if (node instanceof ObjectNode) {
        for (Iterator<Map.Entry<String, JsonNode>> fieldItr = node.fields(); fieldItr.hasNext();) {
            Map.Entry<String, JsonNode> field = fieldItr.next();
            String name = field.getKey();
            JsonNode dsNode = field.getValue();
            LOGGER.debug("Parsing {}", name);
            JsonNode typeNode = dsNode.get("type");
            if (typeNode == null) {
                throw new IllegalArgumentException("type expected in " + name);
            }/* ww w  .java 2s  .c o  m*/
            String type = typeNode.asText();
            LOGGER.debug("{} is a {}", name, type);
            try {
                Class clazz = Class.forName(type);
                DataSourceConfiguration ds = (DataSourceConfiguration) clazz.newInstance();
                ds.initializeFromJson(dsNode);
                datasources.put(name, ds);
            } catch (Exception e) {
                throw new IllegalArgumentException(dsNode + ":" + e);
            }
        }
    } else {
        throw new IllegalArgumentException("node must be instanceof ObjectNode: " + node.toString());
    }
}

From source file:com.marklogic.jena.functionaltests.ConnectedRESTQA.java

public static void setPathRangeIndexInDatabase(String dbName, JsonNode jnode) throws IOException {
    try {/*from   w  w  w. j  av a 2s.com*/
        DefaultHttpClient client = new DefaultHttpClient();
        client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002),
                new UsernamePasswordCredentials("admin", "admin"));

        HttpPut put = new HttpPut(
                "http://localhost:8002" + "/manage/v2/databases/" + dbName + "/properties?format=json");
        put.addHeader("Content-type", "application/json");
        put.setEntity(new StringEntity(jnode.toString()));

        HttpResponse response = client.execute(put);
        HttpEntity respEntity = response.getEntity();
        if (respEntity != null) {
            String content = EntityUtils.toString(respEntity);
            System.out.println(content);
        }
    } catch (Exception e) {
        // writing error to Log
        e.printStackTrace();
    }
}

From source file:com.marklogic.jena.functionaltests.ConnectedRESTQA.java

public static void setDatabaseProperties(String dbName, String prop, String propValue) throws IOException {
    InputStream jsonstream = null;
    try {/*from www.  j  a v  a 2  s  .  com*/
        DefaultHttpClient client = new DefaultHttpClient();
        client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002),
                new UsernamePasswordCredentials("admin", "admin"));
        HttpGet getrequest = new HttpGet(
                "http://localhost:8002" + "/manage/v2/databases/" + dbName + "/properties?format=json");
        HttpResponse response1 = client.execute(getrequest);
        jsonstream = response1.getEntity().getContent();
        JsonNode jnode = new ObjectMapper().readTree(jsonstream);
        if (!jnode.isNull()) {
            ((ObjectNode) jnode).put(prop, propValue);
            //            System.out.println(jnode.toString()+"\n"+ response1.getStatusLine().getStatusCode());
            HttpPut put = new HttpPut(
                    "http://localhost:8002" + "/manage/v2/databases/" + dbName + "/properties?format=json");
            put.addHeader("Content-type", "application/json");
            put.setEntity(new StringEntity(jnode.toString()));

            HttpResponse response2 = client.execute(put);
            HttpEntity respEntity = response2.getEntity();
            if (respEntity != null) {
                String content = EntityUtils.toString(respEntity);
                System.out.println(content);
            }
        } else {
            System.out.println("REST call for database properties returned NULL ");
        }
    } catch (Exception e) {
        // writing error to Log
        e.printStackTrace();
    } finally {
        if (jsonstream == null) {
        } else {
            jsonstream.close();
        }
    }
}

From source file:com.marklogic.jena.functionaltests.ConnectedRESTQA.java

public static void setDatabaseProperties(String dbName, String prop, boolean propValue) throws IOException {
    InputStream jsonstream = null;
    try {/*from  w  ww .j  a  v  a  2 s. c  o  m*/
        DefaultHttpClient client = new DefaultHttpClient();
        client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002),
                new UsernamePasswordCredentials("admin", "admin"));
        HttpGet getrequest = new HttpGet(
                "http://localhost:8002" + "/manage/v2/databases/" + dbName + "/properties?format=json");
        HttpResponse response1 = client.execute(getrequest);
        jsonstream = response1.getEntity().getContent();
        JsonNode jnode = new ObjectMapper().readTree(jsonstream);
        if (!jnode.isNull()) {
            ((ObjectNode) jnode).put(prop, propValue);
            //            System.out.println(jnode.toString()+"\n"+ response1.getStatusLine().getStatusCode());
            HttpPut put = new HttpPut(
                    "http://localhost:8002" + "/manage/v2/databases/" + dbName + "/properties?format=json");
            put.addHeader("Content-type", "application/json");
            put.setEntity(new StringEntity(jnode.toString()));

            HttpResponse response2 = client.execute(put);
            HttpEntity respEntity = response2.getEntity();
            if (respEntity != null) {
                String content = EntityUtils.toString(respEntity);
                System.out.println(content);
            }
        } else {
            System.out.println("REST call for database properties returned NULL ");
        }
    } catch (Exception e) {
        // writing error to Log
        e.printStackTrace();
    } finally {
        if (jsonstream == null) {
        } else {
            jsonstream.close();
        }
    }
}

From source file:com.servioticy.api.commons.data.SO.java

/** Return the streams in output format
 *
 * @return The streams in output format// w w w.ja va 2 s. c  om
 */
public String responseStreams() {

    JsonNode streams = soRoot.path("streams");
    if (streams == null)
        return null;

    JsonNode root = mapper.createObjectNode();
    try {
        Map<String, JsonNode> mstreams = mapper.readValue(streams.traverse(),
                new TypeReference<Map<String, JsonNode>>() {
                });
        ArrayList<JsonNode> astreams = new ArrayList<JsonNode>();
        JsonNode s;

        for (Map.Entry<String, JsonNode> stream : mstreams.entrySet()) {
            s = mapper.createObjectNode();
            ((ObjectNode) s).put("name", stream.getKey());
            ((ObjectNode) s).putAll((ObjectNode) stream.getValue());
            ((ObjectNode) s).remove("data");
            astreams.add(s);
        }
        ((ObjectNode) root).put("streams", mapper.readTree(mapper.writeValueAsString(astreams)));
    } catch (Exception e) {
        LOG.error(e);
        throw new ServIoTWebApplicationException(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage());
    }

    return root.toString();
}