Example usage for com.fasterxml.jackson.databind ObjectMapper readTree

List of usage examples for com.fasterxml.jackson.databind ObjectMapper readTree

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper readTree.

Prototype

public JsonNode readTree(URL source) throws IOException, JsonProcessingException 

Source Link

Document

Method to deserialize JSON content as tree expressed using set of JsonNode instances.

Usage

From source file:org.jasig.cas.support.oauth.web.OAuth20MetadataPrincipalControllerTests.java

@Test
public void verifyNoTokenOrAuthHeader() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST",
            CONTEXT + OAuthConstants.METADATA_URL);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.afterPropertiesSet();

    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertNull(modelAndView);//from w w  w.  j  a  v a  2s.  com
    assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus());
    assertEquals(CONTENT_TYPE, mockResponse.getContentType());

    final String expected = "{\"error\":\"" + OAuthConstants.MISSING_ACCESS_TOKEN
            + "\",\"error_description\":\"" + OAuthConstants.MISSING_ACCESS_TOKEN_DESCRIPTION + "\"}";

    final ObjectMapper mapper = new ObjectMapper();
    final JsonNode expectedObj = mapper.readTree(expected);
    final JsonNode receivedObj = mapper.readTree(mockResponse.getContentAsString());
    assertEquals(expectedObj.get("error").asText(), receivedObj.get("error").asText());
    assertEquals(expectedObj.get("error_description").asText(), receivedObj.get("error_description").asText());
}

From source file:org.jasig.cas.support.oauth.web.OAuth20MetadataPrincipalControllerTests.java

@Test
public void verifyNoTokenAndAuthHeaderIsBlank() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST",
            CONTEXT + OAuthConstants.METADATA_URL);
    mockRequest.addHeader("Authorization", "");
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.afterPropertiesSet();

    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertNull(modelAndView);//from w  ww. j a  v  a 2s.  c  om
    assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus());
    assertEquals(CONTENT_TYPE, mockResponse.getContentType());

    final String expected = "{\"error\":\"" + OAuthConstants.MISSING_ACCESS_TOKEN
            + "\",\"error_description\":\"" + OAuthConstants.MISSING_ACCESS_TOKEN_DESCRIPTION + "\"}";

    final ObjectMapper mapper = new ObjectMapper();
    final JsonNode expectedObj = mapper.readTree(expected);
    final JsonNode receivedObj = mapper.readTree(mockResponse.getContentAsString());
    assertEquals(expectedObj.get("error").asText(), receivedObj.get("error").asText());
    assertEquals(expectedObj.get("error_description").asText(), receivedObj.get("error_description").asText());
}

From source file:org.jasig.cas.support.oauth.web.OAuth20MetadataPrincipalControllerTests.java

@Test
public void verifyNoTokenAndAuthHeaderIsMalformed() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST",
            CONTEXT + OAuthConstants.METADATA_URL);
    mockRequest.addHeader("Authorization", "Let me in i am authorized");
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.afterPropertiesSet();

    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertNull(modelAndView);/*from   ww  w.  j  a  va  2 s. c  om*/
    assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus());
    assertEquals(CONTENT_TYPE, mockResponse.getContentType());

    final String expected = "{\"error\":\"" + OAuthConstants.MISSING_ACCESS_TOKEN
            + "\",\"error_description\":\"" + OAuthConstants.MISSING_ACCESS_TOKEN_DESCRIPTION + "\"}";

    final ObjectMapper mapper = new ObjectMapper();
    final JsonNode expectedObj = mapper.readTree(expected);
    final JsonNode receivedObj = mapper.readTree(mockResponse.getContentAsString());
    assertEquals(expectedObj.get("error").asText(), receivedObj.get("error").asText());
    assertEquals(expectedObj.get("error_description").asText(), receivedObj.get("error_description").asText());
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.external.ConsistentHashTest.java

License:asdf

@Test
public void itAppliesConsistentHashingForRequestsOutsideCoverageZone() throws Exception {
    CloseableHttpResponse response = null;

    try {//w  w w. j ava2 s.com
        String requestPath = URLEncoder.encode("/some/path/thing", "UTF-8");
        HttpGet httpGet = new HttpGet(
                "http://localhost:3333/crs/consistenthash/cache/geolocation?ip=8.8.8.8&deliveryServiceId="
                        + deliveryServiceId + "&requestPath=" + requestPath);

        response = closeableHttpClient.execute(httpGet);

        assertThat(response.getStatusLine().getStatusCode(), equalTo(200));

        ObjectMapper objectMapper = new ObjectMapper(new JsonFactory());
        JsonNode cacheNode = objectMapper.readTree(EntityUtils.toString(response.getEntity()));

        String cacheId = cacheNode.get("id").asText();
        assertThat(cacheId, not(equalTo("")));

        response.close();

        response = closeableHttpClient.execute(httpGet);
        cacheNode = objectMapper.readTree(EntityUtils.toString(response.getEntity()));
        assertThat(cacheNode.get("id").asText(), equalTo(cacheId));

        response.close();

        requestPath = URLEncoder.encode("/another/different/path", "UTF-8");
        httpGet = new HttpGet(
                "http://localhost:3333/crs/consistenthash/cache/geolocation?ip=8.8.8.8&deliveryServiceId="
                        + deliveryServiceId + "&requestPath=" + requestPath);

        response = closeableHttpClient.execute(httpGet);
        cacheNode = objectMapper.readTree(EntityUtils.toString(response.getEntity()));
        assertThat(cacheNode.get("id").asText(), not(equalTo(cacheId)));
        assertThat(cacheNode.get("id").asText(), not(equalTo("")));
    } finally {
        if (response != null)
            response.close();
    }
}

From source file:com.stratio.ingestion.sink.druid.DruidSinkIT.java

private Event getTrackerEvent() {
    Random random = new Random();
    String[] users = new String[] { "user1@santander.com", "user2@santander.com", "user3@santander.com",
            "user4@santander.com" };
    String[] isoCode = new String[] { "DE", "ES", "US", "FR" };
    TimeUnit[] offset = new TimeUnit[] { TimeUnit.DAYS, TimeUnit.HOURS, TimeUnit.SECONDS };
    ObjectNode jsonBody = new ObjectNode(JsonNodeFactory.instance);
    Map<String, String> headers;
    ObjectMapper mapper = new ObjectMapper();
    JsonNode jsonNode = null;//  w w  w . j a v  a  2 s. c  om
    final String fileName = "/trackerSample" + random.nextInt(4) + ".json";
    try {
        jsonNode = mapper.readTree(getClass().getResourceAsStream(fileName));
    } catch (IOException e) {
        e.printStackTrace();
    }
    headers = mapper.convertValue(jsonNode, Map.class);
    headers.put("timestamp",
            String.valueOf(new Date().getTime() + getOffset(offset[random.nextInt(3)]) * random.nextInt(100)));
    headers.put("santanderID", users[random.nextInt(4)]);
    headers.put("isoCode", isoCode[random.nextInt(4)]);

    return EventBuilder.withBody(jsonBody.toString().getBytes(Charsets.UTF_8), headers);
}

From source file:de.ids_mannheim.korap.search.TestMetaFields.java

@Test
public void searchMetaFields() throws IOException {

    // Construct index
    KrillIndex ki = new KrillIndex();
    // Indexing test files
    for (String i : new String[] { "00001", "00002" }) {
        ki.addDoc(getClass().getResourceAsStream("/wiki/" + i + ".json.gz"), true);
    }/*from  w w w.  j a  v a  2s.c o m*/
    ;
    ki.commit();

    String jsonString = getJsonString(getClass().getResource("/queries/metas/fields.jsonld").getFile());

    Krill ks = new Krill(jsonString);

    Result kr = ks.apply(ki);
    assertEquals((long) 17, kr.getTotalResults());
    assertEquals(0, kr.getStartIndex());
    assertEquals(9, kr.getItemsPerPage());

    ObjectMapper mapper = new ObjectMapper();
    JsonNode res = mapper.readTree(kr.toJsonString());

    // System.err.println(res.toString());
    // mirror fields
    assertEquals(9, res.at("/meta/count").asInt());

    if (res.at("/meta/fields/0").asText().equals("UID")) {
        assertEquals("corpusID", res.at("/meta/fields/1").asText());
    } else {
        assertEquals("corpusID", res.at("/meta/fields/0").asText());
        assertEquals("UID", res.at("/meta/fields/1").asText());
    }
    ;

    assertEquals(0, res.at("/matches/0/UID").asInt());
    assertEquals("WPD", res.at("/matches/0/corpusID").asText());
    assertTrue(res.at("/matches/0/docID").isMissingNode());
    assertTrue(res.at("/matches/0/textSigle").isMissingNode());
    assertTrue(res.at("/matches/0/ID").isMissingNode());
    assertTrue(res.at("/matches/0/author").isMissingNode());
    assertTrue(res.at("/matches/0/title").isMissingNode());
    assertTrue(res.at("/matches/0/subTitle").isMissingNode());
    assertTrue(res.at("/matches/0/textClass").isMissingNode());
    assertTrue(res.at("/matches/0/pubPlace").isMissingNode());
    assertTrue(res.at("/matches/0/pubDate").isMissingNode());
    assertTrue(res.at("/matches/0/foundries").isMissingNode());
    assertTrue(res.at("/matches/0/layerInfos").isMissingNode());
    assertTrue(res.at("/matches/0/tokenization").isMissingNode());

    jsonString = getJsonString(getClass().getResource("/queries/metas/fields_2.jsonld").getFile());
    ks = new Krill(jsonString);
    kr = ks.apply(ki);
    assertEquals((long) 17, kr.getTotalResults());
    assertEquals(0, kr.getStartIndex());
    assertEquals(2, kr.getItemsPerPage());

    mapper = new ObjectMapper();
    res = mapper.readTree(kr.toJsonString());
    assertEquals(0, res.at("/matches/0/UID").asInt());
    assertTrue(res.at("/matches/0/corpusID").isMissingNode());
    assertEquals("Ruru,Jens.Ol,Aglarech", res.at("/matches/0/author").asText());
    assertEquals("A", res.at("/matches/0/title").asText());
    assertEquals("WPD_AAA.00001", res.at("/matches/0/docID").asText());
    assertTrue(res.at("/matches/0/textSigle").isMissingNode());
    assertEquals("match-WPD_AAA.00001-p6-7", res.at("/matches/0/matchID").asText());
    // assertEquals("p6-7", res.at("/matches/0/matchID").asText());
    assertEquals("", res.at("/matches/0/subTitle").asText());
    assertEquals("", res.at("/matches/0/textClass").asText());
    assertEquals("", res.at("/matches/0/pubPlace").asText());
    assertEquals("", res.at("/matches/0/pubDate").asText());
    assertEquals("", res.at("/matches/0/foundries").asText());
    assertEquals("", res.at("/matches/0/layerInfo").asText());
    assertEquals("", res.at("/matches/0/tokenization").asText());
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.external.ConsistentHashTest.java

License:asdf

@Test
public void itAppliesConsistentHashingToRequestsForCoverageZone() throws Exception {
    CloseableHttpResponse response = null;

    try {/*w w  w .  jav  a  2 s.co m*/
        String requestPath = URLEncoder.encode("/some/path/thing", "UTF-8");
        HttpGet httpGet = new HttpGet(
                "http://localhost:3333/crs/consistenthash/cache/coveragezone?ip=" + ipAddressInCoverageZone
                        + "&deliveryServiceId=" + deliveryServiceId + "&requestPath=" + requestPath);

        response = closeableHttpClient.execute(httpGet);

        assertThat("Expected to find " + ipAddressInCoverageZone
                + " in coverage zone using delivery service id " + deliveryServiceId,
                response.getStatusLine().getStatusCode(), equalTo(200));

        ObjectMapper objectMapper = new ObjectMapper(new JsonFactory());
        JsonNode cacheNode = objectMapper.readTree(EntityUtils.toString(response.getEntity()));

        String cacheId = cacheNode.get("id").asText();
        assertThat(cacheId, not(equalTo("")));

        response.close();

        response = closeableHttpClient.execute(httpGet);
        cacheNode = objectMapper.readTree(EntityUtils.toString(response.getEntity()));
        assertThat(cacheNode.get("id").asText(), equalTo(cacheId));

        response.close();

        requestPath = URLEncoder.encode("/another/different/path", "UTF-8");
        httpGet = new HttpGet(
                "http://localhost:3333/crs/consistenthash/cache/coveragezone?ip=" + ipAddressInCoverageZone
                        + "&deliveryServiceId=" + deliveryServiceId + "&requestPath=" + requestPath);

        response = closeableHttpClient.execute(httpGet);
        cacheNode = objectMapper.readTree(EntityUtils.toString(response.getEntity()));
        assertThat(cacheNode.get("id").asText(), not(equalTo(cacheId)));
        assertThat(cacheNode.get("id").asText(), not(equalTo("")));
    } finally {
        if (response != null)
            response.close();
    }
}

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

/**
 * Create handler./*  w w  w.j a  v  a2s.co m*/
 *
 * @param securityContext security context
 * @param graphQLDocument post data as jsonapi document
 * @return response
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response post(@Context SecurityContext securityContext, String graphQLDocument) {
    ObjectMapper mapper = elide.getMapper().getObjectMapper();

    JsonNode topLevel;

    try {
        topLevel = mapper.readTree(graphQLDocument);
    } catch (IOException e) {
        log.debug("Invalid json body provided to GraphQL", e);
        // NOTE: Can't get at isVerbose setting here for hardcoding to false. If necessary, we can refactor
        // so this can be set appropriately.
        return buildErrorResponse(new InvalidEntityBodyException(graphQLDocument), false);
    }

    Function<JsonNode, Response> executeRequest = (node) -> executeGraphQLRequest(mapper, securityContext,
            graphQLDocument, node);

    if (topLevel.isArray()) {
        Iterator<JsonNode> nodeIterator = topLevel.iterator();
        Iterable<JsonNode> nodeIterable = () -> nodeIterator;
        // NOTE: Create a non-parallel stream
        // It's unclear whether or not the expectations of the caller would be that requests are intended
        // to run serially even outside of a single transaction. We should revisit this.
        Stream<JsonNode> nodeStream = StreamSupport.stream(nodeIterable.spliterator(), false);
        ArrayNode result = nodeStream.map(executeRequest).map(response -> {
            try {
                return mapper.readTree((String) response.getEntity());
            } catch (IOException e) {
                log.debug("Caught an IO exception while trying to read response body");
                return JsonNodeFactory.instance.objectNode();
            }
        }).reduce(JsonNodeFactory.instance.arrayNode(), (arrayNode, node) -> arrayNode.add(node),
                (left, right) -> left.addAll(right));
        try {
            return Response.ok(mapper.writeValueAsString(result)).build();
        } catch (IOException e) {
            log.error("An unexpected error occurred trying to serialize array response.", e);
            return Response.serverError().build();
        }
    }

    return executeRequest.apply(topLevel);
}

From source file:com.almende.eve.protocol.jsonrpc.formats.JSONRequest.java

/**
 * Instantiates a new JSON request.//from w  ww .j av a2s  . co  m
 * 
 * @param json
 *            the json
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public JSONRequest(final String json) throws IOException {
    final ObjectMapper mapper = JOM.getInstance();
    init(mapper.readTree(json));
}