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.servioticy.api.commons.data.SO.java

/** Generate response to a SO creation
 *
 * @return String/*from  w  w w . j  a v  a2s .c o m*/
 */
public String responseUpdateSO() {
    JsonNode root = mapper.createObjectNode();

    try {
        ((ObjectNode) root).put("id", soId);
        ((ObjectNode) root).put("updatedAt", soRoot.get("updatedAt").asLong());
    } catch (Exception e) {
        LOG.error(e);
        throw new ServIoTWebApplicationException(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage());
    }
    return root.toString();
}

From source file:de.hbz.lobid.helper.CompareJsonMaps.java

/**
 * Construct a map with json paths as keys with aggregated values form json
 * nodes./*from   w w w  .  ja v a2 s  . c o m*/
 * 
 * @param jnode the JsonNode which should be transformed into a map
 * @param map the map constructed out of the JsonNode
 */
public void extractFlatMapFromJsonNode(final JsonNode jnode, final HashMap<String, String> map) {
    if (jnode.getNodeType().equals(JsonNodeType.OBJECT)) {
        final Iterator<Map.Entry<String, JsonNode>> it = jnode.fields();
        while (it.hasNext()) {
            final Map.Entry<String, JsonNode> entry = it.next();
            stack.push(entry.getKey());
            extractFlatMapFromJsonNode(entry.getValue(), map);
            stack.pop();
        }
    } else if (jnode.isArray()) {
        final Iterator<JsonNode> it = jnode.iterator();
        while (it.hasNext()) {
            extractFlatMapFromJsonNode(it.next(), map);
        }
    } else if (jnode.isValueNode()) {
        String value = jnode.toString();
        if (map.containsKey(stack.toString()))
            value = map.get(stack.toString()).concat("," + jnode.toString());
        map.put(stack.toString(), value);
        CompareJsonMaps.logger.trace("Stored this path as key into map:" + stack.toString(), value);
    }
}

From source file:com.googlecode.jsonrpc4j.JsonRpcHttpAsyncClient.java

/**
 * Reads a JSON-PRC response from the server. This blocks until a response
 * is received.//from  ww  w .j  a  va 2s  .c  om
 * 
 * @param returnType
 *            the expected return type
 * @param ips
 *            the {@link InputStream} to read from
 * @return the object returned by the JSON-RPC response
 * @throws Throwable
 *             on error
 */
private <T> T readResponse(Type returnType, InputStream ips) throws Throwable {

    // read the response
    JsonNode response = mapper.readTree(new NoCloseInputStream(ips));
    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.log(Level.FINE, "JSON-PRC Response: " + response.toString());
    }

    // bail on invalid response
    if (!response.isObject()) {
        throw new JsonRpcClientException(0, "Invalid JSON-RPC response", response);
    }
    ObjectNode jsonObject = ObjectNode.class.cast(response);

    // detect errors
    if (jsonObject.has("error") && jsonObject.get("error") != null && !jsonObject.get("error").isNull()) {

        // resolve and throw the exception
        if (exceptionResolver == null) {
            throw DefaultExceptionResolver.INSTANCE.resolveException(jsonObject);
        } else {
            throw exceptionResolver.resolveException(jsonObject);
        }
    }

    // convert it to a return object
    if (jsonObject.has("result") && !jsonObject.get("result").isNull() && jsonObject.get("result") != null) {

        JsonParser returnJsonParser = mapper.treeAsTokens(jsonObject.get("result"));
        JavaType returnJavaType = TypeFactory.defaultInstance().constructType(returnType);

        return mapper.readValue(returnJsonParser, returnJavaType);
    }

    // no return type
    return null;
}

From source file:com.pros.jsontransform.ObjectTransformer.java

private void transformNode(final JsonNode sourceNode, final JsonNode transformNode, final ObjectNode targetNode)
        throws ObjectTransformerException {
    this.sourceNode = sourceNode;
    this.transformNode = transformNode;

    if (logger.getLevel() == Level.DEBUG) {
        logger.debug("transform " + transformNode.toString());
        logger.debug("source " + sourceNode.toString());
        logger.debug("source path " + this.sourceNodePath);
        for (JsonNode parent : sourceNodeParents) {
            int trunc = parent.toString().length() > 100 ? 100 : parent.toString().length();
            logger.debug("parent " + parent.toString().substring(0, trunc));
        }//from  w  w w.  j  a  v  a2s  . c o m
    }

    // process $path directive
    JsonNode newSourceNode = updateSourceFromPath(sourceNode, transformNode.get(PATH));

    Iterator<String> fieldNames = transformNode.fieldNames();
    while (fieldNames.hasNext()) {
        transformNodeFieldName = fieldNames.next();
        if (transformNodeFieldName.equalsIgnoreCase(COMMENT)) {
            // ignore $comment nodes
            continue;
        }

        JsonNode transformChildNode = transformNode.get(transformNodeFieldName);
        if (transformChildNode.get(VALUE) != null || transformChildNode.get(EXPRESSION) != null) {
            // mapping value from transform map
            targetNode.put(transformNodeFieldName, transformExpression(newSourceNode, transformChildNode));
        } else if (transformChildNode.get(STRUCTURE) != null) {
            transformStructure(newSourceNode, transformChildNode, targetNode);
        } else if (transformChildNode.isObject()) {
            transformObject(newSourceNode, transformChildNode, targetNode);
        } else if (transformChildNode.isArray()) {
            transformArray(newSourceNode, transformChildNode, targetNode);
        } else if (!transformNodeFieldName.startsWith("$")) {
            // simple JSON field, copy from transform map
            targetNode.put(transformNodeFieldName, transformChildNode);
        }
    }

    // restore path
    restoreSourceFromPath(sourceNode, transformNode.get(PATH));
}

From source file:org.jboss.aerogear.sync.server.netty.DiffSyncHandler.java

@Override
protected void channelRead0(final ChannelHandlerContext ctx, final WebSocketFrame frame) throws Exception {
    if (frame instanceof CloseWebSocketFrame) {
        logger.debug("Received closeFrame");
        ctx.close();/*  ww w.  j a v a2 s . c  om*/
        return;
    }

    if (frame instanceof TextWebSocketFrame) {
        final JsonNode json = JsonMapper.asJsonNode(((TextWebSocketFrame) frame).text());
        logger.info("Doc:" + json);
        switch (MessageType.from(json.get("msgType").asText())) {
        case ADD:
            final Document<T> doc = syncEngine.documentFromJson(json);
            final String clientId = json.get("clientId").asText();
            final PatchMessage<S> patchMessage = addSubscriber(doc, clientId, ctx);
            ctx.attr(DOC_ADD).set(true);
            ctx.channel().writeAndFlush(textFrame(patchMessage.asJson()));
            break;
        case PATCH:
            final PatchMessage<S> clientPatchMessage = syncEngine.patchMessageFromJson(json.toString());
            checkForReconnect(clientPatchMessage.documentId(), clientPatchMessage.clientId(), ctx);
            logger.debug("Client Edits = " + clientPatchMessage);
            patch(clientPatchMessage);
            break;
        case DETACH:
            // detach the client from a specific document.
            break;
        case UNKNOWN:
            unknownMessageType(ctx, json);
            break;
        }
    } else {
        ctx.fireChannelRead(frame);
    }
}

From source file:com.almende.eve.state.mongo.MongoState.java

@Override
public synchronized boolean locPutIfUnchanged(final String key, final JsonNode newVal, JsonNode oldVal) {
    boolean result = false;
    try {/*from   w  w  w. jav a2 s . c  o m*/
        JsonNode cur = NullNode.getInstance();
        if (properties.containsKey(key)) {
            cur = properties.get(key);
        }
        if (oldVal == null) {
            oldVal = NullNode.getInstance();
        }

        // Poor man's equality as some Numbers are compared incorrectly: e.g.
        // IntNode versus LongNode
        if (oldVal.equals(cur) || oldVal.toString().equals(cur.toString())) {
            properties.put(key, newVal);
            result = updateProperties(false); // updateField(key, newVal);
        }
    } catch (final UpdateConflictException e) {
        LOG.log(Level.WARNING, e.getMessage());
        reloadProperties();
        // recur if update conflict occurs
        locPutIfUnchanged(key, newVal, oldVal);
    } catch (final Exception e) {
        LOG.log(Level.WARNING, "locPutIfUnchanged error", e);
    }

    return result;
}

From source file:com.almende.eve.state.couchdb.CouchDBState.java

@Override
public synchronized boolean locPutIfUnchanged(final String key, final JsonNode newVal, JsonNode oldVal) {
    final String ckey = couchify(key);
    boolean result = false;
    try {/*from   w  w  w  .jav a2  s  .  c  om*/
        JsonNode cur = NullNode.getInstance();
        if (properties.containsKey(ckey)) {
            cur = properties.get(ckey);
        }
        if (oldVal == null) {
            oldVal = NullNode.getInstance();
        }

        // Poor mans equality as some Numbers are compared incorrectly: e.g.
        // IntNode versus LongNode
        if (oldVal.equals(cur) || oldVal.toString().equals(cur.toString())) {
            properties.put(ckey, newVal);
            update();
            result = true;
        }
    } catch (final UpdateConflictException uce) {
        read();
        return locPutIfUnchanged(ckey, newVal, oldVal);
    } catch (final Exception e) {
        LOG.log(Level.WARNING, "", e);
    }

    return result;
}

From source file:io.cloudslang.content.json.actions.GetValueFromObject.java

private JsonNode getValue(JsonNode jsonElement, String aKey) throws Exception {

    //non JSON array object
    if (!aKey.matches(".*" + ESCAPED_SLASH + "[[0-9]+]$")) {
        if (jsonElement.get(aKey) != null) {
            return jsonElement.get(aKey);
        } else/*  w  w w. j a va2s. c o  m*/
            throw new Exception("The " + aKey + " key does not exist in JavaScript object!");
    }
    //JSON array object
    else {
        int startIndex = aKey.indexOf("[");
        int endIndex = aKey.indexOf("]");
        String oneKey = aKey.substring(0, startIndex);
        int index = 0;
        try {
            index = Integer.parseInt(aKey.substring(startIndex + 1, endIndex));
        } catch (NumberFormatException e) {
            throw new Exception("Invalid index provided: " + index);
        }
        JsonNode subObject;
        subObject = jsonElement.get(oneKey);
        if (jsonElement.get(oneKey) != null) {
            if (subObject instanceof ArrayNode) {
                final ArrayNode asJsonArray = (ArrayNode) subObject;
                if ((index >= asJsonArray.size()) || (index < 0)) {
                    throw new Exception("The provided " + index
                            + " index is out of range! Provide a valid index value in the provided JSON!");
                } else {
                    return asJsonArray.get(index);
                }
            } else {
                throw new Exception("Invalid json array provided: " + subObject.toString() + " ");
            }
        } else {
            throw new Exception("The " + aKey + " key does not exist in JavaScript object!");
        }
    }
}

From source file:com.almende.eve.state.couch.CouchState.java

@Override
public boolean locPutIfUnchanged(final String key, final JsonNode newVal, JsonNode oldVal) {
    final String ckey = couchify(key);
    boolean result = false;
    try {//  w  w  w  .  j  a v a2  s. co m
        JsonNode cur = NullNode.getInstance();
        if (properties.containsKey(ckey)) {
            cur = properties.get(ckey);
        }
        if (oldVal == null) {
            oldVal = NullNode.getInstance();
        }

        // Poor mans equality as some Numbers are compared incorrectly: e.g.
        // IntNode versus LongNode
        if (oldVal.equals(cur) || oldVal.toString().equals(cur.toString())) {
            synchronized (properties) {
                properties.put(ckey, newVal);
            }
            db.update(this);
            result = true;
        }
    } catch (final UpdateConflictException uce) {
        read();
        return locPutIfUnchanged(ckey, newVal, oldVal);
    } catch (final Exception e) {
        LOG.log(Level.WARNING, "", e);
    }

    return result;
}

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

@Override
public void initializeFromJson(JsonNode node) {
    if (node != null) {
        JsonNode x = node.get("controllers");
        if (x instanceof ArrayNode) {
            List<ControllerConfiguration> list = new ArrayList<>(x.size());
            for (Iterator<JsonNode> itr = ((ArrayNode) x).elements(); itr.hasNext();) {
                JsonNode controllerNode = itr.next();
                ControllerConfiguration controller = new ControllerConfiguration();
                controller.initializeFromJson(controllerNode);
                list.add(controller);// w ww .  jav a2  s .c  om
            }
            controllers = list.toArray(new ControllerConfiguration[list.size()]);
        } else {
            throw new IllegalArgumentException(
                    "'controllers' must be instanceof ArrayNode: " + node.toString());
        }

        x = node.get("validateRequests");
        if (x != null)
            validateRequests = x.booleanValue();
    }
}