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:com.galenframework.tests.integration.GalenFullJsProjectIT.java

private List<String> collectAllErrorMessagesFromIndividualTestReport(String testId, String jsonReportPath)
        throws IOException {
    ObjectMapper mapper = new ObjectMapper();

    JsonNode testReportNode = mapper
            .readTree(FileUtils.readFileToString(new File(jsonReportPath + "/" + testId + ".json")));
    return collectAllErrorMessagesFrom(testReportNode.get("report").get("nodes"));
}

From source file:com.google.api.tools.framework.importers.swagger.SwaggerToService.java

/**
 * Ensures that all files are valid json/yaml and does schema validation on swagger spec.
 * Returns the path to the valid swagger file.
 * @throws SwaggerConversionException/*  w  ww .  j  a  va2s .c  om*/
 */
private static String validateInputFiles(ImmutableList<String> savedFilePaths)
        throws SwaggerConversionException {
    JsonNode data = null;
    String validSwaggerFilePath = null;
    for (String filePath : savedFilePaths) {
        try {
            File inputFile = new File(filePath);
            String inputFileContent = FileUtils.readFileToString(inputFile, "UTF-8");
            ObjectMapper objMapper = null;
            String fileExtension = Files.getFileExtension(filePath);
            if (fileExtension.equalsIgnoreCase("json")) {
                objMapper = Json.mapper();
            } else if (fileExtension.equalsIgnoreCase("yaml")) {
                objMapper = Yaml.mapper();
            } else {
                throw new IllegalArgumentException(String.format(
                        "Swagger spec files '%s' have invalid extension '%s'. Only files with 'json' and "
                                + "'yaml' file extensions are allowed.",
                        inputFile.getName(), fileExtension));
            }
            data = objMapper.readTree(inputFileContent);
        } catch (Exception e) {
            throw new SwaggerConversionException("Unable to parse the content. " + e.getMessage(), e);
        }

        if (data.get("swagger") != null && data.get("swagger").toString().contains("2.0")) {
            if (validSwaggerFilePath != null) {
                throw new SwaggerConversionException("Multiple swagger files were passed as input. "
                        + "Only one top-level swagger file is allowed which can reference schemas from other "
                        + "files passed as input.");
            }
            validateSwaggerSpec(data);
            validSwaggerFilePath = filePath;
        }
    }
    if (Strings.isNullOrEmpty(validSwaggerFilePath)) {
        throw new SwaggerConversionException("Cannot find a valid swagger 2.0 spec in the input files");
    } else {
        return validSwaggerFilePath;
    }
}

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

@Test
public void itGetsAListOfCaches() throws Exception {
    HttpGet httpGet = new HttpGet("http://localhost:3333/crs/locations/caches");

    CloseableHttpResponse response = null;
    try {/*from   w w w.  j  av a 2s  .c o  m*/
        response = closeableHttpClient.execute(httpGet);

        ObjectMapper objectMapper = new ObjectMapper(new JsonFactory());
        JsonNode jsonNode = objectMapper.readTree(EntityUtils.toString(response.getEntity()));
        String locationName = jsonNode.get("locations").fieldNames().next();
        JsonNode cacheNode = jsonNode.get("locations").get(locationName).get(0);

        assertThat(cacheNode.get("cacheId").asText(), not(equalTo("")));
        assertThat(cacheNode.get("fqdn").asText(), not(equalTo("")));

        assertThat(cacheNode.get("ipAddresses").isArray(), equalTo(true));
        assertThat(cacheNode.has("adminStatus"), equalTo(true));

        assertThat(cacheNode.get("port").asInt(-123456), not(equalTo(-123456)));
        assertThat(cacheNode.get("lastUpdateTime").asInt(-123456), not(equalTo(-123456)));
        assertThat(cacheNode.get("connections").asInt(-123456), not(equalTo(-123456)));
        assertThat(cacheNode.get("currentBW").asInt(-123456), not(equalTo(-123456)));
        assertThat(cacheNode.get("availBW").asInt(-123456), not(equalTo(-123456)));

        assertThat(cacheNode.get("cacheOnline").asText(), anyOf(equalTo("true"), equalTo("false")));
        assertThat(cacheNode.get("lastUpdateHealthy").asText(), anyOf(equalTo("true"), equalTo("false")));
    } finally {
        if (response != null)
            response.close();
    }
}

From source file:com.crushpaper.DbJsonBackupForUserTest.java

@Test
public void test3() throws IOException {
    final TestEntrySet before = new TestEntrySet(
            new TestEntry[] { new TestEntry("1", 1), new TestEntry("2", 2) });

    final ObjectMapper mapper = new ObjectMapper();
    final JsonNode node1 = mapper.readTree("{\n" + "\"note\": \"1\",\n" + "\"modTime\": 1,\n"
            + "\"createTime\": 1,\n" + "\"id\": \"S3\",\n" + "\"type\": \"root\"\n" + "}");

    final JsonNode node2 = mapper.readTree("{\n" + "\"note\": \"2\",\n" + "\"modTime\": 2,\n"
            + "\"createTime\": 2,\n" + "\"id\": \"S4\",\n" + "\"type\": \"root\"\n" + "}\n");
    final Errors errors = new Errors();
    try {//www . ja va  2s  . c o m
        final User user = dbLogic.getOrCreateUser("user");
        assertTrue(dbLogic.addEntries(before, user, createTime, errors));
        dbLogic.commit();
        final StringBuilder result = new StringBuilder();
        dbLogic.backupJsonForUser(user, result);
        final JsonNode resultNode = mapper.readTree(result.toString());
        assertTrue(resultNode.isObject());
        final JsonNode entriesNodes = resultNode.get("entries");
        assertTrue(entriesNodes.isArray());
        assertEquals(2, entriesNodes.size());
        boolean matched1 = false, matched2 = false;
        for (int i = 0; i < 2; ++i) {
            final JsonNode obj = entriesNodes.get(i);
            if (obj.equals(node1)) {
                matched1 = true;
            } else if (obj.equals(node2)) {
                matched2 = true;
            }
        }

        assertTrue(matched1);
        assertTrue(matched2);
    } catch (final IOException e) {
        assertTrue(false);
    }
}

From source file:uk.ac.manchester.cs.owl.semspreadsheets.repository.bioportal.BioPortalRepositoryAccessor.java

public Collection<RepositoryItem> getOntologies() {
    final Collection<RepositoryItem> items = new ArrayList<RepositoryItem>();
    URL url = null;//from  w  w w  .j av a 2  s .c  o m
    try {

        url = new URL(
                BioPortalRepository.ONTOLOGY_LIST + "?format=json&apikey=" + BioPortalRepository.readAPIKey());

        logger.debug("Contacting BioPortal REST API at: " + url.toExternalForm());

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(CONNECT_TIMEOUT);
        connection.setReadTimeout(CONNECT_TIMEOUT);
        int responseCode = connection.getResponseCode();
        logger.info("BioPortal http response: " + responseCode);

        if (responseCode == 400 || responseCode == 403) {
            throw new BioPortalAccessDeniedException();
        }
        ObjectMapper mapper = new ObjectMapper();

        JsonNode node = mapper.readTree(connection.getInputStream());
        for (final JsonNode item : node) {
            String name = item.get("name").asText();
            String id = item.get("acronym").asText();

            BioPortalRepositoryItem repositoryItem = new BioPortalRepositoryItem(id, name, this);
            if (repositoryItem.isCompatible()) {
                items.add(repositoryItem);
            }
        }
        if (SAVE_PROPERTIES_CACHE) {
            BioPortalCache.getInstance().dumpStoredProperties();
        }
    } catch (UnknownHostException e) {
        ErrorHandler.getErrorHandler().handleError(e);
    } catch (MalformedURLException e) {
        logger.error("Error with URL for BioPortal rest API", e);
    } catch (SocketTimeoutException e) {
        logger.error("Timeout connecting to BioPortal", e);
        ErrorHandler.getErrorHandler().handleError(e);
    } catch (IOException e) {
        logger.error("Error communiciating with BioPortal rest API", e);
    } catch (BioPortalAccessDeniedException e) {
        ErrorHandler.getErrorHandler().handleError(e);
    }
    return items;
}

From source file:com.fourspaces.couchdb.CouchResponse.java

/**
 * Returns the body of the response as a Jackson JsonNode (such as for a document)
 *
 * @return/*from w w  w .  j a  v  a 2 s  . co  m*/
 */
public JsonNode getBodyAsJsonNode() throws IOException {
    if (body == null) {
        return null;
    }

    ObjectMapper mapper = new ObjectMapper();
    return mapper.readTree(body);
}

From source file:com.stratio.ingestion.source.rest.url.filter.MongoFilterHandler.java

protected JsonNode loadConfigurationFile(String jsonFile) {
    JsonNode jsonNode = null;/* w ww .  j a  v  a 2 s. c  om*/
    if (StringUtils.isNotBlank(jsonFile)) {
        try {
            File checkpointFile = new File(jsonFile);
            if (checkpointFile.exists()) {
                ObjectMapper mapper = new ObjectMapper();
                jsonNode = mapper.readTree(checkpointFile);
            } else {
                throw new RestSourceException("The configuration file doesn't exist");
            }
        } catch (Exception e) {
            throw new RestSourceException("An error ocurred while json parsing. Verify configuration  file", e);
        }
    }
    return jsonNode;
}

From source file:org.createnet.raptor.models.data.ResultSet.java

private void parse(String jsonString) {

    ObjectMapper mapper = ServiceObject.getMapper();
    JsonNode json;//from w  ww . j  ava2s. c om

    try {
        json = mapper.readTree(jsonString);
    } catch (IOException ex) {
        logger.error("Error parsing: {}", jsonString, ex);
        return;
    }

    parse(json);
}

From source file:com.auditbucket.test.unit.TestJson.java

@Test
public void simpleTextRemainsUncompressed() throws Exception {
    String json = "{\"colname\": \"tinytext.......................\"}";
    System.out.println("Before Comppression" + json.getBytes().length);

    CompressionResult result = CompressionHelper.compress(json);
    Assert.assertEquals(CompressionResult.Method.NONE, result.getMethod());
    System.out.println("Compressed " + result.length());

    String uncompressed = CompressionHelper.decompress(result);

    ObjectMapper mapper = new ObjectMapper();
    JsonNode compareTo = mapper.readTree(json);
    JsonNode other = mapper.readTree(uncompressed);
    Assert.assertTrue(compareTo.equals(other));

}

From source file:com.sinnerschrader.s2b.accounttool.logic.component.licences.LicenseSummary.java

private List<Dependency> loadFromJSON(Resource licenseFile) throws Exception {
    List<Dependency> deps = new LinkedList<>();
    ObjectMapper om = new ObjectMapper();
    JsonNode licenseRoot = om.readTree(licenseFile.getInputStream());
    Iterator<String> entryNames = licenseRoot.fieldNames();
    while (entryNames.hasNext()) {
        String entryName = entryNames.next();
        JsonNode licenceNode = licenseRoot.get(entryName);

        String[] npmNameFragments = StringUtils.split(entryName, '@');
        final String groupId = "npm";
        final String artifactId = npmNameFragments[0];
        final String version = npmNameFragments[1];

        final String lName = getFieldValue(licenceNode, "licenses");
        final String lUrl = getFieldValue(licenceNode, "repository");
        final String lDistro = "repo";
        String comments = "";

        deps.add(new Dependency(groupId, artifactId, version, new License(lName, lUrl, lDistro, comments)));
    }/*w  w  w .ja  v  a2s.c o  m*/
    Collections.sort(deps);
    return deps;
}