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:de.undercouch.bson4jackson.BsonGeneratorTest.java

private BSONObject generateAndParse(Map<String, Object> data, BsonGenerator.Feature... featuresToEnable)
        throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    BsonFactory bsonFactory = new BsonFactory();
    if (featuresToEnable != null) {
        for (BsonGenerator.Feature fe : featuresToEnable) {
            bsonFactory.enable(fe);// ww  w  . ja  v  a2s  .com
        }
    }
    ObjectMapper om = new ObjectMapper(bsonFactory);
    om.registerModule(new BsonModule());
    om.writeValue(baos, data);

    byte[] r = baos.toByteArray();
    ByteArrayInputStream bais = new ByteArrayInputStream(r);

    BSONDecoder decoder = new BasicBSONDecoder();
    return decoder.readObject(bais);
}

From source file:org.phenotips.data.rest.internal.DefaultPatientsFetchResourceImpl.java

/**
 * A custom object mapper to facilitate serializing a list of {@link Patient} objects.
 *
 * @return an object mapper that can serialize {@link Patient} objects
 *///from www  . ja  v  a 2s.  c o  m
private ObjectMapper getCustomObjectMapper() {
    final ObjectMapper mapper = new ObjectMapper();
    SimpleModule m = new SimpleModule("PrimaryEntitySerializer",
            new Version(1, 0, 0, "", "org.phenotips", "PatientReferenceSerializer"));
    m.addSerializer(PrimaryEntity.class, new PrimaryEntitySerializer());
    mapper.registerModule(m);
    return mapper;
}

From source file:org.moserp.common.rest.ObjectMapperCustomizer.java

private void registerQuantitySerializer(ObjectMapper mapper) {
    SimpleModule module = new SimpleModule();
    module.addSerializer(Quantity.class,
            new WithConverterSerializer<>(new BigDecimalWrapperToStringConverter()));
    module.addSerializer(Price.class, new WithConverterSerializer<>(new BigDecimalWrapperToStringConverter()));
    module.addSerializer(RestUri.class, new WithConverterSerializer<>(new RestUriToStringConverter()));
    mapper.registerModule(module);
}

From source file:uk.ac.cam.cl.dtg.segue.dao.content.ContentMapper.java

/**
 * Creates a brand new object mapper./*from  w  w  w  .j a  v  a  2 s .c o m*/
 * This should be used sparingly as it is resource intensive to maintain these things.
 * 
 * @return ObjectMapper that has been configured to handle the segue recursive object model.
 */
public ObjectMapper generateNewPreconfiguredContentMapper() {
    ContentBaseDeserializer contentDeserializer = new ContentBaseDeserializer();
    contentDeserializer.registerTypeMap(jsonTypes);

    ChoiceDeserializer choiceDeserializer = new ChoiceDeserializer(contentDeserializer);

    QuestionValidationResponseDeserializer validationResponseDeserializer = new QuestionValidationResponseDeserializer(
            contentDeserializer, choiceDeserializer);

    SimpleModule contentDeserializerModule = new SimpleModule("ContentDeserializerModule");
    contentDeserializerModule.addDeserializer(ContentBase.class, contentDeserializer);
    contentDeserializerModule.addDeserializer(Choice.class, choiceDeserializer);
    contentDeserializerModule.addDeserializer(QuestionValidationResponse.class, validationResponseDeserializer);

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(contentDeserializerModule);

    return objectMapper;
}

From source file:org.wisdom.monitor.extensions.jcr.script.JcrScriptExecutorExtension.java

@Route(method = HttpMethod.GET, uri = "")
public Result index() throws Exception {
    Session session = jcrRepository.getSession();
    Optional<String> currentMigrationWorkspaceOptional = Arrays
            .asList(session.getWorkspace().getAccessibleWorkspaceNames()).stream()
            .filter(name -> name.startsWith(JCR_MIGRATION_PREFIX)).findFirst();
    String workspace = "";
    String script = "";
    List<Event> events = new ArrayList<>();
    if (currentMigrationWorkspaceOptional.isPresent()) {
        workspace = currentMigrationWorkspaceOptional.get();
        Node rootNode = session.getRepository().login(workspace).getRootNode();
        if (rootNode.hasNode("jcr:migrations")) {
            Node migrationNode = rootNode.getNode("jcr:migrations").getNode(workspace);
            script = migrationNode.getProperty("script").getString();
            ObjectMapper mapper = new ObjectMapper();
            SimpleModule module = new SimpleModule();
            module.addDeserializer(Event.class, new JcrEventDeserializer());
            mapper.registerModule(module);
            events = mapper.readValue(migrationNode.getProperty("events").getString(),
                    mapper.getTypeFactory().constructCollectionType(List.class, Event.class));
        }//from   ww  w. java 2s  . c  om
    }
    return ok(render(scriptTemplate, "script", script, "workspace", workspace, "events", events,
            "eventFormatter", EVENT_FORMATTER));
}

From source file:com.bazaarvoice.jolt.jsonUtil.testdomain.two.MappingTest2.java

@Test
public void testPolymorphicJacksonSerializationAndDeserialization() {
    ObjectMapper mapper = new ObjectMapper();

    SimpleModule testModule = new SimpleModule("testModule", new Version(1, 0, 0, null, null, null))
            .addDeserializer(QueryFilter.class, new QueryFilterDeserializer())
            .addSerializer(LogicalFilter2.class, new LogicalFilter2Serializer());

    mapper.registerModule(testModule);

    // Verifying that we can pass in a custom Mapper and create a new JsonUtil
    JsonUtil jsonUtil = JsonUtils.customJsonUtil(mapper);

    String testFixture = "/jsonUtils/testdomain/two/queryFilter-realAndLogical2.json";

    // TEST JsonUtil and our deserialization logic
    QueryFilter queryFilter = jsonUtil.classpathToType(testFixture, new TypeReference<QueryFilter>() {
    });/* w w  w  .jav  a  2  s  .c  o  m*/

    // Make sure the hydrated QFilter looks right
    AssertJUnit.assertTrue(queryFilter instanceof LogicalFilter2);
    AssertJUnit.assertEquals(QueryParam.AND, queryFilter.getQueryParam());
    AssertJUnit.assertTrue(queryFilter.isLogical());
    AssertJUnit.assertEquals(3, queryFilter.getFilters().size());
    AssertJUnit.assertNotNull(queryFilter.getFilters().get(QueryParam.OR));

    // Make sure one of the top level RealFilters looks right
    QueryFilter productIdFilter = queryFilter.getFilters().get(QueryParam.PRODUCTID);
    AssertJUnit.assertTrue(productIdFilter.isReal());
    AssertJUnit.assertEquals(QueryParam.PRODUCTID, productIdFilter.getQueryParam());
    AssertJUnit.assertEquals("Acme-1234", productIdFilter.getValue());

    // Make sure the nested OR looks right
    QueryFilter orFilter = queryFilter.getFilters().get(QueryParam.OR);
    AssertJUnit.assertTrue(orFilter.isLogical());
    AssertJUnit.assertEquals(QueryParam.OR, orFilter.getQueryParam());
    AssertJUnit.assertEquals(2, orFilter.getFilters().size());

    // Make sure nested AND looks right
    QueryFilter nestedAndFilter = orFilter.getFilters().get(QueryParam.AND);
    AssertJUnit.assertTrue(nestedAndFilter.isLogical());
    AssertJUnit.assertEquals(QueryParam.AND, nestedAndFilter.getQueryParam());
    AssertJUnit.assertEquals(2, nestedAndFilter.getFilters().size());

    // SERIALIZE TO STRING to test serialization logic
    String unitTestString = jsonUtil.toJsonString(queryFilter);

    // LOAD and Diffy the plain vanilla JSON versions of the documents
    Map<String, Object> actual = JsonUtils.jsonToMap(unitTestString);
    Map<String, Object> expected = JsonUtils.classpathToMap(testFixture);

    // Diffy the vanilla versions
    Diffy.Result result = diffy.diff(expected, actual);
    if (!result.isEmpty()) {
        AssertJUnit.fail("Failed.\nhere is a diff:\nexpected: " + JsonUtils.toJsonString(result.expected)
                + "\n  actual: " + JsonUtils.toJsonString(result.actual));
    }
}

From source file:whitespell.net.websockets.socketio.parser.JacksonJsonSupport.java

protected void init(ObjectMapper objectMapper) {
    SimpleModule module = new SimpleModule();
    module.addDeserializer(Event.class, eventDeserializer);
    module.addDeserializer(JsonObject.class, jsonObjectDeserializer);
    module.addDeserializer(AckArgs.class, ackArgsDeserializer);
    objectMapper.registerModule(module);

    objectMapper.setSerializationInclusion(Include.NON_NULL);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    //        TODO If jsonObjectDeserializer will be not enough
    //        TypeResolverBuilder<?> typer = new DefaultTypeResolverBuilder(DefaultTyping.NON_FINAL);
    //        typer.init(JsonTypeInfo.Id.CLASS, null);
    //        typer.inclusion(JsonTypeInfo.As.PROPERTY);
    //        typer.typeProperty(configuration.getJsonTypeFieldName());
    //        objectMapper.setDefaultTyping(typer);
}

From source file:org.wisdom.monitor.extensions.jcr.script.JcrScriptExecutorExtension.java

public String listToJsonString(List list) throws IOException {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.addSerializer(Event.class, new JcrEventSerializer()); // assuming serializer declares correct class to bind to
    mapper.registerModule(module);//from  ww  w . j av  a  2s . c om
    mapper.writeValue(out, list);
    final byte[] data = out.toByteArray();
    return new String(data);
}

From source file:com.griddynamics.deming.ecommerce.api.endpoint.catalog.CatalogManagerEndpoint.java

@POST
@Path("import")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response importCatalog(@FormDataParam("file") InputStream uploadInputStream)
        throws ServiceException, IOException {
    removeCatalog();//w  w w.j a va2 s  .  c o  m

    try {
        ZipInputStream inputStream = new ZipInputStream(uploadInputStream);

        try {
            byte[] buf = new byte[1024];

            for (ZipEntry entry = inputStream.getNextEntry(); entry != null; entry = inputStream
                    .getNextEntry()) {
                try {
                    String entryName = entry.getName();
                    entryName = entryName.replace('/', File.separatorChar);
                    entryName = entryName.replace('\\', File.separatorChar);

                    LOGGER.debug("Entry name: {}", entryName);

                    if (entry.isDirectory()) {
                        LOGGER.debug("Entry ({}) is directory", entryName);
                    } else if (PRODUCT_CATALOG_FILE.equals(entryName)) {
                        ByteArrayOutputStream jsonBytes = new ByteArrayOutputStream(1024);

                        for (int n = inputStream.read(buf, 0, 1024); n > -1; n = inputStream.read(buf, 0,
                                1024)) {
                            jsonBytes.write(buf, 0, n);
                        }

                        byte[] bytes = jsonBytes.toByteArray();

                        ObjectMapper mapper = new ObjectMapper();

                        JaxbAnnotationModule jaxbAnnotationModule = new JaxbAnnotationModule();
                        mapper.registerModule(jaxbAnnotationModule);

                        ImportCategoryWrapper catalog = mapper.readValue(bytes, ImportCategoryWrapper.class);
                        escape(catalog);
                        saveCategoryTree(catalog);
                    } else {
                        MultipartFile file = new MultipartFileAdapter(inputStream, entryName);
                        dmgStaticAssetStorageService.createStaticAssetStorageFromFile(file);
                    }

                } finally {
                    inputStream.closeEntry();
                }
            }
        } finally {
            inputStream.close();
        }

    } catch (IOException e) {
        return Response.status(Response.Status.BAD_REQUEST).entity("Unable load catalog.\n").build();
    }

    Thread rebuildSearchIndex = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(10000);
                searchService.rebuildIndex();
            } catch (Exception e) {
                /* nothing */}
        }
    });
    rebuildSearchIndex.start();

    return Response.status(Response.Status.OK).entity("Catalog was imported successfully!\n").build();
}

From source file:com.intelligentsia.dowsers.entity.reference.ReferenceTest.java

@Test
public void testSerialization() throws JsonParseException, JsonMappingException, IOException {

    final ObjectMapper mapper = JacksonSerializer.getMapper();
    final SimpleModule module = new SimpleModule();
    module.addSerializer(new ReferenceSerializer());
    module.addDeserializer(Reference.class, new ReferenceDeSerializer());
    mapper.registerModule(module);

    final StringWriter writer = new StringWriter();

    final Reference reference = Reference.parseString(
            "urn:dowsers:com.intelligentsia.dowsers.entity.model.Person:identity#4c8b03dd-908a-4cad-8d48-3c7277d44ac9");
    mapper.writeValue(writer, reference);
    final String result = writer.toString();
    final Reference reference2 = mapper.readValue(new StringReader(result), Reference.class);
    assertNotNull(reference2);//www. j a v  a 2  s .c o m
    assertEquals(reference, reference2);
}