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:de.siegmar.logbackgelf.GelfLayoutTest.java

@Test
public void rootExceptionWithoutCause() throws IOException {
    layout.setIncludeRootCauseData(true);
    layout.start();//www.  ja  v  a 2 s  .  c o  m

    final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    final Logger logger = lc.getLogger(LOGGER_NAME);

    final String logMsg;
    try {
        throw new IOException("Example Exception");
    } catch (final IOException e) {
        logMsg = layout.doLayout(simpleLoggingEvent(logger, e));
    }

    final ObjectMapper om = new ObjectMapper();
    final JsonNode jsonNode = om.readTree(logMsg);

    assertEquals("java.io.IOException", jsonNode.get("_root_cause_class_name").textValue());
    assertEquals("Example Exception", jsonNode.get("_root_cause_message").textValue());
}

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

@Test
public void verifyNoSuchClientId() throws Exception {
    final CentralOAuthService centralOAuthService = mock(CentralOAuthService.class);
    when(centralOAuthService.getClientMetadata(NO_SUCH_CLIENT_ID, CLIENT_SECRET)).thenReturn(null);
    when(centralOAuthService.getClientMetadata(CLIENT_ID, WRONG_CLIENT_SECRET)).thenReturn(null);
    when(centralOAuthService.getClientMetadata(CLIENT_ID, CLIENT_SECRET)).thenReturn(METADATA);

    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST",
            CONTEXT + OAuthConstants.METADATA_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, NO_SUCH_CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

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

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

    final String expected = "{\"error\":\"" + OAuthConstants.INVALID_REQUEST + "\",\"error_description\":\""
            + OAuthConstants.INVALID_CLIENT_ID_OR_SECRET_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.OAuth20MetadataClientControllerTests.java

@Test
public void verifyWrongClientSecret() throws Exception {
    final CentralOAuthService centralOAuthService = mock(CentralOAuthService.class);
    when(centralOAuthService.getClientMetadata(NO_SUCH_CLIENT_ID, CLIENT_SECRET)).thenReturn(null);
    when(centralOAuthService.getClientMetadata(CLIENT_ID, WRONG_CLIENT_SECRET)).thenReturn(null);
    when(centralOAuthService.getClientMetadata(CLIENT_ID, CLIENT_SECRET)).thenReturn(METADATA);

    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST",
            CONTEXT + OAuthConstants.METADATA_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, WRONG_CLIENT_SECRET);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

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

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

    final String expected = "{\"error\":\"" + OAuthConstants.INVALID_REQUEST + "\",\"error_description\":\""
            + OAuthConstants.INVALID_CLIENT_ID_OR_SECRET_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:de.siegmar.logbackgelf.GelfLayoutTest.java

@Test
public void rootExceptionWithCause() throws IOException {
    layout.setIncludeRootCauseData(true);
    layout.start();// ww w . j  a  v a 2  s  . co  m

    final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    final Logger logger = lc.getLogger(LOGGER_NAME);

    final String logMsg;
    try {
        throw new IOException("Example Exception", new IllegalStateException("Example Exception 2"));
    } catch (final IOException e) {
        logMsg = layout.doLayout(simpleLoggingEvent(logger, e));
    }

    final ObjectMapper om = new ObjectMapper();
    final JsonNode jsonNode = om.readTree(logMsg);
    basicValidation(jsonNode);

    assertEquals("java.lang.IllegalStateException", jsonNode.get("_root_cause_class_name").textValue());

    assertEquals("Example Exception 2", jsonNode.get("_root_cause_message").textValue());
}

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

@Test
public void verifyOK() throws Exception {
    final CentralOAuthService centralOAuthService = mock(CentralOAuthService.class);
    when(centralOAuthService.getClientMetadata(NO_SUCH_CLIENT_ID, CLIENT_SECRET)).thenReturn(null);
    when(centralOAuthService.getClientMetadata(CLIENT_ID, WRONG_CLIENT_SECRET)).thenReturn(null);
    when(centralOAuthService.getClientMetadata(CLIENT_ID, CLIENT_SECRET)).thenReturn(METADATA);

    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST",
            CONTEXT + OAuthConstants.METADATA_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

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

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

    final String expected = "{\"client_id\":\"" + CLIENT_ID + "\",\"name\":\"" + CLIENT_META_NAME
            + "\",\"description\":\"" + CLIENT_META_DESCRIPTION + "\",\"users\":\"" + CLIENT_META_USERS + "\"}";

    final ObjectMapper mapper = new ObjectMapper();
    final JsonNode expectedObj = mapper.readTree(expected);
    final JsonNode receivedObj = mapper.readTree(mockResponse.getContentAsString());
    assertEquals(expectedObj.get("client_id").asText(), receivedObj.get("client_id").asText());
    assertEquals(expectedObj.get("name").asText(), receivedObj.get("name").asText());
    assertEquals(expectedObj.get("description").asText(), receivedObj.get("description").asText());
    assertEquals(expectedObj.get("users").asText(), receivedObj.get("users").asText());
}

From source file:com.controller.resource.PaymentResource.java

@POST
@Path("/checkout")
@Consumes("application/json")
@ApiOperation(value = "Test API", notes = "Test API")
@ApiResponses(value = { @ApiResponse(code = 404, message = "Session ID not found") })
public Response getPaypalPayment(ProductShoppingCart productShoppingCart,
        @QueryParam("recaptcha") String recaptcha) {

    try {/*from   w w w .  j  a  va  2  s  . c om*/
        HttpClient client = HttpClientBuilder.create().build();

        URIBuilder builder = new URIBuilder(System.getenv("GOOGLE_RECAPTCHA_API_ENDPOINT"));
        builder.setParameter("secret", System.getenv("GOOGLE_RECAPTCHA_API_SECRET"));
        builder.setParameter("response", recaptcha);
        LOGGER.error("RECAPTCHA: " + recaptcha);

        HttpPost httpPost = new HttpPost(builder.build());

        HttpResponse httpResponse = client.execute(httpPost);

        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(httpResponse.getEntity().getContent()));

            StringBuffer result = new StringBuffer();
            String line = "";

            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode captchaResponse = objectMapper.readTree(result.toString());
            LOGGER.error("RECAPTCHA RESPONSE: " + result.toString());
            if (captchaResponse.get("success").asBoolean(false)) {
                PaymentClient paymentClient = new PaymentClient();

                return Response.ok()
                        .entity("{\"paypalHref\":\"" + paymentClient.createPayment(productShoppingCart) + "\"}")
                        .build();
            } else {
                LOGGER.error("Error in validating reCaptcha payment: "
                        + captchaResponse.get("error-codes").asText());
            }
        }
        LOGGER.error("Error in validating reCaptcha payment");
        return Response.serverError().entity("{\"message\":\"internal server error\"}").build();

    } catch (Exception exception) {
        LOGGER.error("Error in calculating payment", exception);
        return Response.serverError().entity("{\"message\":\"internal server error\"}").build();
    }

}

From source file:net.idea.opentox.cli.dataset.DatasetClient.java

@Override
public List<Dataset> processPayload(InputStream in, String mediaType) throws RestException, IOException {
    List<Dataset> list = null;
    if (mime_json.equals(mediaType)) {
        ObjectMapper m = new ObjectMapper();
        JsonNode node = m.readTree(in);
        if (callback != null)
            callback.callback(node);//w ww  . ja va 2s . c  o  m
        ArrayNode data = (ArrayNode) node.get("dataset");
        if (data != null)
            for (int i = 0; i < data.size(); i++) {
                JsonNode metadata = data.get(i);
                Dataset dataset = new Dataset(new Identifier(metadata.get("URI").textValue()));
                if (list == null)
                    list = new ArrayList<Dataset>();
                list.add(dataset);
                try {
                    dataset.getMetadata().setTitle(metadata.get("title").textValue());
                } catch (Exception x) {
                }
                try {
                    dataset.getMetadata().setSeeAlso(metadata.get("seeAlso").textValue());
                } catch (Exception x) {
                }
                try {
                    dataset.getMetadata().setStars(metadata.get("stars").intValue());
                } catch (Exception x) {
                }
                dataset.getMetadata().setRights(new Rights());
                try {
                    dataset.getMetadata().getRights().setRightsHolder(metadata.get("rightsHolder").textValue());
                } catch (Exception x) {
                }
                try {
                    dataset.getMetadata().getRights().setURI(metadata.get("rights").get("URI").textValue());
                } catch (Exception x) {
                }
                try {
                    dataset.getMetadata().getRights()
                            .setType(_type.rights.valueOf(metadata.get("rights").get("type").textValue()));
                } catch (Exception x) {
                }
            }
        return list;
    } else if (mime_rdfxml.equals(mediaType)) {
        return super.processPayload(in, mediaType);
    } else if (mime_n3.equals(mediaType)) {
        return super.processPayload(in, mediaType);
    } else if (mime_csv.equals(mediaType)) {
        return super.processPayload(in, mediaType);
    } else
        return super.processPayload(in, mediaType);
}

From source file:de.siegmar.logbackgelf.GelfLayoutTest.java

@Test
public void complex() throws IOException {
    layout.setIncludeRawMessage(true);/*from w w w  .j a v  a2s  .c om*/
    layout.setIncludeLevelName(true);
    layout.addStaticField("foo:bar");
    layout.setIncludeCallerData(true);
    layout.setIncludeRootCauseData(true);
    layout.start();

    final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    final Logger logger = lc.getLogger(LOGGER_NAME);

    final LoggingEvent event = simpleLoggingEvent(logger, null);

    event.setMDCPropertyMap(ImmutableMap.of("mdc_key", "mdc_value"));

    final String logMsg = layout.doLayout(event);

    final ObjectMapper om = new ObjectMapper();
    final JsonNode jsonNode = om.readTree(logMsg);
    basicValidation(jsonNode);
    assertEquals("DEBUG", jsonNode.get("_level_name").textValue());
    assertEquals("bar", jsonNode.get("_foo").textValue());
    assertEquals("mdc_value", jsonNode.get("_mdc_key").textValue());
    assertEquals("message {}", jsonNode.get("_raw_message").textValue());
    assertNull(jsonNode.get("_exception"));
}

From source file:de.siegmar.logbackgelf.GelfLayoutTest.java

@Test
public void exception() throws IOException {
    layout.start();// ww w.  j av  a2  s .  co m

    final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    final Logger logger = lc.getLogger(LOGGER_NAME);

    final String logMsg;
    try {
        throw new IllegalArgumentException("Example Exception");
    } catch (final IllegalArgumentException e) {
        logMsg = layout.doLayout(
                new LoggingEvent(LOGGER_NAME, logger, Level.DEBUG, "message {}", e, new Object[] { 1 }));
    }

    final ObjectMapper om = new ObjectMapper();
    final JsonNode jsonNode = om.readTree(logMsg);
    basicValidation(jsonNode);

    final LineReader msg = new LineReader(new StringReader(jsonNode.get("full_message").textValue()));

    assertEquals("message 1", msg.readLine());
    assertEquals("java.lang.IllegalArgumentException: Example Exception", msg.readLine());
    final String line = msg.readLine();
    assertTrue("Unexpected line: " + line,
            line.matches("^\tat de.siegmar.logbackgelf.GelfLayoutTest.exception\\(GelfLayoutTest.java:\\d+\\) "
                    + "~\\[test/:na\\]$"));
}

From source file:org.opendaylight.sfc.sbrest.json.ExporterUtilTest.java

private boolean testExportUtilLocatorJson(String locatorTypeName, String expectedResultFile)
        throws IOException {
    DataPlaneLocator dataPlaneLocator = this.buildDataPlaneLocator(locatorTypeName);

    ObjectMapper objectMapper = new ObjectMapper();

    JsonNode expectedLocatorJson = objectMapper.readTree(this.gatherUtilJsonStringFromFile(expectedResultFile));
    JsonNode exportedLocatorJson = ExporterUtil.getDataPlaneLocatorObjectNode(dataPlaneLocator);

    return expectedLocatorJson.equals(exportedLocatorJson);
}