Example usage for com.fasterxml.jackson.databind ObjectMapper readerForUpdating

List of usage examples for com.fasterxml.jackson.databind ObjectMapper readerForUpdating

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper readerForUpdating.

Prototype

public ObjectReader readerForUpdating(Object valueToUpdate) 

Source Link

Document

Factory method for constructing ObjectReader that will update given Object (usually Bean, but can be a Collection or Map as well, but NOT an array) with JSON data.

Usage

From source file:cat.calidos.morfeu.model.injection.DocumentModule.java

@Produces
@Named("ParsedDocument")
public static Document parseDocument(URI uri, @Named("JSONDocumentStream") InputStream docStream,
        ObjectMapper mapper) throws ParsingException, FetchingException {

    try {//from w  w w . j  ava  2  s .co  m

        return mapper.readerForUpdating(new Document(uri)).readValue(docStream);

    } catch (JsonProcessingException jpe) {
        throw new ParsingException("Problem with the json format of '" + uri + "'", jpe);
    } catch (IOException ioe) {
        throw new FetchingException("Problem fetching '" + uri + "'", ioe);
    }

}

From source file:de.bund.bfr.knime.node.editableTable.JSONDataTable.java

/**
 * Loads a table from the settings given. If any errors occur null is returned.
 * @param settings the settings to load from
 * @return the table/*from  w w w .  ja v a  2 s.c o m*/
 * @since 2.10
 */
@JsonIgnore
public static JSONDataTable loadFromNodeSettings(final NodeSettingsRO settings) {
    String tableString = settings.getString(KNIME_DATA_TABLE_CONF, null);
    if (tableString == null) {
        return null;
    }
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    JSONDataTable table = new JSONDataTable();
    ObjectReader reader = mapper.readerForUpdating(table);
    ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(table.getClass().getClassLoader());
        reader.readValue(tableString);
        return table;
    } catch (IOException e) {
        LOGGER.error("Unable to load JSON data table: " + e.getMessage(), e);
        return null;
    } finally {
        Thread.currentThread().setContextClassLoader(oldLoader);
    }
}

From source file:se.altrusoft.docserv.controllers.Application.java

@SuppressWarnings("unchecked")
@BodyParser.Of(Json.class)
public Result getDocument(String templateName, String encoding) {
    // TODO: Use one static ObjectMapper of re-creating?
    ObjectMapper mapper = new ObjectMapper();
    String json = request().body().asJson().toString();
    String acceptHeader = request().getHeader(ACCEPT);

    TemplateModel templateModel = templates.get(templateName);

    try {/*from   w  w w.  j ava 2 s  .c o  m*/
        if (!templateModel.isDynamic()) {
            mapper.readerForUpdating(templateModel).readValue(json);

            templateModel.translateProperties();

            /* Expand model - if needed -HH */
            templateModel.expandModel();
        } else {
            Object readValue = mapper.readValue(json, Object.class);
            LinkedHashMap<String, Object> jsonValue = (LinkedHashMap<String, Object>) readValue;
            TemplateModel dynamicTemplateModel = DynamicModel.getTemplateModel(templateName, jsonValue);
            // TODO: applicationContext properties has to injected in
            // the new dynamically generated model ...
            // This is only partially done here for the template file -
            // needs design?
            dynamicTemplateModel.setTemplateFile(templateModel.getTemplateFile());
            templateModel = dynamicTemplateModel;
        }
    } catch (JsonParseException e) {
        Logger.warn("Unable to parse received Json data - bad request", e);
        return badRequest("JsonParseException");
    } catch (JsonMappingException e) {
        Logger.warn("Received Json data does not map to template model - bad resquest", e);
        return badRequest("Received Json data does not map to template model");
    } catch (IOException e) {
        Logger.error("IOException while reading Json data", e);
        return internalServerError("IOException while reading Json data");
    } catch (java.lang.Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    ByteArrayOutputStream generatedDocumentOutputStream = null;

    try {
        MimeType mimeType = MimeType.getMimeType(acceptHeader);

        if (mimeType != null) {
            generatedDocumentOutputStream = new ByteArrayOutputStream();

            generateDocumentFromTemplate(templateModel, generatedDocumentOutputStream);

            if (mimeType.getConvertFilterName() != null) {
                Logger.debug("Generating " + mimeType.getValue() + "...");

                generatedDocumentOutputStream = convert(generatedDocumentOutputStream,
                        mimeType.getConvertFilterName(), mimeType.getFilterParameters());
            }
        } else {
            String warnMessage = "Unsupported mime-type: " + acceptHeader;
            Logger.warn(warnMessage);
            return badRequest(warnMessage);
        }

        // TODO: Do this in parallel, i.e. do not produce the ByteArray...
        // --HH
        if (encoding != null && encoding.equalsIgnoreCase(ENCODING_BASE64)) {
            byte[] content = generatedDocumentOutputStream.toByteArray();
            byte[] bs64EncodedContent = new Base64().encode(content);
            Logger.info("Returning base 64 encoded content OK");
            response().setHeader(CONTENT_TRANSFER_ENCODING, ENCODING_BASE64);
            return ok(new ByteArrayInputStream(bs64EncodedContent)).as(mimeType.getValue());
        } else {
            Logger.info("Returning OK");
            return ok(new ByteArrayInputStream(generatedDocumentOutputStream.toByteArray()))
                    .as(mimeType.getValue());
        }
    } catch (XDocReportException e) {
        String errorMessage = "Unable to generate document";
        Logger.error(errorMessage, e);
        e.printStackTrace();
        return internalServerError(errorMessage);
    } catch (IOException e) {
        String errorMessage = "Unexpected error when generating document";
        Logger.error(errorMessage, e);
        e.printStackTrace();
        return internalServerError(errorMessage);
    } catch (BootstrapException e) {
        String errorMessage = "Unable to bootstrap LibreOffice";
        Logger.error(errorMessage, e);
        e.printStackTrace();
        return internalServerError(errorMessage);
    } catch (Exception e) {
        String errorMessage = "LibreOffice Exception";
        Logger.error(errorMessage, e);
        e.printStackTrace();
        return internalServerError(errorMessage);
    } finally {
        IOUtils.closeQuietly(generatedDocumentOutputStream);
    }
}

From source file:org.springframework.data.rest.webmvc.json.DomainObjectReader.java

/**
 * Merges the given {@link ObjectNode} onto the given object.
 * //from   w  w  w  .  j ava 2s  .c  om
 * @param root must not be {@literal null}.
 * @param target must not be {@literal null}.
 * @param mapper must not be {@literal null}.
 * @return
 * @throws Exception
 */
private <T> T doMerge(ObjectNode root, T target, ObjectMapper mapper) throws Exception {

    Assert.notNull(root, "Root ObjectNode must not be null!");
    Assert.notNull(target, "Target object instance must not be null!");
    Assert.notNull(mapper, "ObjectMapper must not be null!");

    PersistentEntity<?, ?> entity = entities.getPersistentEntity(target.getClass());

    if (entity == null) {
        return mapper.readerForUpdating(target).readValue(root);
    }

    MappedProperties mappedProperties = getJacksonProperties(entity, mapper);

    for (Iterator<Entry<String, JsonNode>> i = root.fields(); i.hasNext();) {

        Entry<String, JsonNode> entry = i.next();
        JsonNode child = entry.getValue();

        if (child.isArray()) {
            continue;
        }

        String fieldName = entry.getKey();

        if (!mappedProperties.hasPersistentPropertyForField(fieldName)) {
            i.remove();
            continue;
        }

        if (child.isObject()) {

            PersistentProperty<?> property = mappedProperties.getPersistentProperty(fieldName);

            if (associationLinks.isLinkableAssociation(property)) {
                continue;
            }

            PersistentPropertyAccessor accessor = entity.getPropertyAccessor(target);
            Object nested = accessor.getProperty(property);

            ObjectNode objectNode = (ObjectNode) child;

            if (property.isMap()) {

                // Keep empty Map to wipe it as expected
                if (!objectNode.fieldNames().hasNext()) {
                    continue;
                }

                doMergeNestedMap((Map<String, Object>) nested, objectNode, mapper);

                // Remove potentially emptied Map as values have been handled recursively
                if (!objectNode.fieldNames().hasNext()) {
                    i.remove();
                }

                continue;
            }

            if (nested != null && property.isEntity()) {
                doMerge(objectNode, nested, mapper);
            }
        }
    }

    return mapper.readerForUpdating(target).readValue(root);
}

From source file:org.usrz.libs.utils.beans.ObjectMapperTest.java

private void testObjectMapper(ClassBuilder builder) throws Exception {
    final Class<SimpleBean> beanClass = builder.newClass(SimpleBean.class);

    final ObjectMapper mapper = new ObjectMapper().configure(INDENT_OUTPUT, false)
            .configure(WRITE_DATES_AS_TIMESTAMPS, true).configure(ORDER_MAP_ENTRIES_BY_KEYS, true)
            .configure(SORT_PROPERTIES_ALPHABETICALLY, true)
            .setPropertyNamingStrategy(CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);

    SimpleBean bean = InstanceBuilder.newInstance(beanClass);
    bean.setName("fooName");
    bean.setDescription("fooDescription");
    assertEquals(mapper.writeValueAsString(bean), "{\"description\":\"fooDescription\",\"name\":\"fooName\"}");

    bean = mapper.readValue("{\"name\":\"barName\",\"description\":\"barDescription\"}", beanClass);
    assertEquals(bean.getName(), "barName");
    assertEquals(bean.getDescription(), "barDescription");

    mapper.readerForUpdating(bean).readValue("{\"name\":\"bazName\",\"description\":\"bazDescription\"}");
    assertEquals(bean.getName(), "bazName");
    assertEquals(bean.getDescription(), "bazDescription");

}