DATACMNS-885 - Support for binding JSON payloads to projection interfaces.

Projection types annotated with @ProjectedPayload can now be used as parameters for @RequestBody annotated Spring MVC controller method parameters.

Accessor methods will be translated into JSON path property expressions which can be customized by using the @JsonPath annotation. The methods are allowed to return simple types, nested projection interfaces or complex classes which will will be mapped using a Jackson ObjectMapper.
This commit is contained in:
Oliver Gierke
2016-07-17 12:32:59 +02:00
parent 86c1086976
commit eec2b43fd0
14 changed files with 952 additions and 78 deletions

View File

@@ -0,0 +1,42 @@
/*
* Copyright 2016 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
*
* http://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.data.web;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation to explicitly declare a JSON Path expression on a projection interface.
*
* @author Oliver Gierke
* @soundtrack Andy McKee - RyLynn (Live book)
* @since 1.13
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE })
public @interface JsonPath {
/**
* The JSON Path expression to be evaluated when the annotated method is invoked.
*
* @return
*/
String value();
}

View File

@@ -0,0 +1,167 @@
/*
* Copyright 2016 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
*
* http://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.data.web;
import lombok.RequiredArgsConstructor;
import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Map;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.core.ResolvableType;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.data.projection.Accessor;
import org.springframework.data.projection.MethodInterceptorFactory;
import org.springframework.data.util.ClassTypeInformation;
import org.springframework.data.util.TypeInformation;
import org.springframework.util.Assert;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.ParseContext;
import com.jayway.jsonpath.TypeRef;
import com.jayway.jsonpath.spi.mapper.MappingProvider;
/**
* {@link MethodInterceptorFactory} to create a {@link MethodInterceptor} that will
*
* @author Oliver Gierke
* @soundtrack Jeff Coffin - Fruitcake (The Inside Of The Outside)
* @since 1.13
*/
public class JsonProjectingMethodInterceptorFactory implements MethodInterceptorFactory {
private final ParseContext context;
/**
* Creates a new {@link JsonProjectingMethodInterceptorFactory} using the given {@link ObjectMapper}.
*
* @param mapper must not be {@literal null}.
*/
public JsonProjectingMethodInterceptorFactory(MappingProvider mappingProvider) {
Assert.notNull(mappingProvider, "MappingProvider must not be null!");
Configuration build = Configuration.builder()//
.mappingProvider(mappingProvider)//
.build();
this.context = JsonPath.using(build);
}
/*
* (non-Javadoc)
* @see org.springframework.data.projection.MethodInterceptorFactory#createMethodInterceptor(java.lang.Object, java.lang.Class)
*/
@Override
public MethodInterceptor createMethodInterceptor(Object source, Class<?> targetType) {
DocumentContext context = InputStream.class.isInstance(source) ? this.context.parse((InputStream) source)
: this.context.parse(source);
return new InputMessageProjecting(context);
}
/*
* (non-Javadoc)
* @see org.springframework.data.projection.MethodInterceptorFactory#supports(java.lang.Object, java.lang.Class)
*/
@Override
public boolean supports(Object source, Class<?> targetType) {
if (InputStream.class.isInstance(source) || JSONObject.class.isInstance(source)
|| JSONArray.class.isInstance(source)) {
return true;
}
return Map.class.isInstance(source) && hasJsonPathAnnotation(targetType);
}
/**
* Returns whether the given type contains a method with a {@link org.springframework.data.web.JsonPath} annotation.
*
* @param type must not be {@literal null}.
* @return
*/
private static boolean hasJsonPathAnnotation(Class<?> type) {
for (Method method : type.getMethods()) {
if (AnnotationUtils.findAnnotation(method, org.springframework.data.web.JsonPath.class) != null) {
return true;
}
}
return false;
}
@RequiredArgsConstructor
private static class InputMessageProjecting implements MethodInterceptor {
private final DocumentContext context;
/*
* (non-Javadoc)
* @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
*/
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Method method = invocation.getMethod();
TypeInformation<Object> returnType = ClassTypeInformation.fromReturnTypeOf(method);
ResolvableType type = ResolvableType.forMethodReturnType(method);
String jsonPath = getJsonPath(method);
return !returnType.getActualType().getType().isInterface() ? context.read(jsonPath, new ResolvableTypeRef(type))
: context.read(jsonPath);
}
/**
* Returns the JSONPath expression to be used for the given method.
*
* @param method
* @return
*/
private static String getJsonPath(Method method) {
org.springframework.data.web.JsonPath annotation = AnnotationUtils.findAnnotation(method,
org.springframework.data.web.JsonPath.class);
return annotation != null ? annotation.value() : "$.".concat(new Accessor(method).getPropertyName());
}
@RequiredArgsConstructor
private static class ResolvableTypeRef extends TypeRef<Object> {
private final ResolvableType type;
/*
* (non-Javadoc)
* @see com.jayway.jsonpath.TypeRef#getType()
*/
@Override
public Type getType() {
return type.getType();
}
}
}
}

View File

@@ -0,0 +1,37 @@
/*
* Copyright 2016 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
*
* http://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.data.web;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Annotation to mark projection interfaces that are supposed to be used as projection interface to bind request or
* response payloads to.
*
* @author Oliver Gierke
* @soundtrack
* @since 1.13
*/
@Documented
@Retention(RUNTIME)
@Target(TYPE)
public @interface ProjectedPayload {
}

View File

@@ -0,0 +1,141 @@
/*
* Copyright 2016 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
*
* http://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.data.web;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Map;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.core.ResolvableType;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.data.projection.SpelAwareProxyProjectionFactory;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.Assert;
import org.springframework.util.ConcurrentReferenceHashMap;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider;
/**
* {@link HttpMessageConverter} implementation to enable projected JSON binding to interfaces annotated with
* {@link ProjectedPayload}.
*
* @author Oliver Gierke
* @soundtrack Richard Spaven -Ice Is Nice (Spaven's 5ive)
* @since 1.13
*/
public class ProjectingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter
implements BeanClassLoaderAware, BeanFactoryAware {
private final SpelAwareProxyProjectionFactory projectionFactory;
private final Map<Class<?>, Boolean> supportedTypesCache = new ConcurrentReferenceHashMap<Class<?>, Boolean>();
/**
* Creates a new {@link ProjectingJackson2HttpMessageConverter} using a default {@link ObjectMapper}.
*/
public ProjectingJackson2HttpMessageConverter() {
this.projectionFactory = initProjectionFactory(getObjectMapper());
}
/**
* Creates a new {@link ProjectingJackson2HttpMessageConverter} for the given {@link ObjectMapper}.
*
* @param mapper must not be {@literal null}.
*/
public ProjectingJackson2HttpMessageConverter(ObjectMapper mapper) {
super(mapper);
this.projectionFactory = initProjectionFactory(mapper);
}
/**
* Creates a new {@link SpelAwareProxyProjectionFactory} with the {@link JsonProjectingMethodInterceptorFactory}
* registered for the given {@link ObjectMapper}.
*
* @param mapper must not be {@literal null}.
* @return
*/
private static SpelAwareProxyProjectionFactory initProjectionFactory(ObjectMapper mapper) {
Assert.notNull(mapper, "ObjectMapper must not be null!");
SpelAwareProxyProjectionFactory projectionFactory = new SpelAwareProxyProjectionFactory();
projectionFactory
.registerMethodInvokerFactory(new JsonProjectingMethodInterceptorFactory(new JacksonMappingProvider(mapper)));
return projectionFactory;
}
/*
* (non-Javadoc)
* @see org.springframework.beans.factory.BeanClassLoaderAware#setBeanClassLoader(java.lang.ClassLoader)
*/
@Override
public void setBeanClassLoader(ClassLoader classLoader) {
projectionFactory.setBeanClassLoader(classLoader);
}
/*
* (non-Javadoc)
* @see org.springframework.beans.factory.BeanFactoryAware#setBeanFactory(org.springframework.beans.factory.BeanFactory)
*/
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
projectionFactory.setBeanFactory(beanFactory);
}
/*
* (non-Javadoc)
* @see org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter#canRead(java.lang.reflect.Type, java.lang.Class, org.springframework.http.MediaType)
*/
@Override
public boolean canRead(Type type, Class<?> contextClass, MediaType mediaType) {
Class<?> rawType = ResolvableType.forType(type).getRawClass();
Boolean result = supportedTypesCache.get(rawType);
if (result != null) {
return result;
}
result = canRead(mediaType) && rawType.isInterface()
&& AnnotationUtils.findAnnotation(rawType, ProjectedPayload.class) != null;
supportedTypesCache.put(rawType, result);
return result;
}
/*
* (non-Javadoc)
* @see org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter#read(java.lang.reflect.Type, java.lang.Class, org.springframework.http.HttpInputMessage)
*/
@Override
public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException {
return projectionFactory.createProjection(ResolvableType.forType(type).getRawClass(), inputMessage.getBody());
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2016 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.
@@ -28,13 +28,18 @@ import org.springframework.data.geo.format.DistanceFormatter;
import org.springframework.data.geo.format.PointFormatter;
import org.springframework.data.repository.support.DomainClassConverter;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.data.web.ProjectingJackson2HttpMessageConverter;
import org.springframework.data.web.ProxyingHandlerMethodArgumentResolver;
import org.springframework.data.web.SortHandlerMethodArgumentResolver;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.support.FormattingConversionService;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.util.ClassUtils;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Configuration class to register {@link PageableHandlerMethodArgumentResolver},
* {@link SortHandlerMethodArgumentResolver} and {@link DomainClassConverter}.
@@ -100,8 +105,25 @@ public class SpringDataWebConfiguration extends WebMvcConfigurerAdapter {
ProxyingHandlerMethodArgumentResolver resolver = new ProxyingHandlerMethodArgumentResolver(
conversionService.getObject());
resolver.setBeanFactory(context);
resolver.setResourceLoader(context);
resolver.setBeanClassLoader(context.getClassLoader());
argumentResolvers.add(resolver);
}
/*
* (non-Javadoc)
* @see org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter#extendMessageConverters(java.util.List)
*/
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
if (ClassUtils.isPresent("com.jayway.jsonpath.DocumentContext", context.getClassLoader())) {
ProjectingJackson2HttpMessageConverter converter = new ProjectingJackson2HttpMessageConverter(new ObjectMapper());
converter.setBeanClassLoader(context.getClassLoader());
converter.setBeanFactory(context);
converters.add(0, converter);
}
}
}