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.OAuth20RevokeClientPrincipalTokensControllerTests.java

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

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

    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertNull(modelAndView);/*  ww w .j a va 2s. 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.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.openplatform.udm.javamodel.CandidateSchemaTest.java

/**
 * Test address schema./*from  w  ww.  ja  va 2s . c om*/
 *
 * @throws IOException Signals that an I/O exception has occurred.
 */
@Test
public void testAddressSchema() throws IOException {
    //ASSIGN & ACT
    File file = new File(filePathAddress);
    Address addressSchema = Transformer.fromJSON(file, Address.class);
    String outputJson = Transformer.toJSON(addressSchema);
    ObjectMapper diffMapper = new ObjectMapper();
    JsonNode tree1 = diffMapper.readTree(file);
    JsonNode tree2 = diffMapper.readTree(outputJson);

    //ASSERT
    org.junit.Assert.assertTrue(tree1.equals(tree2));
}

From source file:com.openplatform.udm.javamodel.CandidateSchemaTest.java

/**
 * Test person schema.//from  w  w w.  java2  s . c  o  m
 *
 * @throws IOException Signals that an I/O exception has occurred.
 */
@Test
public void testPersonSchema() throws IOException {
    //ASSIGN & ACT
    File file = new File(filePathPerson);
    Person personSchema = Transformer.fromJSON(file, Person.class);
    String outputJson = Transformer.toJSON(personSchema);
    ObjectMapper diffMapper = new ObjectMapper();
    JsonNode tree1 = diffMapper.readTree(file);
    JsonNode tree2 = diffMapper.readTree(outputJson);

    //ASSERT
    org.junit.Assert.assertTrue(tree1.equals(tree2));
}

From source file:com.openplatform.udm.javamodel.CandidateSchemaTest.java

/**
 * Creates an ObjectMapper object that reads in sample candidate JSON data and populates
 * the candidate java model with it. The data is then read from the populated java model.
 * The input and output JSON data from the java model (before deserialisation and after 
 * serialisation, respectively) is constructed into JSON trees and tested for equality.
 * This is different from comparing their string representation; object and property order
 * does not affect the validity of the JSON data against the defined schema
 *
 * @throws IOException Signals that an I/O exception has occurred.
 *//*from   w w w  . j a  v  a  2  s  . c  o m*/

@Test
public void testCandidateSchema() throws IOException {
    //ASSIGN & ACT
    File file = new File(filePathCandidate);
    Candidate candidateSchema = Transformer.fromJSON(file, Candidate.class);
    String outputJson = Transformer.toJSON(candidateSchema);
    ObjectMapper diffMapper = new ObjectMapper();
    JsonNode tree1 = diffMapper.readTree(file);
    JsonNode tree2 = diffMapper.readTree(outputJson);

    //ASSERT
    org.junit.Assert.assertTrue(tree1.equals(tree2));
}

From source file:io.orchestrate.client.EventFetchOperation.java

/** {@inheritDoc} */
@Override//from w  w  w  .  j a  v  a2s  .  com
@SuppressWarnings("unchecked")
Iterable<Event<T>> fromResponse(final int status, final HttpHeader httpHeader, final String json,
        final JacksonMapper mapper) throws IOException {
    assert (status == 200);

    final ObjectMapper objectMapper = mapper.getMapper();
    final JsonNode jsonNode = objectMapper.readTree(json);

    final int count = jsonNode.get("count").asInt();
    final List<Event<T>> events = new ArrayList<Event<T>>(count);

    final Iterator<JsonNode> iter = jsonNode.get("results").elements();
    while (iter.hasNext()) {
        final JsonNode result = iter.next();

        final long timestamp = result.get("timestamp").asLong();

        final JsonNode valueNode = result.get("value");
        final String rawValue = valueNode.toString();

        final T value;
        if (clazz == String.class) {
            // don't deserialize JSON data
            value = (T) rawValue;
        } else {
            value = objectMapper.readValue(rawValue, clazz);
        }

        events.add(new Event<T>(value, rawValue, timestamp));
    }
    return events;
}

From source file:org.apache.taverna.robundle.manifest.TestManifestJSON.java

@Test
public void checkJsonFromSpec() throws Exception {
    // Verify that our test confirms the existing spec example
    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode json = objectMapper.readTree(getClass().getResource("/manifest.json"));
    checkManifestJson(json);//ww w  .  j  a  va  2 s  .  c  o  m

}

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

@Test
public void verifyFailedToRevokeTokens() throws Exception {
    final AccessToken accessToken = mock(AccessToken.class);
    when(accessToken.getId()).thenReturn(AT_ID);

    final CentralOAuthService centralOAuthService = mock(CentralOAuthService.class);
    when(centralOAuthService.getToken(AT_ID, AccessToken.class)).thenReturn(accessToken);
    when(centralOAuthService.revokeClientPrincipalTokens(accessToken, CLIENT_ID)).thenReturn(false);

    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST",
            CONTEXT + OAuthConstants.REVOKE_URL);
    mockRequest.setParameter(OAuthConstants.ACCESS_TOKEN, AT_ID);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

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

    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertNull(modelAndView);//w w  w  . j ava  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_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.github.alexfalappa.nbspringboot.projects.initializr.InitializrService.java

public JsonNode getDependencies(String bootVersion) throws Exception {
    if (!dependencyMetaMap.containsKey(bootVersion)) {
        // set connection timeouts
        timeoutFromPrefs();//  w w w  . jav a 2s .  c  om
        // prepare request
        final String serviceUrl = NbPreferences.forModule(PrefConstants.class).get(PREF_INITIALIZR_URL,
                "http://start.spring.io");
        UriTemplate template = new UriTemplate(serviceUrl.concat("/dependencies?{bootVersion}"));
        RequestEntity<Void> req = RequestEntity.get(template.expand(bootVersion))
                .accept(MediaType.valueOf("application/vnd.initializr.v2.1+json"))
                .header("User-Agent", REST_USER_AGENT).build();
        // connect
        logger.log(INFO, "Getting Spring Initializr dependencies metadata from: {0}", template);
        logger.log(INFO, "Asking metadata as: {0}", REST_USER_AGENT);
        long start = System.currentTimeMillis();
        ResponseEntity<String> respEntity = rt.exchange(req, String.class);
        // analyze response
        final HttpStatus statusCode = respEntity.getStatusCode();
        if (statusCode == OK) {
            ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
            final JsonNode depMeta = mapper.readTree(respEntity.getBody());
            logger.log(INFO,
                    "Retrieved Spring Initializr dependencies metadata for boot version {0}. Took {1} msec",
                    new Object[] { bootVersion, System.currentTimeMillis() - start });
            if (logger.isLoggable(FINE)) {
                logger.fine(mapper.writeValueAsString(depMeta));
            }
            dependencyMetaMap.put(bootVersion, depMeta);
        } else {
            // log status code
            final String errMessage = String.format(
                    "Spring initializr service connection problem. HTTP status code: %s",
                    statusCode.toString());
            logger.severe(errMessage);
            // throw exception in order to set error message
            throw new RuntimeException(errMessage);
        }
    }
    return dependencyMetaMap.get(bootVersion);
}

From source file:com.googlecode.jsonschema2pojo.integration.EnumIT.java

@Test
@SuppressWarnings("unchecked")
public void jacksonCanMarshalEnums() throws NoSuchMethodException, InstantiationException,
        IllegalAccessException, InvocationTargetException, IOException {

    Object valueWithEnumProperty = parentClass.newInstance();
    Method enumSetter = parentClass.getMethod("setEnumProperty", enumClass);
    enumSetter.invoke(valueWithEnumProperty, enumClass.getEnumConstants()[2]);

    ObjectMapper objectMapper = new ObjectMapper();

    String jsonString = objectMapper.writeValueAsString(valueWithEnumProperty);
    JsonNode jsonTree = objectMapper.readTree(jsonString);

    assertThat(jsonTree.size(), is(1));/*  www  . ja  v  a  2  s.  co m*/
    assertThat(jsonTree.has("enum_Property"), is(true));
    assertThat(jsonTree.get("enum_Property").isTextual(), is(true));
    assertThat(jsonTree.get("enum_Property").asText(), is("3rd one"));
}

From source file:com.easarrive.aws.plugins.common.service.impl.TestSNSService.java

@Test
public void aaa() {
    // String message =
    // "{\"Records\":[{\"eventVersion\":\"2.0\",\"eventSource\":\"aws:s3\",\"awsRegion\":\"us-west-2\",\"eventTime\":\"2016-06-28T12:59:55.700Z\",\"eventName\":\"ObjectCreated:Put\",\"userIdentity\":{\"principalId\":\"AFRDGXV7XRMK5\"},\"requestParameters\":{\"sourceIPAddress\":\"124.205.19.130\"},\"responseElements\":{\"x-amz-request-id\":\"CA17C6B0CA3B9D5B\",\"x-amz-id-2\":\"8OnEzpN3a49R+oHXc+BXDRGEaLRjgM9sygcuNhg+G2g6FNWxK9CkE1vaxJhc+WiW\"},\"s3\":{\"s3SchemaVersion\":\"1.0\",\"configurationId\":\"test\",\"bucket\":{\"name\":\"etago-app-dev\",\"ownerIdentity\":{\"principalId\":\"AFRDGXV7XRMK5\"},\"arn\":\"arn:aws:s3:::etago-app-dev\"},\"object\":{\"key\":\"users/image/22.jpg\",\"size\":4006886,\"eTag\":\"229f0eddc267a22e02d938e294ebd7e5\",\"sequencer\":\"00577274CB93A5D229\"}}}]}";
    String message = "{\"Service\":\"Amazon S3\",\"Event\":\"s3:TestEvent\",\"Time\":\"2016-06-29T09:35:00.087Z\",\"Bucket\":\"etago-app-dev\",\"RequestId\":\"3AFC2B9075E9D4F1\",\"HostId\":\"aNL0geUz8N1uvZwQZ9mEdphu3wOYpvYCt9FiHIDTKzAEUjF6xXuOzybqRItfVtLc\"}";
    ObjectMapper mapper = JsonUtil.getInstance();
    try {/*from   w  w  w  .j  a v  a2s  .c  o m*/
        if (StringUtil.isEmpty(message)) {
            return;
        }
        JsonNode jsonNode = mapper.readTree(message);
        if (jsonNode == null) {
            return;
        }
        JsonNode recordsJsonNode = jsonNode.get("Records");
        if (recordsJsonNode == null) {
            return;
        }
        Iterator<JsonNode> recordsJsonNodeI = recordsJsonNode.elements();
        if (recordsJsonNodeI == null) {
            return;
        }
        while (recordsJsonNodeI.hasNext()) {
            JsonNode recordJsonNode = recordsJsonNodeI.next();
            if (recordJsonNode == null) {
                continue;
            }
            JsonNode eventVersion = recordJsonNode.get("eventVersion");
            System.out.println(eventVersion.asText());
            JsonNode eventSource = recordJsonNode.get("eventSource");
            System.out.println(eventSource.asText());
            JsonNode eventName = recordJsonNode.get("eventName");
            System.out.println(eventName.asText());

        }
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}