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:org.activiti.rest.service.api.runtime.TaskCommentResourceTest.java

/**
 * Test getting all comments for a task. GET runtime/tasks/{taskId}/comments
 *//* w  ww  .j ava  2  s.  c om*/
public void testGetComments() throws Exception {
    try {
        Task task = taskService.newTask();
        taskService.saveTask(task);

        // Add a comment as "kermit"
        identityService.setAuthenticatedUserId("kermit");
        Comment comment = taskService.addComment(task.getId(), null, "This is a comment...");
        identityService.setAuthenticatedUserId(null);

        HttpGet httpGet = new HttpGet(SERVER_URL_PREFIX
                + RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_COMMENT_COLLECTION, task.getId()));
        CloseableHttpResponse response = executeRequest(httpGet, HttpStatus.SC_OK);
        JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
        closeResponse(response);
        assertNotNull(responseNode);
        assertTrue(responseNode.isArray());
        assertEquals(1, responseNode.size());

        ObjectNode commentNode = (ObjectNode) responseNode.get(0);
        assertEquals("kermit", commentNode.get("author").textValue());
        assertEquals("This is a comment...", commentNode.get("message").textValue());
        assertEquals(comment.getId(), commentNode.get("id").textValue());
        assertTrue(commentNode.get("taskUrl").textValue().endsWith(
                RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_COMMENT, task.getId(), comment.getId())));
        assertEquals(task.getId(), commentNode.get("taskId").asText());
        assertTrue(commentNode.get("processInstanceUrl").isNull());
        assertTrue(commentNode.get("processInstanceId").isNull());

        // Test with unexisting task
        httpGet = new HttpGet(SERVER_URL_PREFIX
                + RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_COMMENT_COLLECTION, "unexistingtask"));
        closeResponse(executeRequest(httpGet, HttpStatus.SC_NOT_FOUND));

    } finally {
        // Clean adhoc-tasks even if test fails
        List<Task> tasks = taskService.createTaskQuery().list();
        for (Task task : tasks) {
            taskService.deleteTask(task.getId(), true);
        }
    }
}

From source file:org.lendingclub.mercator.ucs.UCSScanner.java

protected void recordChassis(Element element) {

    ObjectNode n = toJson(element);

    String serial = n.get("serial").asText();
    String mercatorId = Hashing.sha1().hashString(serial, Charsets.UTF_8).toString();
    n.put("mercatorId", mercatorId);
    String cypher = "merge (c:UCSChassis {mercatorId:{mercatorId}}) set c+={props}, c.updateTs=timestamp()";

    getProjector().getNeoRxClient().execCypher(cypher, "mercatorId", mercatorId, "props", n);

    cypher = "match (m:UCSManager {mercatorId:{managerId}}), (c:UCSChassis {mercatorId:{chassisId}}) merge (m)-[r:MANAGES]->(c)";

    getProjector().getNeoRxClient().execCypher(cypher, "managerId", getUCSClient().getUCSManagerId(),
            "chassisId", mercatorId);

    getUCSClient().resolveChildren(n.get("dn").asText(), "computeBlade").forEach(it -> {
        recordComputeBlade(mercatorId, it);

    });/* w w  w .  j a v a 2 s  .c o  m*/

}

From source file:com.arpnetworking.metrics.proxy.models.protocol.v1.MetricMessagesProcessor.java

/**
 * {@inheritDoc}/*from  ww w.  j a va  2  s  .  c om*/
 */
@Override
public boolean handleMessage(final Object message) {
    if (message instanceof Command) {
        //TODO(barp): Map with a POJO mapper [MAI-184]
        final Command command = (Command) message;
        final ObjectNode commandNode = (ObjectNode) command.getCommand();
        final String commandString = commandNode.get("command").asText();
        switch (commandString) {
        case COMMAND_GET_METRICS:
            _metrics.incrementCounter(GET_METRICS_COUNTER);
            _connection.getTelemetry().tell(new MetricsListRequest(), _connection.getSelf());
            break;
        case COMMAND_SUBSCRIBE_METRIC: {
            _metrics.incrementCounter(SUBSCRIBE_COUNTER);
            final String service = commandNode.get("service").asText();
            final String metric = commandNode.get("metric").asText();
            final String statistic = commandNode.get("statistic").asText();
            subscribe(service, metric, statistic);
            break;
        }
        case COMMAND_UNSUBSCRIBE_METRIC: {
            _metrics.incrementCounter(UNSUBSCRIBE_COUNTER);
            final String service = commandNode.get("service").asText();
            final String metric = commandNode.get("metric").asText();
            final String statistic = commandNode.get("statistic").asText();
            unsubscribe(service, metric, statistic);
            break;
        }
        default:
            return false;
        }
    } else if (message instanceof NewMetric) {
        //TODO(barp): Map with a POJO mapper [MAI-184]
        _metrics.incrementCounter(NEW_METRIC_COUNTER);
        final NewMetric newMetric = (NewMetric) message;
        processNewMetric(newMetric);
    } else if (message instanceof MetricReport) {
        _metrics.incrementCounter(METRIC_REPORT_COUNTER);
        final MetricReport report = (MetricReport) message;
        processMetricReport(report);
    } else if (message instanceof MetricsList) {
        _metrics.incrementCounter(METRIC_LIST_COUNTER);
        final MetricsList metricsList = (MetricsList) message;
        processMetricsList(metricsList);
    } else {
        return false;
    }
    return true;
}

From source file:com.marklogic.samplestack.web.QnADocumentController.java

/**
 * Exposes an endpoint for searching QnADocuments.
 * @param structuredQuery A JSON structured query.
 * @param start The index of the first result to return.
 * @return A Search Results JSON response.
 *///from   www  .ja  va 2s . c  o m
@RequestMapping(value = "search", method = RequestMethod.POST)
public @ResponseBody JsonNode search(@RequestBody ObjectNode structuredQuery,
        @RequestParam(defaultValue = "1", required = false) long start) {

    JsonNode postedStartNode = structuredQuery.get("start");
    if (postedStartNode != null) {
        start = postedStartNode.asLong();
        structuredQuery.remove("start");
    }
    return qnaService.rawSearch(ClientRole.securityContextRole(), structuredQuery, start);
}

From source file:org.keycloak.testsuite.oidc.OIDCWellKnownProviderTest.java

@Test
public void testIntrospectionEndpointClaim() throws IOException {
    Client client = ClientBuilder.newClient();
    try {/*w  w w.  j a  va  2 s .  c o  m*/
        ObjectNode oidcConfig = JsonSerialization.readValue(getOIDCDiscoveryConfiguration(client),
                ObjectNode.class);
        assertEquals(oidcConfig.get("introspection_endpoint").asText(),
                getOIDCDiscoveryRepresentation(client).getTokenIntrospectionEndpoint());
    } finally {
        client.close();
    }
}

From source file:com.ottogroup.bi.asap.operator.twitter.consumer.TwitterStreamConsumer.java

protected String timing(String msg) {
    try {/*from  w  w  w . jav  a 2  s  .  co m*/
        ObjectNode node = (ObjectNode) jsonMapper.readTree(msg);
        long timestampMillis = node.get("timestamp_ms").asLong();
        node.put("@timestamp", sdf.format(new Date(timestampMillis)));
        return jsonMapper.writeValueAsString(node);
    } catch (IOException e) {
        //
    }
    return msg;
}

From source file:org.gitana.platform.client.node.BaseNodeImpl.java

@Override
public ObjectNode getFeature(String featureId) {
    ObjectNode featureObject = JsonUtil.createObject();

    ObjectNode featuresObject = this.getObject("_features");
    if (featuresObject != null) {
        if (featuresObject.has(featureId)) {
            featureObject = (ObjectNode) featuresObject.get(featureId);
        }//  w  w w .  j  a  v a  2  s .  co  m
    }

    return featureObject;
}

From source file:com.msopentech.odatajclient.engine.data.impl.JSONPropertyDeserializer.java

@Override
protected JSONProperty doDeserialize(final JsonParser parser, final DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    final ObjectNode tree = (ObjectNode) parser.getCodec().readTree(parser);

    final JSONProperty property = new JSONProperty();

    if (tree.hasNonNull(ODataConstants.JSON_METADATA)) {
        property.setMetadata(URI.create(tree.get(ODataConstants.JSON_METADATA).textValue()));
        tree.remove(ODataConstants.JSON_METADATA);
    }/*  w  ww.j ava 2  s  .co m*/

    try {
        final DocumentBuilder builder = XMLUtils.DOC_BUILDER_FACTORY.newDocumentBuilder();
        final Document document = builder.newDocument();

        Element content = document.createElement(ODataConstants.ELEM_PROPERTY);

        if (property.getMetadata() != null) {
            final String metadataURI = property.getMetadata().toASCIIString();
            final int dashIdx = metadataURI.lastIndexOf('#');
            if (dashIdx != -1) {
                content.setAttribute(ODataConstants.ATTR_M_TYPE, metadataURI.substring(dashIdx + 1));
            }
        }

        JsonNode subtree = null;
        if (tree.has(ODataConstants.JSON_VALUE)) {
            if (tree.has(ODataConstants.JSON_TYPE)
                    && StringUtils.isBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {

                content.setAttribute(ODataConstants.ATTR_M_TYPE, tree.get(ODataConstants.JSON_TYPE).asText());
            }

            final JsonNode value = tree.get(ODataConstants.JSON_VALUE);
            if (value.isValueNode()) {
                content.appendChild(document.createTextNode(value.asText()));
            } else if (EdmSimpleType.isGeospatial(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
                subtree = tree.objectNode();
                ((ObjectNode) subtree).put(ODataConstants.JSON_VALUE, tree.get(ODataConstants.JSON_VALUE));
                if (StringUtils.isNotBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
                    ((ObjectNode) subtree).put(ODataConstants.JSON_VALUE + "@" + ODataConstants.JSON_TYPE,
                            content.getAttribute(ODataConstants.ATTR_M_TYPE));
                }
            } else {
                subtree = tree.get(ODataConstants.JSON_VALUE);
            }
        } else {
            subtree = tree;
        }

        if (subtree != null) {
            JSONDOMTreeUtils.buildSubtree(client, content, subtree);
        }

        final List<Node> children = XMLUtils.getChildNodes(content, Node.ELEMENT_NODE);
        if (children.size() == 1) {
            final Element value = (Element) children.iterator().next();
            if (ODataConstants.JSON_VALUE.equals(XMLUtils.getSimpleName(value))) {
                if (StringUtils.isNotBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
                    value.setAttribute(ODataConstants.ATTR_M_TYPE,
                            content.getAttribute(ODataConstants.ATTR_M_TYPE));
                }
                content = value;
            }
        }

        property.setContent(content);
    } catch (ParserConfigurationException e) {
        throw new JsonParseException("Cannot build property", parser.getCurrentLocation(), e);
    }

    return property;
}

From source file:org.apache.streams.components.http.provider.SimpleHttpProvider.java

/**
 Override this to change how metadata is derived from object
 *//*  w  w w. j a v  a 2s  . com*/
protected StreamsDatum newDatum(ObjectNode item) {
    try {
        String id = null;
        if (item.get("id") != null)
            id = item.get("id").asText();
        DateTime timestamp = null;
        if (item.get("timestamp") != null)
            timestamp = new DateTime(item.get("timestamp").asText());
        if (id != null && timestamp != null)
            return new StreamsDatum(item, id, timestamp);
        else if (id != null)
            return new StreamsDatum(item, id);
        else if (timestamp != null)
            return new StreamsDatum(item, null, timestamp);
        else
            return new StreamsDatum(item);
    } catch (Exception e) {
        return new StreamsDatum(item);
    }
}

From source file:org.lendingclub.mercator.aws.SubnetScanner.java

@Override
protected void doScan() {

    rateLimit();/*from  w ww .  j  a v  a 2s  .c  o m*/
    DescribeSubnetsResult result = getClient().describeSubnets();

    GraphNodeGarbageCollector gc = newGarbageCollector().label("AwsSubnet").region(getRegion());

    result.getSubnets().forEach(it -> {
        try {
            ObjectNode n = convertAwsObject(it, getRegion());

            String cypher = "MERGE (v:AwsSubnet {aws_arn:{aws_arn}}) set v+={props}, v.updateTs=timestamp() return v";

            NeoRxClient client = getNeoRxClient();
            Preconditions.checkNotNull(client);
            client.execCypher(cypher, "aws_arn", n.get("aws_arn").asText(), "props", n).forEach(r -> {
                gc.MERGE_ACTION.accept(r);
                getShadowAttributeRemover().removeTagAttributes("AwsSubnet", n, r);
            });
            incrementEntityCount();

        } catch (RuntimeException e) {
            gc.markException(e);
            maybeThrow(e, "problem scanning subnets");
        }
    });

    gc.invoke();
}