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

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

Introduction

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

Prototype

public ObjectMapper registerModule(Module module) 

Source Link

Document

Method for registering a module that can extend functionality provided by this mapper; for example, by adding providers for custom serializers and deserializers.

Usage

From source file:com.netflix.discovery.converters.jackson.EurekaJsonJacksonCodec.java

private ObjectMapper createObjectMapper(KeyFormatter keyFormatter, boolean compact, boolean wrapped) {
    ObjectMapper newMapper = new ObjectMapper();
    SimpleModule jsonModule = new SimpleModule();
    jsonModule.setSerializerModifier(//  w ww  .j a  va 2  s.  c o m
            EurekaJacksonJsonModifiers.createJsonSerializerModifier(keyFormatter, compact));

    newMapper.registerModule(jsonModule);
    newMapper.setSerializationInclusion(Include.NON_NULL);
    newMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, wrapped);
    newMapper.configure(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED, false);
    newMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, wrapped);
    newMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    newMapper.addMixIn(Applications.class, ApplicationsJsonMixIn.class);
    if (compact) {
        addMiniConfig(newMapper);
    } else {
        newMapper.addMixIn(InstanceInfo.class, InstanceInfoJsonMixIn.class);
    }
    return newMapper;
}

From source file:org.springframework.social.linkedin.api.impl.json.LinkedInNetworkUpdateListDeserializer.java

@Override
public LinkedInNetworkUpdate deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new LinkedInModule());
    jp.setCodec(mapper);/*from   w  w w  .j  a v a2s .c o  m*/

    JsonNode dataNode = jp.readValueAs(JsonNode.class);
    if (dataNode != null) {
        LinkedInNetworkUpdate linkedInNetworkUpdate = (LinkedInNetworkUpdate) mapper
                .reader(new TypeReference<LinkedInNetworkUpdate>() {
                }).readValue(dataNode);

        UpdateContent updatedContent = null;
        UpdateType type = linkedInNetworkUpdate.getUpdateType();
        JsonNode updatedNode = dataNode.get("updateContent");
        JsonNode person = updatedNode.get("person");
        if (type == UpdateType.MSFC) {
            // Totally different.  Looks like a bad API to be honest.
            person = updatedNode.get("companyPersonUpdate").get("person");
        }

        switch (type) {
        case CONN:
            updatedContent = mapper.reader(new TypeReference<UpdateContentConnection>() {
            }).readValue(person);
            break;
        case STAT:
            updatedContent = mapper.reader(new TypeReference<UpdateContentStatus>() {
            }).readValue(person);
            break;
        case JGRP:
            updatedContent = mapper.reader(new TypeReference<UpdateContentGroup>() {
            }).readValue(person);
            break;
        case PREC:
        case SVPR:
            updatedContent = mapper.reader(new TypeReference<UpdateContentRecommendation>() {
            }).readValue(person);
            break;
        case APPM:
            updatedContent = mapper.reader(new TypeReference<UpdateContentPersonActivity>() {
            }).readValue(person);
            break;
        case MSFC:
            updatedContent = mapper.reader(new TypeReference<UpdateContentFollow>() {
            }).readValue(person);
            break;
        case VIRL:
            updatedContent = mapper.reader(new TypeReference<UpdateContentViral>() {
            }).readValue(person);
            break;
        case SHAR:
            updatedContent = mapper.reader(new TypeReference<UpdateContentShare>() {
            }).readValue(person);
            break;
        case CMPY:
            updatedContent = mapper.reader(new TypeReference<UpdateContentCompany>() {
            }).readValue(updatedNode);
            break;
        default:
            try {
                updatedContent = mapper.reader(new TypeReference<UpdateContent>() {
                }).readValue(person);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        // Need to use reflection to set private updateContent field
        try {
            Field f = LinkedInNetworkUpdate.class.getDeclaredField("updateContent");
            f.setAccessible(true);
            f.set(linkedInNetworkUpdate, updatedContent);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if (type == UpdateType.MSFC) {
            // Set the action via reflection as it's private
            String action = updatedNode.get("companyPersonUpdate").get("action").get("code").asText();
            try {
                Field f = UpdateContentFollow.class.getDeclaredField("action");
                f.setAccessible(true);
                f.set(updatedContent, action);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            // Set following via reflection as it's private
            Company company = mapper.reader(new TypeReference<Company>() {
            }).readValue(updatedNode.get("company"));
            try {
                Field f = UpdateContentFollow.class.getDeclaredField("following");
                f.setAccessible(true);
                f.set(updatedContent, company);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else if (type == UpdateType.VIRL) {
            JsonNode originalUpdate = updatedNode.path("updateAction").path("originalUpdate");
            UpdateAction updateAction = mapper.reader(new TypeReference<UpdateAction>() {
            }).readValue(originalUpdate);
            String code = updatedNode.path("updateAction").path("action").path("code").textValue();

            // Set private immutable field action on updateAction
            try {
                Field f = UpdateAction.class.getDeclaredField("action");
                f.setAccessible(true);
                f.set(updateAction, code);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            // Set private immutable field  updateAction on updatedContent
            try {
                Field f = UpdateContentViral.class.getDeclaredField("updateAction");
                f.setAccessible(true);
                f.set(updatedContent, updateAction);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        return linkedInNetworkUpdate;
    }

    return null;
}

From source file:it.polimi.diceH2020.SPACE4Cloud.shared.Test2.java

@Test
public void test1() {
    InstanceData_old data = InstanceDataGenerator_old.build();
    System.out.println(data.toString());

    try {/*from w  w w .  j  av a  2  s .  co m*/
        ObjectMapper mapper = new ObjectMapper().registerModule(new Jdk8Module());
        SimpleModule module = new SimpleModule();
        module.addKeyDeserializer(TypeVMJobClassKey.class, TypeVMJobClassKey.getDeserializer());
        mapper.registerModule(module);

        String serialized = mapper.writeValueAsString(data);
        System.out.println(serialized);

        InstanceData_old data2 = mapper.readValue(serialized, InstanceData_old.class);
        System.out.println(data2.toString());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    assertTrue(data.getGamma() == 240);
}

From source file:org.openmhealth.shim.fitbit.FitbitShimTest.java

@Test
@SuppressWarnings("unchecked")
public void testNormalize() throws IOException {
    URL url = Thread.currentThread().getContextClassLoader().getResource("fitbit-heart.json");
    assert url != null;
    InputStream inputStream = url.openStream();

    ObjectMapper objectMapper = new ObjectMapper();

    FitbitShim.FitbitDataType.HEART.getNormalizer();
    SimpleModule module = new SimpleModule();
    module.addDeserializer(ShimDataResponse.class, FitbitShim.FitbitDataType.HEART.getNormalizer());

    objectMapper.registerModule(module);

    ShimDataResponse response = objectMapper.readValue(inputStream, ShimDataResponse.class);

    assertNotNull(response);/*from   ww w .j  a  v  a 2 s  .  com*/

    assertNotNull(response.getShim());

    Map<String, Object> map = (Map<String, Object>) response.getBody();
    assertTrue(map.containsKey(HeartRate.SCHEMA_HEART_RATE));

    List<HeartRate> stepCounts = (List<HeartRate>) map.get(HeartRate.SCHEMA_HEART_RATE);
    assertTrue(stepCounts != null && stepCounts.size() == 6);
}

From source file:edu.ucsd.crbs.cws.dao.rest.JobRestDAOImpl.java

@Override
public List<Job> getJobs(String owner, String status, Boolean notSubmittedToScheduler, boolean noParams,
        boolean noWorkflowParams, final Boolean showDeleted) throws Exception {
    ClientConfig cc = new DefaultClientConfig();
    cc.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
    Client client = Client.create(cc);/* w ww .  j a  v  a  2 s  .  c o  m*/
    client.addFilter(new HTTPBasicAuthFilter(_user.getLogin(), _user.getToken()));
    client.setFollowRedirects(true);
    WebResource resource = client.resource(_restURL).path(Constants.REST_PATH).path(Constants.JOBS_PATH);
    MultivaluedMap queryParams = _multivaluedMapFactory.getMultivaluedMap(_user);

    if (owner != null) {
        queryParams.add(Constants.OWNER_QUERY_PARAM, owner);
    }

    if (status != null) {
        queryParams.add(Constants.STATUS_QUERY_PARAM, status);
    }

    if (notSubmittedToScheduler != null) {
        queryParams.add(Constants.NOTSUBMITTED_TO_SCHED_QUERY_PARAM, notSubmittedToScheduler.toString());
    }

    if (noParams == true) {
        queryParams.add(Constants.NOPARAMS_QUERY_PARAM, Boolean.TRUE.toString());
    }

    if (noWorkflowParams == true) {
        queryParams.add(Constants.NOWORKFLOWPARAMS_QUERY_PARAM, Boolean.TRUE.toString());
    }
    if (showDeleted != null) {
        queryParams.add(Constants.SHOW_DELETED_QUERY_PARAM, showDeleted.toString());
    }

    String json = resource.queryParams(queryParams).accept(MediaType.APPLICATION_JSON).get(String.class);
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new ObjectifyJacksonModule());
    return mapper.readValue(json, new TypeReference<List<Job>>() {
    });
}

From source file:cn.org.once.cstack.initializer.CloudUnitApplicationContext.java

private MappingJackson2HttpMessageConverter jacksonMessageConverter() {
    MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new Hibernate4Module().enable(Hibernate4Module.Feature.USE_TRANSIENT_ANNOTATION));
    messageConverter.setObjectMapper(mapper);
    return messageConverter;
}

From source file:org.cryptomator.ui.model.VaultObjectMapperProvider.java

@Override
public ObjectMapper get() {
    final ObjectMapper om = new ObjectMapper();
    final SimpleModule module = new SimpleModule("VaultJsonMapper");
    module.addSerializer(Vault.class, new VaultSerializer());
    module.addDeserializer(Vault.class, new VaultDeserializer());
    om.registerModule(module);
    return om;//from   w  ww  . j a  va2s  .co  m
}

From source file:gt.dakaik.config.WebContext.java

public MappingJackson2HttpMessageConverter jacksonXmlMessageConverter() {
    MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();

    ObjectMapper mapper = new XmlMapper();

    //Registering Hibernate4Module to support lazy objects
    Hibernate4Module module = new Hibernate4Module();
    module.disable(Hibernate4Module.Feature.USE_TRANSIENT_ANNOTATION);
    mapper.registerModule(module);

    // Cambiar AnnotationIntrospector para usar anotaciones de JAXB
    AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(mapper.getTypeFactory());
    mapper.setAnnotationIntrospector(introspector);

    List<MediaType> MediaTypes = new ArrayList<>();
    MediaTypes.add(MediaType.APPLICATION_XML);
    messageConverter.setSupportedMediaTypes(MediaTypes);

    messageConverter.setObjectMapper(mapper);
    //log.debug("Listado de MediaTypes: [{}]", messageConverter.getSupportedMediaTypes().toString());

    return messageConverter;

}

From source file:org.apache.nifi.processors.att.m2x.GetM2XStream.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final ProcessorLog logger = getLogger();
    final OkHttpClient httpClient = getHttpClient();
    final StateManager stateManager = context.getStateManager();
    final String apiKey = context.getProperty(M2X_API_KEY).getValue();
    final String apiUrl = context.getProperty(M2X_API_URL).getValue();
    final String deviceId = context.getProperty(M2X_DEVICE_ID).getValue();
    final String streamName = context.getProperty(M2X_STREAM_NAME).getValue();
    final String streamType = context.getProperty(M2X_STREAM_TYPE).getValue();
    final String startTime = getLastStartTime(context, stateManager);
    final String streamUrl = getStreamUrl(apiUrl, deviceId, streamName, startTime);

    String responseBody;/*from w ww.  j  a  va2 s.  c o m*/
    try {
        final Request request = new Request.Builder().url(streamUrl).addHeader("X-M2X-KEY", apiKey).build();
        final Response response = httpClient.newCall(request).execute();

        if (!response.isSuccessful()) {
            logger.error(response.message());
            context.yield();
            return;
        }

        responseBody = response.body().string();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        context.yield();
        return;
    }

    final ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JodaModule());
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

    try {
        final M2XStreamValues m2xValues = mapper.readValue(responseBody, M2XStreamValues.class);
        final List<M2XStreamValue> m2xValueList = m2xValues.getValues();

        if (!CollectionUtils.isEmpty(m2xValueList)) {
            for (final M2XStreamValue m2xValue : m2xValueList) {
                final DateTime timestamp = m2xValue.getTimestamp();
                final Object valueObj = m2xValue.getValue();
                final Set<Map.Entry<String, Object>> properties = m2xValue.getAdditionalProperties().entrySet();
                final ByteArrayInputStream bytes = new ByteArrayInputStream(
                        String.valueOf(valueObj).getBytes(StandardCharsets.UTF_8));

                FlowFile newFlowFile = session.create();
                newFlowFile = session.importFrom(bytes, newFlowFile);
                newFlowFile = session.putAttribute(newFlowFile, "m2x.device.id", deviceId);
                newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.name", streamName);
                newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.start",
                        m2xValues.getStart().toString());
                newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.end",
                        m2xValues.getEnd().toString());
                newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.limit",
                        String.valueOf(m2xValues.getLimit()));
                newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.value.timestamp",
                        timestamp.toString());
                newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.value.millis",
                        String.valueOf(timestamp.getMillis()));
                for (final Map.Entry<String, Object> e : properties) {
                    newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.value." + e.getKey(),
                            String.valueOf(e.getValue()));
                }

                session.getProvenanceReporter().create(newFlowFile);
                session.transfer(newFlowFile, REL_SUCCESS);
            }
        }

        setLastStartTime(stateManager, m2xValues.getEnd().toString());
    } catch (Throwable t) {
        logger.error(t.getMessage(), t);
        context.yield();
    }
}