Example usage for com.fasterxml.jackson.databind ObjectReader readValue

List of usage examples for com.fasterxml.jackson.databind ObjectReader readValue

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectReader readValue.

Prototype

@SuppressWarnings("unchecked")
public <T> T readValue(JsonNode src) throws IOException, JsonProcessingException 

Source Link

Document

Convenience method for converting results from given JSON tree into given value type.

Usage

From source file:org.tinymediamanager.core.tvshow.TvShowList.java

/**
 * Load tv shows from database.//from   w  ww  .  jav  a  2 s  .  c o m
 */
void loadTvShowsFromDatabase(MVMap<UUID, String> tvShowMap, ObjectMapper objectMapper) {
    // load all TV shows from the database
    ObjectReader tvShowObjectReader = objectMapper.readerFor(TvShow.class);

    for (UUID uuid : tvShowMap.keyList()) {
        try {
            TvShow tvShow = tvShowObjectReader.readValue(tvShowMap.get(uuid));
            tvShow.setDbId(uuid);

            // for performance reasons we add tv shows directly
            tvShowList.add(tvShow);
        } catch (Exception e) {
            LOGGER.warn("problem decoding TV show json string: ", e);
        }
    }
    LOGGER.info("found " + tvShowList.size() + " TV shows in database");
}

From source file:org.tinymediamanager.core.tvshow.TvShowList.java

/**
 * Load episodes from database./*from  w  ww.  ja  v a 2  s.  co m*/
 */
void loadEpisodesFromDatabase(MVMap<UUID, String> episodesMap, ObjectMapper objectMapper) {
    // load all episodes from the database
    ObjectReader episodeObjectReader = objectMapper.readerFor(TvShowEpisode.class);
    int episodeCount = 0;

    for (UUID uuid : episodesMap.keyList()) {
        try {
            episodeCount++;
            TvShowEpisode episode = episodeObjectReader.readValue(episodesMap.get(uuid));
            episode.setDbId(uuid);

            // and assign it the the right TV show
            for (TvShow tvShow : tvShowList) {
                if (tvShow.getDbId().equals(episode.getTvShowDbId())) {
                    episode.setTvShow(tvShow);
                    tvShow.addEpisode(episode);
                    break;
                }
            }
        } catch (Exception e) {
            LOGGER.warn("problem decoding episode json string: ", e);
        }
    }
    LOGGER.info("found " + episodeCount + " episodes in database");
}

From source file:org.wikidata.wdtk.wikibaseapi.WbEditEntityAction.java

/**
 * Parse a JSON response to extract an entity document.
 * <p>/*  ww w  . j  a  va2  s  .c  om*/
 * TODO This method currently contains code to work around Wikibase issue
 * https://phabricator.wikimedia.org/T73349. This should be removed once the
 * issue is fixed.
 *
 * @param entityNode
 *            the JSON node that should contain the entity document data
 * @return the entitiy document, or null if there were unrecoverable errors
 * @throws IOException
 * @throws JsonProcessingException
 */
private EntityDocument parseJsonResponse(JsonNode entityNode) throws JsonProcessingException, IOException {
    try {
        JacksonTermedStatementDocument ed = mapper.treeToValue(entityNode,
                JacksonTermedStatementDocument.class);
        ed.setSiteIri(this.siteIri);

        return ed;
    } catch (JsonProcessingException e) {
        logger.warn("Error when reading JSON for entity " + entityNode.path("id").asText("UNKNOWN") + ": "
                + e.toString() + "\nTrying to manually fix issue https://phabricator.wikimedia.org/T73349.");
        String jsonString = entityNode.toString();
        jsonString = jsonString.replace("\"sitelinks\":[]", "\"sitelinks\":{}")
                .replace("\"labels\":[]", "\"labels\":{}").replace("\"aliases\":[]", "\"aliases\":{}")
                .replace("\"claims\":[]", "\"claims\":{}")
                .replace("\"descriptions\":[]", "\"descriptions\":{}");

        ObjectReader documentReader = this.mapper.reader(JacksonTermedStatementDocument.class);

        JacksonTermedStatementDocument ed;
        ed = documentReader.readValue(jsonString);
        ed.setSiteIri(this.siteIri);
        return ed;
    }
}

From source file:typicalnerd.musicarchive.client.network.FileUploader.java

/**
 * Uploads the file to the web service./*from w  ww  .j  a  v  a2 s .  c om*/
 * 
 * @param file
 * The file's location in the file system.
 * 
 * @return
 * Returns the {@link FileUploadResult} in case of a successful upload.
 * 
 * @throws IOException
 */
private FileUploadResult uploadFile(Path file) throws IOException {
    URL url = new URL(baseUrl + "/files");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/octet-stream");
    connection.setRequestProperty("Content-Length", String.valueOf(Files.size(file)));
    connection.setRequestProperty("Accept", "application/json");
    connection.setDoOutput(true);
    connection.setDoInput(true);

    try (InputStream in = new BufferedInputStream(new FileInputStream(file.toFile()))) {
        try (OutputStream out = connection.getOutputStream()) {
            // Lazy as we are, we use one of the many nice functions in the Apache
            // Commons library.
            IOUtils.copy(in, out);
        }
    }

    // Now it's time to read the first result. If all goes well, this was a 
    // HTTP 201 - CREATED. If the file is already known, e.g. because hash and
    // name match an existing object, then HTTP 200 is returned and nothing was
    // changed on the server. In that case we query if there is meta data and if
    // so skip the upload in with the assumption that the latest version is already 
    // on the server. If not, we continue as planned.
    connection.connect();
    int result = connection.getResponseCode();

    if (200 != result || 201 != result) {
        try (InputStream in = connection.getInputStream()) {
            ErrorResponse e = mapper.readValue(in, ErrorResponse.class);
            throw new UnknownServiceException("Upload of file failed. " + e.getMessage());
        }
    }

    // Parse the response to get the location of where to put the meta data.
    // We expect a JSON response so let Jackson parse it into an expected response
    // object.
    FileUploadResult uploadResult = new FileUploadResult(result);
    try (InputStream in = connection.getInputStream()) {
        ObjectReader reader = mapper.readerForUpdating(uploadResult);
        reader.readValue(in);
    }
    return uploadResult;
}