Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support JsonNaming and JsonProperty for BeanIntrospectionModule #7139

Merged
merged 5 commits into from
Mar 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions jackson-databind/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ dependencies {

api project(":jackson-core")

compileOnly libs.managed.graal
api libs.managed.jackson.databind
api libs.managed.jackson.datatype.jdk8
api libs.managed.jackson.datatype.jsr310
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* Copyright 2017-2022 original 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 io.micronaut.jackson;

import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.oracle.svm.core.annotate.AutomaticFeature;
import io.micronaut.core.annotation.Internal;
import org.graalvm.nativeimage.hosted.Feature;
import org.graalvm.nativeimage.hosted.RuntimeReflection;

import java.util.stream.Stream;

/**
* A native image feature that configures the jackson-databind library.
*
* @author Jonas Konrad
* @since 3.4.1
*/
@Internal
@AutomaticFeature
final class JacksonDatabindFeature implements Feature {
@SuppressWarnings("deprecation")
@Override
public void beforeAnalysis(BeforeAnalysisAccess access) {
Stream.of(
PropertyNamingStrategies.LowerCamelCaseStrategy.class,
PropertyNamingStrategies.UpperCamelCaseStrategy.class,
PropertyNamingStrategies.SnakeCaseStrategy.class,
PropertyNamingStrategies.UpperSnakeCaseStrategy.class,
PropertyNamingStrategies.LowerCaseStrategy.class,
PropertyNamingStrategies.KebabCaseStrategy.class,
PropertyNamingStrategies.LowerDotCaseStrategy.class,

PropertyNamingStrategy.UpperCamelCaseStrategy.class,
PropertyNamingStrategy.SnakeCaseStrategy.class,
PropertyNamingStrategy.LowerCaseStrategy.class,
PropertyNamingStrategy.KebabCaseStrategy.class,
PropertyNamingStrategy.LowerDotCaseStrategy.class
).forEach(RuntimeReflection::registerForReflectiveInstantiation);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import com.fasterxml.jackson.core.io.SerializedString;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.cfg.MapperConfig;
import com.fasterxml.jackson.databind.deser.BeanDeserializerBuilder;
Expand Down Expand Up @@ -56,6 +57,7 @@
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.databind.util.SimpleBeanPropertyDefinition;
import io.micronaut.context.annotation.Requires;
import io.micronaut.core.annotation.AnnotatedElement;
import io.micronaut.core.annotation.AnnotationMetadata;
import io.micronaut.core.annotation.AnnotationValue;
import io.micronaut.core.annotation.Experimental;
Expand All @@ -69,14 +71,14 @@
import io.micronaut.core.type.Argument;
import io.micronaut.core.util.CollectionUtils;
import io.micronaut.core.util.StringUtils;
import io.micronaut.http.hateoas.Resource;
import io.micronaut.jackson.JacksonConfiguration;
import jakarta.inject.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
Expand Down Expand Up @@ -228,20 +230,53 @@ private JsonFormat.Value parseJsonFormat(@NonNull AnnotationValue<JsonFormat> fo
);
}

@Nullable
private PropertyNamingStrategy findNamingStrategy(MapperConfig<?> mapperConfig, BeanIntrospection<?> introspection) {
AnnotationValue<JsonNaming> namingAnnotation = introspection.getAnnotation(JsonNaming.class);
if (namingAnnotation != null) {
Optional<Class<?>> clazz = namingAnnotation.classValue();
if (clazz.isPresent()) {
try {
Constructor<?> emptyConstructor = clazz.get().getConstructor();
return (PropertyNamingStrategy) emptyConstructor.newInstance();
} catch (NoSuchMethodException ignored) {
return mapperConfig.getPropertyNamingStrategy();
} catch (ReflectiveOperationException e) {
throw new RuntimeException("Failed to construct configured PropertyNamingStrategy", e);
Copy link
Contributor

@sdelamo sdelamo Mar 30, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have addressed two sonar issues. The one remaning is that it is telling us to use a less generic exception.

}
}
}
return mapperConfig.getPropertyNamingStrategy();
}

private String getName(MapperConfig<?> mapperConfig, @Nullable PropertyNamingStrategy namingStrategy, AnnotatedElement property) {
String explicitName = property.getAnnotationMetadata().stringValue(JsonProperty.class).orElse(JsonProperty.USE_DEFAULT_NAME);
if (!explicitName.equals(JsonProperty.USE_DEFAULT_NAME)) {
return explicitName;
}
String implicitName = property.getName();
if (namingStrategy != null) {
return namingStrategy.nameForGetterMethod(mapperConfig, null, implicitName);
} else {
return implicitName;
}
}

/**
* Modifies bean serialization.
*/
private class BeanIntrospectionSerializerModifier extends BeanSerializerModifier {
@Override
public BeanSerializerBuilder updateBuilder(SerializationConfig config, BeanDescription beanDesc, BeanSerializerBuilder builder) {
final Class<?> beanClass = beanDesc.getBeanClass();
final boolean isResource = Resource.class.isAssignableFrom(beanDesc.getBeanClass());
final BeanIntrospection<Object> introspection =
findIntrospection(beanClass);

if (introspection == null) {
return super.updateBuilder(config, beanDesc, builder);
} else {
PropertyNamingStrategy namingStrategy = findNamingStrategy(config, introspection);

final BeanSerializerBuilder newBuilder = new BeanSerializerBuilder(beanDesc) {
@Override
public JsonSerializer<?> build() {
Expand Down Expand Up @@ -270,19 +305,7 @@ public JsonSerializer<?> build() {
if (beanProperty.hasAnnotation(JsonIgnore.class)) {
continue;
}
final String propertyName;
sdelamo marked this conversation as resolved.
Show resolved Hide resolved
if (isResource) {
final String n = beanProperty.getName();
if ("embedded".equals(n)) {
propertyName = Resource.EMBEDDED;
} else if ("links".equals(n)) {
propertyName = Resource.LINKS;
} else {
propertyName = beanProperty.stringValue(JsonProperty.class).orElse(beanProperty.getName());
}
} else {
propertyName = beanProperty.stringValue(JsonProperty.class).orElse(beanProperty.getName());
}
final String propertyName = getName(config, namingStrategy, beanProperty);
BeanPropertyWriter writer = new BeanIntrospectionPropertyWriter(
createVirtualMember(
typeResolutionContext,
Expand Down Expand Up @@ -310,50 +333,18 @@ public JsonSerializer<?> build() {
}

final List<BeanPropertyWriter> newProperties = new ArrayList<>(properties);
Map<String, BeanProperty> named = new LinkedHashMap<>(properties.size());
Map<String, BeanProperty<Object, Object>> named = new LinkedHashMap<>();
for (BeanProperty<Object, Object> beanProperty : beanProperties) {
final Optional<String> n = beanProperty.stringValue(JsonProperty.class);
n.ifPresent(s -> named.put(s, beanProperty));
named.put(getName(config, namingStrategy, beanProperty), beanProperty);
}
for (int i = 0; i < properties.size(); i++) {
final BeanPropertyWriter existing = properties.get(i);

final Optional<BeanProperty<Object, Object>> property;
final String existingName = existing.getName();
if (named.containsKey(existingName)) {
property = Optional.of(named.get(existingName));
} else {
property = introspection.getProperty(existingName);
}
final Optional<BeanProperty<Object, Object>> property = Optional.ofNullable(named.get(existing.getName()));
// ignore properties that are @JsonIgnore, so that we don't replace other properties of the
// same name
if (property.isPresent() && !property.get().isAnnotationPresent(JsonIgnore.class)) {
final BeanProperty<Object, Object> beanProperty = property.get();
if (isResource) {
sdelamo marked this conversation as resolved.
Show resolved Hide resolved
if ("embedded".equals(beanProperty.getName())) {
newProperties.set(i, new BeanIntrospectionPropertyWriter(
new SerializedString(Resource.EMBEDDED),
existing,
beanProperty,
existing.getSerializer(),
config.getTypeFactory(),
existing.getViews()
)
);
continue;
} else if ("links".equals(beanProperty.getName())) {
newProperties.set(i, new BeanIntrospectionPropertyWriter(
new SerializedString(Resource.LINKS),
existing,
beanProperty,
existing.getSerializer(),
config.getTypeFactory(),
existing.getViews()
)
);
continue;
}
}
newProperties.set(i, new BeanIntrospectionPropertyWriter(
existing,
beanProperty,
Expand Down Expand Up @@ -394,6 +385,8 @@ public BeanDeserializerBuilder updateBuilder(
if (introspection == null) {
return builder;
} else {
PropertyNamingStrategy propertyNamingStrategy = findNamingStrategy(config, introspection);

final Iterator<SettableBeanProperty> properties = builder.getProperties();
if ((ignoreReflectiveProperties || !properties.hasNext()) && introspection.getPropertyNames().length > 0) {
// mismatch, probably GraalVM reflection not enabled for bean. Try recreate
Expand All @@ -403,6 +396,7 @@ public BeanDeserializerBuilder updateBuilder(
beanDesc.getClassInfo(),
config.getTypeFactory(),
beanProperty,
getName(config, propertyNamingStrategy, beanProperty),
findSerializerFromAnnotation(beanProperty, JsonDeserialize.class)),
true);
}
Expand All @@ -416,7 +410,7 @@ public BeanDeserializerBuilder updateBuilder(
continue;
}

remainingProperties.put(beanProperty.getName(), beanProperty);
remainingProperties.put(getName(config, propertyNamingStrategy, beanProperty), beanProperty);
}
while (properties.hasNext()) {
final SettableBeanProperty settableBeanProperty = properties.next();
Expand Down Expand Up @@ -444,6 +438,7 @@ public BeanDeserializerBuilder updateBuilder(
beanDesc.getClassInfo(),
config.getTypeFactory(),
entry.getValue(),
entry.getKey(),
findSerializerFromAnnotation(entry.getValue(), JsonDeserialize.class)),
true);
}
Expand All @@ -468,7 +463,7 @@ public SettableBeanProperty[] getFromObjectArguments(DeserializationConfig confi
final JavaType javaType = existingProperty != null ? existingProperty.getType() : newType(argument, typeFactory);
final AnnotationMetadata annotationMetadata = argument.getAnnotationMetadata();
PropertyMetadata propertyMetadata = newPropertyMetadata(argument, annotationMetadata);
final String simpleName = existingProperty != null ? existingProperty.getName() : annotationMetadata.stringValue(JsonProperty.class).orElse(argument.getName());
final String simpleName = existingProperty != null ? existingProperty.getName() : getName(config, propertyNamingStrategy, argument);
TypeDeserializer typeDeserializer;
try {
typeDeserializer = config.findTypeDeserializer(javaType);
Expand Down Expand Up @@ -673,9 +668,9 @@ private class VirtualSetter extends SettableBeanProperty {
final BeanProperty beanProperty;
final TypeResolutionContext typeResolutionContext;

VirtualSetter(TypeResolutionContext typeResolutionContext, TypeFactory typeFactory, BeanProperty beanProperty, JsonDeserializer<Object> valueDeser) {
VirtualSetter(TypeResolutionContext typeResolutionContext, TypeFactory typeFactory, BeanProperty<?,?> beanProperty, String propertyName, JsonDeserializer<Object> valueDeser) {
super(
new PropertyName(beanProperty.getName()),
new PropertyName(propertyName),
newType(beanProperty.asArgument(), typeFactory),
newPropertyMetadata(beanProperty.asArgument(), beanProperty.getAnnotationMetadata()), valueDeser);
this.beanProperty = beanProperty;
Expand Down
Loading