Created
February 13, 2020 13:43
-
-
Save odrotbohm/f00079458c970b43f69c2e1b292459e3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Copyright 2020 the original author or authors. | |
* | |
* Licensed under the Apache License, Version 2.0 (the "License"); | |
* you may not use this file except in compliance with the License. | |
* You may obtain a copy of the License at | |
* | |
* https://www.apache.org/licenses/LICENSE-2.0 | |
* | |
* Unless required by applicable law or agreed to in writing, software | |
* distributed under the License is distributed on an "AS IS" BASIS, | |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
* See the License for the specific language governing permissions and | |
* limitations under the License. | |
*/ | |
package org.springframework.hateoas.support; | |
import static org.assertj.core.api.Assertions.*; | |
import lombok.RequiredArgsConstructor; | |
import java.io.IOException; | |
import java.lang.annotation.Retention; | |
import java.lang.annotation.RetentionPolicy; | |
import java.util.List; | |
import java.util.Locale; | |
import org.junit.jupiter.api.BeforeAll; | |
import org.junit.jupiter.api.Test; | |
import org.junit.jupiter.api.TestInstance; | |
import org.junit.jupiter.api.TestInstance.Lifecycle; | |
import org.springframework.context.MessageSource; | |
import org.springframework.context.i18n.LocaleContextHolder; | |
import org.springframework.context.support.MessageSourceAccessor; | |
import org.springframework.context.support.StaticMessageSource; | |
import com.fasterxml.jackson.annotation.JsonAutoDetect; | |
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; | |
import com.fasterxml.jackson.core.JsonGenerator; | |
import com.fasterxml.jackson.databind.BeanDescription; | |
import com.fasterxml.jackson.databind.ObjectMapper; | |
import com.fasterxml.jackson.databind.SerializationConfig; | |
import com.fasterxml.jackson.databind.SerializerProvider; | |
import com.fasterxml.jackson.databind.module.SimpleModule; | |
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter; | |
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier; | |
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; | |
import com.jayway.jsonpath.DocumentContext; | |
import com.jayway.jsonpath.JsonPath; | |
/** | |
* @author Oliver Drotbohm | |
*/ | |
@TestInstance(Lifecycle.PER_CLASS) | |
class JacksonInternationalizationUnitTests { | |
ObjectMapper mapper = new ObjectMapper(); | |
@BeforeAll | |
void setUp() { | |
StaticMessageSource messageSource = new StaticMessageSource(); | |
messageSource.addMessage("message", Locale.US, "message"); | |
messageSource.addMessage("message", Locale.GERMAN, "Botschaft"); | |
mapper.registerModule(new I18nModule(messageSource)); | |
mapper.setDefaultVisibility(JsonAutoDetect.Value // | |
.defaultVisibility() // | |
.withFieldVisibility(Visibility.ANY)); | |
} | |
@Test | |
void rendersAnnotatedPropertyUsingMessageSource() throws Exception { | |
Sample sample = new Sample(); | |
sample.message = "message"; | |
sample.plainValue = "plainValue"; | |
LocaleContextHolder.setLocale(Locale.GERMAN); | |
DocumentContext parse = JsonPath.parse(mapper.writeValueAsString(sample)); | |
assertThat(parse.read("$.message", String.class)).isEqualTo("Botschaft"); | |
assertThat(parse.read("$.plainValue", String.class)).isEqualTo("plainValue"); | |
} | |
@Test | |
void rejectsAnnotationOnNonStringProperty() { | |
assertThatExceptionOfType(IllegalStateException.class) | |
.isThrownBy(() -> mapper.writeValueAsString(new InvalidExample())); | |
} | |
static class Sample { | |
@JsonInternationalized String message; | |
String plainValue; | |
} | |
static class InvalidExample { | |
@JsonInternationalized Integer invalid; | |
} | |
@Retention(RetentionPolicy.RUNTIME) | |
@interface JsonInternationalized {} | |
@RequiredArgsConstructor | |
static class I18nModule extends SimpleModule { | |
private static final long serialVersionUID = -6745718985183239662L; | |
private final MessageSource messageSource; | |
@Override | |
public void setupModule(SetupContext context) { | |
MessageSourceAccessor accessor = new MessageSourceAccessor(messageSource); | |
InternationalizedSerializer serializer = new InternationalizedSerializer(accessor); | |
context.addBeanSerializerModifier(new InternationalizingBeanSerializerModifier(serializer)); | |
} | |
@RequiredArgsConstructor | |
static class InternationalizingBeanSerializerModifier extends BeanSerializerModifier { | |
private static final String PROPERTY_MUST_BE_STRING = "Invalid use of @" | |
+ JsonInternationalized.class.getSimpleName() + " on %s! Can only be used on properties of type String!"; | |
private final InternationalizedSerializer serializer; | |
/* | |
* (non-Javadoc) | |
* @see com.fasterxml.jackson.databind.ser.BeanSerializerModifier#changeProperties(com.fasterxml.jackson.databind.SerializationConfig, com.fasterxml.jackson.databind.BeanDescription, java.util.List) | |
*/ | |
@Override | |
public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, | |
List<BeanPropertyWriter> beanProperties) { | |
for (BeanPropertyWriter writer : beanProperties) { | |
if (writer.getAnnotation(JsonInternationalized.class) != null) { | |
if (!writer.getType().isTypeOrSubTypeOf(String.class)) { | |
throw new IllegalStateException(String.format(PROPERTY_MUST_BE_STRING, writer)); | |
} | |
writer.assignSerializer(serializer); | |
} | |
} | |
return beanProperties; | |
} | |
} | |
/** | |
* Serializer that resolves an object's to String | |
* | |
* @author Oliver Drotbohm | |
*/ | |
@RequiredArgsConstructor | |
static class InternationalizedSerializer extends ToStringSerializer { | |
private static final long serialVersionUID = -2391442803792997283L; | |
private final MessageSourceAccessor accessor; | |
/* | |
* (non-Javadoc) | |
* @see com.fasterxml.jackson.databind.ser.std.ToStringSerializerBase#serialize(java.lang.Object, com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider) | |
*/ | |
@Override | |
public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException { | |
gen.writeString(accessor.getMessage(value.toString())); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment