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:net.mindengine.galen.tests.runner.ReportingTest.java

private void assertJsonFileContents(String title, String actualPath, String expectedPath) throws IOException {
    String actualContent = readFileToString(new File(actualPath));

    String expectedContent = readFileToString(new File(getClass().getResource(expectedPath).getFile()));

    ObjectMapper mapper = new ObjectMapper();

    JsonNode actualTree = mapper.readTree(actualContent);
    JsonNode expectedTree = mapper.readTree(expectedContent);
    assertThat(title + " content should be", actualTree, is(expectedTree));
}

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

private boolean testExportAclJson(String accessListType, String expectedResultFile, boolean nameOnly)
        throws IOException {
    Acl accessList;/*  w w w .  j  ava 2  s  .  com*/
    String exportedAclString;
    AclExporterFactory aclExporterFactory = new AclExporterFactory();

    if (nameOnly) {
        accessList = this.buildAccessListNameOnly();
        exportedAclString = aclExporterFactory.getExporter().exportJsonNameOnly(accessList);
    } else {
        accessList = this.buildAccessList(accessListType);
        exportedAclString = aclExporterFactory.getExporter().exportJson(accessList);
    }

    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode expectedAclJson = objectMapper
            .readTree(this.gatherAccessListJsonStringFromFile(expectedResultFile));
    JsonNode exportedAclJson = objectMapper.readTree(exportedAclString);

    return expectedAclJson.equals(exportedAclJson);
}

From source file:UserChangePasswordTest.java

@Test
public void testRouteResetPasswordStep1() {
    running(getFakeApplication(), new Runnable() {
        public void run() {
            //create a user
            String sFakeUser = new AdminUserFunctionalTest().routeCreateNewUser();

            //try to reset password: fails because there i no email attribute
            FakeRequest request = new FakeRequest("GET", "/user/" + sFakeUser + "/password/reset");
            request = request.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
            Result result = routeAndCall(request);
            assertRoute(result, "testRouteChangePassword 1", Status.BAD_REQUEST,
                    "the \\\"email\\\" attribute is not defined into the user's private profile", true);

            //set the email attribute
            //change its role
            FakeRequest request1 = new FakeRequest(PUT, "/me");
            String sPwd = getPayloadFieldValue("/adminUserCreatePayload.json", "password");
            String sAuthEnc = TestConfig.encodeAuth(sFakeUser, sPwd);
            request1 = request1.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
            request1 = request1.withHeader(TestConfig.KEY_AUTH, sAuthEnc);

            ObjectMapper mapper = new ObjectMapper();
            JsonNode actualObj = null;//w ww. j  a  v  a  2s . co m
            try {
                actualObj = mapper.readTree("{\"visibleByTheUser\":{\"email\":\"john@example.com\"}}");
            } catch (JsonProcessingException e) {
                assertFail(ExceptionUtils.getStackTrace(e));
            } catch (IOException e) {
                assertFail(ExceptionUtils.getStackTrace(e));
            }
            request1 = request1.withJsonBody(actualObj, PUT);
            request1 = request1.withHeader("Content-Type", "application/json");
            result = route(request1);
            assertRoute(result, "testRouteChangePassword 2", Status.OK, "john@example.com", true);

            //try to reset password: fails because there i no smtp server defined
            request = new FakeRequest("GET", "/user/" + sFakeUser + "/password/reset");
            request = request.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
            result = routeAndCall(request);
            assertRoute(result, "testRouteChangePassword 3", Status.BAD_REQUEST,
                    "Cannot send mail to reset the password:  Could not reach the mail server. Please contact the server administrator",
                    true);
        }
    });
}

From source file:ac.ucy.cs.spdx.service.Compatibility.java

@POST
@Path("/node/")
@Consumes(MediaType.TEXT_PLAIN)/*w w  w  .j a  v a2s  .  co m*/
@Produces(MediaType.APPLICATION_JSON)
public String addNode(String jsonString) {

    ObjectMapper mapper = new ObjectMapper();
    JsonNode licenseNode = null;
    try {
        licenseNode = mapper.readTree(jsonString);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    ArrayList<String> licenses = new ArrayList<String>();
    String nodeIdentifier = licenseNode.get("nodeIdentifier").toString();
    nodeIdentifier = nodeIdentifier.substring(1, nodeIdentifier.length() - 1);

    String nodeCategory = licenseNode.get("nodeCategory").toString();
    nodeCategory = nodeCategory.substring(1, nodeCategory.length() - 1);
    Category category = Category.UNCATEGORIZED;

    if (nodeCategory == "PERMISSIVE") {
        category = Category.PERMISSIVE;
    } else if (nodeCategory == "WEAK_COPYLEFT") {
        category = Category.WEAK_COPYLEFT;
    } else if (nodeCategory == "STRONG_COPYLEFT") {
        category = Category.STRONG_COPYLEFT;
    } else {
        category = Category.UNCATEGORIZED;
    }

    JsonNode licensesJSON = licenseNode.get("nodelicenses");

    for (int i = 0; i < licensesJSON.size(); i++) {
        String licenseId = licensesJSON.get(i).get("identifier").toString();
        licenseId = licenseId.substring(1, licenseId.length() - 1);
        licenses.add(licenseId);
    }

    try {
        LicenseGraph.addLicenseNode(nodeIdentifier, category, licenses.toArray(new String[licenses.size()]));
    } catch (LicenseNodeAlreadyExistsException e) {
        e.printStackTrace();
        return "{\"status\":\"failure\",\"message\":\"" + e.getMessage() + "\"}";
    }

    LicenseGraph.exportGraph();

    return "{\"status\":\"success\",\"message\":\"" + nodeIdentifier + " added in the system.\"}";// {"nodeIdentifier":"Caldera","nodeCategory":"PERMISSIVE","nodelicenses":[{"identifier":"Caldera"}]}
}

From source file:hu.fnf.devel.wishbox.ui.MainPage.java

private Container getItemContiner() {
    IndexedContainer container = new IndexedContainer();
    container.addContainerProperty("First", String.class, "1st");
    container.addContainerProperty("Second", String.class, "2nd");
    //        WebClient client = WebClient.create("http://195.228.45.136:8181/cxf/test");
    //        client = client.accept("application/json")
    //                .type("application/json")
    //                .path("/say/list");
    //        TestResp testResp = client.get(TestResp.class);

    if (getSession().getAttribute("state") == null) {
        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
        getSession().setAttribute("user", user);

        URI uri = null;/*from  w w w. j av a 2s .c o  m*/
        try {
            uri = new URI(("http://jenna.fnf.hu/gateway/persistence/user/" + user.getUserId()));
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        String plainCreds = "API_KEY:API_PASS";

        byte[] plainCredsBytes = plainCreds.getBytes();
        byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
        String base64Creds = new String(base64CredsBytes);

        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Basic " + base64Creds);
        HttpEntity<String> request = new HttpEntity<String>(headers);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET, request, String.class);

        JsonFactory factory = new JsonFactory();

        ObjectMapper m = new ObjectMapper(factory);
        JsonNode rootNode = null;
        try {
            rootNode = m.readTree(response.getBody());
        } catch (IOException e) {
            e.printStackTrace();
        }

        Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
        while (fieldsIterator.hasNext()) {

            Map.Entry<String, JsonNode> field = fieldsIterator.next();
            if (!field.getKey().startsWith("_")) {
                getSession().setAttribute(field.getKey(), field.getValue().asText());
            } else {

            }
            System.out.println("Key: " + field.getKey() + ":\t" + field.getValue());
        }
        getSession().setAttribute("state", "loaded");
    }
    com.vaadin.data.Item item = container.addItem(((User) getSession().getAttribute("user")).getNickname());
    item.getItemProperty("First").setValue(getSession().getAttribute("firstName").toString());
    item.getItemProperty("Second").setValue(getSession().getAttribute("lastName").toString());

    return container;
}

From source file:com.facebook.presto.hive.AbstractTestHiveFileFormats.java

protected void checkCursor(RecordCursor cursor) throws IOException {
    for (int row = 0; row < NUM_ROWS; row++) {
        assertTrue(cursor.advanceNextPosition());
        assertTrue(cursor.isNull(0));//  w  w w .  ja  va  2s .c  o m
        assertTrue(cursor.isNull(1));
        for (int i = 2; i < TEST_VALUES.size(); i++) {
            Object fieldFromCursor;

            Type type = HiveType.getHiveType(FIELD_INSPECTORS.get(i)).getNativeType();
            if (BOOLEAN.equals(type)) {
                fieldFromCursor = cursor.getBoolean(i);
            } else if (BIGINT.equals(type)) {
                fieldFromCursor = cursor.getLong(i);
            } else if (DOUBLE.equals(type)) {
                fieldFromCursor = cursor.getDouble(i);
            } else if (VARCHAR.equals(type)) {
                fieldFromCursor = cursor.getSlice(i);
            } else if (VARBINARY.equals(type)) {
                fieldFromCursor = cursor.getSlice(i);
            } else if (TimestampType.TIMESTAMP.equals(type)) {
                fieldFromCursor = cursor.getLong(i);
            } else {
                throw new RuntimeException("unknown type");
            }

            if (FIELD_INSPECTORS.get(i).getTypeName().equals("float")
                    || FIELD_INSPECTORS.get(i).getTypeName().equals("double")) {
                assertEquals((double) fieldFromCursor, (double) TEST_VALUES.get(i).getValue(), EPSILON);
            } else if (FIELD_INSPECTORS.get(i).getCategory() == ObjectInspector.Category.PRIMITIVE) {
                assertEquals(fieldFromCursor, TEST_VALUES.get(i).getValue(),
                        String.format("Wrong value for column %d", i));
            } else {
                ObjectMapper mapper = new ObjectMapper();
                JsonNode expected = mapper.readTree((String) TEST_VALUES.get(i).getValue());
                JsonNode actual = mapper.readTree(((Slice) fieldFromCursor).getBytes());
                assertEquals(actual, expected, String.format("Wrong value for column %s", COLUMN_NAMES.get(i)));
            }
        }
    }
}

From source file:volker.streaming.music.lastfm.LastFmApi.java

public Track getNowPlaying() {
    Track result = null;/*  w  ww .jav  a 2  s. co  m*/

    // setup API url
    URI uri = null;
    try {
        uri = getApiUri().addParameter("method", "user.getrecenttracks").addParameter("user", config.getUser())
                .addParameter("api_key", config.getApiKey()).addParameter("format", "json")
                .addParameter("limit", "1").addParameter("extended", "0").build();
    } catch (URISyntaxException e) {
        LOG.fatal("Configuration error. Invalid API url.", e);
        return null;
    }

    // setup the request
    CloseableHttpClient client = getClient().build();
    HttpGet getRequest = new HttpGet(uri);
    setHeaders(getRequest);

    // execute the request
    CloseableHttpResponse response = null;
    try {
        response = client.execute(getRequest);
    } catch (IOException e) {
        LOG.fatal("Failed to execute request.", e);
        close(response, client);
        return null;
    }

    // read the response
    InputStream responseStream = null;
    JsonNode root = null;
    try {
        ObjectMapper mapper = new ObjectMapper();
        responseStream = response.getEntity().getContent();
        root = mapper.readTree(responseStream);
        LOG.info("Last FM API returned :" + root.toString());
    } catch (JsonProcessingException e1) {
        LOG.fatal("Returned JSON was invalid.", e1);
        close(response, client);
        return null;
    } catch (IOException e1) {
        LOG.fatal("Failed to read response stream.", e1);
        close(response, client);
        return null;
    } finally {
        close(responseStream);
    }

    if (root.hasNonNull("error")) {
        LOG.error("Error returned by API: " + (root.hasNonNull("message") ? root.get("message").asText() : ""));
    } else {
        JsonNode recentTracks = root.get("recenttracks");
        Iterator<JsonNode> tracks;
        if (recentTracks.hasNonNull("track")) {
            tracks = recentTracks.get("track").elements();
        } else {
            // no tracks ever listened to
            tracks = new ArrayList<JsonNode>().iterator();
        }
        if (tracks.hasNext()) {
            JsonNode mostRecent = tracks.next();
            if (mostRecent.hasNonNull("@attr")) {
                JsonNode attr = mostRecent.get("@attr");
                if (attr.hasNonNull("nowplaying") && attr.get("nowplaying").asBoolean()) {
                    // mostRecent is the currently playing track
                    try {
                        result = LastFmTrackFactory.fromJson(mostRecent);
                    } catch (IllegalArgumentException e) {
                        LOG.error("JSON response contained an invalid Track.", e);
                    }
                }
            }
        }
    }

    // close stuff
    close(response, client);
    return result;
}

From source file:io.liveoak.pgsql.BasePgSqlHttpTest.java

protected JsonNode parseJson(String jsonString) throws IOException {
    ObjectMapper mapper = new ObjectMapper(JSON_FACTORY);
    JsonParser jp = JSON_FACTORY.createParser(jsonString);
    return mapper.readTree(jp);
}

From source file:net.jawr.web.resource.bundle.factory.util.JsonPropertiesSource.java

@Override
protected void loadConfig(Properties props, String path, InputStream is) {
    try {//from w w  w.j a  v  a2 s.  com

        // load properties into a Properties object
        String jsonContent = IOUtils.toString(is);
        // create an ObjectMapper instance.
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);

        // use the ObjectMapper to read the json string and create a tree
        JsonNode node = mapper.readTree(jsonContent);
        generateProperties(node, null, props);
    } catch (JsonParseException e) {

        throw new BundlingProcessException(
                "jawr configuration could not be loaded at " + path + FIELD_NAME_SEPARATOR, e);
    } catch (IOException e) {
        throw new BundlingProcessException(
                "jawr configuration could not be loaded at " + path + FIELD_NAME_SEPARATOR, e);
    }
}

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

@Test
public void verifyNoToken() throws Exception {
    final CentralOAuthService centralOAuthService = mock(CentralOAuthService.class);
    when(centralOAuthService.getToken(null)).thenThrow(new InvalidTokenException("error"));

    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST",
            CONTEXT + OAuthConstants.REVOKE_URL);
    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 w  w . j av a 2 s .  com
    assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus());
    assertEquals(CONTENT_TYPE, mockResponse.getContentType());

    final ObjectMapper mapper = new ObjectMapper();

    final String expected = "{\"error\":\"" + OAuthConstants.INVALID_REQUEST
            + "\",\"error_description\":\"Invalid Token\"}";
    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());
}