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

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

Introduction

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

Prototype

public SimpleModule addSerializer(JsonSerializer<?> ser) 

Source Link

Usage

From source file:com.mastfrog.jackson.OptionalSerializer.java

@Override
public ObjectMapper configure(ObjectMapper mapper) {
    SimpleModule sm = new SimpleModule("optional", new Version(1, 0, 0, null, "com.mastfrog", "jackson"));
    sm.addSerializer(new OptionalSer());
    sm.addSerializer(new ReflectionOptionalSerializer());
    mapper.registerModule(sm);/*  w w w . j a  v  a  2 s.  c o m*/
    return mapper;
}

From source file:org.craftercms.social.util.serialization.UGCObjectMapper.java

protected void registerSerializationModule() {
    SimpleModule module = new SimpleModule("UGCSerializationModule", new Version(1, 0, 0, null, null, null));

    for (JsonSerializer ser : serializerList) {
        module.addSerializer(ser);
    }/* w ww . j a va2  s  .com*/

    for (Class key : deserializerMap.keySet()) {
        JsonDeserializer deser = deserializerMap.get(key);
        module.addDeserializer(key, deser);
    }

    registerModule(module);

}

From source file:io.swagger.inflector.SwaggerInflector.java

protected void init(Configuration configuration) {
    config = configuration;/*  w  ww .ja  v  a 2  s .c  om*/
    Swagger swagger = new SwaggerParser().read(config.getSwaggerUrl(), null, true);

    if (swagger != null) {
        originalBasePath = swagger.getBasePath();
        StringBuilder b = new StringBuilder();

        if (!"".equals(configuration.getRootPath()))
            b.append(configuration.getRootPath());
        if (swagger.getBasePath() != null) {
            b.append(swagger.getBasePath());
        }
        if (b.length() > 0) {
            swagger.setBasePath(b.toString());
        }

        Map<String, Path> paths = swagger.getPaths();
        Map<String, Model> definitions = swagger.getDefinitions();
        for (String pathString : paths.keySet()) {
            Path path = paths.get(pathString);
            final Resource.Builder builder = Resource.builder();
            this.basePath = configuration.getRootPath() + swagger.getBasePath();

            builder.path(basePath(originalBasePath, pathString));
            Operation operation;

            operation = path.getGet();
            if (operation != null) {
                addOperation(pathString, builder, HttpMethod.GET, operation, definitions);
            }
            operation = path.getPost();
            if (operation != null) {
                addOperation(pathString, builder, HttpMethod.POST, operation, definitions);
            }
            operation = path.getPut();
            if (operation != null) {
                addOperation(pathString, builder, HttpMethod.PUT, operation, definitions);
            }
            operation = path.getDelete();
            if (operation != null) {
                addOperation(pathString, builder, HttpMethod.DELETE, operation, definitions);
            }
            operation = path.getOptions();
            if (operation != null) {
                addOperation(pathString, builder, HttpMethod.OPTIONS, operation, definitions);
            }
            operation = path.getPatch();
            if (operation != null) {
                addOperation(pathString, builder, "PATCH", operation, definitions);
            }
            registerResources(builder.build());
        }

        // enable swagger JSON
        enableSwaggerJSON(swagger);

        // enable swagger YAML
        enableSwaggerYAML(swagger);
    } else {
        LOGGER.error("No swagger definition detected!  Not much to do...");
    }
    // JSON
    register(JacksonJsonProvider.class);

    // XML
    register(JacksonJaxbXMLProvider.class);

    register(new MultiPartFeature());

    // Swagger serializers
    register(SwaggerSerializers.class);

    // XML mapper
    SimpleModule simpleModule = new SimpleModule();
    simpleModule.addSerializer(new JsonExampleSerializer());
    Json.mapper().registerModule(simpleModule);
    Yaml.mapper().registerModule(simpleModule);

    // Example serializer
    register(ExampleSerializer.class);
}

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);//  ww w .  j  a  v  a 2s  .  com

    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);
    assertEquals(reference, reference2);
}

From source file:gaffer.jsonserialisation.JSONSerialiser.java

/**
 * Constructs a <code>JSONSerialiser</code> that skips nulls and default values and adds the custom serialisers.
 *
 * @param customTypeSerialisers custom type {@link com.fasterxml.jackson.databind.JsonSerializer}
 */// ww  w .  jav  a  2  s.c  o m
public JSONSerialiser(final JsonSerializer... customTypeSerialisers) {
    this();
    final SimpleModule module = new SimpleModule("custom", new Version(1, 0, 0, null, null, null));
    for (JsonSerializer customTypeSerialiser : customTypeSerialisers) {
        module.addSerializer(customTypeSerialiser);
    }
    mapper.registerModule(module);
}

From source file:monasca.api.MonApiApplication.java

@Override
@SuppressWarnings("unchecked")
public void run(ApiConfig config, Environment environment) throws Exception {
    /** Wire services */
    Injector.registerModules(new MonApiModule(environment, config));

    /** Configure resources */
    environment.jersey().register(Injector.getInstance(VersionResource.class));
    environment.jersey().register(Injector.getInstance(AlarmDefinitionResource.class));
    environment.jersey().register(Injector.getInstance(AlarmResource.class));
    environment.jersey().register(Injector.getInstance(DimensionResource.class));
    environment.jersey().register(Injector.getInstance(MetricResource.class));
    environment.jersey().register(Injector.getInstance(MeasurementResource.class));
    environment.jersey().register(Injector.getInstance(StatisticResource.class));
    environment.jersey().register(Injector.getInstance(NotificationMethodResource.class));
    environment.jersey().register(Injector.getInstance(NotificationMethodTypesResource.class));

    /** Configure providers */
    removeExceptionMappers(environment.jersey().getResourceConfig().getSingletons());
    environment.jersey().register(new EntityExistsExceptionMapper());
    environment.jersey().register(new EntityNotFoundExceptionMapper());
    environment.jersey().register(new IllegalArgumentExceptionMapper());
    environment.jersey().register(new InvalidEntityExceptionMapper());
    environment.jersey().register(new JsonProcessingExceptionMapper());
    environment.jersey().register(new JsonMappingExceptionManager());
    environment.jersey().register(new ConstraintViolationExceptionMapper());
    environment.jersey().register(new ThrowableExceptionMapper<Throwable>() {
    });//from w ww  .  j av a 2s.  c  om
    environment.jersey().register(new MultipleMetricsExceptionMapper());

    /** Configure Jackson */
    environment.getObjectMapper()
            .setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
    environment.getObjectMapper().enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
    environment.getObjectMapper().disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    environment.getObjectMapper().disable(DeserializationFeature.WRAP_EXCEPTIONS);
    SimpleModule module = new SimpleModule("SerializationModule");
    module.addSerializer(new SubAlarmExpressionSerializer());
    environment.getObjectMapper().registerModule(module);

    /** Configure CORS filter */
    Dynamic corsFilter = environment.servlets().addFilter("cors", CrossOriginFilter.class);
    corsFilter.addMappingForUrlPatterns(null, true, "/*");
    corsFilter.setInitParameter("allowedOrigins", "*");
    corsFilter.setInitParameter("allowedHeaders", "X-Requested-With,Content-Type,Accept,Origin,X-Auth-Token");
    corsFilter.setInitParameter("allowedMethods", "OPTIONS,GET,HEAD");

    if (config.middleware.enabled) {
        ensureHasValue(config.middleware.serverVIP, "serverVIP", "enabled", "true");
        ensureHasValue(config.middleware.serverPort, "serverPort", "enabled", "true");
        ensureHasValue(config.middleware.adminAuthMethod, "adminAuthMethod", "enabled", "true");
        if ("password".equalsIgnoreCase(config.middleware.adminAuthMethod)) {
            ensureHasValue(config.middleware.adminUser, "adminUser", "adminAuthMethod", "password");
            ensureHasValue(config.middleware.adminPassword, "adminPassword", "adminAuthMethod", "password");
        } else if ("token".equalsIgnoreCase(config.middleware.adminAuthMethod)) {
            ensureHasValue(config.middleware.adminToken, "adminToken", "adminAuthMethod", "token");
        } else {
            throw new Exception(
                    String.format("Invalid value '%s' for adminAuthMethod. Must be either password or token",
                            config.middleware.adminAuthMethod));
        }
        if (config.middleware.defaultAuthorizedRoles == null
                || config.middleware.defaultAuthorizedRoles.isEmpty()) {
            ensureHasValue(null, "defaultAuthorizedRoles", "enabled", "true");
        }
        if (config.middleware.connSSLClientAuth) {
            ensureHasValue(config.middleware.keystore, "keystore", "connSSLClientAuth", "true");
            ensureHasValue(config.middleware.keystorePassword, "keystorePassword", "connSSLClientAuth", "true");
        }
        Map<String, String> authInitParams = new HashMap<String, String>();
        authInitParams.put("ServerVIP", config.middleware.serverVIP);
        authInitParams.put("ServerPort", config.middleware.serverPort);
        authInitParams.put(AuthConstants.USE_HTTPS, String.valueOf(config.middleware.useHttps));
        authInitParams.put("ConnTimeout", config.middleware.connTimeout);
        authInitParams.put("ConnSSLClientAuth", String.valueOf(config.middleware.connSSLClientAuth));
        authInitParams.put("ConnPoolMaxActive", config.middleware.connPoolMaxActive);
        authInitParams.put("ConnPoolMaxIdle", config.middleware.connPoolMaxActive);
        authInitParams.put("ConnPoolEvictPeriod", config.middleware.connPoolEvictPeriod);
        authInitParams.put("ConnPoolMinIdleTime", config.middleware.connPoolMinIdleTime);
        authInitParams.put("ConnRetryTimes", config.middleware.connRetryTimes);
        authInitParams.put("ConnRetryInterval", config.middleware.connRetryInterval);
        authInitParams.put("AdminToken", config.middleware.adminToken);
        authInitParams.put("TimeToCacheToken", config.middleware.timeToCacheToken);
        authInitParams.put("AdminAuthMethod", config.middleware.adminAuthMethod);
        authInitParams.put("AdminUser", config.middleware.adminUser);
        authInitParams.put("AdminPassword", config.middleware.adminPassword);
        authInitParams.put(AuthConstants.ADMIN_PROJECT_ID, config.middleware.adminProjectId);
        authInitParams.put(AuthConstants.ADMIN_PROJECT_NAME, config.middleware.adminProjectName);
        authInitParams.put(AuthConstants.ADMIN_USER_DOMAIN_ID, config.middleware.adminUserDomainId);
        authInitParams.put(AuthConstants.ADMIN_USER_DOMAIN_NAME, config.middleware.adminUserDomainName);
        authInitParams.put(AuthConstants.ADMIN_PROJECT_DOMAIN_ID, config.middleware.adminProjectDomainId);
        authInitParams.put(AuthConstants.ADMIN_PROJECT_DOMAIN_NAME, config.middleware.adminProjectDomainName);
        authInitParams.put("MaxTokenCacheSize", config.middleware.maxTokenCacheSize);
        setIfNotNull(authInitParams, AuthConstants.TRUSTSTORE, config.middleware.truststore);
        setIfNotNull(authInitParams, AuthConstants.TRUSTSTORE_PASS, config.middleware.truststorePassword);
        setIfNotNull(authInitParams, AuthConstants.KEYSTORE, config.middleware.keystore);
        setIfNotNull(authInitParams, AuthConstants.KEYSTORE_PASS, config.middleware.keystorePassword);

        /** Configure auth filters */
        Dynamic preAuthenticationFilter = environment.servlets().addFilter("pre-auth",
                new PreAuthenticationFilter());
        preAuthenticationFilter.addMappingForUrlPatterns(null, true, "/");
        preAuthenticationFilter.addMappingForUrlPatterns(null, true, "/v2.0/*");

        Dynamic tokenAuthFilter = environment.servlets().addFilter("token-auth", new TokenAuth());
        tokenAuthFilter.addMappingForUrlPatterns(null, true, "/");
        tokenAuthFilter.addMappingForUrlPatterns(null, true, "/v2.0/*");
        tokenAuthFilter.setInitParameters(authInitParams);

        Dynamic postAuthenticationFilter = environment.servlets().addFilter("post-auth",
                new PostAuthenticationFilter(config.middleware.defaultAuthorizedRoles,
                        config.middleware.agentAuthorizedRoles, config.middleware.readOnlyAuthorizedRoles));
        postAuthenticationFilter.addMappingForUrlPatterns(null, true, "/");
        postAuthenticationFilter.addMappingForUrlPatterns(null, true, "/v2.0/*");

        environment.jersey().getResourceConfig().getContainerRequestFilters()
                .add(new RoleAuthorizationFilter());
    } else {
        Dynamic mockAuthenticationFilter = environment.servlets().addFilter("mock-auth",
                new MockAuthenticationFilter());
        mockAuthenticationFilter.addMappingForUrlPatterns(null, true, "/");
        mockAuthenticationFilter.addMappingForUrlPatterns(null, true, "/v2.0/*");
    }
}

From source file:io.swagger.test.examples.ExampleBuilderTest.java

@Test
public void testComplexArrayWithExample() throws Exception {
    Map<String, Model> definitions = new HashMap<String, Model>();

    Model address = new ModelImpl().example("{\"foo\":\"bar\"}").xml(new Xml().name("address"))
            .property("street", new StringProperty().example("12345 El Monte Blvd"))
            .property("city", new StringProperty().example("Los Altos Hills"))
            .property("state", new StringProperty().example("CA").minLength(2).maxLength(2))
            .property("zip", new StringProperty().example("94022"));

    definitions.put("Address", address);

    // register the JSON serializer
    SimpleModule simpleModule = new SimpleModule();
    simpleModule.addSerializer(new JsonNodeExampleSerializer());
    simpleModule.addDeserializer(Example.class, new JsonExampleDeserializer());
    Json.mapper().registerModule(simpleModule);

    Example rep = (Example) ExampleBuilder.fromProperty(new StringProperty("hello").example("fun"),
            definitions);/* w  ww.j  a va 2 s .  c o  m*/
    assertEqualsIgnoreLineEnding(Json.pretty(rep), "\"fun\"");
}

From source file:net.solarnetwork.util.ObjectMapperFactoryBean.java

@Override
public ObjectMapper getObject() throws Exception {
    if (mapper == null) {
        mapper = new ObjectMapper();
    }// ww  w .j a  v  a2 s  .  c om
    SimpleModule module = new SimpleModule(moduleName, moduleVersion);
    if (serializers != null) {
        for (JsonSerializer<?> serializer : serializers) {
            module.addSerializer(serializer);
        }
    }
    if (deserializers != null) {
        for (JsonDeserializer<?> deserializer : deserializers) {
            if (deserializer instanceof StdDeserializer<?>) {
                registerStdDeserializer(module, (StdDeserializer<?>) deserializer);
            }
        }
    }
    if (serializationInclusion != null) {
        mapper.setSerializationInclusion(serializationInclusion);
    }
    setupFeatures(mapper, featuresToEnable, true);
    setupFeatures(mapper, featuresToDisable, false);
    mapper.registerModule(module);
    return mapper;
}