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:org.dd4t.databind.builder.json.JsonModelConverter.java

private <T extends BaseViewModel> BaseViewModel getBaseViewModel(final JsonNode currentField,
        final Class<T> modelClassToUse) throws SerializationException {
    final BaseViewModel strongModel = databinder.buildModel(currentField, modelClassToUse, "");
    final ViewModel viewModelParameters = modelClassToUse.getAnnotation(ViewModel.class);
    if (viewModelParameters.setRawData()) {
        strongModel.setRawData(currentField.toString());
    }//from  w  w  w  . j  a v a 2  s. c o  m
    return strongModel;
}

From source file:com.yahoo.elide.graphql.GraphQLEndpoint.java

private Response buildErrorResponse(HttpStatusException error, boolean isVerbose) {
    ObjectMapper mapper = elide.getMapper().getObjectMapper();
    JsonNode errorNode;
    if (!(error instanceof CustomErrorException) && elideSettings.isReturnErrorObjects()) {
        ErrorObjects errors = ErrorObjects.builder().addError()
                .with("message", isVerbose ? error.getVerboseMessage() : error.toString()).build();
        errorNode = mapper.convertValue(errors, JsonNode.class);
    } else {/*from ww  w .  jav a  2s  .c  o  m*/
        errorNode = isVerbose ? error.getVerboseErrorResponse().getRight()
                : error.getErrorResponse().getRight();
    }
    String errorBody;
    try {
        errorBody = mapper.writeValueAsString(errorNode);
    } catch (JsonProcessingException e) {
        errorBody = errorNode.toString();
    }
    return Response.status(error.getStatus()).entity(errorBody).build();
}

From source file:com.almende.eve.state.ConcurrentJsonFileState.java

@Override
public synchronized boolean locPutIfUnchanged(final String key, final JsonNode newVal, JsonNode oldVal) {
    boolean result = false;
    try {/*from   w ww .j av  a  2  s  .  c om*/
        openFile();
        read();

        JsonNode cur = NullNode.getInstance();
        if (properties.containsKey(key)) {
            cur = properties.get(key);
        }
        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(key, newVal);
            write();
            result = true;
        }
    } catch (final Exception e) {
        LOG.log(Level.WARNING, "", e);
        // Don't let users loop if exception is thrown. They
        // would get into a deadlock....
        result = true;
    }
    closeFile();
    return result;
}

From source file:com.almende.eve.state.file.ConcurrentJsonFileState.java

@Override
public boolean locPutIfUnchanged(final String key, final JsonNode newVal, JsonNode oldVal) {
    boolean result = false;
    try {/*  w  w  w  .  j a  v  a2s .c o  m*/
        openFile();
        read();

        JsonNode cur = NullNode.getInstance();
        if (properties.containsKey(key)) {
            cur = properties.get(key);
        }
        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(key, newVal);
            write();
            result = true;
        }
    } catch (final IllegalStateException e) {
        LOG.log(Level.WARNING, "Couldn't handle Statefile: " + e.getMessage(), e);
    } catch (final Exception e) {
        LOG.log(Level.WARNING, "", e);
        // Don't let users loop if exception is thrown. They
        // would get into a deadlock....
        result = true;
    }
    closeFile();
    return result;
}

From source file:fr.gouv.vitam.query.parser.AbstractQueryParser.java

/**
 * { expression, $depth : exactdepth, $relativedepth : /- depth }, $depth and $relativedepth being optional (mutual exclusive)
 *
 * @param command//  ww w. j a  v a2  s .  c  o m
 * @throws InvalidParseOperationException
 */
protected void analyzeRootRequest(final JsonNode command) throws InvalidParseOperationException {
    if (command == null) {
        throw new InvalidParseOperationException("Not correctly parsed");
    }
    sources.add(command.toString());
    int relativedepth = 1; // default is immediate next level
    int exactdepth = 0; // default is to not specify any exact depth (implicit)
    boolean isDepth = false;
    // first verify if depth is set
    if (command.has(REQUESTARGS.depth.exactToken())) {
        final JsonNode jdepth = ((ObjectNode) command).remove(REQUESTARGS.depth.exactToken());
        if (jdepth != null) {
            exactdepth = jdepth.asInt();
            isDepth = true;
        }
        ((ObjectNode) command).remove(REQUESTARGS.relativedepth.exactToken());
    } else if (command.has(REQUESTARGS.relativedepth.exactToken())) {
        final JsonNode jdepth = ((ObjectNode) command).remove(REQUESTARGS.relativedepth.exactToken());
        if (jdepth != null) {
            relativedepth = jdepth.asInt();
            if (relativedepth == 0) {
                relativedepth = GlobalDatas.MAXDEPTH;
            }
            isDepth = true;
        }
    }
    // Root may be empty: ok since it means validate all "start nodes"
    if (command.size() == 0) {
        TypeRequest tr = new TypeRequest();
        tr.requestModel = JsonHandler.createObjectNode();
        tr.type = REQUEST._all_;
        getRequests().add(tr);
        return;
    }
    // now single element
    final Entry<String, JsonNode> requestItem = JsonHandler.checkUnicity("RootRequest", command);
    TypeRequest tr = null;
    if (requestItem.getKey().equalsIgnoreCase(REQUEST.path.exactToken())) {
        if (isDepth) {
            throw new InvalidParseOperationException("Invalid combined command Depth and Path: " + command);
        }
        final int prevDepth = lastDepth;
        tr = analyzePath(requestItem.getKey(), requestItem.getValue());
        LOGGER.debug("Depth step: {}:{}", lastDepth, lastDepth - prevDepth);
    } else {
        tr = analyzeOneCommand(requestItem.getKey(), requestItem.getValue());
        tr.relativedepth = relativedepth;
        tr.exactdepth = exactdepth;
        tr.isDepth = isDepth;
        final int prevDepth = lastDepth;
        if (exactdepth > 0) {
            lastDepth = exactdepth;
        } else if (relativedepth != 0) {
            lastDepth += relativedepth;
        }
        LOGGER.debug("Depth step: {}:{}:{}:{}:{}", lastDepth, lastDepth - prevDepth, relativedepth, exactdepth,
                isDepth);
        checkRootTypeRequest(tr, command, prevDepth);
    }
    getRequests().add(tr);
}

From source file:com.redhat.lightblue.metadata.parser.JSONMetadataParserTest.java

License:asdf

private void testResource(String resource) throws IOException, JSONException, ProcessingException {
    // verify json is schema compliant
    runValidJsonTest("json-schema/metadata/metadata.json", resource);

    JsonNode object = loadJsonNode(resource);

    // json to java
    EntityMetadata em = parser.parseEntityMetadata(object);

    // verify got something
    Assert.assertNotNull(em);//from  w  w w  . j  a  va  2 s . co m

    // java back to json
    JsonNode converted = parser.convert(em);

    String original = loadResource(resource);
    String before = object.toString();
    String after = converted.toString();
    JSONAssert.assertEquals(original, before, false);
    JSONAssert.assertEquals(original, after, false);
}

From source file:com.hollowsoft.library.utility.request.HttpRequest.java

/**
 *
 * @param url/*from   w  ww  .  j a va  2s  . c om*/
 * @param jsonNode
 * @return
 * @throws RequestException
 */
public JsonNode doPut(final String url, final JsonNode jsonNode) throws RequestException {
    if (url == null || url.isEmpty()) {
        throw new IllegalArgumentException("The url cannot be null or empty.");
    }

    if (jsonNode == null || jsonNode.isNull()) {
        throw new IllegalArgumentException("The jsonNode cannot be null or empty.");
    }

    try {

        final HttpPut httpPut = new HttpPut(url);
        httpPut.setEntity(new StringEntity(jsonNode.toString(), Constants.DEFAULT_CHARSET.name()));

        final HttpEntity httpEntity = httpClient.execute(httpPut).getEntity();

        return new ObjectMapper().reader().readTree(httpEntity.getContent());

    } catch (final ClientProtocolException e) {
        throw new RequestException(e);

    } catch (final JsonProcessingException e) {
        throw new RequestException(e);

    } catch (final IllegalStateException e) {
        throw new RequestException(e);

    } catch (final IOException e) {
        throw new RequestException(e);
    }
}

From source file:com.hollowsoft.library.utility.request.HttpRequest.java

/**
 *
 * @param url/*from   ww  w.j a  v  a 2s . co  m*/
 * @param jsonNode
 * @return
 * @throws RequestException
 */
public JsonNode doPost(final String url, final JsonNode jsonNode) throws RequestException {
    if (url == null || url.isEmpty()) {
        throw new IllegalArgumentException("The url cannot be null or empty.");
    }

    if (jsonNode == null || jsonNode.isNull()) {
        throw new IllegalArgumentException("The jsonNode cannot be null or empty.");
    }

    try {

        final HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new StringEntity(jsonNode.toString(), Constants.DEFAULT_CHARSET.name()));

        final HttpEntity httpEntity = httpClient.execute(httpPost).getEntity();

        return new ObjectMapper().reader().readTree(httpEntity.getContent());

    } catch (final ClientProtocolException e) {
        throw new RequestException(e);

    } catch (final JsonProcessingException e) {
        throw new RequestException(e);

    } catch (final IllegalStateException e) {
        throw new RequestException(e);

    } catch (final IOException e) {
        throw new RequestException(e);
    }
}

From source file:com.evrythng.java.wrapper.mapping.CreateActionsJobInputDeserializer.java

@Override
public CreateActionJob.Input deserialize(final JsonParser jp, final DeserializationContext ctx)
        throws IOException {

    ObjectMapper mapper = JSONUtils.OBJECT_MAPPER;
    JsonNode node = mapper.readTree(jp);
    JsonNode typeNode = node.get(CreateActionJob.Input.FIELD_TYPE);
    if (typeNode == null) {
        throw new JsonMappingException("Cannot deserialize create actions job input without type field");
    }/* w  w w .j a va 2  s.  co m*/
    String typeRaw = getFieldValue(typeNode);
    JsonNode contentTypeNode = node.get(CreateActionJob.Input.FIELD_CONTENT_TYPE);
    if (contentTypeNode == null) {
        throw new JsonMappingException("Cannot deserialize create actions job input without contentType field");
    }
    String contentTypeRaw = getFieldValue(contentTypeNode);
    Class<? extends CreateActionJob.Input> subtypeClass = classForType(
            CreateActionJob.Input.Type.valueOf(typeRaw.toUpperCase()),
            CreateActionJob.Input.ContentType.valueOf(contentTypeRaw.toUpperCase()));
    return mapper.readValue(node.toString(), subtypeClass);
}

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

private void computeArrayNodeDiffs(final Path parentPath, final Path path, final ObjectNode targetToAdd,
        final ObjectNode targetToReplace, final List<PatchOperation> operations, final boolean removeMissing,
        final JsonNode sourceNode, final JsonNode targetValueToAdd, final JsonNode targetValueToReplace,
        final String sourceKey) {
    if (targetValueToAdd.size() == 0) {
        if ((sourceNode != null) && (sourceNode.isArray()) && (sourceNode.size() == 0)) {
            return;
        }//from www.  j  ava 2  s .c om

        // Explicitly clear all attribute values.
        operations.add(PatchOperation.remove(path));
    } else {
        // Go through each value and try to individually patch them first
        // instead of replacing all values.
        List<PatchOperation> targetOpToRemoveOrReplace = new LinkedList<PatchOperation>();
        boolean replaceAllValues = false;
        for (JsonNode sv : sourceNode) {
            JsonNode tv = removeMatchingValue(sv, (ArrayNode) targetValueToAdd);
            Filter valueFilter = generateValueFilter(sv);
            if (valueFilter == null) {
                replaceAllValues = true;
                Debug.debug(Level.WARNING, DebugType.OTHER,
                        "Performing full replace of target " + "array node " + path + " since the it is not "
                                + "possible to generate a value filter to uniquely " + "identify the value "
                                + sv.toString());
                break;
            }
            Path valuePath = parentPath.attribute(sourceKey, valueFilter);
            if (tv != null) {
                // The value is in both source and target arrays.
                if (sv.isObject() && tv.isObject()) {
                    // Recursively diff the object node.
                    diff(valuePath, (ObjectNode) sv, (ObjectNode) tv, (ObjectNode) tv, operations,
                            removeMissing);
                    if (tv.size() > 0) {
                        targetOpToRemoveOrReplace.add(PatchOperation.replace(valuePath, tv));
                    }
                }
            } else {
                targetOpToRemoveOrReplace.add(PatchOperation.remove(valuePath));
            }
        }
        if (!replaceAllValues
                && targetValueToReplace.size() <= targetValueToAdd.size() + targetOpToRemoveOrReplace.size()) {
            // We are better off replacing the entire array.
            Debug.debug(Level.INFO, DebugType.OTHER,
                    "Performing full replace of target " + "array node " + path + " since the " + "array ("
                            + targetValueToReplace.size() + ") " + "is smaller than removing and "
                            + "replacing (" + targetOpToRemoveOrReplace.size() + ") " + "then adding ("
                            + targetValueToAdd.size() + ")  " + "the values individually");
            replaceAllValues = true;
            targetToReplace.set(sourceKey, targetValueToReplace);

        }
        if (replaceAllValues) {
            targetToReplace.set(sourceKey, targetValueToReplace);
        } else {
            if (!targetOpToRemoveOrReplace.isEmpty()) {
                operations.addAll(targetOpToRemoveOrReplace);
            }
            if (targetValueToAdd.size() > 0) {
                targetToAdd.set(sourceKey, targetValueToAdd);
            }
        }
    }
}