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.proofpoint.event.collector.TestFilteringMapSerializer.java

private ObjectMapper getMapper(FilteringMapSerializer filteringMapSerializer) {
    SimpleModule testModule = new SimpleModule("FilteringEventModule", Version.unknownVersion());
    testModule.addSerializer(filteringMapSerializer);
    ObjectMapper mapper = new ObjectMapperProvider().get();
    mapper.registerModule(testModule);
    return mapper;
}

From source file:org.inbio.neoportal.image_crawler.flickr.GroupPoolsInterface.java

/**
 * Return and JSONArray with the next photos page
 * @param groupId//from www .  ja v a 2  s.c o m
 * @return JSONArray or null when finish
 */
public JSONArray nextPhotosPage(String groupId) {
    this.page++;

    if (this.pages > 0 && this.pages < this.page)
        throw new NoSuchElementException();

    String flickrPoolUrl = "http://api.flickr.com/services/rest/?method=flickr.groups.pools.getPhotos";
    flickrPoolUrl += "&api_key=" + this.apiKey;
    flickrPoolUrl += "&group_id=" + groupId;
    flickrPoolUrl += "&page=" + page;
    //flickrPoolUrl += "&extras=description%2C+license%2C+date_upload%2C+date_taken%2C+owner_name%2C+icon_server%2C+original_format%2C+last_update%2C+geo%2C+tags%2C+machine_tags%2C+o_dims%2C+views%2C+media%2C+path_alias%2C+url_sq%2C+url_t%2C+url_s%2C+url_q%2C+url_m%2C+url_n%2C+url_z%2C+url_c%2C+url_l%2C+url_o";
    flickrPoolUrl += "&extras=description,license,date_upload,date_taken,owner_name,icon_server,original_format,last_update,geo,tags,machine_tags,o_dims,views,media,path_alias,url_sq,url_t,url_s,url_q,url_m,url_n,url_z,url_c,url_l,url_o";
    flickrPoolUrl += "&format=json&nojsoncallback=1";

    InputStream in = null;
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule((Module) new JsonOrgModule());

    try {
        in = new URL(flickrPoolUrl).openStream();

        String json = IOUtils.toString(in);

        JSONObject jsonObject = mapper.readValue(json, JSONObject.class);

        this.pages = ((JSONObject) jsonObject.get("photos")).getInt("pages");

        JSONArray photoArray = ((JSONObject) jsonObject.get("photos")).getJSONArray("photo");

        return photoArray;

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(in);
    }

    return null;
}

From source file:io.apptik.comm.jus.converter.JacksonConverterFactoryTest.java

@Before
public void setUp() {
    queue = Jus.newRequestQueue();//from   w  w w .  ja v  a  2s .com
    SimpleModule module = new SimpleModule();
    module.addSerializer(AnInterface.class, new AnInterfaceSerializer());
    module.addDeserializer(AnInterface.class, new AnInterfaceDeserializer());
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(module);
    mapper.configure(MapperFeature.AUTO_DETECT_GETTERS, false);
    mapper.configure(MapperFeature.AUTO_DETECT_SETTERS, false);
    mapper.configure(MapperFeature.AUTO_DETECT_IS_GETTERS, false);
    mapper.setVisibilityChecker(mapper.getSerializationConfig().getDefaultVisibilityChecker()
            .withFieldVisibility(JsonAutoDetect.Visibility.ANY));

    RetroProxy retroProxy = new RetroProxy.Builder().baseUrl(server.url("/").toString())
            .addConverterFactory(JacksonConverterFactory.create(mapper)).requestQueue(queue).build();
    service = retroProxy.create(Service.class);
}

From source file:io.github.cdelmas.spike.restlet.infrastructure.JacksonCustomConverter.java

private ObjectMapper createMapper() {
    JsonFactory jsonFactory = new JsonFactory();
    jsonFactory.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
    ObjectMapper mapper = new ObjectMapper(jsonFactory);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.registerModule(new Jdk8Module());
    return mapper;
}

From source file:com.github.helenusdriver.driver.tools.Tool.java

/**
 * Creates all defined Json schemas based on the provided set of package names
 * and options and add the schemas to the specified map.
 *
 * @author paouelle/*ww w.java 2 s .co  m*/
 *
 * @param  pkgs the set of packages to create Json schemas for
 * @param  suffixes the map of provided suffix values
 * @param  matching whether or not to only create schemas for keyspaces that
 *         matches the specified set of suffixes
 * @param  schemas the map where to record the Json schema for the pojo classes
 *         found
 * @throws LinkageError if the linkage fails for one of the specified entity
 *         class
 * @throws ExceptionInInitializerError if the initialization provoked by one
 *         of the specified entity class fails
 * @throws IllegalArgumentException if no pojos are found in any of the
 *         specified packages
 * @throws IOException if an I/O error occurs while generating the Json schemas
 */
private static void createJsonSchemasFromPackages(String[] pkgs, Map<String, String> suffixes, boolean matching,
        Map<Class<?>, JsonSchema> schemas) throws IOException {
    for (final String pkg : pkgs) {
        if (pkg == null) {
            continue;
        }
        final CreateSchemas cs = (matching ? StatementBuilder.createMatchingSchemas(pkg)
                : StatementBuilder.createSchemas(pkg));

        // pass all suffixes
        for (final Map.Entry<String, String> e : suffixes.entrySet()) {
            // register the suffix value with the corresponding suffix type
            cs.where(StatementBuilder.eq(e.getKey(), e.getValue()));
        }
        for (final Class<?> c : cs.getObjectClasses()) {
            System.out.println(Tool.class.getSimpleName() + ": creating Json schema for " + c.getName());
            final ObjectMapper m = new ObjectMapper();
            final SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();

            m.registerModule(new Jdk8Module());
            m.enable(SerializationFeature.INDENT_OUTPUT);
            m.acceptJsonFormatVisitor(m.constructType(c), visitor);
            schemas.put(c, visitor.finalSchema());
        }
    }
}

From source file:org.springframework.cloud.dataflow.rest.client.JobExecutionDeserializationTests.java

@Test
public void testDeserializationOfSingleJobExecution() throws IOException {

    final ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new Jackson2HalModule());

    final InputStream inputStream = JobExecutionDeserializationTests.class
            .getResourceAsStream("/SingleJobExecutionJson.txt");

    final String json = new String(StreamUtils.copyToByteArray(inputStream));

    objectMapper.addMixIn(JobExecution.class, JobExecutionJacksonMixIn.class);
    objectMapper.addMixIn(JobParameters.class, JobParametersJacksonMixIn.class);
    objectMapper.addMixIn(JobParameter.class, JobParameterJacksonMixIn.class);
    objectMapper.addMixIn(JobInstance.class, JobInstanceJacksonMixIn.class);
    objectMapper.addMixIn(StepExecution.class, StepExecutionJacksonMixIn.class);
    objectMapper.addMixIn(StepExecutionHistory.class, StepExecutionHistoryJacksonMixIn.class);
    objectMapper.addMixIn(ExecutionContext.class, ExecutionContextJacksonMixIn.class);
    objectMapper.addMixIn(ExitStatus.class, ExitStatusJacksonMixIn.class);
    objectMapper.setDateFormat(new ISO8601DateFormatWithMilliSeconds());

    final JobExecutionResource jobExecutionInfoResource = objectMapper.readValue(json,
            JobExecutionResource.class);

    Assert.assertNotNull(jobExecutionInfoResource);
    Assert.assertEquals(Long.valueOf(1), jobExecutionInfoResource.getJobId());
    Assert.assertEquals("ff.job", jobExecutionInfoResource.getName());
    Assert.assertEquals("COMPLETED", jobExecutionInfoResource.getJobExecution().getStatus().name());

}

From source file:nl.knaw.huygens.timbuctoo.rest.providers.HTMLProviderHelper.java

/**
 * Returns an object writer for a class with the specified annotations.
 * <ul>//w  w  w .j ava  2 s.  c  o  m
 * <li>The current implementation is not thread safe.</li>
 * <li>Apparently uses undocumented features of Jackson. In version 2.1 it used
 * <code>com.fasterxml.jackson.jaxrs.json.util.AnnotationBundleKey</code> and
 * <code>com.fasterxml.jackson.jaxrs.json.annotation.EndpointConfig</code>.
 * In Jackson 2.2 the first of these classes was moved to a different package,
 * and the second was replaced by <code>JsonEndpointConfig</code>.</li>
 * </ul>
 */
public ObjectWriter getObjectWriter(Annotation[] annotations) {
    AnnotationBundleKey key = new AnnotationBundleKey(annotations, AnnotationBundleKey.class);
    ObjectWriter writer = writers.get(key);
    if (writer == null) {
        // A quick hack to add custom serialization of the Reference type.
        SimpleModule module = new SimpleModule();
        module.addSerializer(new ReferenceSerializer(registry));
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(module);
        JsonEndpointConfig endpointConfig = JsonEndpointConfig.forWriting(mapper, annotations, null);
        writer = endpointConfig.getWriter();
        writers.put(key, writer);
    }
    return writer;
}

From source file:net.sf.gazpachoquest.questionnaires.resource.ResourceProducer.java

@Produces
@GazpachoResource/*ww w.  j a va2 s.  co m*/
@RequestScoped
public QuestionnaireResource createQuestionnairResource(HttpServletRequest request) {
    RespondentAccount principal = (RespondentAccount) request.getUserPrincipal();
    String apiKey = principal.getApiKey();
    String secret = principal.getSecret();

    logger.info("Getting QuestionnaireResource using api key {}/{} ", apiKey, secret);

    JacksonJsonProvider jacksonProvider = new JacksonJsonProvider();
    ObjectMapper mapper = new ObjectMapper();
    // mapper.findAndRegisterModules();
    mapper.registerModule(new JSR310Module());
    mapper.setSerializationInclusion(Include.NON_EMPTY);
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

    jacksonProvider.setMapper(mapper);

    QuestionnaireResource resource = JAXRSClientFactory.create(BASE_URI, QuestionnaireResource.class,
            Collections.singletonList(jacksonProvider), null);
    // proxies
    // WebClient.client(resource).header("Authorization", "GZQ " + apiKey);

    Client client = WebClient.client(resource);
    ClientConfiguration config = WebClient.getConfig(client);
    config.getOutInterceptors().add(new HmacAuthInterceptor(apiKey, secret));
    return resource;
}

From source file:org.springframework.data.rest.tests.RepositoryTestsConfig.java

@Bean
public ObjectMapper objectMapper() {

    RelProvider relProvider = new EvoInflectorRelProvider();
    ObjectMapper mapper = new ObjectMapper();

    mapper.registerModule(new Jackson2HalModule());
    mapper.registerModule(persistentEntityModule());
    mapper.setHandlerInstantiator(new Jackson2HalModule.HalHandlerInstantiator(relProvider, null, null));
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.setSerializationInclusion(Include.NON_EMPTY);

    return mapper;
}

From source file:com.aceevo.ursus.client.UrsusJerseyClientBuilder.java

/**
 * Builds the {@link Client} instance./* ww w  . j a  v  a2 s.c  o  m*/
 *
 * @return a fully-configured {@link Client}
 */

public Client build() {
    ClientConfig clientConfig = new ClientConfig();
    clientConfig.property(ClientProperties.READ_TIMEOUT, configuration.getReadTimeout());
    clientConfig.property(ClientProperties.CONNECT_TIMEOUT, configuration.getConnectTimeout());
    clientConfig.property(ApacheClientProperties.DISABLE_COOKIES, true);

    PoolingHttpClientConnectionManager poolingClientConnectionManager = new PoolingHttpClientConnectionManager();
    poolingClientConnectionManager.setMaxTotal(configuration.getMaxTotalThread());
    poolingClientConnectionManager.setDefaultMaxPerRoute(configuration.getDefaultMaxPerRoute());

    clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, poolingClientConnectionManager);

    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.registerModule(new GuavaModule());

    // create JsonProvider to provide custom ObjectMapper
    JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider();
    provider.setMapper(mapper);

    return ClientBuilder.newBuilder().register(provider).withConfig(clientConfig).build();
}