Java Code Examples for org.springframework.http.converter.json.Jackson2ObjectMapperBuilder

The following are top voted examples for showing how to use org.springframework.http.converter.json.Jackson2ObjectMapperBuilder. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: jigsaw-payment   File: ProtobufConfiguration.java   View source code 7 votes vote down vote up
@Bean
public Jackson2ObjectMapperBuilderCustomizer configProtobufSerializer() {
	return new Jackson2ObjectMapperBuilderCustomizer() {

		@Override
		public void customize(
				Jackson2ObjectMapperBuilder builder) {
			builder.serializerByType(Message.class, new JsonSerializer<Message>(){

				@Override
				public void serialize(Message message, JsonGenerator generator,
						SerializerProvider provider) throws IOException {
					if(message == null)
						return;
					JsonJacksonFormat format = new JsonJacksonFormat();
					format.print(message, generator);
				}});
			
		}
	};
}
 
Example 2
Project: spring-boot-concourse   File: JacksonAutoConfigurationTests.java   View source code 7 votes vote down vote up
@Test
public void defaultObjectMapperBuilder() throws Exception {
	this.context.register(JacksonAutoConfiguration.class);
	this.context.refresh();
	Jackson2ObjectMapperBuilder builder = this.context
			.getBean(Jackson2ObjectMapperBuilder.class);
	ObjectMapper mapper = builder.build();
	assertThat(MapperFeature.DEFAULT_VIEW_INCLUSION.enabledByDefault()).isTrue();
	assertThat(mapper.getDeserializationConfig()
			.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse();
	assertThat(MapperFeature.DEFAULT_VIEW_INCLUSION.enabledByDefault()).isTrue();
	assertThat(mapper.getDeserializationConfig()
			.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse();
	assertThat(mapper.getSerializationConfig()
			.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse();
	assertThat(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault())
			.isTrue();
	assertThat(mapper.getDeserializationConfig()
			.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)).isFalse();
}
 
Example 3
Project: bookshop-api   File: BookControllerTest.java   View source code 7 votes vote down vote up
@Test
public void testCreateBookInternalServerError() throws Exception {
	
	Book book = buildBook(3L, Currency.EUR, 20.50, Arrays.asList(buildAuthor(1L, toDate("1978-09-25"), null)));
	book.setId(null);

	when(bookService.createNew(book)).thenThrow(new BookServiceException());
	
	this.mockMvc.perform( post( "/api/books" ).accept( MediaType.parseMediaType( "application/json;charset=UTF-8" ) )
   		.content(Jackson2ObjectMapperBuilder.json().build().writeValueAsString(book))
   		.contentType(MediaType.APPLICATION_JSON))
           .andDo( print() )
        .andExpect( jsonPath("$.code").value("GENERIC_ERROR")) ;

       verify(bookService).createNew(book);
}
 
Example 4
Project: cas-5.1.0   File: DefaultAuthenticationTests.java   View source code 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    mapper = Jackson2ObjectMapperBuilder.json()
            .featuresToDisable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)
            .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .build();
    mapper.findAndRegisterModules();
}
 
Example 5
Project: rug-resolver   File: MetadataWriter.java   View source code 6 votes vote down vote up
private static ObjectMapper objectMapper(Format format) {
    ObjectMapper mapper = null;
    if (format == Format.YAML) {
        mapper = new ObjectMapper(new YAMLFactory());
    }
    else {
        mapper = new ObjectMapper();
    }
    new Jackson2ObjectMapperBuilder()
            .modulesToInstall(new MetadataModule(), new DefaultScalaModule())
            .serializationInclusion(JsonInclude.Include.NON_NULL)
            .serializationInclusion(JsonInclude.Include.NON_ABSENT)
            .serializationInclusion(JsonInclude.Include.NON_EMPTY)
            .featuresToEnable(SerializationFeature.INDENT_OUTPUT)
            .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,
                    DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE,
                    DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
            .configure(mapper);
    return mapper;
}
 
Example 6
Project: citrus-admin   File: Project.java   View source code 6 votes vote down vote up
/**
 * Load settings from project info file.
 */
public void loadSettings() {
    try (FileInputStream fileInput = new FileInputStream(getProjectInfoFile())) {
        String projectInfo = FileUtils.readToString(fileInput);

        // support legacy build configuration
        projectInfo = projectInfo.replaceAll("com\\.consol\\.citrus\\.admin\\.model\\.build\\.maven\\.MavenBuildConfiguration", MavenBuildContext.class.getName());

        Project project = Jackson2ObjectMapperBuilder.json().build().readerFor(Project.class).readValue(projectInfo);

        setName(project.getName());
        setDescription(project.getDescription());
        setSettings(project.getSettings());
        setVersion(project.getVersion());
    } catch (IOException e) {
        throw new CitrusRuntimeException("Failed to read project settings file", e);
    }
}
 
Example 7
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: JacksonAutoConfiguration.java   View source code 6 votes vote down vote up
@Override
public void customize(Jackson2ObjectMapperBuilder builder) {

	if (this.jacksonProperties.getDefaultPropertyInclusion() != null) {
		builder.serializationInclusion(
				this.jacksonProperties.getDefaultPropertyInclusion());
	}
	if (this.jacksonProperties.getTimeZone() != null) {
		builder.timeZone(this.jacksonProperties.getTimeZone());
	}
	configureFeatures(builder, this.jacksonProperties.getDeserialization());
	configureFeatures(builder, this.jacksonProperties.getSerialization());
	configureFeatures(builder, this.jacksonProperties.getMapper());
	configureFeatures(builder, this.jacksonProperties.getParser());
	configureFeatures(builder, this.jacksonProperties.getGenerator());
	configureDateFormat(builder);
	configurePropertyNamingStrategy(builder);
	configureModules(builder);
	configureLocale(builder);
}
 
Example 8
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: JacksonAutoConfiguration.java   View source code 6 votes vote down vote up
private void configureDateFormat(Jackson2ObjectMapperBuilder builder) {
	// We support a fully qualified class name extending DateFormat or a date
	// pattern string value
	String dateFormat = this.jacksonProperties.getDateFormat();
	if (dateFormat != null) {
		try {
			Class<?> dateFormatClass = ClassUtils.forName(dateFormat, null);
			builder.dateFormat(
					(DateFormat) BeanUtils.instantiateClass(dateFormatClass));
		}
		catch (ClassNotFoundException ex) {
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
					dateFormat);
			// Since Jackson 2.6.3 we always need to set a TimeZone (see
			// gh-4170). If none in our properties fallback to the Jackson's
			// default
			TimeZone timeZone = this.jacksonProperties.getTimeZone();
			if (timeZone == null) {
				timeZone = new ObjectMapper().getSerializationConfig()
						.getTimeZone();
			}
			simpleDateFormat.setTimeZone(timeZone);
			builder.dateFormat(simpleDateFormat);
		}
	}
}
 
Example 9
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: JacksonAutoConfiguration.java   View source code 6 votes vote down vote up
private void configurePropertyNamingStrategy(
		Jackson2ObjectMapperBuilder builder) {
	// We support a fully qualified class name extending Jackson's
	// PropertyNamingStrategy or a string value corresponding to the constant
	// names in PropertyNamingStrategy which hold default provided
	// implementations
	String strategy = this.jacksonProperties.getPropertyNamingStrategy();
	if (strategy != null) {
		try {
			configurePropertyNamingStrategyClass(builder,
					ClassUtils.forName(strategy, null));
		}
		catch (ClassNotFoundException ex) {
			configurePropertyNamingStrategyField(builder, strategy);
		}
	}
}
 
Example 10
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: JacksonAutoConfiguration.java   View source code 6 votes vote down vote up
private void configurePropertyNamingStrategyField(
		Jackson2ObjectMapperBuilder builder, String fieldName) {
	// Find the field (this way we automatically support new constants
	// that may be added by Jackson in the future)
	Field field = ReflectionUtils.findField(PropertyNamingStrategy.class,
			fieldName, PropertyNamingStrategy.class);
	Assert.notNull(field, "Constant named '" + fieldName + "' not found on "
			+ PropertyNamingStrategy.class.getName());
	try {
		builder.propertyNamingStrategy(
				(PropertyNamingStrategy) field.get(null));
	}
	catch (Exception ex) {
		throw new IllegalStateException(ex);
	}
}
 
Example 11
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: JacksonAutoConfigurationTests.java   View source code 6 votes vote down vote up
@Test
public void defaultObjectMapperBuilder() throws Exception {
	this.context.register(JacksonAutoConfiguration.class);
	this.context.refresh();
	Jackson2ObjectMapperBuilder builder = this.context
			.getBean(Jackson2ObjectMapperBuilder.class);
	ObjectMapper mapper = builder.build();
	assertThat(MapperFeature.DEFAULT_VIEW_INCLUSION.enabledByDefault()).isTrue();
	assertThat(mapper.getDeserializationConfig()
			.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse();
	assertThat(MapperFeature.DEFAULT_VIEW_INCLUSION.enabledByDefault()).isTrue();
	assertThat(mapper.getDeserializationConfig()
			.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse();
	assertThat(mapper.getSerializationConfig()
			.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse();
	assertThat(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault())
			.isTrue();
	assertThat(mapper.getDeserializationConfig()
			.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)).isFalse();
}
 
Example 12
Project: spring-boot-concourse   File: JacksonAutoConfiguration.java   View source code 6 votes vote down vote up
@Override
public void customize(Jackson2ObjectMapperBuilder builder) {

	if (this.jacksonProperties.getDefaultPropertyInclusion() != null) {
		builder.serializationInclusion(
				this.jacksonProperties.getDefaultPropertyInclusion());
	}
	if (this.jacksonProperties.getTimeZone() != null) {
		builder.timeZone(this.jacksonProperties.getTimeZone());
	}
	configureFeatures(builder, this.jacksonProperties.getDeserialization());
	configureFeatures(builder, this.jacksonProperties.getSerialization());
	configureFeatures(builder, this.jacksonProperties.getMapper());
	configureFeatures(builder, this.jacksonProperties.getParser());
	configureFeatures(builder, this.jacksonProperties.getGenerator());
	configureDateFormat(builder);
	configurePropertyNamingStrategy(builder);
	configureModules(builder);
	configureLocale(builder);
}
 
Example 13
Project: spring-boot-concourse   File: JacksonAutoConfiguration.java   View source code 6 votes vote down vote up
private void configureDateFormat(Jackson2ObjectMapperBuilder builder) {
	// We support a fully qualified class name extending DateFormat or a date
	// pattern string value
	String dateFormat = this.jacksonProperties.getDateFormat();
	if (dateFormat != null) {
		try {
			Class<?> dateFormatClass = ClassUtils.forName(dateFormat, null);
			builder.dateFormat(
					(DateFormat) BeanUtils.instantiateClass(dateFormatClass));
		}
		catch (ClassNotFoundException ex) {
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
					dateFormat);
			// Since Jackson 2.6.3 we always need to set a TimeZone (see
			// gh-4170). If none in our properties fallback to the Jackson's
			// default
			TimeZone timeZone = this.jacksonProperties.getTimeZone();
			if (timeZone == null) {
				timeZone = new ObjectMapper().getSerializationConfig()
						.getTimeZone();
			}
			simpleDateFormat.setTimeZone(timeZone);
			builder.dateFormat(simpleDateFormat);
		}
	}
}
 
Example 14
Project: spring-boot-concourse   File: JacksonAutoConfiguration.java   View source code 6 votes vote down vote up
private void configurePropertyNamingStrategy(
		Jackson2ObjectMapperBuilder builder) {
	// We support a fully qualified class name extending Jackson's
	// PropertyNamingStrategy or a string value corresponding to the constant
	// names in PropertyNamingStrategy which hold default provided
	// implementations
	String strategy = this.jacksonProperties.getPropertyNamingStrategy();
	if (strategy != null) {
		try {
			configurePropertyNamingStrategyClass(builder,
					ClassUtils.forName(strategy, null));
		}
		catch (ClassNotFoundException ex) {
			configurePropertyNamingStrategyField(builder, strategy);
		}
	}
}
 
Example 15
Project: spring-boot-concourse   File: JacksonAutoConfiguration.java   View source code 6 votes vote down vote up
private void configurePropertyNamingStrategyField(
		Jackson2ObjectMapperBuilder builder, String fieldName) {
	// Find the field (this way we automatically support new constants
	// that may be added by Jackson in the future)
	Field field = ReflectionUtils.findField(PropertyNamingStrategy.class,
			fieldName, PropertyNamingStrategy.class);
	Assert.notNull(field, "Constant named '" + fieldName + "' not found on "
			+ PropertyNamingStrategy.class.getName());
	try {
		builder.propertyNamingStrategy(
				(PropertyNamingStrategy) field.get(null));
	}
	catch (Exception ex) {
		throw new IllegalStateException(ex);
	}
}
 
Example 16
Project: angularjs-springmvc-sample-boot   File: Jackson2ObjectMapperConfig.java   View source code 6 votes vote down vote up
@Bean
public Jackson2ObjectMapperBuilder objectMapperBuilder(JsonComponentModule jsonComponentModule) {
   
    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder
//                .serializerByType(ZonedDateTime.class, new JsonSerializer<ZonedDateTime>() {
//                    @Override
//                    public void serialize(ZonedDateTime zonedDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
//                        jsonGenerator.writeString(DateTimeFormatter.ISO_ZONED_DATE_TIME.format(zonedDateTime));
//                    }
//                })
            .serializationInclusion(JsonInclude.Include.NON_EMPTY)
            .featuresToDisable(
                    SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,
                    DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES,
                    DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
            )
            .featuresToEnable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
            .indentOutput(true)
            .modulesToInstall(jsonComponentModule);

    return builder;
}
 
Example 17
Project: contestparser   File: JacksonAutoConfiguration.java   View source code 6 votes vote down vote up
@Bean
@ConditionalOnMissingBean(Jackson2ObjectMapperBuilder.class)
public Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder() {
	Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
	builder.applicationContext(this.applicationContext);
	if (this.jacksonProperties.getSerializationInclusion() != null) {
		builder.serializationInclusion(
				this.jacksonProperties.getSerializationInclusion());
	}
	if (this.jacksonProperties.getTimeZone() != null) {
		builder.timeZone(this.jacksonProperties.getTimeZone());
	}
	configureFeatures(builder, this.jacksonProperties.getDeserialization());
	configureFeatures(builder, this.jacksonProperties.getSerialization());
	configureFeatures(builder, this.jacksonProperties.getMapper());
	configureFeatures(builder, this.jacksonProperties.getParser());
	configureFeatures(builder, this.jacksonProperties.getGenerator());
	configureDateFormat(builder);
	configurePropertyNamingStrategy(builder);
	configureModules(builder);
	configureLocale(builder);
	return builder;
}
 
Example 18
Project: contestparser   File: JacksonAutoConfiguration.java   View source code 6 votes vote down vote up
private void configurePropertyNamingStrategy(
		Jackson2ObjectMapperBuilder builder) {
	// We support a fully qualified class name extending Jackson's
	// PropertyNamingStrategy or a string value corresponding to the constant
	// names in PropertyNamingStrategy which hold default provided implementations
	String strategy = this.jacksonProperties.getPropertyNamingStrategy();
	if (strategy != null) {
		try {
			configurePropertyNamingStrategyClass(builder,
					ClassUtils.forName(strategy, null));
		}
		catch (ClassNotFoundException ex) {
			configurePropertyNamingStrategyField(builder, strategy);
		}
	}
}
 
Example 19
Project: contestparser   File: JacksonAutoConfigurationTests.java   View source code 6 votes vote down vote up
@Test
public void defaultObjectMapperBuilder() throws Exception {
	this.context.register(JacksonAutoConfiguration.class);
	this.context.refresh();
	Jackson2ObjectMapperBuilder builder = this.context
			.getBean(Jackson2ObjectMapperBuilder.class);
	ObjectMapper mapper = builder.build();
	assertTrue(MapperFeature.DEFAULT_VIEW_INCLUSION.enabledByDefault());
	assertFalse(mapper.getDeserializationConfig()
			.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION));
	assertTrue(MapperFeature.DEFAULT_VIEW_INCLUSION.enabledByDefault());
	assertFalse(mapper.getDeserializationConfig()
			.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION));
	assertFalse(mapper.getSerializationConfig()
			.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION));
	assertTrue(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault());
	assertFalse(mapper.getDeserializationConfig()
			.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
}
 
Example 20
Project: egd-web   File: JacksonConfiguration.java   View source code 6 votes vote down vote up
@Bean
Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
    JavaTimeModule module = new JavaTimeModule();
    module.addSerializer(OffsetDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(ZonedDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(LocalDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(Instant.class, JSR310DateTimeSerializer.INSTANCE);
    module.addDeserializer(LocalDate.class, JSR310LocalDateDeserializer.INSTANCE);

    return new Jackson2ObjectMapperBuilder()
        .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
        .serializationInclusion(JsonInclude.Include.NON_NULL)
        .findModulesViaServiceLoader(true)
        //.featuresToEnable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING)
        //.featuresToEnable(DeserializationFeature.READ_ENUMS_USING_TO_STRING)
        .modulesToInstall(module);
}
 
Example 21
Project: bookshop-api   File: AbstractWebConfig.java   View source code 6 votes vote down vote up
@Override
public void configureMessageConverters( final List<HttpMessageConverter<?>> converters ) {

    final ByteArrayHttpMessageConverter byteArrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
    byteArrayHttpMessageConverter.setSupportedMediaTypes( Arrays.asList( MediaType.APPLICATION_OCTET_STREAM ) );
    converters.add( byteArrayHttpMessageConverter );

    final ObjectMapper mapper = Jackson2ObjectMapperBuilder.json()
     .serializationInclusion(JsonInclude.Include.NON_NULL) // Don’t include null values
     .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) //ISODate
     .build();
    
    final MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
    jsonConverter.setSupportedMediaTypes( Arrays.asList( MediaType.APPLICATION_JSON ) );
    jsonConverter.setObjectMapper( mapper );
    converters.add( jsonConverter );

    super.configureMessageConverters( converters );
}
 
Example 22
Project: bookshop-api   File: BookControllerTest.java   View source code 6 votes vote down vote up
@Test
public void testCreateBook() throws Exception {
	
	Book book = buildBook(3L, Currency.EUR, 20.50, Arrays.asList(buildAuthor(1L, toDate("1978-09-25"), null)));
	book.setId(null);
	Book savedBook = buildBook(3L, Currency.EUR, 20.50, Arrays.asList(buildAuthor(1L, toDate("1978-09-25"), null)));
	when(bookService.createNew(book)).thenReturn(savedBook);
	
	this.mockMvc.perform( post( "/api/books" ).accept( MediaType.parseMediaType( "application/json;charset=UTF-8" ) )
       		.content(Jackson2ObjectMapperBuilder.json().build().writeValueAsString(book))
       		.contentType(MediaType.APPLICATION_JSON))
       	.andDo( print() )
        .andExpect( status().isCreated() )
        .andExpect( content().contentType( "application/json;charset=UTF-8" ) )
        .andExpect( jsonPath( "$.id" ).value( savedBook.getId().intValue() ) )
        .andExpect( jsonPath( "$.title" ).value( savedBook.getTitle() ) )
        .andExpect( jsonPath( "$.description" ).value( savedBook.getDescription() ) );
	
	verify(bookService).createNew(book);
}
 
Example 23
Project: bookshop-api   File: BookControllerTest.java   View source code 6 votes vote down vote up
@Test
public void testCreateBookNotValid() throws Exception {
	
	Book book = buildBook(3L, null, 20.50, Arrays.asList(buildAuthor(1L, toDate("1978-09-25"), null)));
	book.setId(null);
	// set mandatory field to null
	book.setTitle(null);
	book.setIsbn("ssss");
	
	ImmutableMap.of("field","isbn","rejectedValue","ssss","message","ISBN not valid");
	this.mockMvc.perform( post( "/api/books" ).accept( MediaType.parseMediaType( "application/json;charset=UTF-8" ) )
       		.content(Jackson2ObjectMapperBuilder.json().build().writeValueAsString(book))
       		.contentType(MediaType.APPLICATION_JSON))
       	.andDo( print() )
        .andExpect( status().isBadRequest() )
        .andExpect( content().contentType( "application/json;charset=UTF-8" ) )
        .andExpect( jsonPath( "$.code" ).value( ErrorCode.VALIDATION_ERROR ) )
        .andExpect( jsonPath( "$.message" ).value( "Validation Failure" ) )
		.andExpect( jsonPath( "$.violations", hasSize(3)) )
		.andExpect( jsonPath( "$.violations[?(@.field == 'isbn' && @.code == 'error.validation.isbn.notvalid' && @.rejectedValue == 'ssss')]").exists())
		.andExpect( jsonPath( "$.violations[?(@.field == 'title' && @.code == 'error.validation.title.notnull')]").exists())
		.andExpect( jsonPath( "$.violations[?(@.field == 'currency' && @.code == 'error.validation.currency.notnull')]").exists());
}
 
Example 24
Project: yona-server   File: CoreConfiguration.java   View source code 6 votes vote down vote up
@Bean
@Primary
ObjectMapper objectMapper()
{
	// HATEOAS disables the default Spring configuration options described at
	// https://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html#howto-customize-the-jackson-objectmapper
	// See https://github.com/spring-projects/spring-hateoas/issues/333.
	// We fix this by applying the Spring configurator on the HATEOAS object mapper
	// See also
	// https://github.com/spring-projects/spring-boot/blob/v1.3.2.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfiguration.java
	// which already seems to do this but does not work
	ObjectMapper springHateoasObjectMapper = beanFactory.getBean(SPRING_HATEOAS_OBJECT_MAPPER, ObjectMapper.class);
	Jackson2ObjectMapperBuilder builder = beanFactory.getBean(Jackson2ObjectMapperBuilder.class);
	builder.configure(springHateoasObjectMapper);

	// By default, Jackson converts dates to UTC. This causes issues when passing inactivity creation requests from the app
	// service to the analysis engine service.
	springHateoasObjectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);

	// This way, the JsonView annotations on the controlers work properly
	springHateoasObjectMapper.enable(MapperFeature.DEFAULT_VIEW_INCLUSION);

	return springHateoasObjectMapper;
}
 
Example 25
Project: find   File: DashboardConfigService.java   View source code 6 votes vote down vote up
@Autowired
public DashboardConfigService(final JsonDeserializer<TagName> tagNameDeserializer) {
    super(
        "dashboards.json",
        "defaultDashboardsConfigFile.json",
        DashboardConfig.class,
        DashboardConfig.builder().build(),
        new Jackson2ObjectMapperBuilder()
            .mixIn(Widget.class, WidgetMixins.class)
            .mixIn(WidgetDatasource.class, WidgetDatasourceMixins.class)
            .deserializersByType(ImmutableMap.of(TagName.class, tagNameDeserializer))
            .serializersByType(ImmutableMap.of(TagName.class, new TagNameSerializer()))
            .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,
                               DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)
    );
}
 
Example 26
Project: find   File: IdolConfiguration.java   View source code 6 votes vote down vote up
@SuppressWarnings("SpringJavaAutowiringInspection")
@Bean
@Autowired
@Primary
public ObjectMapper jacksonObjectMapper(
        final Jackson2ObjectMapperBuilder builder,
        final AuthenticationInformationRetriever<?, ?> authenticationInformationRetriever
) {
    final ObjectMapper mapper = builder
            .createXmlMapper(false)
            .mixIn(Authentication.class, IdolAuthenticationMixins.class)
            .mixIn(Widget.class, WidgetMixins.class)
            .mixIn(WidgetDatasource.class, WidgetDatasourceMixins.class)
            .mixIn(QueryRestrictions.class, IdolQueryRestrictionsMixin.class)
            .mixIn(IdolQueryRestrictions.class, IdolQueryRestrictionsMixin.class)
            .featuresToEnable(SerializationFeature.INDENT_OUTPUT)
            .build();

    mapper.setInjectableValues(new InjectableValues.Std().addValue(AuthenticationInformationRetriever.class, authenticationInformationRetriever));

    return mapper;
}
 
Example 27
Project: find   File: FindConfigFileService.java   View source code 6 votes vote down vote up
protected FindConfigFileService(final FilterProvider filterProvider,
                                final TextEncryptor textEncryptor,
                                final JsonSerializer<FieldPath> fieldPathSerializer,
                                final JsonDeserializer<FieldPath> fieldPathDeserializer) {

    final ObjectMapper objectMapper = new Jackson2ObjectMapperBuilder()
        .featuresToEnable(SerializationFeature.INDENT_OUTPUT)
        .mixIns(customMixins())
        .serializersByType(ImmutableMap.of(FieldPath.class, fieldPathSerializer))
        .deserializersByType(ImmutableMap.of(FieldPath.class, fieldPathDeserializer))
        .createXmlMapper(false)
        .build();

    setConfigFileLocation(CONFIG_FILE_LOCATION);
    setConfigFileName(CONFIG_FILE_NAME);
    setDefaultConfigFile(getDefaultConfigFile());
    setMapper(objectMapper);
    setTextEncryptor(textEncryptor);
    setFilterProvider(filterProvider);
}
 
Example 28
Project: find   File: CustomizationConfigService.java   View source code 6 votes vote down vote up
protected CustomizationConfigService(
    final String configFileName,
    final String defaultFileName,
    final Class<T> configClass,
    final T emptyConfig,
    final Jackson2ObjectMapperBuilder objectMapperBuilder
) {
    this.configClass = configClass;
    this.emptyConfig = emptyConfig;

    final ObjectMapper objectMapper = objectMapperBuilder
        .featuresToEnable(SerializationFeature.INDENT_OUTPUT)
        .createXmlMapper(false)
        .build();

    setMapper(objectMapper);
    setConfigFileLocation(FindConfigFileService.CONFIG_FILE_LOCATION);
    setConfigFileName(Paths.get(CONFIG_DIRECTORY).resolve(configFileName).toString());
    setDefaultConfigFile('/' + defaultFileName);
}
 
Example 29
Project: spring-social-slideshare   File: JacksonUtils.java   View source code 6 votes vote down vote up
private static XmlMapper createXmlMapper() {
	return new Jackson2ObjectMapperBuilder()
			// mixins
			.mixIn(Slideshow.class, SlideshowMixIn.class)
			.mixIn(Slideshow.Tag.class, SlideshowMixIn.TagMixin.class)
			.mixIn(Slideshow.RelatedSlideshow.class, SlideshowMixIn.RelatedSlideshowMixin.class)

			.mixIn(GetSlideshowsResponse.class, GetSlideshowsResponseMixin.class)
			.mixIn(SearchSlideshowsResponse.class, SearchSlideshowsResponseMixin.class)
			.mixIn(SearchSlideshowsResponse.MetaInfo.class, SearchSlideshowsResponseMixin.MetaInfoMixin.class)
			.mixIn(SlideshowIdHolder.class, SlideshowIdHolderMixin.class)

			// errors
			.mixIn(SlideShareServiceError.class, SlideShareServiceErrorMixin.class)
			.mixIn(SlideShareServiceError.Message.class, SlideShareServiceErrorMixin.MessageMixin.class)

			.dateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzz"))
			.createXmlMapper(true)
			.build();
}
 
Example 30
Project: spring-cloud-aws   File: QueueMessageHandler.java   View source code 6 votes vote down vote up
private CompositeMessageConverter createPayloadArgumentCompositeConverter() {
    List<MessageConverter> payloadArgumentConverters = new ArrayList<>();

    if (JACKSON_2_PRESENT) {
        MappingJackson2MessageConverter jacksonMessageConverter = new MappingJackson2MessageConverter();
        jacksonMessageConverter.setObjectMapper(Jackson2ObjectMapperBuilder.json().build());
        jacksonMessageConverter.setSerializedPayloadClass(String.class);
        jacksonMessageConverter.setStrictContentTypeMatch(true);
        payloadArgumentConverters.add(jacksonMessageConverter);
    }

    ObjectMessageConverter objectMessageConverter = new ObjectMessageConverter();
    objectMessageConverter.setStrictContentTypeMatch(true);
    payloadArgumentConverters.add(objectMessageConverter);

    payloadArgumentConverters.add(new SimpleMessageConverter());

    return new CompositeMessageConverter(payloadArgumentConverters);
}
 
Example 31
Project: spring-cloud-aws   File: AbstractMessageChannelMessagingSendingTemplate.java   View source code 6 votes vote down vote up
protected void initMessageConverter(MessageConverter messageConverter) {

        StringMessageConverter stringMessageConverter = new StringMessageConverter();
        stringMessageConverter.setSerializedPayloadClass(String.class);

        List<MessageConverter> messageConverters = new ArrayList<>();
        messageConverters.add(stringMessageConverter);

        if (messageConverter != null) {
            messageConverters.add(messageConverter);
        } else if (JACKSON_2_PRESENT) {
            MappingJackson2MessageConverter mappingJackson2MessageConverter = new MappingJackson2MessageConverter();
            mappingJackson2MessageConverter.setObjectMapper(Jackson2ObjectMapperBuilder.json().build());
            mappingJackson2MessageConverter.setSerializedPayloadClass(String.class);
            messageConverters.add(mappingJackson2MessageConverter);
        }

        setMessageConverter(new CompositeMessageConverter(messageConverters));
    }
 
Example 32
Project: spring-cloud-aws   File: QueueMessagingTemplateTest.java   View source code 6 votes vote down vote up
@Test
public void instantiation_WithCustomJacksonConverterThatSupportsJava8Types_shouldConvertMessageToString() throws IOException {

    // Arrange
    AmazonSQSAsync amazonSqs = createAmazonSqs();

    ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().build();

    MappingJackson2MessageConverter simpleMessageConverter = new MappingJackson2MessageConverter();
    simpleMessageConverter.setSerializedPayloadClass(String.class);
    simpleMessageConverter.setObjectMapper(objectMapper);

    QueueMessagingTemplate queueMessagingTemplate = new QueueMessagingTemplate(amazonSqs, (ResourceIdResolver) null, simpleMessageConverter);

    // Act
    queueMessagingTemplate.convertAndSend("test", new TestPerson("Agim", "Emruli", LocalDate.of(2017, 1, 1)));

    // Assert
    ArgumentCaptor<SendMessageRequest> sendMessageRequestArgumentCaptor = ArgumentCaptor.forClass(SendMessageRequest.class);
    verify(amazonSqs).sendMessage(sendMessageRequestArgumentCaptor.capture());
    TestPerson testPerson = objectMapper.readValue(sendMessageRequestArgumentCaptor.getValue().getMessageBody(), TestPerson.class);

    assertEquals("Agim", testPerson.getFirstName());
    assertEquals("Emruli", testPerson.getLastName());
    assertEquals(LocalDate.of(2017, 1, 1), testPerson.getActiveSince());
}
 
Example 33
Project: spring-cloud-aws   File: QueueMessagingTemplateTest.java   View source code 6 votes vote down vote up
@Test
public void instantiation_withDefaultMapping2JacksonConverter_shouldSupportJava8Types() throws IOException {

    // Arrange
    AmazonSQSAsync amazonSqs = createAmazonSqs();

    ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().build();

    QueueMessagingTemplate queueMessagingTemplate = new QueueMessagingTemplate(amazonSqs);

    // Act
    queueMessagingTemplate.convertAndSend("test", new TestPerson("Agim", "Emruli", LocalDate.of(2017, 1, 1)));

    // Assert
    ArgumentCaptor<SendMessageRequest> sendMessageRequestArgumentCaptor = ArgumentCaptor.forClass(SendMessageRequest.class);
    verify(amazonSqs).sendMessage(sendMessageRequestArgumentCaptor.capture());
    TestPerson testPerson = objectMapper.readValue(sendMessageRequestArgumentCaptor.getValue().getMessageBody(), TestPerson.class);

    assertEquals("Agim", testPerson.getFirstName());
    assertEquals("Emruli", testPerson.getLastName());
    assertEquals(LocalDate.of(2017, 1, 1), testPerson.getActiveSince());
}
 
Example 34
Project: arsnova-backend   File: AppConfig.java   View source code 6 votes vote down vote up
@Bean
public MappingJackson2HttpMessageConverter defaultJsonMessageConverter() {
	Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
	builder
			.serializationInclusion(JsonInclude.Include.NON_EMPTY)
			.defaultViewInclusion(false)
			.indentOutput(apiIndent)
			.simpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
	ObjectMapper mapper = builder.build();
	mapper.setConfig(mapper.getSerializationConfig().withView(View.Public.class));
	MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(mapper);
	List<MediaType> mediaTypes = new ArrayList<>();
	mediaTypes.add(API_V3_MEDIA_TYPE);
	mediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
	converter.setSupportedMediaTypes(mediaTypes);

	return converter;
}
 
Example 35
Project: arsnova-backend   File: AppConfig.java   View source code 6 votes vote down vote up
@Bean
public MappingJackson2HttpMessageConverter apiV2JsonMessageConverter() {
	Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
	builder
			.serializationInclusion(JsonInclude.Include.NON_EMPTY)
			.defaultViewInclusion(false)
			.indentOutput(apiIndent)
			.featuresToEnable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
			.featuresToEnable(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS)
			.modules(new CouchDbDocumentModule());
	ObjectMapper mapper = builder.build();
	mapper.setConfig(mapper.getSerializationConfig().withView(View.Public.class));
	MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(mapper);
	List<MediaType> mediaTypes = new ArrayList<>();
	mediaTypes.add(API_V2_MEDIA_TYPE);
	mediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
	converter.setSupportedMediaTypes(mediaTypes);

	return converter;
}
 
Example 36
Project: carina   File: RestTemplateBuilder.java   View source code 6 votes vote down vote up
public RestTemplateBuilder withSpecificJsonMessageConverter() {
	isUseDefaultJsonMessageConverter = false;

	AbstractHttpMessageConverter<?> jsonMessageConverter = new MappingJackson2HttpMessageConverter(
			Jackson2ObjectMapperBuilder
					.json()
					.featuresToEnable(
                               DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY,
                               DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT)
					.build());
	jsonMessageConverter.setSupportedMediaTypes(Lists.newArrayList(
			MediaType.TEXT_HTML, MediaType.TEXT_PLAIN,
			MediaType.APPLICATION_JSON));

	withMessageConverter(jsonMessageConverter);

	return this;
}
 
Example 37
Project: amv-access-api-poc   File: JacksonConfig.java   View source code 5 votes vote down vote up
@Bean
public Jackson2ObjectMapperBuilder objectMapperBuilder() {
    return new Jackson2ObjectMapperBuilder()
            .failOnUnknownProperties(false)
            .indentOutput(true)
            .serializationInclusion(JsonInclude.Include.NON_NULL)
            .modulesToInstall(
                    new Jdk8Module(),
                    new JavaTimeModule()
            );
}
 
Example 38
Project: cas-5.1.0   File: ServiceTicketImplTests.java   View source code 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    // needed in order to serialize ZonedDateTime class
    mapper = Jackson2ObjectMapperBuilder.json()
            .featuresToDisable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)
            .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .build();
    mapper.findAndRegisterModules();
}
 
Example 39
Project: cas-5.1.0   File: TicketGrantingTicketImplTests.java   View source code 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    // needed in order to serialize ZonedDateTime class
    mapper = Jackson2ObjectMapperBuilder.json()
            .featuresToDisable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)
            .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .build();
    mapper.findAndRegisterModules();
}
 
Example 40
Project: buenojo   File: JacksonConfiguration.java   View source code 5 votes vote down vote up
@Bean
Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
    JavaTimeModule module = new JavaTimeModule();
    module.addSerializer(OffsetDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(ZonedDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(LocalDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(Instant.class, JSR310DateTimeSerializer.INSTANCE);
    module.addDeserializer(LocalDate.class, JSR310LocalDateDeserializer.INSTANCE);
    return new Jackson2ObjectMapperBuilder()
            .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .findModulesViaServiceLoader(true)
            .modulesToInstall(module);
}