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:controllers.impl.StandardApi.java

@Override
public F.Promise<Result> updateStagePackageVersions(final String envName, final String stageName) {
    final models.Stage stage = models.Stage.getByEnvironmentNameAndName(envName, stageName);
    if (stage == null) {
        return F.Promise.pure(notFound());
    }/*from   w w  w  . j  a  va  2 s.  co m*/

    final List<models.PackageVersion> versions = Lists.newArrayList();
    final JsonNode requestJson = request().body().asJson();
    if (requestJson == null) {
        return F.Promise.pure(badRequest());
    }
    final ArrayNode packages = (ArrayNode) requestJson.get("packages");
    for (final JsonNode node : packages) {
        final ObjectNode packageNode = (ObjectNode) node;
        final String packageName = packageNode.get("name").asText();
        final String version = packageNode.get("version").asText();
        final PackageVersion pkgVersion = getPackageVersion(packageName, version);
        versions.add(pkgVersion);
    }

    final ManifestHistory currentHistory = ManifestHistory.getCurrentForStage(stage);
    final Manifest currentManifest = currentHistory.getManifest();

    final LinkedHashMap<String, PackageVersion> newPackages = Maps
            .newLinkedHashMap(currentManifest.asPackageMap());
    versions.forEach(pv -> newPackages.put(pv.getPkg().getName(), pv));
    final Manifest newManifest = new Manifest();
    newManifest.getPackages().addAll(newPackages.values());
    newManifest.save();

    final Future<Object> ask = Patterns.ask(_deploymentManager,
            new FleetDeploymentCommands.DeployStage(stage, newManifest, "api"),
            Timeout.apply(30L, TimeUnit.SECONDS));

    return F.Promise.wrap(ask).map(o -> {
        if (o instanceof Deployment) {
            final Deployment deployment = (Deployment) o;
            return ok(JsonNodeFactory.instance.objectNode().put("deployId", deployment.getId()));
        }
        Logger.error("Expected Deployment response from deployment manager, got " + o);
        return internalServerError();
    });
}

From source file:io.macgyver.neorx.rest.NeoRxClientIntegrationTest.java

@Test
public void testCreateParameters() {
    ObjectNode n = getClient().createParameters("abc", null);
    Assertions.assertThat(n.get("abc").isNull()).isTrue();
}

From source file:models.protocol.v2.LogMessagesProcessor.java

/**
 * {@inheritDoc}/* w w  w .  j  a  v  a2  s.com*/
 */
@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_LOGS:
            _metrics.incrementCounter(GET_LOGS_COUNTER);
            _connectionContext.getContext().parent().tell(new LogsListRequest(), _connectionContext.getSelf());
            break;
        case COMMAND_SUBSCRIBE_LOG: {
            _metrics.incrementCounter(SUBSCRIBE_COUNTER);
            final Path log = Paths.get(commandNode.get("log").asText());
            final ArrayNode regexes = commandNode.withArray("regexes");
            subscribe(log, regexes);
            break;
        }
        case COMMAND_UNSUBSCRIBE_LOG: {
            _metrics.incrementCounter(UNSUBSCRIBE_COUNTER);
            final Path log = Paths.get(commandNode.get("log").asText());
            final ArrayNode regexes = commandNode.withArray("regexes");
            unsubscribe(log, regexes);
            break;
        }
        default:
            return false;
        }
    } else if (message instanceof LogLine) {
        final LogLine logReport = (LogLine) message;
        processLogReport(logReport);
    } else if (message instanceof NewLog) {
        final NewLog newLog = (NewLog) message;
        processNewLog(newLog);
    } else if (message instanceof LogsList) {
        final LogsList logsList = (LogsList) message;
        processLogsList(logsList);

    } else {
        return false;
    }
    return true;
}

From source file:com.spotify.helios.cli.command.JobCreateCommandTest.java

/**
 * Test that when the environment variables we have defaults for are set, they are picked up in
 * the job metadata./*from w  ww .j av a2  s . com*/
 */
@Test
public void testMetadataPicksUpEnvVars() throws Exception {
    envVars.put("GIT_COMMIT", "abcdef1234");

    when(options.getString("id")).thenReturn(JOB_ID);
    when(options.getString("image")).thenReturn("busybox:latest");

    when(options.getList("metadata")).thenReturn(Lists.<Object>newArrayList("foo=bar"));

    final int ret = runCommand();

    assertEquals(0, ret);
    final String output = baos.toString();

    final String expectedOutputPrefix = "Creating job: ";
    assertThat(output, startsWith(expectedOutputPrefix));

    final ObjectMapper objectMapper = new ObjectMapper();

    final String jsonFromOutput = output.split("\n")[0].substring(expectedOutputPrefix.length());
    final JsonNode jsonNode = objectMapper.readTree(jsonFromOutput);

    final ArrayList<String> fieldNames = Lists.newArrayList(jsonNode.fieldNames());
    assertThat(fieldNames, hasItem("metadata"));

    assertThat(jsonNode.get("metadata").isObject(), equalTo(true));

    final ObjectNode metadataNode = (ObjectNode) jsonNode.get("metadata");
    assertThat(metadataNode.get("foo").asText(), equalTo("bar"));
    assertThat(metadataNode.get("GIT_COMMIT").asText(), equalTo("abcdef1234"));
}

From source file:com.arpnetworking.test.junitbenchmarks.JsonBenchmarkConsumerTest.java

@Test
public void testNormalBenchmarkCase() throws IOException {
    final Path path = Paths.get("target/tmp/test/testConsumer.json");
    path.toFile().deleteOnExit();/*  ww w .  j  a  v  a  2s.  c  om*/
    Files.deleteIfExists(path);
    final JsonBenchmarkConsumer consumer = new JsonBenchmarkConsumer(path);

    final Result result = DataCreator.createResult();
    consumer.accept(result);
    consumer.close();

    // Read the file back in as json
    final ObjectMapper mapper = ObjectMapperFactory.getInstance();
    final JsonNode resultsArray = mapper.readTree(path.toFile());
    Assert.assertEquals(1, resultsArray.size());
    final JsonNode augmentedResultNode = resultsArray.get(0);
    Assert.assertTrue(augmentedResultNode.isObject());
    final JsonNode resultNode = augmentedResultNode.get("result");
    Assert.assertTrue(resultNode.isObject());

    Assert.assertEquals("com.arpnetworking.test.junitbenchmarks.JsonBenchmarkConsumerTest",
            resultNode.get("testClassName").asText());
    Assert.assertEquals("testNormalBenchmarkCase", resultNode.get("testMethodName").asText());

    Assert.assertEquals(result.benchmarkRounds, resultNode.get("benchmarkRounds").asInt());
    Assert.assertEquals(result.warmupRounds, resultNode.get("warmupRounds").asInt());
    Assert.assertEquals(result.warmupTime, resultNode.get("warmupTime").asInt());
    Assert.assertEquals(result.benchmarkTime, resultNode.get("benchmarkTime").asInt());

    Assert.assertTrue(resultNode.get("roundAverage").isObject());
    final ObjectNode roundAverageNode = (ObjectNode) resultNode.get("roundAverage");
    Assert.assertEquals(result.roundAverage.avg, roundAverageNode.get("avg").asDouble(), 0.0001d);
    Assert.assertEquals(result.roundAverage.stddev, roundAverageNode.get("stddev").asDouble(), 0.0001d);

    Assert.assertTrue(resultNode.get("blockedAverage").isObject());
    final ObjectNode blockedAverageNode = (ObjectNode) resultNode.get("blockedAverage");
    Assert.assertEquals(result.blockedAverage.avg, blockedAverageNode.get("avg").asDouble(), 0.0001d);
    Assert.assertEquals(result.blockedAverage.stddev, blockedAverageNode.get("stddev").asDouble(), 0.0001d);

    Assert.assertTrue(resultNode.get("gcAverage").isObject());
    final ObjectNode gcAverageNode = (ObjectNode) resultNode.get("gcAverage");
    Assert.assertEquals(result.gcAverage.avg, gcAverageNode.get("avg").asDouble(), 0.0001d);
    Assert.assertEquals(result.gcAverage.stddev, gcAverageNode.get("stddev").asDouble(), 0.0001d);

    Assert.assertTrue(resultNode.get("gcInfo").isObject());
    final ObjectNode gcInfoNode = (ObjectNode) resultNode.get("gcInfo");
    Assert.assertEquals(result.gcInfo.accumulatedInvocations(),
            gcInfoNode.get("accumulatedInvocations").asInt());
    Assert.assertEquals(result.gcInfo.accumulatedTime(), gcInfoNode.get("accumulatedTime").asInt());

    Assert.assertEquals(result.getThreadCount(), resultNode.get("threadCount").asInt());
}

From source file:org.activiti.rest.service.api.history.HistoricProcessInstanceCommentResourceTest.java

/**
 * Test getting all comments for a historic process instance. GET history/historic-process-instances/{processInstanceId}/comments
 *///w w  w  . j a  v a  2 s.co m
@Deployment(resources = { "org/activiti/rest/service/api/repository/oneTaskProcess.bpmn20.xml" })
public void testGetComments() throws Exception {
    ProcessInstance pi = null;

    try {
        pi = runtimeService.startProcessInstanceByKey("oneTaskProcess");

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

        CloseableHttpResponse response = executeRequest(
                new HttpGet(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(
                        RestUrls.URL_HISTORIC_PROCESS_INSTANCE_COMMENT_COLLECTION, pi.getId())),
                HttpStatus.SC_OK);

        assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());

        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("processInstanceUrl").textValue().endsWith(RestUrls.createRelativeResourceUrl(
                        RestUrls.URL_HISTORIC_PROCESS_INSTANCE_COMMENT, pi.getId(), comment.getId())));
        assertEquals(pi.getProcessInstanceId(), commentNode.get("processInstanceId").asText());
        assertTrue(commentNode.get("taskUrl").isNull());
        assertTrue(commentNode.get("taskId").isNull());

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

    } finally {
        if (pi != null) {
            List<Comment> comments = taskService.getProcessInstanceComments(pi.getId());
            for (Comment c : comments) {
                taskService.deleteComment(c.getId());
            }
        }
    }
}

From source file:org.flowable.rest.service.api.history.HistoricProcessInstanceCommentResourceTest.java

/**
 * Test getting all comments for a historic process instance. GET history/historic-process-instances/{processInstanceId}/comments
 */// w  ww  .j a  va  2s . c  o  m
@Deployment(resources = { "org/flowable/rest/service/api/repository/oneTaskProcess.bpmn20.xml" })
public void testGetComments() throws Exception {
    ProcessInstance pi = null;

    try {
        pi = runtimeService.startProcessInstanceByKey("oneTaskProcess");

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

        CloseableHttpResponse response = executeRequest(
                new HttpGet(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(
                        RestUrls.URL_HISTORIC_PROCESS_INSTANCE_COMMENT_COLLECTION, pi.getId())),
                HttpStatus.SC_OK);

        assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());

        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("processInstanceUrl").textValue().endsWith(RestUrls.createRelativeResourceUrl(
                        RestUrls.URL_HISTORIC_PROCESS_INSTANCE_COMMENT, pi.getId(), comment.getId())));
        assertEquals(pi.getProcessInstanceId(), commentNode.get("processInstanceId").asText());
        assertTrue(commentNode.get("taskUrl").isNull());
        assertTrue(commentNode.get("taskId").isNull());

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

    } finally {
        if (pi != null) {
            List<Comment> comments = taskService.getProcessInstanceComments(pi.getId());
            for (Comment c : comments) {
                taskService.deleteComment(c.getId());
            }
        }
    }
}

From source file:com.google.api.server.spi.response.ServletResponseResultWriterTest.java

private ObjectNode testTypeChangesAsString(Object value) throws Exception {
    String responseBody = writeToResponse(value);
    ObjectNode output = ObjectMapperUtil.createStandardObjectMapper().readValue(responseBody, ObjectNode.class);
    assertTrue(output.get("nonPrimitive").isTextual());
    assertEquals("100", output.get("nonPrimitive").asText());
    assertTrue(output.get("primitive").isTextual());
    assertEquals("200", output.get("primitive").asText());
    assertEquals(new com.google.api.client.util.DateTime(DATE_VALUE_STRING),
            new com.google.api.client.util.DateTime(output.get("date").asText()));
    assertEquals(DATE_AND_TIME_VALUE_STRING, output.get("dateAndTime").asText());
    assertEquals(DateAndTime.parseRfc3339String(DATE_AND_TIME_VALUE_STRING),
            DateAndTime.parseRfc3339String(output.get("dateAndTime").asText()));
    assertEquals(SIMPLE_DATE_VALUE_STRING, output.get("simpleDate").asText());
    return output;
}

From source file:com.ikanow.aleph2.search_service.elasticsearch.utils.ElasticsearchIndexUtils.java

/** Utility function to handle fields
 * TODO (ALEPH-14): need to be able to specify different options for different fields via columnar settings
 * @param mutable_mapping//www.j  a  va2 s . c  om
 * @param fielddata_info
 * @param mapper
 */
protected static void handleMappingFields(final ObjectNode mutable_mapping,
        final Optional<Tuple3<JsonNode, JsonNode, Boolean>> fielddata_info, final ObjectMapper mapper,
        final String index_type) {
    Optional.ofNullable(mutable_mapping.get("fields")).filter(j -> !j.isNull() && j.isObject()).ifPresent(j -> {
        StreamSupport.stream(Spliterators.spliteratorUnknownSize(j.fields(), Spliterator.ORDERED), false)
                .forEach(Lambdas.wrap_consumer_u(kv -> {
                    final ObjectNode mutable_o = (ObjectNode) kv.getValue();
                    setMapping(mutable_o, fielddata_info, mapper, index_type);
                }));
    });
}

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

protected void projectResourceRecordSet(String hostedZoneId, ResourceRecordSet rs, long timestamp) {

    ObjectNode n = toJson(rs);

    getNeoRxClient().execCypher(/*from  w  w  w .ja  v a  2  s  .c  o m*/
            "merge (a:AwsRoute53RecordSet {aws_name:{aws_name}}) set a+={props}, a.updateTs={updateTs} return a",
            "aws_name", n.get("aws_name").asText(), "props", n, "updateTs", timestamp);

    getNeoRxClient().execCypher(
            "match (r:AwsRoute53RecordSet {aws_name:{aws_name}}), (z:AwsRoute53HostedZone {aws_id : {aws_id}}) merge (z)-[x:CONTAINS]->(r) set x.updateTs={updateTs}",
            "aws_name", rs.getName(), "aws_id", hostedZoneId, "updateTs", timestamp);

    ScannerContext.getScannerContext().ifPresent(sc -> {
        sc.incrementEntityCount();
    });

}