Example usage for com.fasterxml.jackson.databind.node ObjectNode get

List of usage examples for com.fasterxml.jackson.databind.node ObjectNode get

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind.node ObjectNode get.

Prototype

public JsonNode get(String paramString) 

Source Link

Usage

From source file:ca.intelliware.ihtsdo.mlds.web.rest.ApplicationResource.java

/**
 * Verify that the requestBody has the same applicationType, or default it to the original type
 * @param requestBody/*from w  w  w. j  av a2 s .  c  o  m*/
 * @param original
 * @return a detached Application instance with all of the changes applied
 */
private Application constructUpdatedApplication(ObjectNode requestBody, Application original)
        throws IOException, JsonParseException, JsonMappingException, JsonProcessingException {
    ObjectNode treeCopyOfOriginal = objectMapper.readValue(objectMapper.writeValueAsString(original),
            ObjectNode.class);
    String typeTag = requestBody.get("applicationType") != null ? requestBody.get("applicationType").asText()
            : null;
    String originalTypeTag = treeCopyOfOriginal.get("applicationType").asText();
    if (!Strings.isNullOrEmpty(typeTag) && !typeTag.equals(originalTypeTag)) {
        throw new IllegalArgumentException("Can't change type of application via update");
    } else {
        requestBody.put("applicationType", originalTypeTag);
    }
    Application updatedApplication = objectMapper.treeToValue(requestBody, Application.class);
    return updatedApplication;
}

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

private void transformStructure(final JsonNode sourceNode, final JsonNode transformNode,
        final ObjectNode targetNode) throws ObjectTransformerException {
    // process $path directive
    JsonNode newSourceNode = updateSourceFromPath(sourceNode, transformNode.get(PATH));

    JsonNode structureNode = transformNode.get(STRUCTURE);
    if (structureNode.isObject()) {
        // mapping an object
        ObjectNode childNode = (ObjectNode) targetNode.get(transformNode.path(APPEND).asText());
        if (childNode == null) {
            // no $append directive found, need new object
            childNode = mapper.createObjectNode();
            targetNode.replace(transformNodeFieldName, childNode);
        }//from   w  w  w.  j av  a 2s  .  c o m

        // visit child object
        transformNode(newSourceNode, structureNode, childNode);
    } else if (structureNode.isArray()) {
        // mapping an array
        ArrayNode childNode = (ArrayNode) targetNode.get(transformNode.path(APPEND).asText());
        if (childNode == null) {
            // no $append directive found, need new object
            childNode = mapper.createArrayNode();
            targetNode.replace(transformNodeFieldName, childNode);
        }

        processArray(newSourceNode, transformNode, childNode);
    }

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

From source file:com.joyent.manta.client.multipart.ServerSideMultipartManager.java

@Override
public MantaMultipartUploadPart getPart(final ServerSideMultipartUpload upload, final int partNumber)
        throws IOException {
    Validate.notNull(upload, "Upload state object must not be null");
    validatePartNumber(partNumber);//from   w  w w .  ja  va 2s. c  o m

    final int adjustedPartNumber = partNumber - 1;

    final String getPath = upload.getPartsDirectory() + SEPARATOR + "state";
    final HttpGet get = httpHelper.getRequestFactory().get(getPath);

    final String objectPath;

    final int expectedStatusCode = HttpStatus.SC_OK;
    final CloseableHttpClient httpClient = httpHelper.getConnectionContext().getHttpClient();

    try (CloseableHttpResponse response = httpClient.execute(get)) {
        StatusLine statusLine = response.getStatusLine();
        validateStatusCode(expectedStatusCode, statusLine.getStatusCode(),
                "Unable to get status for multipart upload", get, response, null, null);
        validateEntityIsPresent(get, response, null, null);

        try (InputStream in = response.getEntity().getContent()) {
            ObjectNode objectNode = MantaObjectMapper.INSTANCE.readValue(in, ObjectNode.class);

            JsonNode objectPathNode = objectNode.get("targetObject");
            Validate.notNull(objectPathNode, "Unable to read object path from response");
            objectPath = objectPathNode.textValue();
            Validate.notBlank(objectPath, "Object path field was blank in response");
        } catch (JsonParseException e) {
            String msg = "Response body was not JSON";
            MantaMultipartException me = new MantaMultipartException(msg, e);
            annotateException(me, get, response, null, null);
            throw me;
        } catch (NullPointerException | IllegalArgumentException e) {
            String msg = "Expected response field was missing or malformed";
            MantaMultipartException me = new MantaMultipartException(msg, e);
            annotateException(me, get, response, null, null);
            throw me;
        }
    }

    final String headPath = upload.getPartsDirectory() + SEPARATOR + adjustedPartNumber;
    final HttpHead head = httpHelper.getRequestFactory().head(headPath);

    final String etag;

    try (CloseableHttpResponse response = httpClient.execute(head)) {
        StatusLine statusLine = response.getStatusLine();

        if (statusLine.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            return null;
        }

        validateStatusCode(expectedStatusCode, statusLine.getStatusCode(),
                "Unable to get status for multipart upload part", get, response, null, null);

        try {
            final Header etagHeader = response.getFirstHeader(HttpHeaders.ETAG);
            Validate.notNull(etagHeader, "ETag header was not returned");
            etag = etagHeader.getValue();
            Validate.notBlank(etag, "ETag is blank");
        } catch (NullPointerException | IllegalArgumentException e) {
            String msg = "Expected header was missing or malformed";
            MantaMultipartException me = new MantaMultipartException(msg, e);
            annotateException(me, get, response, null, null);
            throw me;
        }
    }

    return new MantaMultipartUploadPart(partNumber, objectPath, etag);
}

From source file:org.apache.streams.graph.GraphHttpPersistWriter.java

@Override
protected ObjectNode preparePayload(StreamsDatum entry) throws Exception {

    Activity activity = null;/*from   ww  w .  j a v  a2s . c o m*/
    ActivityObject activityObject;
    Object document = entry.getDocument();

    if (document instanceof Activity) {
        activity = (Activity) document;
        activityObject = activity.getObject();
    } else if (document instanceof ActivityObject) {
        activityObject = (ActivityObject) document;
    } else {
        ObjectNode objectNode;
        if (document instanceof ObjectNode) {
            objectNode = (ObjectNode) document;
        } else if (document instanceof String) {
            try {
                objectNode = mapper.readValue((String) document, ObjectNode.class);
            } catch (IOException ex) {
                LOGGER.error("Can't handle input: ", entry);
                throw ex;
            }
        } else {
            LOGGER.error("Can't handle input: ", entry);
            throw new Exception("Can't create payload from datum.");
        }

        if (objectNode.get("verb") != null) {
            try {
                activity = mapper.convertValue(objectNode, Activity.class);
                activityObject = activity.getObject();
            } catch (Exception ex) {
                activityObject = mapper.convertValue(objectNode, ActivityObject.class);
            }
        } else {
            activityObject = mapper.convertValue(objectNode, ActivityObject.class);
        }
    }

    Preconditions.checkArgument(activity != null || activityObject != null);

    ObjectNode request = mapper.createObjectNode();
    ArrayNode statements = mapper.createArrayNode();

    // always add vertices first

    List<String> labels = Collections.singletonList("streams");

    if (activityObject != null) {
        if (activityObject.getObjectType() != null) {
            labels.add(activityObject.getObjectType());
        }
        statements.add(httpGraphHelper.createHttpRequest(queryGraphHelper.mergeVertexRequest(activityObject)));
    }

    if (activity != null) {

        ActivityObject actor = activity.getActor();
        Provider provider = activity.getProvider();

        if (provider != null && StringUtils.isNotBlank(provider.getId())) {
            labels.add(provider.getId());
        }
        if (actor != null && StringUtils.isNotBlank(actor.getId())) {
            if (actor.getObjectType() != null) {
                labels.add(actor.getObjectType());
            }
            statements.add(httpGraphHelper.createHttpRequest(queryGraphHelper.mergeVertexRequest(actor)));
        }

        if (activityObject != null && StringUtils.isNotBlank(activityObject.getId())) {
            if (activityObject.getObjectType() != null) {
                labels.add(activityObject.getObjectType());
            }
            statements.add(
                    httpGraphHelper.createHttpRequest(queryGraphHelper.mergeVertexRequest(activityObject)));
        }

        // then add edge

        if (StringUtils.isNotBlank(activity.getVerb())) {
            statements.add(httpGraphHelper.createHttpRequest(queryGraphHelper.createEdgeRequest(activity)));
        }
    }

    request.put("statements", statements);
    return request;

}

From source file:com.almende.eve.monitor.ResultMonitorFactory.java

@Access(AccessType.PUBLIC)
@Override//w  ww  .  j av  a2  s .c om
public final void unregisterPush(@Name("pushId") final String id, @Sender final String senderUrl)
        throws IOException {
    ObjectNode config = null;
    if (myAgent.getState() != null && myAgent.getState().containsKey("_push_" + senderUrl + "_" + id)) {
        config = (ObjectNode) JOM.getInstance()
                .readTree(myAgent.getState().get("_push_" + senderUrl + "_" + id, String.class));
    }
    if (config == null) {
        return;
    }
    if (config.has("taskId") && myAgent.getScheduler() != null) {
        final String taskId = config.get("taskId").textValue();
        myAgent.getScheduler().cancelTask(taskId);
    }
    if (config.has("subscriptionId")) {
        try {
            myAgent.getEventsFactory().unsubscribe(myAgent.getFirstUrl(),
                    config.get("subscriptionId").textValue());
        } catch (final Exception e) {
            LOG.severe("Failed to unsubscribe push:" + e);
        }
    }
}

From source file:com.okta.swagger.codegen.AbstractOktaJavaClientCodegen.java

private SortedSet<String> parentPathParams(ObjectNode n) {

    SortedSet<String> result = new TreeSet<>();
    ArrayNode argNodeList = (ArrayNode) n.get("arguments");

    if (argNodeList != null) {
        for (JsonNode argNode : argNodeList) {
            if (argNode.has("parentSrc")) {
                String src = argNode.get("parentSrc").textValue();
                String dest = argNode.get("dest").textValue();
                if (src != null) {
                    result.add(dest);//from   w ww  .j  a v a  2  s .c  o  m
                }
            }
        }
    }
    return result;
}

From source file:org.apache.streams.graph.GraphPersistWriter.java

@Override
protected ObjectNode executePost(HttpPost httpPost) {

    Preconditions.checkNotNull(httpPost);

    ObjectNode result = null;

    CloseableHttpResponse response = null;

    String entityString = null;//from   ww w.j a  va2 s  . co  m
    try {
        response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (response.getStatusLine().getStatusCode() == 200
                || response.getStatusLine().getStatusCode() == 201 && entity != null) {
            entityString = EntityUtils.toString(entity);
            result = mapper.readValue(entityString, ObjectNode.class);
        }
        LOGGER.debug("Writer response:\n{}\n{}\n{}", httpPost.toString(),
                response.getStatusLine().getStatusCode(), entityString);
        if (result == null || (result.get("errors") != null && result.get("errors").isArray()
                && result.get("errors").iterator().hasNext())) {
            LOGGER.error("Write Error: " + result.get("errors"));
        } else {
            LOGGER.info("Write Success");
        }
    } catch (IOException e) {
        LOGGER.error("IO error:\n{}\n{}\n{}", httpPost.toString(), response, e.getMessage());
    } catch (Exception e) {
        LOGGER.error("Write Exception:\n{}\n{}\n{}", httpPost.toString(), response, e.getMessage());
    } finally {
        try {
            if (response != null)
                response.close();
        } catch (IOException e) {
        }
    }
    return result;
}

From source file:ru.gkpromtech.exhibition.db.Table.java

private ContentValues jsonToRow(ObjectNode object) throws IllegalAccessException, ParseException {
    ContentValues values = new ContentValues();

    for (int i = 0; i < mFields.length; ++i) {
        String fieldName = mFields[i].getName();
        JsonNode field = object.get(fieldName);
        if (field == null)
            continue;
        if (field.isNull()) {
            values.putNull(mColumns[i]);
            continue;
        }/*from   w w  w .  j  a  v  a 2 s  . c  om*/

        switch (mType[i]) {
        case INTEGER:
            values.put(mColumns[i], field.asInt());
            break;
        case SHORT:
            values.put(mColumns[i], (short) field.asInt());
            break;
        case LONG:
            values.put(mColumns[i], field.asLong());
            break;
        case FLOAT:
            values.put(mColumns[i], (float) field.asDouble());
            break;
        case DOUBLE:
            values.put(mColumns[i], field.asDouble());
            break;
        case STRING:
            values.put(mColumns[i], field.asText());
            break;
        case BYTE_ARRAY:
            values.put(mColumns[i], Base64.decode(field.asText(), Base64.DEFAULT));
            break;
        case DATE:
            values.put(mColumns[i], mDateFormat.parse(field.asText()).getTime());
            break;
        case BOOLEAN:
            values.put(mColumns[i], field.asBoolean() ? 1 : 0);
            break;
        }
    }
    return values;
}

From source file:com.okta.swagger.codegen.AbstractOktaJavaClientCodegen.java

private Map<String, String> createArgMap(ObjectNode n) {

    Map<String, String> argMap = new LinkedHashMap<>();
    ArrayNode argNodeList = (ArrayNode) n.get("arguments");

    if (argNodeList != null) {
        for (Iterator argNodeIter = argNodeList.iterator(); argNodeIter.hasNext();) {
            JsonNode argNode = (JsonNode) argNodeIter.next();

            if (argNode.has("src")) {
                String src = argNode.get("src").textValue();
                String dest = argNode.get("dest").textValue();
                if (src != null) {
                    argMap.put(dest, src); // reverse lookup
                }/*  w w w  . j  a v a  2s.com*/
            }

            if (argNode.has("self")) {
                String dest = argNode.get("dest").textValue();
                argMap.put(dest, "this"); // reverse lookup
            }
        }
    }
    return argMap;
}

From source file:com.github.reinert.jjschema.JsonSchemaGenerator.java

private void addPropertyToSchema(ObjectNode schema, Field field, Method method, ObjectNode prop) {

    String name = getPropertyName(field, method);
    if (prop.has("selfRequired")) {
        ArrayNode requiredNode;/*from   w  w w.  j av  a  2s  .c om*/
        if (!schema.has(TAG_REQUIRED)) {
            requiredNode = schema.putArray(TAG_REQUIRED);
        } else {
            requiredNode = (ArrayNode) schema.get(TAG_REQUIRED);
        }
        requiredNode.add(name);
        prop.remove("selfRequired");
    }
    if (!schema.has(TAG_PROPERTIES))
        schema.putObject(TAG_PROPERTIES);
    ((ObjectNode) schema.get(TAG_PROPERTIES)).put(name, prop);
}