Example usage for com.fasterxml.jackson.databind.module SimpleModule SimpleModule

List of usage examples for com.fasterxml.jackson.databind.module SimpleModule SimpleModule

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind.module SimpleModule SimpleModule.

Prototype

public SimpleModule(String name, Version version) 

Source Link

Document

Constructor to use for actual reusable modules.

Usage

From source file:org.kiji.rest.KijiRESTService.java

/**
 * Registers custom serializers with the Jackson ObjectMapper via DropWizard's
 * ObjectMapperFactory. This is used by both the service initialization and the test
 * setup method to ensure consistency between test and production.
 *
 * @param mapperFactory is the ObjectMapperFactory.
 *///from w  ww  . ja  va 2s . c o  m
public static void registerSerializers(ObjectMapperFactory mapperFactory) {
    // TODO: Add a module to convert btw Avro's specific types and JSON. The default
    // mapping seems to throw an exception.
    SimpleModule module = new SimpleModule("KijiRestModule",
            new Version(1, 0, 0, null, "org.kiji.rest", "serializers"));
    module.addSerializer(new AvroToJsonStringSerializer());
    module.addSerializer(new Utf8ToJsonSerializer());
    module.addSerializer(new TableLayoutToJsonSerializer());
    module.addSerializer(new SchemaOptionToJson());
    module.addDeserializer(SchemaOption.class, new JsonToSchemaOption());
    module.addSerializer(new KijiRestEntityIdToJson());
    module.addDeserializer(KijiRestEntityId.class, new JsonToKijiRestEntityId());
    mapperFactory.registerModule(module);
}

From source file:com.netflix.bdp.inviso.history.TraceService.java

/**
 * Returns a json object representing the job history.
 *
 * @param jobId//  w ww  . jav a  2  s .  c  om
 * @param path Use the given path as opposed to the history locator
 * @param summary Return just the top level details of the job
 * @param counters Include counters
 * @return Json string
 * @throws Exception
 */
@Path("load/{jobId}")
@GET
@Produces("application/json")
public String trace(@PathParam("jobId") final String jobId, @QueryParam("path") final String path,
        @QueryParam("summary") boolean summary, @QueryParam("counters") @DefaultValue("true") boolean counters)
        throws Exception {

    Pair<org.apache.hadoop.fs.Path, org.apache.hadoop.fs.Path> historyPath;

    if (path != null) {
        historyPath = new ImmutablePair<>(null, new org.apache.hadoop.fs.Path(path));
    } else {
        historyPath = historyLocator.locate(jobId);
    }

    if (historyPath == null) {
        throw new WebApplicationException(404);
    }

    TraceJobHistoryLoader loader = new TraceJobHistoryLoader(properties);

    FileSystem fs = FileSystem.get(historyPath.getRight().toUri(), config);
    CompressionCodec codec = new CompressionCodecFactory(config).getCodec(historyPath.getRight());

    FSDataInputStream fin = fs.open(historyPath.getRight());

    if (codec != null) {
        fin = new FSDataInputStream(new WrappedCompressionInputStream(codec.createInputStream(fin)));
    }

    JobHistoryParser parser = new JobHistoryParser(fin);
    parser.parse(loader);

    String[] ignore = { "counters" };

    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule("MyModule", new Version(1, 0, 0, null));

    //Job
    JavaType jobMapType = MapLikeType.construct(Job.class, SimpleType.construct(String.class),
            SimpleType.construct(Object.class));
    module.addSerializer(Job.class, MapSerializer.construct(ignore, jobMapType, false, null, null, null, null));

    //Task
    JavaType taskMapType = MapLikeType.construct(Task.class, SimpleType.construct(String.class),
            SimpleType.construct(Object.class));
    module.addSerializer(Task.class,
            MapSerializer.construct(ignore, taskMapType, false, null, null, null, null));

    //Attempt
    JavaType attemptMapType = MapLikeType.construct(TaskAttempt.class, SimpleType.construct(String.class),
            SimpleType.construct(Object.class));
    module.addSerializer(TaskAttempt.class,
            MapSerializer.construct(ignore, attemptMapType, false, null, null, null, null));

    if (!counters) {
        mapper.registerModule(module);
    }

    if (summary) {
        loader.getJob().clearTasks();
    }

    return mapper.writeValueAsString(loader.getJob());
}

From source file:org.brutusin.json.impl.JacksonCodec.java

@Override
public void registerStringFormat(Class clazz, String format) {
    this.schemaFactory.registerStringFormat(clazz, format);
    SimpleModule testModule = new SimpleModule("json-provider-module:" + format,
            new Version(1, 0, 0, null, "org.brutusin", "json-provider:" + format));
    testModule.addSerializer(new StdSerializer(clazz) {
        @Override/*from   w  w w .  ja  va  2  s  . co m*/
        public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {
            gen.writeString(value.toString());
        }
    });
    mapper.registerModule(testModule);
}

From source file:org.springframework.cloud.dataflow.server.stream.SkipperStreamDeployer.java

public static List<AppStatus> deserializeAppStatus(String platformStatus) {
    try {//from   w w w .j  av  a  2  s  .  c om
        if (platformStatus != null) {
            ObjectMapper mapper = new ObjectMapper();
            mapper.addMixIn(AppStatus.class, AppStatusMixin.class);
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            SimpleModule module = new SimpleModule("CustomModel", Version.unknownVersion());
            SimpleAbstractTypeResolver resolver = new SimpleAbstractTypeResolver();
            resolver.addMapping(AppInstanceStatus.class, AppInstanceStatusImpl.class);
            module.setAbstractTypes(resolver);
            mapper.registerModule(module);
            TypeReference<List<AppStatus>> typeRef = new TypeReference<List<AppStatus>>() {
            };
            return mapper.readValue(platformStatus, typeRef);
        }
        return new ArrayList<AppStatus>();
    } catch (Exception e) {
        logger.error("Could not parse Skipper Platform Status JSON [" + platformStatus + "]. "
                + "Exception message = " + e.getMessage());
        return new ArrayList<AppStatus>();
    }
}

From source file:com.google.api.server.spi.response.ServletResponseResultWriter.java

private static SimpleModule getWriteSimpleDateAsStringModule() {
    JsonSerializer<SimpleDate> simpleDateSerializer = new JsonSerializer<SimpleDate>() {
        @Override//from   w ww. j a  v  a  2 s  . c  o m
        public void serialize(SimpleDate value, JsonGenerator jgen, SerializerProvider provider)
                throws IOException {
            jgen.writeString(
                    String.format("%04d-%02d-%02d", value.getYear(), value.getMonth(), value.getDay()));
        }
    };
    SimpleModule writeSimpleDateAsModule = new SimpleModule("writeSimpleDateAsModule",
            new Version(1, 0, 0, null, null, null));
    writeSimpleDateAsModule.addSerializer(SimpleDate.class, simpleDateSerializer);
    return writeSimpleDateAsModule;
}

From source file:eu.bittrade.libs.steemj.communication.CommunicationHandler.java

/**
 * Get a preconfigured Jackson Object Mapper instance.
 * //www .ja v a2 s .c  o  m
 * @return The object mapper.
 */
public static ObjectMapper getObjectMapper() {
    if (mapper == null) {
        mapper = new ObjectMapper();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
                SteemJConfig.getInstance().getDateTimePattern());
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone(SteemJConfig.getInstance().getTimeZoneId()));

        mapper.setDateFormat(simpleDateFormat);
        mapper.setTimeZone(TimeZone.getTimeZone(SteemJConfig.getInstance().getTimeZoneId()));
        mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

        SimpleModule simpleModule = new SimpleModule("BooleanAsString", new Version(1, 0, 0, null, null, null));
        simpleModule.addSerializer(Boolean.class, new BooleanSerializer());
        simpleModule.addSerializer(boolean.class, new BooleanSerializer());

        mapper.registerModule(simpleModule);
    }

    return mapper;
}

From source file:com.logsniffer.app.CoreAppConfig.java

@Bean
public ObjectMapper jsonObjectMapper() {
    final ObjectMapper jsonMapper = new ObjectMapper();
    jsonMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    jsonMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    jsonMapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
    jsonMapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);

    final SimpleModule module = new SimpleModule("FieldsMapping", Version.unknownVersion());
    module.setSerializerModifier(new BeanSerializerModifier() {
        @Override//from  w  ww  . j a v a2s.  c o  m
        public JsonSerializer<?> modifyMapSerializer(final SerializationConfig config, final MapType valueType,
                final BeanDescription beanDesc, final JsonSerializer<?> serializer) {
            if (FieldsMap.class.isAssignableFrom(valueType.getRawClass())) {
                return new FieldsMapMixInLikeSerializer();
            } else {
                return super.modifyMapSerializer(config, valueType, beanDesc, serializer);
            }
        }
    });
    jsonMapper.registerModule(module);
    return jsonMapper;
}

From source file:com.google.api.server.spi.response.ServletResponseResultWriter.java

private static SimpleModule getWriteDateAsStringModule() {
    JsonSerializer<Date> dateSerializer = new JsonSerializer<Date>() {
        @Override/*ww w. java2 s  .c  o  m*/
        public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
            jgen.writeString(new com.google.api.client.util.DateTime(value).toStringRfc3339());
        }
    };
    SimpleModule writeDateAsStringModule = new SimpleModule("writeDateAsStringModule",
            new Version(1, 0, 0, null, null, null));
    writeDateAsStringModule.addSerializer(Date.class, dateSerializer);
    return writeDateAsStringModule;
}

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);/*from  ww  w.  j  a v a 2  s.  c  o  m*/
    return mapper;
}