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:org.apache.syncope.client.lib.SyncopeClientFactoryBean.java

protected JacksonJaxbJsonProvider defaultJsonProvider() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new JodaModule());
    objectMapper.configure(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,
            false);// w  w  w  . j  a  v  a 2s. c om
    return new JacksonJaxbJsonProvider(objectMapper, JacksonJaxbJsonProvider.DEFAULT_ANNOTATIONS);
}

From source file:nl.ortecfinance.opal.jacksonweb.SimulationResponseTest.java

@Test
public void testJsonIgnore() throws IOException {

    SimulationResponse resp = new SimulationResponse();

    resp.setCapitalGoalProbabilities(Arrays.asList(new Double(10), null, new Double(33)));

    StringWriter sr = new StringWriter();
    ObjectMapper om = new ObjectMapper();

    SimpleModule module = new SimpleModule();
    //      module.addSerializer(List<Double[]>.class, new ListOfDoubleArraySerializer());
    module.addSerializer(Double[].class, new MyDoubleArraySerializer());
    om.registerModule(module);
    om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    om.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);

    om.writeValue(sr, resp);/*from   www .j av  a 2 s.  c om*/

    System.out.println("SimulationResponse=" + sr);

}

From source file:com.example.common.MoneyJacksonAutoConfiguration.java

public CustomPojoToJsonMessageConverter(ObjectMapper mapper) {
    super(MimeTypeUtils.APPLICATION_JSON);
    this.mapper = mapper;
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    mapper.registerModule(new JodaMoneyModule());
}

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

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;/*from   ww w .j a v a2 s  . c o m*/
    }

    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 streamUrl = new StringBuilder().append(apiUrl.replaceAll("/*$", "")).append("/devices/")
            .append(deviceId).append("/streams/").append(streamName).append("/value").toString();

    try {
        final AtomicReference<String> postBodyRef = new AtomicReference<>();
        session.read(flowFile, new InputStreamCallback() {
            @Override
            public void process(InputStream is) {
                try {
                    String timestamp = flowFile.getAttribute("m2x.stream.value.timestamp");
                    if (StringUtils.isEmpty(timestamp)) {
                        timestamp = ISODateTimeFormat.dateTime().print(flowFile.getEntryDate());
                    }
                    final String value = IOUtils.toString(is, StandardCharsets.UTF_8);

                    final M2XStreamValue m2xValue = new M2XStreamValue();
                    m2xValue.setValue(value);
                    m2xValue.setTimestamp(timestamp);

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

                    final String postBody = mapper.writeValueAsString(m2xValue);
                    logger.warn("POST body is {}", new Object[] { postBody });
                    postBodyRef.set(postBody);
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        });

        final String postBody = postBodyRef.get();
        if (StringUtils.isEmpty(postBody)) {
            logger.error("FlowFile {} contents didn't produce a valid M2X stream value",
                    new Object[] { flowFile });
            session.transfer(flowFile, REL_FAILURE);
            return;
        }

        final Request request = new Request.Builder().url(streamUrl).addHeader("X-M2X-KEY", apiKey)
                .put(RequestBody.create(MEDIA_TYPE_JSON, postBody)).build();
        final Response response = httpClient.newCall(request).execute();

        if (!response.isSuccessful()) {
            logger.error(response.message());
            context.yield();
            session.penalize(flowFile);
            return;
        }
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        context.yield();
        session.penalize(flowFile);
        return;
    }

    session.transfer(flowFile, REL_SUCCESS);
}

From source file:org.efaps.rest.AbstractRest.java

/**
 * Gets the JSON reply.//  ww  w.j ava  2  s. c om
 *
 * @param _jsonObject the _json object
 * @return the JSON reply
 * @throws JsonProcessingException the json processing exception
 */
protected String getJSONReply(final Object _jsonObject) {
    String ret = "";
    final ObjectMapper mapper = new ObjectMapper();
    if (LOG.isDebugEnabled()) {
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
    }
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    mapper.registerModule(new JodaModule());
    try {
        ret = mapper.writeValueAsString(_jsonObject);
    } catch (final JsonProcessingException e) {
        LOG.error("Catched JsonProcessingException", e);
    }
    return ret;
}

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

/**
 * Gets Job via REST call/*from ww  w .  j av  a 2s  . c  o  m*/
 * @param jobId
 * @return Job obtained from REST call
 * @throws Exception 
 */
@Override
public Job getJobById(String jobId) throws Exception {
    ClientConfig cc = new DefaultClientConfig();
    cc.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
    Client client = Client.create(cc);
    client.addFilter(new HTTPBasicAuthFilter(_user.getLogin(), _user.getToken()));
    client.setFollowRedirects(true);
    WebResource resource = client.resource(_restURL).path(Constants.REST_PATH).path(Constants.JOBS_PATH)
            .path(jobId);

    String json = resource.accept(MediaType.APPLICATION_JSON).get(String.class);

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new ObjectifyJacksonModule());
    return mapper.readValue(json, new TypeReference<Job>() {
    });

}

From source file:org.killbill.billing.server.listeners.KillbillPlatformGuiceListener.java

protected void initializeGuice(final ServletContextEvent event) {
    final ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new JodaModule());
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    guiceModules = ImmutableList.<Module>of(getServletModule(), getJacksonModule(),
            new JMXModule(KillbillHealthcheck.class, NotificationQueueService.class, PersistentBus.class),
            new StatsModule(METRICS_SERVLETS_PATHS.get(0), METRICS_SERVLETS_PATHS.get(1),
                    METRICS_SERVLETS_PATHS.get(2), METRICS_SERVLETS_PATHS.get(3),
                    ImmutableList.<Class<? extends HealthCheck>>of(KillbillHealthcheck.class)),
            getModule(event.getServletContext()));

    // Start the Guice machinery
    super.contextInitialized(event);

    injector = injector(event);//w w w  . ja  va 2  s . c om
    event.getServletContext().setAttribute(Injector.class.getName(), injector);

    // Already started at this point - we just need the instance for shutdown
    embeddedDB = injector.getInstance(EmbeddedDB.class);

    killbillLifecycle = injector.getInstance(Lifecycle.class);
    killbillBusService = injector.getInstance(BusService.class);
}

From source file:cc.arduino.contributions.libraries.LibrariesIndexer.java

private void parseIndex(File file) throws IOException {
    InputStream indexIn = null;/*from   w ww.  j a v  a 2s .  c  o m*/
    try {
        indexIn = new FileInputStream(file);
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new MrBeanModule());
        mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
        mapper.configure(DeserializationFeature.EAGER_DESERIALIZER_FETCH, true);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        LibrariesIndex newIndex = mapper.readValue(indexIn, LibrariesIndex.class);

        newIndex.getLibraries().stream()
                .filter(library -> library.getCategory() == null || "".equals(library.getCategory())
                        || !Constants.LIBRARY_CATEGORIES.contains(library.getCategory()))
                .forEach(library -> library.setCategory("Uncategorized"));

        index = newIndex;
    } catch (JsonParseException | JsonMappingException e) {
        System.err.println(format(tr(
                "Error parsing libraries index: {0}\nTry to open the Library Manager to update the libraries index."),
                e.getMessage()));
    } catch (Exception e) {
        System.err.println(format(tr("Error reading libraries index: {0}"), e.getMessage()));
    } finally {
        IOUtils.closeQuietly(indexIn);
    }
}

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

@Override
public Job resave(long jobId) throws Exception {
    ClientConfig cc = new DefaultClientConfig();
    cc.getClasses().add(StringProvider.class);
    Client client = Client.create(cc);/* w w  w.ja  v  a 2s . com*/
    client.addFilter(new HTTPBasicAuthFilter(_user.getLogin(), _user.getToken()));
    client.setFollowRedirects(true);
    WebResource resource = client.resource(_restURL).path(Constants.REST_PATH).path(Constants.JOBS_PATH)
            .path(Long.toString(jobId));

    MultivaluedMap queryParams = _multivaluedMapFactory.getMultivaluedMap(_user);

    queryParams.add(Constants.RESAVE_QUERY_PARAM, "true");

    String json = resource.queryParams(queryParams).accept(MediaType.APPLICATION_JSON)
            .type(MediaType.APPLICATION_JSON_TYPE).entity("{}").post(String.class);

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new ObjectifyJacksonModule());
    return mapper.readValue(json, new TypeReference<Job>() {
    });
}

From source file:org.mayocat.configuration.internal.DefaultConfigurationService.java

public Map<String, Serializable> getGestaltConfiguration() {
    ObjectMapper mapper = getObjectMapper();
    mapper.registerModule(new GestaltConfigurationModule());

    Map<String, Object> result = Maps.newHashMap();
    for (String key : this.gestaltConfigurationSources.keySet()) {
        Object value = this.gestaltConfigurationSources.get(key).get();
        if (ExposedSettings.class.isAssignableFrom(value.getClass()) && this.context.getTenant() != null) {
            // If the gestalt source returns an "exposed setting", then we get the version merged with the tenant
            // configuration.
            Class<? extends ExposedSettings> configurationClass = (Class<? extends ExposedSettings>) value
                    .getClass();//from  w ww .j  av  a2s .c  o m
            value = this.getSettings(configurationClass);
        }
        result.put(key, value);
    }
    try {
        return mapper.readValue(mapper.writeValueAsString(result), new TypeReference<Map<String, Object>>() {
        });
    } catch (JsonProcessingException e) {
        this.logger.error("Failed to convert gestalt configuration [{}]", e);
        throw new RuntimeException(e);
    } catch (IOException e) {
        this.logger.error("Failed to convert configurations to map", e);
        throw new RuntimeException(e);
    }
}