language
stringclasses
1 value
owner
stringlengths
2
15
repo
stringlengths
2
21
sha
stringlengths
45
45
message
stringlengths
7
36.3k
path
stringlengths
1
199
patch
stringlengths
15
102k
is_multipart
bool
2 classes
Other
spring-projects
spring-framework
b50bb5071ac353e77e9d38c72f888de3add923b2.json
Address various ExtendedBeanInfo bugs - Ensure that ExtendedBeanInfoTests succeeds when building under JDK 7 - Improve handling of read and write method registration where generic interfaces are involved, per SPR-9453 - Add repro test for SPR-9702, in which EBI fails to register an indexed read method under certain circumstances Issue: SPR-9702, SPR-9414, SPR-9453
spring-beans/src/main/java/org/springframework/beans/ExtendedBeanInfo.java
@@ -34,6 +34,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.springframework.core.BridgeMethodResolver; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; @@ -77,7 +78,7 @@ public ExtendedBeanInfo(BeanInfo delegate) throws IntrospectionException { ALL_METHODS: for (MethodDescriptor md : delegate.getMethodDescriptors()) { - Method method = md.getMethod(); + Method method = resolveMethod(md.getMethod()); // bypass non-getter java.lang.Class methods for efficiency if (ReflectionUtils.isObjectMethod(method) && !method.getName().startsWith("get")) { @@ -91,8 +92,8 @@ public ExtendedBeanInfo(BeanInfo delegate) throws IntrospectionException { continue ALL_METHODS; } for (PropertyDescriptor pd : delegate.getPropertyDescriptors()) { - Method readMethod = pd.getReadMethod(); - Method writeMethod = pd.getWriteMethod(); + Method readMethod = readMethodFor(pd); + Method writeMethod = writeMethodFor(pd); // has the setter already been found by the wrapped BeanInfo? if (writeMethod != null && writeMethod.getName().equals(method.getName())) { @@ -126,10 +127,10 @@ public ExtendedBeanInfo(BeanInfo delegate) throws IntrospectionException { continue DELEGATE_PD; } IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd; - Method readMethod = ipd.getReadMethod(); - Method writeMethod = ipd.getWriteMethod(); - Method indexedReadMethod = ipd.getIndexedReadMethod(); - Method indexedWriteMethod = ipd.getIndexedWriteMethod(); + Method readMethod = readMethodFor(ipd); + Method writeMethod = writeMethodFor(ipd); + Method indexedReadMethod = indexedReadMethodFor(ipd); + Method indexedWriteMethod = indexedWriteMethodFor(ipd); // has the setter already been found by the wrapped BeanInfo? if (!(indexedWriteMethod != null && indexedWriteMethod.getName().equals(method.getName()))) { @@ -149,33 +150,54 @@ public ExtendedBeanInfo(BeanInfo delegate) throws IntrospectionException { for (PropertyDescriptor pd : delegate.getPropertyDescriptors()) { // have we already copied this read method to a property descriptor locally? String propertyName = pd.getName(); - Method readMethod = pd.getReadMethod(); + Method readMethod = readMethodFor(pd); Method mostSpecificReadMethod = ClassUtils.getMostSpecificMethod(readMethod, method.getDeclaringClass()); for (PropertyDescriptor existingPD : this.propertyDescriptors) { if (method.equals(mostSpecificReadMethod) && existingPD.getName().equals(propertyName)) { - if (existingPD.getReadMethod() == null) { + if (readMethodFor(existingPD) == null) { // no -> add it now - this.addOrUpdatePropertyDescriptor(pd, propertyName, method, pd.getWriteMethod()); + this.addOrUpdatePropertyDescriptor(pd, propertyName, method, writeMethodFor(pd)); } // yes -> do not add a duplicate continue ALL_METHODS; } } if (method.equals(mostSpecificReadMethod) - || (pd instanceof IndexedPropertyDescriptor && method.equals(((IndexedPropertyDescriptor) pd).getIndexedReadMethod()))) { + || (pd instanceof IndexedPropertyDescriptor && method.equals(indexedReadMethodFor((IndexedPropertyDescriptor) pd)))) { // yes -> copy it, including corresponding setter method (if any -- may be null) if (pd instanceof IndexedPropertyDescriptor) { - this.addOrUpdatePropertyDescriptor(pd, propertyName, readMethod, pd.getWriteMethod(), ((IndexedPropertyDescriptor)pd).getIndexedReadMethod(), ((IndexedPropertyDescriptor)pd).getIndexedWriteMethod()); + this.addOrUpdatePropertyDescriptor(pd, propertyName, readMethod, writeMethodFor(pd), indexedReadMethodFor((IndexedPropertyDescriptor)pd), indexedWriteMethodFor((IndexedPropertyDescriptor)pd)); } else { - this.addOrUpdatePropertyDescriptor(pd, propertyName, readMethod, pd.getWriteMethod()); + this.addOrUpdatePropertyDescriptor(pd, propertyName, readMethod, writeMethodFor(pd)); } continue ALL_METHODS; } } } } + + private static Method resolveMethod(Method method) { + return BridgeMethodResolver.findBridgedMethod(method); + } + + private static Method readMethodFor(PropertyDescriptor pd) { + return resolveMethod(pd.getReadMethod()); + } + + private static Method writeMethodFor(PropertyDescriptor pd) { + return resolveMethod(pd.getWriteMethod()); + } + + private static Method indexedReadMethodFor(IndexedPropertyDescriptor ipd) { + return resolveMethod(ipd.getIndexedReadMethod()); + } + + private static Method indexedWriteMethodFor(IndexedPropertyDescriptor ipd) { + return resolveMethod(ipd.getIndexedWriteMethod()); + } + private void addOrUpdatePropertyDescriptor(PropertyDescriptor pd, String propertyName, Method readMethod, Method writeMethod) throws IntrospectionException { addOrUpdatePropertyDescriptor(pd, propertyName, readMethod, writeMethod, null, null); } @@ -186,9 +208,9 @@ private void addOrUpdatePropertyDescriptor(PropertyDescriptor pd, String propert for (PropertyDescriptor existingPD : this.propertyDescriptors) { if (existingPD.getName().equals(propertyName)) { // is there already a descriptor that captures this read method or its corresponding write method? - if (existingPD.getReadMethod() != null) { - if (readMethod != null && existingPD.getReadMethod().getReturnType() != readMethod.getReturnType() - || writeMethod != null && existingPD.getReadMethod().getReturnType() != writeMethod.getParameterTypes()[0]) { + if (readMethodFor(existingPD) != null) { + if (readMethod != null && readMethodFor(existingPD).getReturnType() != readMethod.getReturnType() + || writeMethod != null && readMethodFor(existingPD).getReturnType() != writeMethod.getParameterTypes()[0]) { // no -> add a new descriptor for it below break; } @@ -205,9 +227,9 @@ private void addOrUpdatePropertyDescriptor(PropertyDescriptor pd, String propert } // is there already a descriptor that captures this write method or its corresponding read method? - if (existingPD.getWriteMethod() != null) { - if (readMethod != null && existingPD.getWriteMethod().getParameterTypes()[0] != readMethod.getReturnType() - || writeMethod != null && existingPD.getWriteMethod().getParameterTypes()[0] != writeMethod.getParameterTypes()[0]) { + if (writeMethodFor(existingPD) != null) { + if (readMethod != null && writeMethodFor(existingPD).getParameterTypes()[0] != readMethod.getReturnType() + || writeMethod != null && writeMethodFor(existingPD).getParameterTypes()[0] != writeMethod.getParameterTypes()[0]) { // no -> add a new descriptor for it below break; } @@ -224,9 +246,9 @@ private void addOrUpdatePropertyDescriptor(PropertyDescriptor pd, String propert IndexedPropertyDescriptor existingIPD = (IndexedPropertyDescriptor) existingPD; // is there already a descriptor that captures this indexed read method or its corresponding indexed write method? - if (existingIPD.getIndexedReadMethod() != null) { - if (indexedReadMethod != null && existingIPD.getIndexedReadMethod().getReturnType() != indexedReadMethod.getReturnType() - || indexedWriteMethod != null && existingIPD.getIndexedReadMethod().getReturnType() != indexedWriteMethod.getParameterTypes()[1]) { + if (indexedReadMethodFor(existingIPD) != null) { + if (indexedReadMethod != null && indexedReadMethodFor(existingIPD).getReturnType() != indexedReadMethod.getReturnType() + || indexedWriteMethod != null && indexedReadMethodFor(existingIPD).getReturnType() != indexedWriteMethod.getParameterTypes()[1]) { // no -> add a new descriptor for it below break; } @@ -243,9 +265,9 @@ private void addOrUpdatePropertyDescriptor(PropertyDescriptor pd, String propert } // is there already a descriptor that captures this indexed write method or its corresponding indexed read method? - if (existingIPD.getIndexedWriteMethod() != null) { - if (indexedReadMethod != null && existingIPD.getIndexedWriteMethod().getParameterTypes()[1] != indexedReadMethod.getReturnType() - || indexedWriteMethod != null && existingIPD.getIndexedWriteMethod().getParameterTypes()[1] != indexedWriteMethod.getParameterTypes()[1]) { + if (indexedWriteMethodFor(existingIPD) != null) { + if (indexedReadMethod != null && indexedWriteMethodFor(existingIPD).getParameterTypes()[1] != indexedReadMethod.getReturnType() + || indexedWriteMethod != null && indexedWriteMethodFor(existingIPD).getParameterTypes()[1] != indexedWriteMethod.getParameterTypes()[1]) { // no -> add a new descriptor for it below break; }
true
Other
spring-projects
spring-framework
b50bb5071ac353e77e9d38c72f888de3add923b2.json
Address various ExtendedBeanInfo bugs - Ensure that ExtendedBeanInfoTests succeeds when building under JDK 7 - Improve handling of read and write method registration where generic interfaces are involved, per SPR-9453 - Add repro test for SPR-9702, in which EBI fails to register an indexed read method under certain circumstances Issue: SPR-9702, SPR-9414, SPR-9453
spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoTests.java
@@ -16,29 +16,30 @@ package org.springframework.beans; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.lessThan; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.beans.BeanInfo; import java.beans.IndexedPropertyDescriptor; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; + import java.lang.reflect.Method; +import org.junit.Ignore; import org.junit.Test; + import org.springframework.beans.ExtendedBeanInfo.PropertyDescriptorComparator; import org.springframework.core.JdkVersion; import org.springframework.util.ClassUtils; import test.beans.TestBean; +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.lessThan; + /** * Unit tests for {@link ExtendedBeanInfo}. * @@ -149,7 +150,7 @@ public void standardReadMethodsAndOverloadedNonStandardWriteMethods() throws Exc ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi); assertThat(hasReadMethodForProperty(bi, "foo"), is(true)); - assertThat(hasWriteMethodForProperty(bi, "foo"), is(true)); + assertThat(hasWriteMethodForProperty(bi, "foo"), is(trueUntilJdk17())); assertThat(hasReadMethodForProperty(ebi, "foo"), is(true)); assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true)); @@ -163,6 +164,50 @@ public void standardReadMethodsAndOverloadedNonStandardWriteMethods() throws Exc fail("never matched write method"); } + @Test + public void cornerSpr9414() throws IntrospectionException { + @SuppressWarnings("unused") class Parent { + public Number getProperty1() { + return 1; + } + } + class Child extends Parent { + @Override + public Integer getProperty1() { + return 2; + } + } + { // always passes + ExtendedBeanInfo bi = new ExtendedBeanInfo(Introspector.getBeanInfo(Parent.class)); + assertThat(hasReadMethodForProperty(bi, "property1"), is(true)); + } + { // failed prior to fix for SPR-9414 + ExtendedBeanInfo bi = new ExtendedBeanInfo(Introspector.getBeanInfo(Child.class)); + assertThat(hasReadMethodForProperty(bi, "property1"), is(true)); + } + } + + interface Spr9453<T> { + T getProp(); + } + + @Test + public void cornerSpr9453() throws IntrospectionException { + final class Bean implements Spr9453<Class<?>> { + public Class<?> getProp() { + return null; + } + } + { // always passes + BeanInfo info = Introspector.getBeanInfo(Bean.class); + assertThat(info.getPropertyDescriptors().length, equalTo(2)); + } + { // failed prior to fix for SPR-9453 + BeanInfo info = new ExtendedBeanInfo(Introspector.getBeanInfo(Bean.class)); + assertThat(info.getPropertyDescriptors().length, equalTo(2)); + } + } + @Test public void standardReadMethodInSuperclassAndNonStandardWriteMethodInSubclass() throws Exception { @SuppressWarnings("unused") class B { @@ -471,6 +516,53 @@ class C { assertThat(hasIndexedWriteMethodForProperty(ebi, "foos"), is(true)); } + @Ignore // see comments at SPR-9702 + @Test + public void cornerSpr9702() throws IntrospectionException { + { // baseline with standard write method + @SuppressWarnings("unused") + class C { + // VOID-RETURNING, NON-INDEXED write method + public void setFoos(String[] foos) { } + // indexed read method + public String getFoos(int i) { return null; } + } + + BeanInfo bi = Introspector.getBeanInfo(C.class); + assertThat(hasReadMethodForProperty(bi, "foos"), is(false)); + assertThat(hasIndexedReadMethodForProperty(bi, "foos"), is(true)); + assertThat(hasWriteMethodForProperty(bi, "foos"), is(true)); + assertThat(hasIndexedWriteMethodForProperty(bi, "foos"), is(false)); + + BeanInfo ebi = Introspector.getBeanInfo(C.class); + assertThat(hasReadMethodForProperty(ebi, "foos"), is(false)); + assertThat(hasIndexedReadMethodForProperty(ebi, "foos"), is(true)); + assertThat(hasWriteMethodForProperty(ebi, "foos"), is(true)); + assertThat(hasIndexedWriteMethodForProperty(ebi, "foos"), is(false)); + } + { // variant with non-standard write method + @SuppressWarnings("unused") + class C { + // NON-VOID-RETURNING, NON-INDEXED write method + public C setFoos(String[] foos) { return this; } + // indexed read method + public String getFoos(int i) { return null; } + } + + BeanInfo bi = Introspector.getBeanInfo(C.class); + assertThat(hasReadMethodForProperty(bi, "foos"), is(false)); + assertThat(hasIndexedReadMethodForProperty(bi, "foos"), is(true)); + assertThat(hasWriteMethodForProperty(bi, "foos"), is(false)); + assertThat(hasIndexedWriteMethodForProperty(bi, "foos"), is(false)); + + BeanInfo ebi = new ExtendedBeanInfo(Introspector.getBeanInfo(C.class)); + assertThat(hasReadMethodForProperty(ebi, "foos"), is(false)); + assertThat(hasIndexedReadMethodForProperty(ebi, "foos"), is(true)); + assertThat(hasWriteMethodForProperty(ebi, "foos"), is(true)); + assertThat(hasIndexedWriteMethodForProperty(ebi, "foos"), is(false)); + } + } + @Test public void subclassWriteMethodWithCovariantReturnType() throws IntrospectionException { @SuppressWarnings("unused") class B {
true
Other
spring-projects
spring-framework
70b0b97b54d545118696b6fe279b57044f739e92.json
Fix cyclical package dependency
spring-web/src/main/java/org/springframework/web/method/ControllerAdviceBean.java
@@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.web.bind.support; +package org.springframework.web.method; import java.util.ArrayList; import java.util.List; @@ -29,7 +29,11 @@ /** * Encapsulates information about an {@linkplain ControllerAdvice @ControllerAdvice} - * bean without requiring the bean to be instantiated. + * Spring-managed bean without necessarily requiring it to be instantiated. + * + * <p>The {@link #findAnnotatedBeans(ApplicationContext)} method can be used to discover + * such beans. However, an {@code ControllerAdviceBean} may be created from + * any object, including ones without an {@code @ControllerAdvice}. * * @author Rossen Stoyanchev * @since 3.2 @@ -55,7 +59,12 @@ public ControllerAdviceBean(String beanName, BeanFactory beanFactory) { "Bean factory [" + beanFactory + "] does not contain bean " + "with name [" + beanName + "]"); this.bean = beanName; this.beanFactory = beanFactory; - this.order = initOrder(this.beanFactory.getType(beanName)); + this.order = initOrderFromBeanType(this.beanFactory.getType(beanName)); + } + + private static int initOrderFromBeanType(Class<?> beanType) { + Order annot = AnnotationUtils.findAnnotation(beanType, Order.class); + return (annot != null) ? annot.value() : Ordered.LOWEST_PRECEDENCE; } /** @@ -65,21 +74,20 @@ public ControllerAdviceBean(String beanName, BeanFactory beanFactory) { public ControllerAdviceBean(Object bean) { Assert.notNull(bean, "'bean' must not be null"); this.bean = bean; - this.order = initOrder(bean.getClass()); + this.order = initOrderFromBean(bean); this.beanFactory = null; } - private static int initOrder(Class<?> beanType) { - Order orderAnnot = AnnotationUtils.findAnnotation(beanType, Order.class); - return (orderAnnot != null) ? orderAnnot.value() : Ordered.LOWEST_PRECEDENCE; + private static int initOrderFromBean(Object bean) { + return (bean instanceof Ordered) ? ((Ordered) bean).getOrder() : initOrderFromBeanType(bean.getClass()); } /** * Find the names of beans annotated with * {@linkplain ControllerAdvice @ControllerAdvice} in the given * ApplicationContext and wrap them as {@code ControllerAdviceBean} instances. */ - public static List<ControllerAdviceBean> findBeans(ApplicationContext applicationContext) { + public static List<ControllerAdviceBean> findAnnotatedBeans(ApplicationContext applicationContext) { List<ControllerAdviceBean> beans = new ArrayList<ControllerAdviceBean>(); for (String name : applicationContext.getBeanDefinitionNames()) { if (applicationContext.findAnnotationOnBean(name, ControllerAdvice.class) != null) { @@ -90,12 +98,9 @@ public static List<ControllerAdviceBean> findBeans(ApplicationContext applicatio } /** - * Return a bean instance if necessary resolving the bean name through the BeanFactory. + * Returns the order value extracted from the {@link ControllerAdvice} + * annotation or {@link Ordered#LOWEST_PRECEDENCE} otherwise. */ - public Object resolveBean() { - return (this.bean instanceof String) ? this.beanFactory.getBean((String) this.bean) : this.bean; - } - public int getOrder() { return this.order; } @@ -111,6 +116,13 @@ public Class<?> getBeanType() { return ClassUtils.getUserClass(clazz); } + /** + * Return a bean instance if necessary resolving the bean name through the BeanFactory. + */ + public Object resolveBean() { + return (this.bean instanceof String) ? this.beanFactory.getBean((String) this.bean) : this.bean; + } + @Override public boolean equals(Object o) { if (this == o) {
true
Other
spring-projects
spring-framework
70b0b97b54d545118696b6fe279b57044f739e92.json
Fix cyclical package dependency
spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java
@@ -29,13 +29,15 @@ import org.springframework.util.ClassUtils; /** - * Encapsulates information about a bean method consisting of a {@linkplain #getMethod() method} and a - * {@linkplain #getBean() bean}. Provides convenient access to method parameters, the method return value, - * method annotations. + * Encapsulates information about a bean method consisting of a + * {@linkplain #getMethod() method} and a {@linkplain #getBean() bean}. Provides + * convenient access to method parameters, the method return value, method + * annotations. * - * <p>The class may be created with a bean instance or with a bean name (e.g. lazy bean, prototype bean). - * Use {@link #createWithResolvedBean()} to obtain an {@link HandlerMethod} instance with a bean instance - * initialized through the bean factory. + * <p>The class may be created with a bean instance or with a bean name (e.g. lazy + * bean, prototype bean). Use {@link #createWithResolvedBean()} to obtain an + * {@link HandlerMethod} instance with a bean instance initialized through the + * bean factory. * * @author Arjen Poutsma * @author Rossen Stoyanchev
true
Other
spring-projects
spring-framework
70b0b97b54d545118696b6fe279b57044f739e92.json
Fix cyclical package dependency
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolver.java
@@ -41,8 +41,8 @@ import org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter; import org.springframework.web.accept.ContentNegotiationManager; import org.springframework.web.bind.annotation.ControllerAdvice; -import org.springframework.web.bind.support.ControllerAdviceBean; import org.springframework.web.context.request.ServletWebRequest; +import org.springframework.web.method.ControllerAdviceBean; import org.springframework.web.method.HandlerMethod; import org.springframework.web.method.annotation.ExceptionHandlerMethodResolver; import org.springframework.web.method.annotation.MapMethodProcessor; @@ -285,7 +285,7 @@ private void initExceptionHandlerAdviceCache() { logger.debug("Looking for exception mappings: " + getApplicationContext()); } - List<ControllerAdviceBean> beans = ControllerAdviceBean.findBeans(getApplicationContext()); + List<ControllerAdviceBean> beans = ControllerAdviceBean.findAnnotatedBeans(getApplicationContext()); Collections.sort(beans, new OrderComparator()); for (ControllerAdviceBean bean : beans) {
true
Other
spring-projects
spring-framework
70b0b97b54d545118696b6fe279b57044f739e92.json
Fix cyclical package dependency
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapter.java
@@ -54,7 +54,6 @@ import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.support.ControllerAdviceBean; import org.springframework.web.bind.support.DefaultDataBinderFactory; import org.springframework.web.bind.support.DefaultSessionAttributeStore; import org.springframework.web.bind.support.SessionAttributeStore; @@ -67,6 +66,7 @@ import org.springframework.web.context.request.async.AsyncWebRequest; import org.springframework.web.context.request.async.AsyncWebUtils; import org.springframework.web.context.request.async.WebAsyncManager; +import org.springframework.web.method.ControllerAdviceBean; import org.springframework.web.method.HandlerMethod; import org.springframework.web.method.HandlerMethodSelector; import org.springframework.web.method.annotation.ErrorsMethodArgumentResolver; @@ -592,7 +592,7 @@ private void initControllerAdviceCache() { logger.debug("Looking for controller advice: " + getApplicationContext()); } - List<ControllerAdviceBean> beans = ControllerAdviceBean.findBeans(getApplicationContext()); + List<ControllerAdviceBean> beans = ControllerAdviceBean.findAnnotatedBeans(getApplicationContext()); Collections.sort(beans, new OrderComparator()); for (ControllerAdviceBean bean : beans) {
true
Other
spring-projects
spring-framework
cb564b287fe36bf5d6840a674d4486f2d0fc91fd.json
Provide support for filter registrations The AbstractDispatcherServletInitializer now provides support for the registration of filters to be mapped to the DispatcherServlet. It also sets the asyncSupported flag by default on the DispatcherServlet and all registered filters. Issue: SPR-9696
spring-webmvc/src/main/java/org/springframework/web/servlet/support/AbstractDispatcherServletInitializer.java
@@ -16,11 +16,19 @@ package org.springframework.web.servlet.support; +import java.util.EnumSet; + +import javax.servlet.DispatcherType; +import javax.servlet.Filter; +import javax.servlet.FilterRegistration; +import javax.servlet.FilterRegistration.Dynamic; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; +import org.springframework.core.Conventions; import org.springframework.util.Assert; +import org.springframework.util.ObjectUtils; import org.springframework.web.context.AbstractContextLoaderInitializer; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; @@ -44,6 +52,7 @@ * * @author Arjen Poutsma * @author Chris Beams + * @author Rossen Stoyanchev * @since 3.2 */ public abstract class AbstractDispatcherServletInitializer @@ -87,6 +96,14 @@ protected void registerDispatcherServlet(ServletContext servletContext) { servletContext.addServlet(servletName, dispatcherServlet); registration.setLoadOnStartup(1); registration.addMapping(getServletMappings()); + registration.setAsyncSupported(isAsyncSupported()); + + Filter[] filters = getServletFilters(); + if (!ObjectUtils.isEmpty(filters)) { + for (Filter filter : filters) { + registerServletFilter(servletContext, filter); + } + } this.customizeRegistration(registration); } @@ -111,12 +128,63 @@ protected String getServletName() { protected abstract WebApplicationContext createServletApplicationContext(); /** - * Specify the servlet mapping(s) for the {@code DispatcherServlet}, e.g. '/', '/app', - * etc. + * Specify the servlet mapping(s) for the {@code DispatcherServlet}, e.g. '/', '/app', etc. * @see #registerDispatcherServlet(ServletContext) */ protected abstract String[] getServletMappings(); + /** + * Specify filters to add and also map to the {@code DispatcherServlet}. + * + * @return an array of filters or {@code null} + * @see #registerServletFilters(ServletContext, String, Filter...) + */ + protected Filter[] getServletFilters() { + return null; + } + + /** + * Add the given filter to the ServletContext and map it to the + * {@code DispatcherServlet} as follows: + * <ul> + * <li>a default filter name is chosen based on its concrete type + * <li>the {@code asyncSupported} flag is set depending on the + * return value of {@link #isAsyncSupported() asyncSupported} + * <li>a filter mapping is created with dispatcher types {@code REQUEST}, + * {@code FORWARD}, {@code INCLUDE}, and conditionally {@code ASYNC} depending + * on the return value of {@link #isAsyncSupported() asyncSupported} + * </ul> + * <p>If the above defaults are not suitable or insufficient, register + * filters directly with the {@code ServletContext}. + * + * @param servletContext the servlet context to register filters with + * @param servletName the name of the servlet to map the filters to + * @param filters the filters to be registered + * @return the filter registration + */ + protected FilterRegistration.Dynamic registerServletFilter(ServletContext servletContext, Filter filter) { + String filterName = Conventions.getVariableName(filter); + Dynamic registration = servletContext.addFilter(filterName, filter); + registration.setAsyncSupported(isAsyncSupported()); + registration.addMappingForServletNames(getDispatcherTypes(), false, getServletName()); + return registration; + } + + private EnumSet<DispatcherType> getDispatcherTypes() { + return isAsyncSupported() ? + EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.ASYNC) : + EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE); + } + + /** + * A single place to control the {@code asyncSupported} flag for the + * {@code DispatcherServlet} and all filters added via {@link #getServletFilters()}. + * <p>The default value is "true". + */ + protected boolean isAsyncSupported() { + return true; + } + /** * Optionally perform further registration customization once * {@link #registerDispatcherServlet(ServletContext)} has completed.
true
Other
spring-projects
spring-framework
cb564b287fe36bf5d6840a674d4486f2d0fc91fd.json
Provide support for filter registrations The AbstractDispatcherServletInitializer now provides support for the registration of filters to be mapped to the DispatcherServlet. It also sets the asyncSupported flag by default on the DispatcherServlet and all registered filters. Issue: SPR-9696
spring-webmvc/src/test/java/org/springframework/web/servlet/support/AnnotationConfigDispatcherServletInitializerTests.java
@@ -16,26 +16,33 @@ package org.springframework.web.servlet.support; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + import java.util.Collections; +import java.util.EnumSet; import java.util.LinkedHashMap; import java.util.Map; +import javax.servlet.DispatcherType; +import javax.servlet.Filter; +import javax.servlet.FilterRegistration.Dynamic; import javax.servlet.Servlet; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import org.junit.Before; import org.junit.Test; - import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.mock.web.MockServletContext; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.filter.HiddenHttpMethodFilter; import org.springframework.web.servlet.DispatcherServlet; -import static org.junit.Assert.*; - /** * Test case for {@link AbstractAnnotationConfigDispatcherServletInitializer}. * @@ -45,6 +52,8 @@ public class AnnotationConfigDispatcherServletInitializerTests { private static final String SERVLET_NAME = "myservlet"; + private static final String FILTER_NAME = "hiddenHttpMethodFilter"; + private static final String ROLE_NAME = "role"; private static final String SERVLET_MAPPING = "/myservlet"; @@ -55,14 +64,21 @@ public class AnnotationConfigDispatcherServletInitializerTests { private Map<String, Servlet> servlets; - private Map<String, MockDynamic> registrations; + private Map<String, MockServletRegistration> servletRegistrations; + + private Map<String, Filter> filters; + + private Map<String, MockFilterRegistration> filterRegistrations; + @Before public void setUp() throws Exception { servletContext = new MyMockServletContext(); initializer = new MyAnnotationConfigDispatcherServletInitializer(); - servlets = new LinkedHashMap<String, Servlet>(2); - registrations = new LinkedHashMap<String, MockDynamic>(2); + servlets = new LinkedHashMap<String, Servlet>(1); + servletRegistrations = new LinkedHashMap<String, MockServletRegistration>(1); + filters = new LinkedHashMap<String, Filter>(1); + filterRegistrations = new LinkedHashMap<String, MockFilterRegistration>(); } @Test @@ -73,29 +89,82 @@ public void register() throws ServletException { assertNotNull(servlets.get(SERVLET_NAME)); DispatcherServlet servlet = (DispatcherServlet) servlets.get(SERVLET_NAME); - WebApplicationContext servletContext = servlet.getWebApplicationContext(); - ((AnnotationConfigWebApplicationContext) servletContext).refresh(); + WebApplicationContext dispatcherServletContext = servlet.getWebApplicationContext(); + ((AnnotationConfigWebApplicationContext) dispatcherServletContext).refresh(); + + assertTrue(dispatcherServletContext.containsBean("bean")); + assertTrue(dispatcherServletContext.getBean("bean") instanceof MyBean); + + assertEquals(1, servletRegistrations.size()); + assertNotNull(servletRegistrations.get(SERVLET_NAME)); + + MockServletRegistration servletRegistration = servletRegistrations.get(SERVLET_NAME); + + assertEquals(Collections.singleton(SERVLET_MAPPING), servletRegistration.getMappings()); + assertEquals(1, servletRegistration.getLoadOnStartup()); + assertEquals(ROLE_NAME, servletRegistration.getRunAsRole()); + assertTrue(servletRegistration.isAsyncSupported()); + + assertEquals(1, filterRegistrations.size()); + assertNotNull(filterRegistrations.get(FILTER_NAME)); + + MockFilterRegistration filterRegistration = filterRegistrations.get(FILTER_NAME); + + assertTrue(filterRegistration.isAsyncSupported()); + assertEquals(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.ASYNC), + filterRegistration.getMappings().get(SERVLET_NAME)); + } + + @Test + public void asyncSupportedFalse() throws ServletException { + initializer = new MyAnnotationConfigDispatcherServletInitializer() { + @Override + protected boolean isAsyncSupported() { + return false; + } + }; + + initializer.onStartup(servletContext); + + MockServletRegistration servletRegistration = servletRegistrations.get(SERVLET_NAME); + assertFalse(servletRegistration.isAsyncSupported()); - assertTrue(servletContext.containsBean("bean")); - assertTrue(servletContext.getBean("bean") instanceof MyBean); + MockFilterRegistration filterRegistration = filterRegistrations.get(FILTER_NAME); + assertFalse(filterRegistration.isAsyncSupported()); + assertEquals(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE), + filterRegistration.getMappings().get(SERVLET_NAME)); + } + + @Test + public void noFilters() throws ServletException { + initializer = new MyAnnotationConfigDispatcherServletInitializer() { + @Override + protected Filter[] getServletFilters() { + return null; + } + }; - assertEquals(1, registrations.size()); - assertNotNull(registrations.get(SERVLET_NAME)); + initializer.onStartup(servletContext); - MockDynamic registration = registrations.get(SERVLET_NAME); - assertEquals(Collections.singleton(SERVLET_MAPPING), registration.getMappings()); - assertEquals(1, registration.getLoadOnStartup()); - assertEquals(ROLE_NAME, registration.getRunAsRole()); + assertEquals(0, filterRegistrations.size()); } + private class MyMockServletContext extends MockServletContext { @Override - public ServletRegistration.Dynamic addServlet(String servletName, - Servlet servlet) { + public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) { servlets.put(servletName, servlet); - MockDynamic registration = new MockDynamic(); - registrations.put(servletName, registration); + MockServletRegistration registration = new MockServletRegistration(); + servletRegistrations.put(servletName, registration); + return registration; + } + + @Override + public Dynamic addFilter(String filterName, Filter filter) { + filters.put(filterName, filter); + MockFilterRegistration registration = new MockFilterRegistration(); + filterRegistrations.put(filterName, registration); return registration; } } @@ -118,6 +187,11 @@ protected String[] getServletMappings() { return new String[]{"/myservlet"}; } + @Override + protected Filter[] getServletFilters() { + return new Filter[] { new HiddenHttpMethodFilter() }; + } + @Override protected void customizeRegistration(ServletRegistration.Dynamic registration) { registration.setRunAsRole("role");
true
Other
spring-projects
spring-framework
cb564b287fe36bf5d6840a674d4486f2d0fc91fd.json
Provide support for filter registrations The AbstractDispatcherServletInitializer now provides support for the registration of filters to be mapped to the DispatcherServlet. It also sets the asyncSupported flag by default on the DispatcherServlet and all registered filters. Issue: SPR-9696
spring-webmvc/src/test/java/org/springframework/web/servlet/support/DispatcherServletInitializerTests.java
@@ -51,14 +51,14 @@ public class DispatcherServletInitializerTests { private Map<String, Servlet> servlets; - private Map<String, MockDynamic> registrations; + private Map<String, MockServletRegistration> registrations; @Before public void setUp() throws Exception { servletContext = new MyMockServletContext(); initializer = new MyDispatcherServletInitializer(); servlets = new LinkedHashMap<String, Servlet>(2); - registrations = new LinkedHashMap<String, MockDynamic>(2); + registrations = new LinkedHashMap<String, MockServletRegistration>(2); } @Test @@ -77,7 +77,7 @@ public void register() throws ServletException { assertEquals(1, registrations.size()); assertNotNull(registrations.get(SERVLET_NAME)); - MockDynamic registration = registrations.get(SERVLET_NAME); + MockServletRegistration registration = registrations.get(SERVLET_NAME); assertEquals(Collections.singleton(SERVLET_MAPPING), registration.getMappings()); assertEquals(1, registration.getLoadOnStartup()); assertEquals(ROLE_NAME, registration.getRunAsRole()); @@ -89,7 +89,7 @@ private class MyMockServletContext extends MockServletContext { public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) { servlets.put(servletName, servlet); - MockDynamic registration = new MockDynamic(); + MockServletRegistration registration = new MockServletRegistration(); registrations.put(servletName, registration); return registration; }
true
Other
spring-projects
spring-framework
cb564b287fe36bf5d6840a674d4486f2d0fc91fd.json
Provide support for filter registrations The AbstractDispatcherServletInitializer now provides support for the registration of filters to be mapped to the DispatcherServlet. It also sets the asyncSupported flag by default on the DispatcherServlet and all registered filters. Issue: SPR-9696
spring-webmvc/src/test/java/org/springframework/web/servlet/support/MockFilterRegistration.java
@@ -0,0 +1,92 @@ +/* + * Copyright 2002-2012 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.web.servlet.support; + +import java.util.Collection; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import javax.servlet.DispatcherType; +import javax.servlet.FilterRegistration.Dynamic; + +class MockFilterRegistration implements Dynamic { + + private boolean asyncSupported = false; + + private Map<String, EnumSet<DispatcherType>> mappings = new HashMap<String, EnumSet<DispatcherType>>(); + + + public Map<String, EnumSet<DispatcherType>> getMappings() { + return this.mappings; + } + + public boolean isAsyncSupported() { + return this.asyncSupported; + } + + public void setAsyncSupported(boolean isAsyncSupported) { + this.asyncSupported = isAsyncSupported; + } + + public void addMappingForServletNames(EnumSet<DispatcherType> dispatcherTypes, + boolean isMatchAfter, String... servletNames) { + + for (String servletName : servletNames) { + this.mappings.put(servletName, dispatcherTypes); + } + } + + // Not implemented + + public String getName() { + return null; + } + + public Collection<String> getServletNameMappings() { + return null; + } + + public void addMappingForUrlPatterns(EnumSet<DispatcherType> dispatcherTypes, + boolean isMatchAfter, String... urlPatterns) { + } + + public Collection<String> getUrlPatternMappings() { + return null; + } + + public String getClassName() { + return null; + } + + public boolean setInitParameter(String name, String value) { + return false; + } + + public String getInitParameter(String name) { + return null; + } + + public Set<String> setInitParameters(Map<String, String> initParameters) { + return null; + } + + public Map<String, String> getInitParameters() { + return null; + } + +}
true
Other
spring-projects
spring-framework
cb564b287fe36bf5d6840a674d4486f2d0fc91fd.json
Provide support for filter registrations The AbstractDispatcherServletInitializer now provides support for the registration of filters to be mapped to the DispatcherServlet. It also sets the asyncSupported flag by default on the DispatcherServlet and all registered filters. Issue: SPR-9696
spring-webmvc/src/test/java/org/springframework/web/servlet/support/MockServletRegistration.java
@@ -26,14 +26,16 @@ import javax.servlet.ServletRegistration; import javax.servlet.ServletSecurityElement; -class MockDynamic implements ServletRegistration.Dynamic { +class MockServletRegistration implements ServletRegistration.Dynamic { private int loadOnStartup; private Set<String> mappings = new LinkedHashSet<String>(); private String roleName; + private boolean asyncSupported = false; + public int getLoadOnStartup() { return loadOnStartup; } @@ -59,10 +61,16 @@ public String getRunAsRole() { return roleName; } - // not implemented public void setAsyncSupported(boolean isAsyncSupported) { + this.asyncSupported = isAsyncSupported; + } + + public boolean isAsyncSupported() { + return this.asyncSupported; } + // not implemented + public String getName() { return null; }
true
Other
spring-projects
spring-framework
cb564b287fe36bf5d6840a674d4486f2d0fc91fd.json
Provide support for filter registrations The AbstractDispatcherServletInitializer now provides support for the registration of filters to be mapped to the DispatcherServlet. It also sets the asyncSupported flag by default on the DispatcherServlet and all registered filters. Issue: SPR-9696
src/reference/docbook/mvc.xml
@@ -272,7 +272,33 @@ <para>In the preceding example, all requests starting with <literal>/example</literal> will be handled by the <classname>DispatcherServlet</classname> instance named - <literal>example</literal>. This is only the first step in setting up + <literal>example</literal>. + In a Servlet 3.0+ environment, you also have the + option of configuring the Servlet container programmatically. Below is the code + based equivalent of the above <filename>web.xml</filename> example:</para> + + <programlisting language="java">public class MyWebApplicationInitializer implements WebApplicationInitializer { + + @Override + public void onStartup(ServletContext container) { + ServletRegistration.Dynamic registration = container.addServlet("dispatcher", new DispatcherServlet()); + registration.setLoadOnStartup(1); + registration.addMapping("/example/*"); + } + +}</programlisting> + + <para><interfacename>WebApplicationInitializer</interfacename> is an interface + provided by Spring MVC that ensures your code-based configuration is detected and + automatically used to initialize any Servlet 3 container. An abstract base class + implementation of this interace named + <classname>AbstractDispatcherServletInitializer</classname> makes it even easier + to register the <classname>DispatcherServlet</classname> by simply specifying + its servlet mapping. See + <link linkend="mvc-container-config">Code-based Servlet container initialization</link> + for more details.</para> + + <para>The above is only the first step in setting up Spring Web MVC. <!--The discussion below is a little vague about what you're doing, when you do it, and what you're accomplishing. --><!-- Is the next step shown in the next example screen?-->You now need to configure the various beans used by the Spring Web MVC framework (over and above the <classname>DispatcherServlet</classname> @@ -4394,6 +4420,108 @@ public class ErrorController { &lt;/filter-mapping&gt;</programlisting> </section> + <section id="mvc-container-config"> + <title>Code-based Servlet container initialization</title> + + <para>In a Servlet 3.0+ environment, you have the option of configuring the + Servlet container programmatically as an alternative or in combination with + a <filename>web.xml</filename> file. + Below is an example of registering a <classname>DispatcherServlet</classname>:</para> + + <programlisting language="java">import org.springframework.web.WebApplicationInitializer; + +public class MyWebApplicationInitializer implements WebApplicationInitializer { + + @Override + public void onStartup(ServletContext container) { + XmlWebApplicationContext appContext = new XmlWebApplicationContext(); + appContext.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml"); + + ServletRegistration.Dynamic registration = container.addServlet("dispatcher", new DispatcherServlet(appContext)); + registration.setLoadOnStartup(1); + registration.addMapping("/"); + } + +}</programlisting> + + <para><interfacename>WebApplicationInitializer</interfacename> is an interface + provided by Spring MVC that ensures your implementation is detected and + automatically used to initialize any Servlet 3 container. An abstract base + class implementation of <interfacename>WebApplicationInitializer</interfacename> named + <classname>AbstractDispatcherServletInitializer</classname> makes it even + easier to register the <classname>DispatcherServlet</classname> by simply overriding + methods to specify the servlet mapping and the location of the + <classname>DispatcherServlet</classname> configuration:</para> + + <programlisting language="java">public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { + + @Override + protected Class&lt;?&gt;[] getRootConfigClasses() { + return null; + } + + @Override + protected Class&lt;?&gt;[] getServletConfigClasses() { + return new Class[] { MyWebConfig.class }; + } + + @Override + protected String[] getServletMappings() { + return new String[] { "/" }; + } + +}</programlisting> + + <para>The above example is for an application that uses Java-based Spring + configuration. If using XML-based Spring configuration, extend directly from + <classname>AbstractDispatcherServletInitializer</classname>:</para> + + <programlisting language="java">public class MyWebAppInitializer extends AbstractDispatcherServletInitializer { + + @Override + protected WebApplicationContext createRootApplicationContext() { + return null; + } + + @Override + protected WebApplicationContext createServletApplicationContext() { + XmlWebApplicationContext cxt = new XmlWebApplicationContext(); + cxt.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml"); + return cxt; + } + + @Override + protected String[] getServletMappings() { + return new String[] { "/" }; + } + +}</programlisting> + + <para><classname>AbstractDispatcherServletInitializer</classname> also provides + a convenient way to add <interfacename>Filter</interfacename> instances + and have them automatically mapped to the <classname>DispatcherServlet</classname>:</para> + + <programlisting language="java">public class MyWebAppInitializer extends AbstractDispatcherServletInitializer { + + // ... + + @Override + protected Filter[] getServletFilters() { + return new Filter[] { new HiddenHttpMethodFilter(), new CharacterEncodingFilter() }; + } + +}</programlisting> + + <para>Each filter is added with a default name based on its concrete type and + automatically mapped to the <classname>DispatcherServlet</classname>.</para> + + <para>The <code>isAsyncSupported</code> protected method of + <classname>AbstractDispatcherServletInitializer</classname> provides + a single place to enable async support on the <classname>DispatcherServlet</classname> + and all filters mapped to it. By default this flag is set to <code>true</code>.</para> + + </section> + <section id="mvc-config"> <title>Configuring Spring MVC</title>
true
Other
spring-projects
spring-framework
cb564b287fe36bf5d6840a674d4486f2d0fc91fd.json
Provide support for filter registrations The AbstractDispatcherServletInitializer now provides support for the registration of filters to be mapped to the DispatcherServlet. It also sets the asyncSupported flag by default on the DispatcherServlet and all registered filters. Issue: SPR-9696
src/reference/docbook/new-in-3.2.xml
@@ -66,7 +66,7 @@ </section> <section id="new-in-3.2-webmvc-controller-advice"> - <title>New <interfacename>@ControllerAdvice</interfacename> annotation</title> + <title><interfacename>@ControllerAdvice</interfacename> annotation</title> <para>Classes annotated with <interfacename>@ControllerAdvice</interfacename> can contain <interfacename>@ExceptionHandler</interfacename>, @@ -88,8 +88,21 @@ For more details see <xref linkend="mvc-ann-matrix-variables"/>.</para> </section> + <section id="new-in-3.2-dispatcher-servlet-initializer"> + <title>Abstract base class for code-based Servlet 3+ container initialization</title> + + <para>An abstract base class implementation of the + <interfacename>WebApplicationInitializer</interfacename> interface is provided to + simplify code-based registration of a DispatcherServlet and filters + mapped to it. The new class is named + <classname>AbstractDispatcherServletInitializer</classname> and its + sub-class <classname>AbstractAnnotationConfigDispatcherServletInitializer</classname> + can be used with Java-based Spring configuration. + For more details see <xref linkend="mvc-container-config"/>.</para> + </section> + <section id="new-in-3.2-webmvc-exception-handler-support"> - <title>New <classname>ResponseEntityExceptionHandler</classname> class</title> + <title><classname>ResponseEntityExceptionHandler</classname> class</title> <para>A convenient base class with an <interfacename>@ExceptionHandler</interfacename>
true
Other
spring-projects
spring-framework
a49851d5ebcb5d3c65e324f279f3a8c33f4db16f.json
Add equals/hashcode to ResponseEntity Issue: SPR-9714
spring-web/src/main/java/org/springframework/http/HttpEntity.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2012 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. @@ -17,6 +17,7 @@ package org.springframework.http; import org.springframework.util.MultiValueMap; +import org.springframework.util.ObjectUtils; /** * Represents an HTTP request or response entity, consisting of headers and body. @@ -122,6 +123,24 @@ public boolean hasBody() { return (this.body != null); } + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof HttpEntity)) { + return false; + } + HttpEntity<?> otherEntity = (HttpEntity<?>) other; + return (ObjectUtils.nullSafeEquals(this.headers, otherEntity.headers) && + ObjectUtils.nullSafeEquals(this.body, otherEntity.body)); + } + + @Override + public int hashCode() { + return ObjectUtils.nullSafeHashCode(this.headers) * 29 + ObjectUtils.nullSafeHashCode(this.body); + } + @Override public String toString() { StringBuilder builder = new StringBuilder("<"); @@ -137,4 +156,5 @@ public String toString() { builder.append('>'); return builder.toString(); } + }
true
Other
spring-projects
spring-framework
a49851d5ebcb5d3c65e324f279f3a8c33f4db16f.json
Add equals/hashcode to ResponseEntity Issue: SPR-9714
spring-web/src/main/java/org/springframework/http/ResponseEntity.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2012 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. @@ -17,6 +17,7 @@ package org.springframework.http; import org.springframework.util.MultiValueMap; +import org.springframework.util.ObjectUtils; /** * Extension of {@link HttpEntity} that adds a {@link HttpStatus} status code. @@ -94,6 +95,23 @@ public HttpStatus getStatusCode() { return statusCode; } + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof ResponseEntity)) { + return false; + } + ResponseEntity<?> otherEntity = (ResponseEntity<?>) other; + return (ObjectUtils.nullSafeEquals(this.statusCode, otherEntity.statusCode) && super.equals(other)); + } + + @Override + public int hashCode() { + return super.hashCode() * 29 + ObjectUtils.nullSafeHashCode(this.statusCode); + } + @Override public String toString() { StringBuilder builder = new StringBuilder("<");
true
Other
spring-projects
spring-framework
a49851d5ebcb5d3c65e324f279f3a8c33f4db16f.json
Add equals/hashcode to ResponseEntity Issue: SPR-9714
spring-web/src/test/java/org/springframework/http/HttpEntityTests.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2012 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. @@ -34,7 +34,7 @@ public void noHeaders() { assertSame(body, entity.getBody()); assertTrue(entity.getHeaders().isEmpty()); } - + @Test public void httpHeaders() { HttpHeaders headers = new HttpHeaders(); @@ -56,7 +56,30 @@ public void multiValueMap() { assertEquals(MediaType.TEXT_PLAIN, entity.getHeaders().getContentType()); assertEquals("text/plain", entity.getHeaders().getFirst("Content-Type")); } - + + @Test + public void testEquals() { + MultiValueMap<String, String> map1 = new LinkedMultiValueMap<String, String>(); + map1.set("Content-Type", "text/plain"); + + MultiValueMap<String, String> map2 = new LinkedMultiValueMap<String, String>(); + map2.set("Content-Type", "application/json"); + + assertTrue(new HttpEntity<Object>().equals(new HttpEntity<Object>())); + assertFalse(new HttpEntity<Object>(map1).equals(new HttpEntity<Object>())); + assertFalse(new HttpEntity<Object>().equals(new HttpEntity<Object>(map2))); + + assertTrue(new HttpEntity<Object>(map1).equals(new HttpEntity<Object>(map1))); + assertFalse(new HttpEntity<Object>(map1).equals(new HttpEntity<Object>(map2))); + + assertTrue(new HttpEntity<String>(null, null).equals(new HttpEntity<String>(null, null))); + assertFalse(new HttpEntity<String>("foo", null).equals(new HttpEntity<String>(null, null))); + assertFalse(new HttpEntity<String>(null, null).equals(new HttpEntity<String>("bar", null))); + + assertTrue(new HttpEntity<String>("foo", map1).equals(new HttpEntity<String>("foo", map1))); + assertFalse(new HttpEntity<String>("foo", map1).equals(new HttpEntity<String>("bar", map1))); + } + @Test public void responseEntity() { HttpHeaders headers = new HttpHeaders();
true
Other
spring-projects
spring-framework
2201dd8c45051230ad1a5a0e895cb5951edbfb74.json
Add support for matrix variables A new @MatrixVariable annotation allows injecting matrix variables into @RequestMapping methods. The matrix variables may appear in any path segment and should be wrapped in a URI template for request mapping purposes to ensure request matching is not affected by the order or the presence/absence of such variables. The @MatrixVariable annotation has an optional "pathVar" attribute that can be used to refer to the URI template where a matrix variable is located. Previously, ";" (semicolon) delimited content was removed from the path used for request mapping purposes. To preserve backwards compatibility that continues to be the case (except for the MVC namespace and Java config) and may be changed by setting the "removeSemicolonContent" property of RequestMappingHandlerMapping to "false". Applications using the MVC namespace and Java config do not need to do anything further to extract and use matrix variables. Issue: SPR-5499, SPR-7818
spring-web/src/main/java/org/springframework/web/bind/annotation/MatrixVariable.java
@@ -0,0 +1,66 @@ +/* + * Copyright 2002-2010 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.web.bind.annotation; + +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 which indicates that a method parameter should be bound to a + * name-value pair within a path segment. Supported for {@link RequestMapping} + * annotated handler methods in Servlet environments. + * + * @author Rossen Stoyanchev + * @since 3.2 + */ +@Target(ElementType.PARAMETER) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface MatrixVariable { + + /** + * The name of the matrix variable. + */ + String value() default ""; + + /** + * The name of the URI path variable where the matrix variable is located, + * if necessary for disambiguation (e.g. a matrix variable with the same + * name present in more than one path segment). + */ + String pathVar() default ValueConstants.DEFAULT_NONE; + + /** + * Whether the matrix variable is required. + * <p>Default is <code>true</code>, leading to an exception thrown in case + * of the variable missing in the request. Switch this to <code>false</code> + * if you prefer a <code>null</value> in case of the variable missing. + * <p>Alternatively, provide a {@link #defaultValue() defaultValue}, + * which implicitly sets this flag to <code>false</code>. + */ + boolean required() default true; + + /** + * The default value to use as a fallback. Supplying a default value implicitly + * sets {@link #required()} to false. + */ + String defaultValue() default ValueConstants.DEFAULT_NONE; + +}
true
Other
spring-projects
spring-framework
2201dd8c45051230ad1a5a0e895cb5951edbfb74.json
Add support for matrix variables A new @MatrixVariable annotation allows injecting matrix variables into @RequestMapping methods. The matrix variables may appear in any path segment and should be wrapped in a URI template for request mapping purposes to ensure request matching is not affected by the order or the presence/absence of such variables. The @MatrixVariable annotation has an optional "pathVar" attribute that can be used to refer to the URI template where a matrix variable is located. Previously, ";" (semicolon) delimited content was removed from the path used for request mapping purposes. To preserve backwards compatibility that continues to be the case (except for the MVC namespace and Java config) and may be changed by setting the "removeSemicolonContent" property of RequestMappingHandlerMapping to "false". Applications using the MVC namespace and Java config do not need to do anything further to extract and use matrix variables. Issue: SPR-5499, SPR-7818
spring-web/src/main/java/org/springframework/web/bind/annotation/RequestMapping.java
@@ -82,6 +82,13 @@ * Additionally, {@code @PathVariable} can be used on a * {@link java.util.Map Map&lt;String, String&gt;} to gain access to all * URI template variables. + * <li>{@link MatrixVariable @MatrixVariable} annotated parameters (Servlet-only) + * for access to name-value pairs located in URI path segments. Matrix variables + * must be represented with a URI template variable. For example /hotels/{hotel} + * where the incoming URL may be "/hotels/42;q=1". + * Additionally, {@code @MatrixVariable} can be used on a + * {@link java.util.Map Map&lt;String, String&gt;} to gain access to all + * matrix variables in the URL or to those in a specific path variable. * <li>{@link RequestParam @RequestParam} annotated parameters for access to * specific Servlet/Portlet request parameters. Parameter values will be * converted to the declared method argument type. Additionally,
true
Other
spring-projects
spring-framework
2201dd8c45051230ad1a5a0e895cb5951edbfb74.json
Add support for matrix variables A new @MatrixVariable annotation allows injecting matrix variables into @RequestMapping methods. The matrix variables may appear in any path segment and should be wrapped in a URI template for request mapping purposes to ensure request matching is not affected by the order or the presence/absence of such variables. The @MatrixVariable annotation has an optional "pathVar" attribute that can be used to refer to the URI template where a matrix variable is located. Previously, ";" (semicolon) delimited content was removed from the path used for request mapping purposes. To preserve backwards compatibility that continues to be the case (except for the MVC namespace and Java config) and may be changed by setting the "removeSemicolonContent" property of RequestMappingHandlerMapping to "false". Applications using the MVC namespace and Java config do not need to do anything further to extract and use matrix variables. Issue: SPR-5499, SPR-7818
spring-web/src/main/java/org/springframework/web/method/annotation/AbstractNamedValueMethodArgumentResolver.java
@@ -35,19 +35,21 @@ import org.springframework.web.method.support.ModelAndViewContainer; /** - * Abstract base class for resolving method arguments from a named value. Request parameters, request headers, and - * path variables are examples of named values. Each may have a name, a required flag, and a default value. + * Abstract base class for resolving method arguments from a named value. + * Request parameters, request headers, and path variables are examples of named + * values. Each may have a name, a required flag, and a default value. * <p>Subclasses define how to do the following: * <ul> * <li>Obtain named value information for a method parameter * <li>Resolve names into argument values * <li>Handle missing argument values when argument values are required * <li>Optionally handle a resolved value * </ul> - * <p>A default value string can contain ${...} placeholders and Spring Expression Language #{...} expressions. - * For this to work a {@link ConfigurableBeanFactory} must be supplied to the class constructor. - * <p>A {@link WebDataBinder} is created to apply type conversion to the resolved argument value if it doesn't - * match the method parameter type. + * <p>A default value string can contain ${...} placeholders and Spring Expression + * Language #{...} expressions. For this to work a + * {@link ConfigurableBeanFactory} must be supplied to the class constructor. + * <p>A {@link WebDataBinder} is created to apply type conversion to the resolved + * argument value if it doesn't match the method parameter type. * * @author Arjen Poutsma * @author Rossen Stoyanchev @@ -63,8 +65,9 @@ public abstract class AbstractNamedValueMethodArgumentResolver implements Handle new ConcurrentHashMap<MethodParameter, NamedValueInfo>(); /** - * @param beanFactory a bean factory to use for resolving ${...} placeholder and #{...} SpEL expressions - * in default values, or {@code null} if default values are not expected to contain expressions + * @param beanFactory a bean factory to use for resolving ${...} placeholder + * and #{...} SpEL expressions in default values, or {@code null} if default + * values are not expected to contain expressions */ public AbstractNamedValueMethodArgumentResolver(ConfigurableBeanFactory beanFactory) { this.configurableBeanFactory = beanFactory;
true
Other
spring-projects
spring-framework
2201dd8c45051230ad1a5a0e895cb5951edbfb74.json
Add support for matrix variables A new @MatrixVariable annotation allows injecting matrix variables into @RequestMapping methods. The matrix variables may appear in any path segment and should be wrapped in a URI template for request mapping purposes to ensure request matching is not affected by the order or the presence/absence of such variables. The @MatrixVariable annotation has an optional "pathVar" attribute that can be used to refer to the URI template where a matrix variable is located. Previously, ";" (semicolon) delimited content was removed from the path used for request mapping purposes. To preserve backwards compatibility that continues to be the case (except for the MVC namespace and Java config) and may be changed by setting the "removeSemicolonContent" property of RequestMappingHandlerMapping to "false". Applications using the MVC namespace and Java config do not need to do anything further to extract and use matrix variables. Issue: SPR-5499, SPR-7818
spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.java
@@ -61,6 +61,8 @@ public class UrlPathHelper { private boolean urlDecode = true; + private boolean removeSemicolonContent = true; + private String defaultEncoding = WebUtils.DEFAULT_CHARACTER_ENCODING; @@ -92,6 +94,21 @@ public void setUrlDecode(boolean urlDecode) { this.urlDecode = urlDecode; } + /** + * Set if ";" (semicolon) content should be stripped from the request URI. + * <p>Default is "true". + */ + public void setRemoveSemicolonContent(boolean removeSemicolonContent) { + this.removeSemicolonContent = removeSemicolonContent; + } + + /** + * Whether configured to remove ";" (semicolon) content from the request URI. + */ + public boolean shouldRemoveSemicolonContent() { + return this.removeSemicolonContent; + } + /** * Set the default character encoding to use for URL decoding. * Default is ISO-8859-1, according to the Servlet spec. @@ -318,9 +335,9 @@ public String getOriginatingQueryString(HttpServletRequest request) { * Decode the supplied URI string and strips any extraneous portion after a ';'. */ private String decodeAndCleanUriString(HttpServletRequest request, String uri) { + uri = removeSemicolonContent(uri); uri = decodeRequestString(request, uri); - int semicolonIndex = uri.indexOf(';'); - return (semicolonIndex != -1 ? uri.substring(0, semicolonIndex) : uri); + return uri; } /** @@ -375,10 +392,49 @@ protected String determineEncoding(HttpServletRequest request) { } /** - * Decode the given URI path variables via {@link #decodeRequestString(HttpServletRequest, String)} - * unless {@link #setUrlDecode(boolean)} is set to {@code true} in which case - * it is assumed the URL path from which the variables were extracted is - * already decoded through a call to {@link #getLookupPathForRequest(HttpServletRequest)}. + * Remove ";" (semicolon) content from the given request URI if the + * {@linkplain #setRemoveSemicolonContent(boolean) removeSemicolonContent} + * property is set to "true". Note that "jssessionid" is always removed. + * + * @param requestUri the request URI string to remove ";" content from + * @return the updated URI string + */ + public String removeSemicolonContent(String requestUri) { + if (this.removeSemicolonContent) { + return removeSemicolonContentInternal(requestUri); + } + return removeJsessionid(requestUri); + } + + private String removeSemicolonContentInternal(String requestUri) { + int semicolonIndex = requestUri.indexOf(';'); + while (semicolonIndex != -1) { + int slashIndex = requestUri.indexOf('/', semicolonIndex); + String start = requestUri.substring(0, semicolonIndex); + requestUri = (slashIndex != -1) ? start + requestUri.substring(slashIndex) : start; + semicolonIndex = requestUri.indexOf(';', semicolonIndex); + } + return requestUri; + } + + private String removeJsessionid(String requestUri) { + int startIndex = requestUri.indexOf(";jsessionid="); + if (startIndex != -1) { + int endIndex = requestUri.indexOf(';', startIndex + 12); + String start = requestUri.substring(0, startIndex); + requestUri = (endIndex != -1) ? start + requestUri.substring(endIndex) : start; + } + return requestUri; + } + + /** + * Decode the given URI path variables via + * {@link #decodeRequestString(HttpServletRequest, String)} unless + * {@link #setUrlDecode(boolean)} is set to {@code true} in which case it is + * assumed the URL path from which the variables were extracted is already + * decoded through a call to + * {@link #getLookupPathForRequest(HttpServletRequest)}. + * * @param request current HTTP request * @param vars URI variables extracted from the URL path * @return the same Map or a new Map instance
true
Other
spring-projects
spring-framework
2201dd8c45051230ad1a5a0e895cb5951edbfb74.json
Add support for matrix variables A new @MatrixVariable annotation allows injecting matrix variables into @RequestMapping methods. The matrix variables may appear in any path segment and should be wrapped in a URI template for request mapping purposes to ensure request matching is not affected by the order or the presence/absence of such variables. The @MatrixVariable annotation has an optional "pathVar" attribute that can be used to refer to the URI template where a matrix variable is located. Previously, ";" (semicolon) delimited content was removed from the path used for request mapping purposes. To preserve backwards compatibility that continues to be the case (except for the MVC namespace and Java config) and may be changed by setting the "removeSemicolonContent" property of RequestMappingHandlerMapping to "false". Applications using the MVC namespace and Java config do not need to do anything further to extract and use matrix variables. Issue: SPR-5499, SPR-7818
spring-web/src/main/java/org/springframework/web/util/WebUtils.java
@@ -20,6 +20,7 @@ import java.io.FileNotFoundException; import java.util.Enumeration; import java.util.Map; +import java.util.StringTokenizer; import java.util.TreeMap; import javax.servlet.ServletContext; @@ -33,6 +34,8 @@ import javax.servlet.http.HttpSession; import org.springframework.util.Assert; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; import org.springframework.util.StringUtils; /** @@ -706,6 +709,7 @@ public static String extractFilenameFromUrlPath(String urlPath) { } return filename; } + /** * Extract the full URL filename (including file extension) from the given request URL path. * Correctly resolves nested paths such as "/products/view.html" as well. @@ -724,4 +728,35 @@ public static String extractFullFilenameFromUrlPath(String urlPath) { return urlPath.substring(begin, end); } + /** + * Parse the given string with matrix variables. An example string would look + * like this {@code "q1=a;q1=b;q2=a,b,c"}. The resulting map would contain + * keys {@code "q1"} and {@code "q2"} with values {@code ["a","b"]} and + * {@code ["a","b","c"]} respectively. + * + * @param matrixVariables the unparsed matrix variables string + * @return a map with matrix variable names and values, never {@code null} + */ + public static MultiValueMap<String, String> parseMatrixVariables(String matrixVariables) { + MultiValueMap<String, String> result = new LinkedMultiValueMap<String, String>(); + if (!StringUtils.hasText(matrixVariables)) { + return result; + } + StringTokenizer pairs = new StringTokenizer(matrixVariables, ";"); + while (pairs.hasMoreTokens()) { + String pair = pairs.nextToken(); + int index = pair.indexOf('='); + if (index != -1) { + String name = pair.substring(0, index); + String rawValue = pair.substring(index + 1); + for (String value : StringUtils.commaDelimitedListToStringArray(rawValue)) { + result.add(name, value); + } + } + else { + result.add(pair, ""); + } + } + return result; + } }
true
Other
spring-projects
spring-framework
2201dd8c45051230ad1a5a0e895cb5951edbfb74.json
Add support for matrix variables A new @MatrixVariable annotation allows injecting matrix variables into @RequestMapping methods. The matrix variables may appear in any path segment and should be wrapped in a URI template for request mapping purposes to ensure request matching is not affected by the order or the presence/absence of such variables. The @MatrixVariable annotation has an optional "pathVar" attribute that can be used to refer to the URI template where a matrix variable is located. Previously, ";" (semicolon) delimited content was removed from the path used for request mapping purposes. To preserve backwards compatibility that continues to be the case (except for the MVC namespace and Java config) and may be changed by setting the "removeSemicolonContent" property of RequestMappingHandlerMapping to "false". Applications using the MVC namespace and Java config do not need to do anything further to extract and use matrix variables. Issue: SPR-5499, SPR-7818
spring-web/src/test/java/org/springframework/web/util/UrlPathHelperTests.java
@@ -16,11 +16,14 @@ package org.springframework.web.util; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.io.UnsupportedEncodingException; + import org.junit.Before; import org.junit.Ignore; import org.junit.Test; - import org.springframework.mock.web.MockHttpServletRequest; /** @@ -79,10 +82,32 @@ public void getRequestUri() { } + @Test + public void getRequestRemoveSemicolonContent() throws UnsupportedEncodingException { + helper.setRemoveSemicolonContent(true); + + request.setRequestURI("/foo;f=F;o=O;o=O/bar;b=B;a=A;r=R"); + assertEquals("/foo/bar", helper.getRequestUri(request)); + } + + @Test + public void getRequestKeepSemicolonContent() throws UnsupportedEncodingException { + helper.setRemoveSemicolonContent(false); + + request.setRequestURI("/foo;a=b;c=d"); + assertEquals("/foo;a=b;c=d", helper.getRequestUri(request)); + + request.setRequestURI("/foo;jsessionid=c0o7fszeb1"); + assertEquals("jsessionid should always be removed", "/foo", helper.getRequestUri(request)); + + request.setRequestURI("/foo;a=b;jsessionid=c0o7fszeb1;c=d"); + assertEquals("jsessionid should always be removed", "/foo;a=b;c=d", helper.getRequestUri(request)); + } + // // suite of tests root requests for default servlets (SRV 11.2) on Websphere vs Tomcat and other containers // see: http://jira.springframework.org/browse/SPR-7064 - // + // // @@ -297,7 +322,7 @@ public void getOriginatingQueryString() { request.setAttribute(WebUtils.FORWARD_QUERY_STRING_ATTRIBUTE, "original=on"); assertEquals("original=on", this.helper.getOriginatingQueryString(request)); } - + @Test public void getOriginatingQueryStringNotPresent() { request.setQueryString("forward=true");
true
Other
spring-projects
spring-framework
2201dd8c45051230ad1a5a0e895cb5951edbfb74.json
Add support for matrix variables A new @MatrixVariable annotation allows injecting matrix variables into @RequestMapping methods. The matrix variables may appear in any path segment and should be wrapped in a URI template for request mapping purposes to ensure request matching is not affected by the order or the presence/absence of such variables. The @MatrixVariable annotation has an optional "pathVar" attribute that can be used to refer to the URI template where a matrix variable is located. Previously, ";" (semicolon) delimited content was removed from the path used for request mapping purposes. To preserve backwards compatibility that continues to be the case (except for the MVC namespace and Java config) and may be changed by setting the "removeSemicolonContent" property of RequestMappingHandlerMapping to "false". Applications using the MVC namespace and Java config do not need to do anything further to extract and use matrix variables. Issue: SPR-5499, SPR-7818
spring-web/src/test/java/org/springframework/web/util/WebUtilsTests.java
@@ -16,16 +16,19 @@ package org.springframework.web.util; +import java.util.Arrays; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import org.junit.Test; +import org.springframework.util.MultiValueMap; /** * @author Juergen Hoeller * @author Arjen Poutsma + * @author Rossen Stoyanchev */ public class WebUtilsTests { @@ -64,4 +67,34 @@ public void extractFullFilenameFromUrlPath() { assertEquals("view.html", WebUtils.extractFullFilenameFromUrlPath("/products/view.html?param=/path/a.do")); } + @Test + public void parseMatrixVariablesString() { + MultiValueMap<String, String> variables; + + variables = WebUtils.parseMatrixVariables(null); + assertEquals(0, variables.size()); + + variables = WebUtils.parseMatrixVariables("year"); + assertEquals(1, variables.size()); + assertEquals("", variables.getFirst("year")); + + variables = WebUtils.parseMatrixVariables("year=2012"); + assertEquals(1, variables.size()); + assertEquals("2012", variables.getFirst("year")); + + variables = WebUtils.parseMatrixVariables("year=2012;colors=red,blue,green"); + assertEquals(2, variables.size()); + assertEquals(Arrays.asList("red", "blue", "green"), variables.get("colors")); + assertEquals("2012", variables.getFirst("year")); + + variables = WebUtils.parseMatrixVariables(";year=2012;colors=red,blue,green;"); + assertEquals(2, variables.size()); + assertEquals(Arrays.asList("red", "blue", "green"), variables.get("colors")); + assertEquals("2012", variables.getFirst("year")); + + variables = WebUtils.parseMatrixVariables("colors=red;colors=blue;colors=green"); + assertEquals(1, variables.size()); + assertEquals(Arrays.asList("red", "blue", "green"), variables.get("colors")); + } + }
true
Other
spring-projects
spring-framework
2201dd8c45051230ad1a5a0e895cb5951edbfb74.json
Add support for matrix variables A new @MatrixVariable annotation allows injecting matrix variables into @RequestMapping methods. The matrix variables may appear in any path segment and should be wrapped in a URI template for request mapping purposes to ensure request matching is not affected by the order or the presence/absence of such variables. The @MatrixVariable annotation has an optional "pathVar" attribute that can be used to refer to the URI template where a matrix variable is located. Previously, ";" (semicolon) delimited content was removed from the path used for request mapping purposes. To preserve backwards compatibility that continues to be the case (except for the MVC namespace and Java config) and may be changed by setting the "removeSemicolonContent" property of RequestMappingHandlerMapping to "false". Applications using the MVC namespace and Java config do not need to do anything further to extract and use matrix variables. Issue: SPR-5499, SPR-7818
spring-webmvc/src/main/java/org/springframework/web/servlet/HandlerMapping.java
@@ -93,10 +93,21 @@ public interface HandlerMapping { String URI_TEMPLATE_VARIABLES_ATTRIBUTE = HandlerMapping.class.getName() + ".uriTemplateVariables"; /** - * Name of the {@link HttpServletRequest} attribute that contains the set of producible MediaTypes - * applicable to the mapped handler. - * <p>Note: This attribute is not required to be supported by all HandlerMapping implementations. - * Handlers should not necessarily expect this request attribute to be present in all scenarios. + * Name of the {@link HttpServletRequest} attribute that contains a map with + * URI matrix variables. + * <p>Note: This attribute is not required to be supported by all + * HandlerMapping implementations and may also not be present depending on + * whether the HandlerMapping is configured to keep matrix variable content + * in the request URI. + */ + String MATRIX_VARIABLES_ATTRIBUTE = HandlerMapping.class.getName() + ".matrixVariables"; + + /** + * Name of the {@link HttpServletRequest} attribute that contains the set of + * producible MediaTypes applicable to the mapped handler. + * <p>Note: This attribute is not required to be supported by all + * HandlerMapping implementations. Handlers should not necessarily expect + * this request attribute to be present in all scenarios. */ String PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE = HandlerMapping.class.getName() + ".producibleMediaTypes";
true
Other
spring-projects
spring-framework
2201dd8c45051230ad1a5a0e895cb5951edbfb74.json
Add support for matrix variables A new @MatrixVariable annotation allows injecting matrix variables into @RequestMapping methods. The matrix variables may appear in any path segment and should be wrapped in a URI template for request mapping purposes to ensure request matching is not affected by the order or the presence/absence of such variables. The @MatrixVariable annotation has an optional "pathVar" attribute that can be used to refer to the URI template where a matrix variable is located. Previously, ";" (semicolon) delimited content was removed from the path used for request mapping purposes. To preserve backwards compatibility that continues to be the case (except for the MVC namespace and Java config) and may be changed by setting the "removeSemicolonContent" property of RequestMappingHandlerMapping to "false". Applications using the MVC namespace and Java config do not need to do anything further to extract and use matrix variables. Issue: SPR-5499, SPR-7818
spring-webmvc/src/main/java/org/springframework/web/servlet/config/AnnotationDrivenBeanDefinitionParser.java
@@ -157,6 +157,7 @@ public BeanDefinition parse(Element element, ParserContext parserContext) { handlerMappingDef.setSource(source); handlerMappingDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); handlerMappingDef.getPropertyValues().add("order", 0); + handlerMappingDef.getPropertyValues().add("removeSemicolonContent", false); handlerMappingDef.getPropertyValues().add("contentNegotiationManager", contentNegotiationManager); String methodMappingName = parserContext.getReaderContext().registerWithGeneratedName(handlerMappingDef);
true
Other
spring-projects
spring-framework
2201dd8c45051230ad1a5a0e895cb5951edbfb74.json
Add support for matrix variables A new @MatrixVariable annotation allows injecting matrix variables into @RequestMapping methods. The matrix variables may appear in any path segment and should be wrapped in a URI template for request mapping purposes to ensure request matching is not affected by the order or the presence/absence of such variables. The @MatrixVariable annotation has an optional "pathVar" attribute that can be used to refer to the URI template where a matrix variable is located. Previously, ";" (semicolon) delimited content was removed from the path used for request mapping purposes. To preserve backwards compatibility that continues to be the case (except for the MVC namespace and Java config) and may be changed by setting the "removeSemicolonContent" property of RequestMappingHandlerMapping to "false". Applications using the MVC namespace and Java config do not need to do anything further to extract and use matrix variables. Issue: SPR-5499, SPR-7818
spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java
@@ -183,6 +183,7 @@ public void setApplicationContext(ApplicationContext applicationContext) throws public RequestMappingHandlerMapping requestMappingHandlerMapping() { RequestMappingHandlerMapping handlerMapping = new RequestMappingHandlerMapping(); handlerMapping.setOrder(0); + handlerMapping.setRemoveSemicolonContent(false); handlerMapping.setInterceptors(getInterceptors()); handlerMapping.setContentNegotiationManager(mvcContentNegotiationManager()); return handlerMapping;
true
Other
spring-projects
spring-framework
2201dd8c45051230ad1a5a0e895cb5951edbfb74.json
Add support for matrix variables A new @MatrixVariable annotation allows injecting matrix variables into @RequestMapping methods. The matrix variables may appear in any path segment and should be wrapped in a URI template for request mapping purposes to ensure request matching is not affected by the order or the presence/absence of such variables. The @MatrixVariable annotation has an optional "pathVar" attribute that can be used to refer to the URI template where a matrix variable is located. Previously, ";" (semicolon) delimited content was removed from the path used for request mapping purposes. To preserve backwards compatibility that continues to be the case (except for the MVC namespace and Java config) and may be changed by setting the "removeSemicolonContent" property of RequestMappingHandlerMapping to "false". Applications using the MVC namespace and Java config do not need to do anything further to extract and use matrix variables. Issue: SPR-5499, SPR-7818
spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMapping.java
@@ -37,7 +37,7 @@ /** * Abstract base class for {@link org.springframework.web.servlet.HandlerMapping} - * implementations. Supports ordering, a default handler, handler interceptors, + * implementations. Supports ordering, a default handler, handler interceptors, * including handler interceptors mapped by path patterns. * * <p>Note: This base class does <i>not</i> support exposure of the @@ -72,6 +72,7 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport private final List<MappedInterceptor> mappedInterceptors = new ArrayList<MappedInterceptor>(); + /** * Specify the order value for this HandlerMapping bean. * <p>Default value is <code>Integer.MAX_VALUE</code>, meaning that it's non-ordered. @@ -124,6 +125,14 @@ public void setUrlDecode(boolean urlDecode) { this.urlPathHelper.setUrlDecode(urlDecode); } + /** + * Set if ";" (semicolon) content should be stripped from the request URI. + * @see org.springframework.web.util.UrlPathHelper#setRemoveSemicolonContent(boolean) + */ + public void setRemoveSemicolonContent(boolean removeSemicolonContent) { + this.urlPathHelper.setRemoveSemicolonContent(removeSemicolonContent); + } + /** * Set the UrlPathHelper to use for resolution of lookup paths. * <p>Use this to override the default UrlPathHelper with a custom subclass, @@ -162,7 +171,7 @@ public PathMatcher getPathMatcher() { /** * Set the interceptors to apply for all handlers mapped by this handler mapping. - * <p>Supported interceptor types are HandlerInterceptor, WebRequestInterceptor, and MappedInterceptor. + * <p>Supported interceptor types are HandlerInterceptor, WebRequestInterceptor, and MappedInterceptor. * Mapped interceptors apply only to request URLs that match its path patterns. * Mapped interceptor beans are also detected by type during initialization. * @param interceptors array of handler interceptors, or <code>null</code> if none @@ -203,8 +212,8 @@ protected void extendInterceptors(List<Object> interceptors) { /** * Detects beans of type {@link MappedInterceptor} and adds them to the list of mapped interceptors. * This is done in addition to any {@link MappedInterceptor}s that may have been provided via - * {@link #setInterceptors(Object[])}. Subclasses can override this method to change that. - * + * {@link #setInterceptors(Object[])}. Subclasses can override this method to change that. + * * @param mappedInterceptors an empty list to add MappedInterceptor types to */ protected void detectMappedInterceptors(List<MappedInterceptor> mappedInterceptors) { @@ -214,7 +223,7 @@ protected void detectMappedInterceptors(List<MappedInterceptor> mappedIntercepto } /** - * Initialize the specified interceptors, checking for {@link MappedInterceptor}s and adapting + * Initialize the specified interceptors, checking for {@link MappedInterceptor}s and adapting * HandlerInterceptors where necessary. * @see #setInterceptors * @see #adaptInterceptor @@ -235,7 +244,7 @@ protected void initInterceptors() { } } } - + /** * Adapt the given interceptor object to the HandlerInterceptor interface. * <p>Supported interceptor types are HandlerInterceptor and WebRequestInterceptor. @@ -276,7 +285,7 @@ protected final MappedInterceptor[] getMappedInterceptors() { int count = mappedInterceptors.size(); return (count > 0) ? mappedInterceptors.toArray(new MappedInterceptor[count]) : null; } - + /** * Look up a handler for the given request, falling back to the default * handler if no specific one is found. @@ -330,19 +339,19 @@ public final HandlerExecutionChain getHandler(HttpServletRequest request) throws * @see #getAdaptedInterceptors() */ protected HandlerExecutionChain getHandlerExecutionChain(Object handler, HttpServletRequest request) { - HandlerExecutionChain chain = + HandlerExecutionChain chain = (handler instanceof HandlerExecutionChain) ? (HandlerExecutionChain) handler : new HandlerExecutionChain(handler); - + chain.addInterceptors(getAdaptedInterceptors()); - + String lookupPath = urlPathHelper.getLookupPathForRequest(request); for (MappedInterceptor mappedInterceptor : mappedInterceptors) { if (mappedInterceptor.matches(lookupPath, pathMatcher)) { chain.addInterceptor(mappedInterceptor.getInterceptor()); } } - + return chain; }
true
Other
spring-projects
spring-framework
2201dd8c45051230ad1a5a0e895cb5951edbfb74.json
Add support for matrix variables A new @MatrixVariable annotation allows injecting matrix variables into @RequestMapping methods. The matrix variables may appear in any path segment and should be wrapped in a URI template for request mapping purposes to ensure request matching is not affected by the order or the presence/absence of such variables. The @MatrixVariable annotation has an optional "pathVar" attribute that can be used to refer to the URI template where a matrix variable is located. Previously, ";" (semicolon) delimited content was removed from the path used for request mapping purposes. To preserve backwards compatibility that continues to be the case (except for the MVC namespace and Java config) and may be changed by setting the "removeSemicolonContent" property of RequestMappingHandlerMapping to "false". Applications using the MVC namespace and Java config do not need to do anything further to extract and use matrix variables. Issue: SPR-5499, SPR-7818
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/AbstractUrlViewController.java
@@ -65,6 +65,14 @@ public void setUrlDecode(boolean urlDecode) { this.urlPathHelper.setUrlDecode(urlDecode); } + /** + * Set if ";" (semicolon) content should be stripped from the request URI. + * @see org.springframework.web.util.UrlPathHelper#setRemoveSemicolonContent(boolean) + */ + public void setRemoveSemicolonContent(boolean removeSemicolonContent) { + this.urlPathHelper.setRemoveSemicolonContent(removeSemicolonContent); + } + /** * Set the UrlPathHelper to use for the resolution of lookup paths. * <p>Use this to override the default UrlPathHelper with a custom subclass, @@ -87,7 +95,7 @@ protected UrlPathHelper getUrlPathHelper() { /** * Retrieves the URL path to use for lookup and delegates to - * {@link #getViewNameForRequest}. Also adds the content of + * {@link #getViewNameForRequest}. Also adds the content of * {@link RequestContextUtils#getInputFlashMap} to the model. */ @Override
true
Other
spring-projects
spring-framework
2201dd8c45051230ad1a5a0e895cb5951edbfb74.json
Add support for matrix variables A new @MatrixVariable annotation allows injecting matrix variables into @RequestMapping methods. The matrix variables may appear in any path segment and should be wrapped in a URI template for request mapping purposes to ensure request matching is not affected by the order or the presence/absence of such variables. The @MatrixVariable annotation has an optional "pathVar" attribute that can be used to refer to the URI template where a matrix variable is located. Previously, ";" (semicolon) delimited content was removed from the path used for request mapping purposes. To preserve backwards compatibility that continues to be the case (except for the MVC namespace and Java config) and may be changed by setting the "removeSemicolonContent" property of RequestMappingHandlerMapping to "false". Applications using the MVC namespace and Java config do not need to do anything further to extract and use matrix variables. Issue: SPR-5499, SPR-7818
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMapping.java
@@ -19,13 +19,16 @@ import java.util.ArrayList; import java.util.Comparator; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.Map; +import java.util.Map.Entry; import java.util.Set; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import org.springframework.http.MediaType; +import org.springframework.util.MultiValueMap; import org.springframework.util.StringUtils; import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.HttpMediaTypeNotSupportedException; @@ -34,6 +37,7 @@ import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerMapping; import org.springframework.web.servlet.handler.AbstractHandlerMethodMapping; +import org.springframework.web.util.WebUtils; /** * Abstract base class for classes for which {@link RequestMappingInfo} defines @@ -77,8 +81,10 @@ public int compare(RequestMappingInfo info1, RequestMappingInfo info2) { } /** - * Expose URI template variables and producible media types in the request. + * Expose URI template variables, matrix variables, and producible media types in the request. + * * @see HandlerMapping#URI_TEMPLATE_VARIABLES_ATTRIBUTE + * @see HandlerMapping#MATRIX_VARIABLES_ATTRIBUTE * @see HandlerMapping#PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE */ @Override @@ -89,16 +95,50 @@ protected void handleMatch(RequestMappingInfo info, String lookupPath, HttpServl String bestPattern = patterns.isEmpty() ? lookupPath : patterns.iterator().next(); request.setAttribute(BEST_MATCHING_PATTERN_ATTRIBUTE, bestPattern); - Map<String, String> vars = getPathMatcher().extractUriTemplateVariables(bestPattern, lookupPath); - Map<String, String> decodedVars = getUrlPathHelper().decodePathVariables(request, vars); - request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, decodedVars); + Map<String, String> uriVariables = getPathMatcher().extractUriTemplateVariables(bestPattern, lookupPath); + Map<String, String> decodedUriVariables = getUrlPathHelper().decodePathVariables(request, uriVariables); + request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, decodedUriVariables); + + if (isMatrixVariableContentAvailable()) { + request.setAttribute(HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE, extractMatrixVariables(uriVariables)); + } if (!info.getProducesCondition().getProducibleMediaTypes().isEmpty()) { Set<MediaType> mediaTypes = info.getProducesCondition().getProducibleMediaTypes(); request.setAttribute(PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, mediaTypes); } } + private boolean isMatrixVariableContentAvailable() { + return !getUrlPathHelper().shouldRemoveSemicolonContent(); + } + + private Map<String, MultiValueMap<String, String>> extractMatrixVariables(Map<String, String> uriVariables) { + Map<String, MultiValueMap<String, String>> result = new LinkedHashMap<String, MultiValueMap<String, String>>(); + for (Entry<String, String> uriVar : uriVariables.entrySet()) { + String uriVarValue = uriVar.getValue(); + + int equalsIndex = uriVarValue.indexOf('='); + if (equalsIndex == -1) { + continue; + } + + String matrixVariables; + + int semicolonIndex = uriVarValue.indexOf(';'); + if ((semicolonIndex == -1) || (semicolonIndex == 0) || (equalsIndex < semicolonIndex)) { + matrixVariables = uriVarValue; + } + else { + matrixVariables = uriVarValue.substring(semicolonIndex + 1); + uriVariables.put(uriVar.getKey(), uriVarValue.substring(0, semicolonIndex)); + } + + result.put(uriVar.getKey(), WebUtils.parseMatrixVariables(matrixVariables)); + } + return result; + } + /** * Iterate all RequestMappingInfos once again, look if any match by URL at * least and raise exceptions accordingly.
true
Other
spring-projects
spring-framework
2201dd8c45051230ad1a5a0e895cb5951edbfb74.json
Add support for matrix variables A new @MatrixVariable annotation allows injecting matrix variables into @RequestMapping methods. The matrix variables may appear in any path segment and should be wrapped in a URI template for request mapping purposes to ensure request matching is not affected by the order or the presence/absence of such variables. The @MatrixVariable annotation has an optional "pathVar" attribute that can be used to refer to the URI template where a matrix variable is located. Previously, ";" (semicolon) delimited content was removed from the path used for request mapping purposes. To preserve backwards compatibility that continues to be the case (except for the MVC namespace and Java config) and may be changed by setting the "removeSemicolonContent" property of RequestMappingHandlerMapping to "false". Applications using the MVC namespace and Java config do not need to do anything further to extract and use matrix variables. Issue: SPR-5499, SPR-7818
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/CopyOfRequestMappingHandlerMapping.java
@@ -0,0 +1,199 @@ +/* + * Copyright 2002-2012 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.web.servlet.mvc.method.annotation; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; + +import org.springframework.core.annotation.AnnotationUtils; +import org.springframework.stereotype.Controller; +import org.springframework.util.Assert; +import org.springframework.web.accept.ContentNegotiationManager; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.mvc.condition.AbstractRequestCondition; +import org.springframework.web.servlet.mvc.condition.CompositeRequestCondition; +import org.springframework.web.servlet.mvc.condition.ConsumesRequestCondition; +import org.springframework.web.servlet.mvc.condition.HeadersRequestCondition; +import org.springframework.web.servlet.mvc.condition.ParamsRequestCondition; +import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition; +import org.springframework.web.servlet.mvc.condition.ProducesRequestCondition; +import org.springframework.web.servlet.mvc.condition.RequestCondition; +import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition; +import org.springframework.web.servlet.mvc.method.RequestMappingInfo; +import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping; + +/** + * Creates {@link RequestMappingInfo} instances from type and method-level + * {@link RequestMapping @RequestMapping} annotations in + * {@link Controller @Controller} classes. + * + * @author Arjen Poutsma + * @author Rossen Stoyanchev + * @since 3.1 + */ +public class CopyOfRequestMappingHandlerMapping extends RequestMappingInfoHandlerMapping { + + private boolean useSuffixPatternMatch = true; + + private boolean useTrailingSlashMatch = true; + + private ContentNegotiationManager contentNegotiationManager = new ContentNegotiationManager(); + + private final List<String> contentNegotiationFileExtensions = new ArrayList<String>(); + + /** + * Whether to use suffix pattern match (".*") when matching patterns to + * requests. If enabled a method mapped to "/users" also matches to "/users.*". + * <p>The default value is {@code true}. + */ + public void setUseSuffixPatternMatch(boolean useSuffixPatternMatch) { + this.useSuffixPatternMatch = useSuffixPatternMatch; + } + + /** + * Whether to match to URLs irrespective of the presence of a trailing slash. + * If enabled a method mapped to "/users" also matches to "/users/". + * <p>The default value is {@code true}. + */ + public void setUseTrailingSlashMatch(boolean useTrailingSlashMatch) { + this.useTrailingSlashMatch = useTrailingSlashMatch; + } + + /** + * Set the {@link ContentNegotiationManager} to use to determine requested media types. + * If not set, the default constructor is used. + */ + public void setContentNegotiationManager(ContentNegotiationManager contentNegotiationManager) { + Assert.notNull(contentNegotiationManager); + this.contentNegotiationManager = contentNegotiationManager; + this.contentNegotiationFileExtensions.addAll(contentNegotiationManager.getAllFileExtensions()); + } + + /** + * Whether to use suffix pattern matching. + */ + public boolean useSuffixPatternMatch() { + return this.useSuffixPatternMatch; + } + /** + * Whether to match to URLs irrespective of the presence of a trailing slash. + */ + public boolean useTrailingSlashMatch() { + return this.useTrailingSlashMatch; + } + + /** + * Return the configured {@link ContentNegotiationManager}. + */ + public ContentNegotiationManager getContentNegotiationManager() { + return this.contentNegotiationManager; + } + + /** + * Return the known file extensions for content negotiation. + */ + public List<String> getContentNegotiationFileExtensions() { + return this.contentNegotiationFileExtensions; + } + + /** + * {@inheritDoc} + * Expects a handler to have a type-level @{@link Controller} annotation. + */ + @Override + protected boolean isHandler(Class<?> beanType) { + return ((AnnotationUtils.findAnnotation(beanType, Controller.class) != null) || + (AnnotationUtils.findAnnotation(beanType, RequestMapping.class) != null)); + } + + /** + * Uses method and type-level @{@link RequestMapping} annotations to create + * the RequestMappingInfo. + * + * @return the created RequestMappingInfo, or {@code null} if the method + * does not have a {@code @RequestMapping} annotation. + * + * @see #getCustomMethodCondition(Method) + * @see #getCustomTypeCondition(Class) + */ + @Override + protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) { + RequestMappingInfo info = null; + RequestMapping methodAnnotation = AnnotationUtils.findAnnotation(method, RequestMapping.class); + if (methodAnnotation != null) { + RequestCondition<?> methodCondition = getCustomMethodCondition(method); + info = createRequestMappingInfo(methodAnnotation, methodCondition); + RequestMapping typeAnnotation = AnnotationUtils.findAnnotation(handlerType, RequestMapping.class); + if (typeAnnotation != null) { + RequestCondition<?> typeCondition = getCustomTypeCondition(handlerType); + info = createRequestMappingInfo(typeAnnotation, typeCondition).combine(info); + } + } + return info; + } + + /** + * Provide a custom type-level request condition. + * The custom {@link RequestCondition} can be of any type so long as the + * same condition type is returned from all calls to this method in order + * to ensure custom request conditions can be combined and compared. + * + * <p>Consider extending {@link AbstractRequestCondition} for custom + * condition types and using {@link CompositeRequestCondition} to provide + * multiple custom conditions. + * + * @param handlerType the handler type for which to create the condition + * @return the condition, or {@code null} + */ + protected RequestCondition<?> getCustomTypeCondition(Class<?> handlerType) { + return null; + } + + /** + * Provide a custom method-level request condition. + * The custom {@link RequestCondition} can be of any type so long as the + * same condition type is returned from all calls to this method in order + * to ensure custom request conditions can be combined and compared. + * + * <p>Consider extending {@link AbstractRequestCondition} for custom + * condition types and using {@link CompositeRequestCondition} to provide + * multiple custom conditions. + * + * @param method the handler method for which to create the condition + * @return the condition, or {@code null} + */ + protected RequestCondition<?> getCustomMethodCondition(Method method) { + return null; + } + + /** + * Created a RequestMappingInfo from a RequestMapping annotation. + */ + private RequestMappingInfo createRequestMappingInfo(RequestMapping annotation, RequestCondition<?> customCondition) { + return new RequestMappingInfo( + new PatternsRequestCondition(annotation.value(), getUrlPathHelper(), getPathMatcher(), + this.useSuffixPatternMatch, this.useTrailingSlashMatch, this.contentNegotiationFileExtensions), + new RequestMethodsRequestCondition(annotation.method()), + new ParamsRequestCondition(annotation.params()), + new HeadersRequestCondition(annotation.headers()), + new ConsumesRequestCondition(annotation.consumes(), annotation.headers()), + new ProducesRequestCondition(annotation.produces(), annotation.headers(), getContentNegotiationManager()), + customCondition); + } + +}
true
Other
spring-projects
spring-framework
2201dd8c45051230ad1a5a0e895cb5951edbfb74.json
Add support for matrix variables A new @MatrixVariable annotation allows injecting matrix variables into @RequestMapping methods. The matrix variables may appear in any path segment and should be wrapped in a URI template for request mapping purposes to ensure request matching is not affected by the order or the presence/absence of such variables. The @MatrixVariable annotation has an optional "pathVar" attribute that can be used to refer to the URI template where a matrix variable is located. Previously, ";" (semicolon) delimited content was removed from the path used for request mapping purposes. To preserve backwards compatibility that continues to be the case (except for the MVC namespace and Java config) and may be changed by setting the "removeSemicolonContent" property of RequestMappingHandlerMapping to "false". Applications using the MVC namespace and Java config do not need to do anything further to extract and use matrix variables. Issue: SPR-5499, SPR-7818
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MatrixVariableMapMethodArgumentResolver.java
@@ -0,0 +1,88 @@ +/* + * Copyright 2002-2012 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.web.servlet.mvc.method.annotation; + +import java.util.Collections; +import java.util.Map; + +import org.springframework.core.MethodParameter; +import org.springframework.util.CollectionUtils; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.MatrixVariable; +import org.springframework.web.bind.annotation.ValueConstants; +import org.springframework.web.bind.support.WebDataBinderFactory; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.method.support.HandlerMethodArgumentResolver; +import org.springframework.web.method.support.ModelAndViewContainer; +import org.springframework.web.servlet.HandlerMapping; + +/** + * Resolves method arguments of type Map annotated with + * {@link MatrixVariable @MatrixVariable} where the annotation the does not + * specify a name. If a name specified then the argument will by resolved by the + * {@link MatrixVariableMethodArgumentResolver} instead. + * + * @author Rossen Stoyanchev + * @since 3.2 + */ +public class MatrixVariableMapMethodArgumentResolver implements HandlerMethodArgumentResolver { + + public boolean supportsParameter(MethodParameter parameter) { + MatrixVariable paramAnnot = parameter.getParameterAnnotation(MatrixVariable.class); + if (paramAnnot != null) { + if (Map.class.isAssignableFrom(parameter.getParameterType())) { + return !StringUtils.hasText(paramAnnot.value()); + } + } + return false; + } + + public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, + NativeWebRequest request, WebDataBinderFactory binderFactory) throws Exception { + + @SuppressWarnings("unchecked") + Map<String, MultiValueMap<String, String>> matrixVariables = + (Map<String, MultiValueMap<String, String>>) request.getAttribute( + HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST); + + if (CollectionUtils.isEmpty(matrixVariables)) { + return Collections.emptyMap(); + } + + String pathVariable = parameter.getParameterAnnotation(MatrixVariable.class).pathVar(); + + if (!pathVariable.equals(ValueConstants.DEFAULT_NONE)) { + MultiValueMap<String, String> map = matrixVariables.get(pathVariable); + return (map != null) ? map : Collections.emptyMap(); + } + + MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>(); + for (MultiValueMap<String, String> vars : matrixVariables.values()) { + for (String name : vars.keySet()) { + for (String value : vars.get(name)) { + map.add(name, value); + } + } + } + + return map; + } + +} \ No newline at end of file
true
Other
spring-projects
spring-framework
2201dd8c45051230ad1a5a0e895cb5951edbfb74.json
Add support for matrix variables A new @MatrixVariable annotation allows injecting matrix variables into @RequestMapping methods. The matrix variables may appear in any path segment and should be wrapped in a URI template for request mapping purposes to ensure request matching is not affected by the order or the presence/absence of such variables. The @MatrixVariable annotation has an optional "pathVar" attribute that can be used to refer to the URI template where a matrix variable is located. Previously, ";" (semicolon) delimited content was removed from the path used for request mapping purposes. To preserve backwards compatibility that continues to be the case (except for the MVC namespace and Java config) and may be changed by setting the "removeSemicolonContent" property of RequestMappingHandlerMapping to "false". Applications using the MVC namespace and Java config do not need to do anything further to extract and use matrix variables. Issue: SPR-5499, SPR-7818
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MatrixVariableMethodArgumentResolver.java
@@ -0,0 +1,129 @@ +/* + * Copyright 2002-2012 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.web.servlet.mvc.method.annotation; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.springframework.core.MethodParameter; +import org.springframework.util.CollectionUtils; +import org.springframework.util.MultiValueMap; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.ServletRequestBindingException; +import org.springframework.web.bind.annotation.MatrixVariable; +import org.springframework.web.bind.annotation.ValueConstants; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver; +import org.springframework.web.servlet.HandlerMapping; + +/** + * Resolves method arguments annotated with an {@link MatrixVariable @PathParam}. + * + * <p>If the method parameter is of type Map and no name is specified, then it will + * by resolved by the {@link MatrixVariableMapMethodArgumentResolver} instead. + * + * @author Rossen Stoyanchev + * @since 3.2 + */ +public class MatrixVariableMethodArgumentResolver extends AbstractNamedValueMethodArgumentResolver { + + public MatrixVariableMethodArgumentResolver() { + super(null); + } + + public boolean supportsParameter(MethodParameter parameter) { + if (!parameter.hasParameterAnnotation(MatrixVariable.class)) { + return false; + } + if (Map.class.isAssignableFrom(parameter.getParameterType())) { + String paramName = parameter.getParameterAnnotation(MatrixVariable.class).value(); + return StringUtils.hasText(paramName); + } + return true; + } + + @Override + protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) { + MatrixVariable annotation = parameter.getParameterAnnotation(MatrixVariable.class); + return new PathParamNamedValueInfo(annotation); + } + + @Override + protected Object resolveName(String name, MethodParameter parameter, NativeWebRequest request) throws Exception { + + @SuppressWarnings("unchecked") + Map<String, MultiValueMap<String, String>> pathParameters = + (Map<String, MultiValueMap<String, String>>) request.getAttribute( + HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST); + + if (CollectionUtils.isEmpty(pathParameters)) { + return null; + } + + String pathVar = parameter.getParameterAnnotation(MatrixVariable.class).pathVar(); + List<String> paramValues = null; + + if (!pathVar.equals(ValueConstants.DEFAULT_NONE)) { + if (pathParameters.containsKey(pathVar)) { + paramValues = pathParameters.get(pathVar).get(name); + } + } + else { + boolean found = false; + paramValues = new ArrayList<String>(); + for (MultiValueMap<String, String> params : pathParameters.values()) { + if (params.containsKey(name)) { + if (found) { + String paramType = parameter.getParameterType().getName(); + throw new ServletRequestBindingException( + "Found more than one match for URI path parameter '" + name + + "' for parameter type [" + paramType + "]. Use pathVar attribute to disambiguate."); + } + paramValues.addAll(params.get(name)); + found = true; + } + } + } + + if (CollectionUtils.isEmpty(paramValues)) { + return null; + } + else if (paramValues.size() == 1) { + return paramValues.get(0); + } + else { + return paramValues; + } + } + + @Override + protected void handleMissingValue(String name, MethodParameter param) throws ServletRequestBindingException { + String paramType = param.getParameterType().getName(); + throw new ServletRequestBindingException( + "Missing URI path parameter '" + name + "' for method parameter type [" + paramType + "]"); + } + + + private static class PathParamNamedValueInfo extends NamedValueInfo { + + private PathParamNamedValueInfo(MatrixVariable annotation) { + super(annotation.value(), annotation.required(), annotation.defaultValue()); + } + } +} \ No newline at end of file
true
Other
spring-projects
spring-framework
2201dd8c45051230ad1a5a0e895cb5951edbfb74.json
Add support for matrix variables A new @MatrixVariable annotation allows injecting matrix variables into @RequestMapping methods. The matrix variables may appear in any path segment and should be wrapped in a URI template for request mapping purposes to ensure request matching is not affected by the order or the presence/absence of such variables. The @MatrixVariable annotation has an optional "pathVar" attribute that can be used to refer to the URI template where a matrix variable is located. Previously, ";" (semicolon) delimited content was removed from the path used for request mapping purposes. To preserve backwards compatibility that continues to be the case (except for the MVC namespace and Java config) and may be changed by setting the "removeSemicolonContent" property of RequestMappingHandlerMapping to "false". Applications using the MVC namespace and Java config do not need to do anything further to extract and use matrix variables. Issue: SPR-5499, SPR-7818
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/PathVariableMethodArgumentResolver.java
@@ -100,11 +100,9 @@ protected void handleMissingValue(String name, MethodParameter param) throws Ser @Override @SuppressWarnings("unchecked") - protected void handleResolvedValue(Object arg, - String name, - MethodParameter parameter, - ModelAndViewContainer mavContainer, - NativeWebRequest request) { + protected void handleResolvedValue(Object arg, String name, MethodParameter parameter, + ModelAndViewContainer mavContainer, NativeWebRequest request) { + String key = View.PATH_VARIABLES; int scope = RequestAttributes.SCOPE_REQUEST; Map<String, Object> pathVars = (Map<String, Object>) request.getAttribute(key, scope);
true
Other
spring-projects
spring-framework
2201dd8c45051230ad1a5a0e895cb5951edbfb74.json
Add support for matrix variables A new @MatrixVariable annotation allows injecting matrix variables into @RequestMapping methods. The matrix variables may appear in any path segment and should be wrapped in a URI template for request mapping purposes to ensure request matching is not affected by the order or the presence/absence of such variables. The @MatrixVariable annotation has an optional "pathVar" attribute that can be used to refer to the URI template where a matrix variable is located. Previously, ";" (semicolon) delimited content was removed from the path used for request mapping purposes. To preserve backwards compatibility that continues to be the case (except for the MVC namespace and Java config) and may be changed by setting the "removeSemicolonContent" property of RequestMappingHandlerMapping to "false". Applications using the MVC namespace and Java config do not need to do anything further to extract and use matrix variables. Issue: SPR-5499, SPR-7818
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapter.java
@@ -480,6 +480,8 @@ private List<HandlerMethodArgumentResolver> getDefaultArgumentResolvers() { resolvers.add(new RequestParamMapMethodArgumentResolver()); resolvers.add(new PathVariableMethodArgumentResolver()); resolvers.add(new PathVariableMapMethodArgumentResolver()); + resolvers.add(new MatrixVariableMethodArgumentResolver()); + resolvers.add(new MatrixVariableMapMethodArgumentResolver()); resolvers.add(new ServletModelAttributeMethodProcessor(false)); resolvers.add(new RequestResponseBodyMethodProcessor(getMessageConverters())); resolvers.add(new RequestPartMethodArgumentResolver(getMessageConverters())); @@ -522,6 +524,9 @@ private List<HandlerMethodArgumentResolver> getDefaultInitBinderArgumentResolver resolvers.add(new RequestParamMethodArgumentResolver(getBeanFactory(), false)); resolvers.add(new RequestParamMapMethodArgumentResolver()); resolvers.add(new PathVariableMethodArgumentResolver()); + resolvers.add(new PathVariableMapMethodArgumentResolver()); + resolvers.add(new MatrixVariableMethodArgumentResolver()); + resolvers.add(new MatrixVariableMapMethodArgumentResolver()); resolvers.add(new ExpressionValueMethodArgumentResolver(getBeanFactory())); // Type-based argument resolution
true
Other
spring-projects
spring-framework
2201dd8c45051230ad1a5a0e895cb5951edbfb74.json
Add support for matrix variables A new @MatrixVariable annotation allows injecting matrix variables into @RequestMapping methods. The matrix variables may appear in any path segment and should be wrapped in a URI template for request mapping purposes to ensure request matching is not affected by the order or the presence/absence of such variables. The @MatrixVariable annotation has an optional "pathVar" attribute that can be used to refer to the URI template where a matrix variable is located. Previously, ";" (semicolon) delimited content was removed from the path used for request mapping purposes. To preserve backwards compatibility that continues to be the case (except for the MVC namespace and Java config) and may be changed by setting the "removeSemicolonContent" property of RequestMappingHandlerMapping to "false". Applications using the MVC namespace and Java config do not need to do anything further to extract and use matrix variables. Issue: SPR-5499, SPR-7818
spring-webmvc/src/main/java/org/springframework/web/servlet/view/DefaultRequestToViewNameTranslator.java
@@ -145,6 +145,14 @@ public void setUrlDecode(boolean urlDecode) { this.urlPathHelper.setUrlDecode(urlDecode); } + /** + * Set if ";" (semicolon) content should be stripped from the request URI. + * @see org.springframework.web.util.UrlPathHelper#setRemoveSemicolonContent(boolean) + */ + public void setRemoveSemicolonContent(boolean removeSemicolonContent) { + this.urlPathHelper.setRemoveSemicolonContent(removeSemicolonContent); + } + /** * Set the {@link org.springframework.web.util.UrlPathHelper} to use for * the resolution of lookup paths.
true
Other
spring-projects
spring-framework
2201dd8c45051230ad1a5a0e895cb5951edbfb74.json
Add support for matrix variables A new @MatrixVariable annotation allows injecting matrix variables into @RequestMapping methods. The matrix variables may appear in any path segment and should be wrapped in a URI template for request mapping purposes to ensure request matching is not affected by the order or the presence/absence of such variables. The @MatrixVariable annotation has an optional "pathVar" attribute that can be used to refer to the URI template where a matrix variable is located. Previously, ";" (semicolon) delimited content was removed from the path used for request mapping purposes. To preserve backwards compatibility that continues to be the case (except for the MVC namespace and Java config) and may be changed by setting the "removeSemicolonContent" property of RequestMappingHandlerMapping to "false". Applications using the MVC namespace and Java config do not need to do anything further to extract and use matrix variables. Issue: SPR-5499, SPR-7818
spring-webmvc/src/test/java/org/springframework/web/servlet/handler/MappedInterceptorTests.java
@@ -45,15 +45,21 @@ public void noPatterns() { } @Test - public void includePatternOnly() { + public void includePattern() { MappedInterceptor mappedInterceptor = new MappedInterceptor(new String[] { "/foo/*" }, this.interceptor); assertTrue(mappedInterceptor.matches("/foo/bar", pathMatcher)); assertFalse(mappedInterceptor.matches("/bar/foo", pathMatcher)); } @Test - public void excludePatternOnly() { + public void includePatternWithMatrixVariables() { + MappedInterceptor mappedInterceptor = new MappedInterceptor(new String[] { "/foo*/*" }, this.interceptor); + assertTrue(mappedInterceptor.matches("/foo;q=1/bar;s=2", pathMatcher)); + } + + @Test + public void excludePattern() { MappedInterceptor mappedInterceptor = new MappedInterceptor(null, new String[] { "/admin/**" }, this.interceptor); assertTrue(mappedInterceptor.matches("/foo", pathMatcher));
true
Other
spring-projects
spring-framework
2201dd8c45051230ad1a5a0e895cb5951edbfb74.json
Add support for matrix variables A new @MatrixVariable annotation allows injecting matrix variables into @RequestMapping methods. The matrix variables may appear in any path segment and should be wrapped in a URI template for request mapping purposes to ensure request matching is not affected by the order or the presence/absence of such variables. The @MatrixVariable annotation has an optional "pathVar" attribute that can be used to refer to the URI template where a matrix variable is located. Previously, ";" (semicolon) delimited content was removed from the path used for request mapping purposes. To preserve backwards compatibility that continues to be the case (except for the MVC namespace and Java config) and may be changed by setting the "removeSemicolonContent" property of RequestMappingHandlerMapping to "false". Applications using the MVC namespace and Java config do not need to do anything further to extract and use matrix variables. Issue: SPR-5499, SPR-7818
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/UrlFilenameViewControllerTests.java
@@ -55,6 +55,15 @@ public void testWithFilenamePlusExtension() throws Exception { assertTrue(mv.getModel().isEmpty()); } + public void testWithFilenameAndMatrixVariables() throws Exception { + UrlFilenameViewController ctrl = new UrlFilenameViewController(); + MockHttpServletRequest request = new MockHttpServletRequest("GET", "/index;a=A;b=B"); + MockHttpServletResponse response = new MockHttpServletResponse(); + ModelAndView mv = ctrl.handleRequest(request, response); + assertEquals("index", mv.getViewName()); + assertTrue(mv.getModel().isEmpty()); + } + public void testWithPrefixAndSuffix() throws Exception { UrlFilenameViewController ctrl = new UrlFilenameViewController(); ctrl.setPrefix("mypre_");
true
Other
spring-projects
spring-framework
2201dd8c45051230ad1a5a0e895cb5951edbfb74.json
Add support for matrix variables A new @MatrixVariable annotation allows injecting matrix variables into @RequestMapping methods. The matrix variables may appear in any path segment and should be wrapped in a URI template for request mapping purposes to ensure request matching is not affected by the order or the presence/absence of such variables. The @MatrixVariable annotation has an optional "pathVar" attribute that can be used to refer to the URI template where a matrix variable is located. Previously, ";" (semicolon) delimited content was removed from the path used for request mapping purposes. To preserve backwards compatibility that continues to be the case (except for the MVC namespace and Java config) and may be changed by setting the "removeSemicolonContent" property of RequestMappingHandlerMapping to "false". Applications using the MVC namespace and Java config do not need to do anything further to extract and use matrix variables. Issue: SPR-5499, SPR-7818
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java
@@ -30,12 +30,15 @@ import java.util.Map; import java.util.Set; +import javax.servlet.http.HttpServletRequest; + import org.junit.Before; import org.junit.Test; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.http.MediaType; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.stereotype.Controller; +import org.springframework.util.MultiValueMap; import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.HttpMediaTypeNotSupportedException; import org.springframework.web.HttpRequestMethodNotSupportedException; @@ -65,7 +68,7 @@ */ public class RequestMappingInfoHandlerMappingTests { - private TestRequestMappingInfoHandlerMapping mapping; + private TestRequestMappingInfoHandlerMapping handlerMapping; private Handler handler; @@ -85,15 +88,16 @@ public void setUp() throws Exception { this.barMethod = new HandlerMethod(handler, "bar"); this.emptyMethod = new HandlerMethod(handler, "empty"); - this.mapping = new TestRequestMappingInfoHandlerMapping(); - this.mapping.registerHandler(this.handler); + this.handlerMapping = new TestRequestMappingInfoHandlerMapping(); + this.handlerMapping.registerHandler(this.handler); + this.handlerMapping.setRemoveSemicolonContent(false); } @Test public void getMappingPathPatterns() throws Exception { RequestMappingInfo info = new RequestMappingInfo( new PatternsRequestCondition("/foo/*", "/foo", "/bar/*", "/bar"), null, null, null, null, null, null); - Set<String> paths = this.mapping.getMappingPathPatterns(info); + Set<String> paths = this.handlerMapping.getMappingPathPatterns(info); HashSet<String> expected = new HashSet<String>(Arrays.asList("/foo/*", "/foo", "/bar/*", "/bar")); assertEquals(expected, paths); @@ -102,41 +106,41 @@ public void getMappingPathPatterns() throws Exception { @Test public void directMatch() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo"); - HandlerMethod hm = (HandlerMethod) this.mapping.getHandler(request).getHandler(); + HandlerMethod hm = (HandlerMethod) this.handlerMapping.getHandler(request).getHandler(); assertEquals(this.fooMethod.getMethod(), hm.getMethod()); } @Test public void globMatch() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bar"); - HandlerMethod hm = (HandlerMethod) this.mapping.getHandler(request).getHandler(); + HandlerMethod hm = (HandlerMethod) this.handlerMapping.getHandler(request).getHandler(); assertEquals(this.barMethod.getMethod(), hm.getMethod()); } @Test public void emptyPathMatch() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); - HandlerMethod hm = (HandlerMethod) this.mapping.getHandler(request).getHandler(); + HandlerMethod hm = (HandlerMethod) this.handlerMapping.getHandler(request).getHandler(); assertEquals(this.emptyMethod.getMethod(), hm.getMethod()); request = new MockHttpServletRequest("GET", "/"); - hm = (HandlerMethod) this.mapping.getHandler(request).getHandler(); + hm = (HandlerMethod) this.handlerMapping.getHandler(request).getHandler(); assertEquals(this.emptyMethod.getMethod(), hm.getMethod()); } @Test public void bestMatch() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo"); request.setParameter("p", "anything"); - HandlerMethod hm = (HandlerMethod) this.mapping.getHandler(request).getHandler(); + HandlerMethod hm = (HandlerMethod) this.handlerMapping.getHandler(request).getHandler(); assertEquals(this.fooParamMethod.getMethod(), hm.getMethod()); } @Test public void requestMethodNotAllowed() throws Exception { try { MockHttpServletRequest request = new MockHttpServletRequest("POST", "/bar"); - this.mapping.getHandler(request); + this.handlerMapping.getHandler(request); fail("HttpRequestMethodNotSupportedException expected"); } catch (HttpRequestMethodNotSupportedException ex) { @@ -155,7 +159,7 @@ private void testMediaTypeNotSupported(String url) throws Exception { try { MockHttpServletRequest request = new MockHttpServletRequest("PUT", url); request.setContentType("application/json"); - this.mapping.getHandler(request); + this.handlerMapping.getHandler(request); fail("HttpMediaTypeNotSupportedException expected"); } catch (HttpMediaTypeNotSupportedException ex) { @@ -175,7 +179,7 @@ private void testMediaTypeNotAccepted(String url) throws Exception { try { MockHttpServletRequest request = new MockHttpServletRequest("GET", url); request.addHeader("Accept", "application/json"); - this.mapping.getHandler(request); + this.handlerMapping.getHandler(request); fail("HttpMediaTypeNotAcceptableException expected"); } catch (HttpMediaTypeNotAcceptableException ex) { @@ -190,7 +194,7 @@ public void uriTemplateVariables() { RequestMappingInfo key = new RequestMappingInfo(patterns, null, null, null, null, null, null); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/1/2"); String lookupPath = new UrlPathHelper().getLookupPathForRequest(request); - this.mapping.handleMatch(key, lookupPath, request); + this.handlerMapping.handleMatch(key, lookupPath, request); @SuppressWarnings("unchecked") Map<String, String> uriVariables = @@ -214,8 +218,8 @@ public void uriTemplateVariablesDecode() { pathHelper.setUrlDecode(false); String lookupPath = pathHelper.getLookupPathForRequest(request); - this.mapping.setUrlPathHelper(pathHelper); - this.mapping.handleMatch(key, lookupPath, request); + this.handlerMapping.setUrlPathHelper(pathHelper); + this.handlerMapping.handleMatch(key, lookupPath, request); @SuppressWarnings("unchecked") Map<String, String> uriVariables = @@ -232,7 +236,7 @@ public void bestMatchingPatternAttribute() { RequestMappingInfo key = new RequestMappingInfo(patterns, null, null, null, null, null, null); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/1/2"); - this.mapping.handleMatch(key, "/1/2", request); + this.handlerMapping.handleMatch(key, "/1/2", request); assertEquals("/{path1}/2", request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)); } @@ -243,7 +247,7 @@ public void bestMatchingPatternAttributeNoPatternsDefined() { RequestMappingInfo key = new RequestMappingInfo(patterns, null, null, null, null, null, null); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/1/2"); - this.mapping.handleMatch(key, "/1/2", request); + this.handlerMapping.handleMatch(key, "/1/2", request); assertEquals("/1/2", request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)); } @@ -252,14 +256,14 @@ public void bestMatchingPatternAttributeNoPatternsDefined() { public void producibleMediaTypesAttribute() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/content"); request.addHeader("Accept", "application/xml"); - this.mapping.getHandler(request); + this.handlerMapping.getHandler(request); assertEquals(Collections.singleton(MediaType.APPLICATION_XML), request.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE)); request = new MockHttpServletRequest("GET", "/content"); request.addHeader("Accept", "application/json"); - this.mapping.getHandler(request); + this.handlerMapping.getHandler(request); assertNull("Negated expression should not be listed as a producible type", request.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE)); @@ -285,7 +289,74 @@ public void mappedInterceptors() throws Exception { assertNull(chain); } - @SuppressWarnings("unused") + @Test + public void matrixVariables() { + + MockHttpServletRequest request; + MultiValueMap<String, String> matrixVariables; + Map<String, String> uriVariables; + + String lookupPath = "/cars;colors=red,blue,green;year=2012"; + + // Pattern "/{cars}" : matrix variables stripped from "cars" variable + + request = new MockHttpServletRequest(); + testHandleMatch(request, "/{cars}", lookupPath); + + matrixVariables = getMatrixVariables(request, "cars"); + assertNotNull(matrixVariables); + assertEquals(Arrays.asList("red", "blue", "green"), matrixVariables.get("colors")); + assertEquals("2012", matrixVariables.getFirst("year")); + + uriVariables = getUriTemplateVariables(request); + assertEquals("cars", uriVariables.get("cars")); + + // Pattern "/{cars:[^;]+}{params}" : "cars" and "params" variables unchanged + + request = new MockHttpServletRequest(); + testHandleMatch(request, "/{cars:[^;]+}{params}", lookupPath); + + matrixVariables = getMatrixVariables(request, "params"); + assertNotNull(matrixVariables); + assertEquals(Arrays.asList("red", "blue", "green"), matrixVariables.get("colors")); + assertEquals("2012", matrixVariables.getFirst("year")); + + uriVariables = getUriTemplateVariables(request); + assertEquals("cars", uriVariables.get("cars")); + assertEquals(";colors=red,blue,green;year=2012", uriVariables.get("params")); + + // matrix variables not present : "params" variable is empty + + request = new MockHttpServletRequest(); + testHandleMatch(request, "/{cars:[^;]+}{params}", "/cars"); + + matrixVariables = getMatrixVariables(request, "params"); + assertNull(matrixVariables); + + uriVariables = getUriTemplateVariables(request); + assertEquals("cars", uriVariables.get("cars")); + assertEquals("", uriVariables.get("params")); + } + + private void testHandleMatch(MockHttpServletRequest request, String pattern, String lookupPath) { + PatternsRequestCondition patterns = new PatternsRequestCondition(pattern); + RequestMappingInfo info = new RequestMappingInfo(patterns, null, null, null, null, null, null); + this.handlerMapping.handleMatch(info, lookupPath, request); + } + + @SuppressWarnings("unchecked") + private MultiValueMap<String, String> getMatrixVariables(HttpServletRequest request, String uriVarName) { + String attrName = HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE; + return ((Map<String, MultiValueMap<String, String>>) request.getAttribute(attrName)).get(uriVarName); + } + + @SuppressWarnings("unchecked") + private Map<String, String> getUriTemplateVariables(HttpServletRequest request) { + String attrName = HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE; + return (Map<String, String>) request.getAttribute(attrName); + } + + @Controller private static class Handler {
true
Other
spring-projects
spring-framework
2201dd8c45051230ad1a5a0e895cb5951edbfb74.json
Add support for matrix variables A new @MatrixVariable annotation allows injecting matrix variables into @RequestMapping methods. The matrix variables may appear in any path segment and should be wrapped in a URI template for request mapping purposes to ensure request matching is not affected by the order or the presence/absence of such variables. The @MatrixVariable annotation has an optional "pathVar" attribute that can be used to refer to the URI template where a matrix variable is located. Previously, ";" (semicolon) delimited content was removed from the path used for request mapping purposes. To preserve backwards compatibility that continues to be the case (except for the MVC namespace and Java config) and may be changed by setting the "removeSemicolonContent" property of RequestMappingHandlerMapping to "false". Applications using the MVC namespace and Java config do not need to do anything further to extract and use matrix variables. Issue: SPR-5499, SPR-7818
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/AbstractServletHandlerMethodTests.java
@@ -31,24 +31,24 @@ import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver; /** - * Base class for tests using on the DispatcherServlet and HandlerMethod infrastructure classes: + * Base class for tests using on the DispatcherServlet and HandlerMethod infrastructure classes: * <ul> - * <li>RequestMappingHandlerMapping - * <li>RequestMappingHandlerAdapter + * <li>RequestMappingHandlerMapping + * <li>RequestMappingHandlerAdapter * <li>ExceptionHandlerExceptionResolver * </ul> - * + * * @author Rossen Stoyanchev */ public class AbstractServletHandlerMethodTests { private DispatcherServlet servlet; - + @After public void tearDown() { this.servlet = null; } - + protected DispatcherServlet getServlet() { assertNotNull("DispatcherServlet not initialized", servlet); return servlet; @@ -68,30 +68,32 @@ protected WebApplicationContext initServletWithControllers(final Class<?>... con */ @SuppressWarnings("serial") protected WebApplicationContext initServlet( - final ApplicationContextInitializer<GenericWebApplicationContext> initializer, + final ApplicationContextInitializer<GenericWebApplicationContext> initializer, final Class<?>... controllerClasses) throws ServletException { - + final GenericWebApplicationContext wac = new GenericWebApplicationContext(); - + servlet = new DispatcherServlet() { @Override protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { for (Class<?> clazz : controllerClasses) { wac.registerBeanDefinition(clazz.getSimpleName(), new RootBeanDefinition(clazz)); } - + Class<?> mappingType = RequestMappingHandlerMapping.class; - wac.registerBeanDefinition("handlerMapping", new RootBeanDefinition(mappingType)); - + RootBeanDefinition beanDef = new RootBeanDefinition(mappingType); + beanDef.getPropertyValues().add("removeSemicolonContent", "false"); + wac.registerBeanDefinition("handlerMapping", beanDef); + Class<?> adapterType = RequestMappingHandlerAdapter.class; wac.registerBeanDefinition("handlerAdapter", new RootBeanDefinition(adapterType)); - + Class<?> resolverType = ExceptionHandlerExceptionResolver.class; wac.registerBeanDefinition("requestMappingResolver", new RootBeanDefinition(resolverType)); - + resolverType = ResponseStatusExceptionResolver.class; wac.registerBeanDefinition("responseStatusResolver", new RootBeanDefinition(resolverType)); - + resolverType = DefaultHandlerExceptionResolver.class; wac.registerBeanDefinition("defaultResolver", new RootBeanDefinition(resolverType)); @@ -103,9 +105,9 @@ protected WebApplicationContext createWebApplicationContext(WebApplicationContex return wac; } }; - + servlet.init(new MockServletConfig()); - + return wac; }
true
Other
spring-projects
spring-framework
2201dd8c45051230ad1a5a0e895cb5951edbfb74.json
Add support for matrix variables A new @MatrixVariable annotation allows injecting matrix variables into @RequestMapping methods. The matrix variables may appear in any path segment and should be wrapped in a URI template for request mapping purposes to ensure request matching is not affected by the order or the presence/absence of such variables. The @MatrixVariable annotation has an optional "pathVar" attribute that can be used to refer to the URI template where a matrix variable is located. Previously, ";" (semicolon) delimited content was removed from the path used for request mapping purposes. To preserve backwards compatibility that continues to be the case (except for the MVC namespace and Java config) and may be changed by setting the "removeSemicolonContent" property of RequestMappingHandlerMapping to "false". Applications using the MVC namespace and Java config do not need to do anything further to extract and use matrix variables. Issue: SPR-5499, SPR-7818
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/MatrixVariablesMapMethodArgumentResolverTests.java
@@ -0,0 +1,186 @@ +/* + * Copyright 2002-2011 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.web.servlet.mvc.method.annotation; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.core.MethodParameter; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.bind.annotation.MatrixVariable; +import org.springframework.web.context.request.ServletWebRequest; +import org.springframework.web.method.support.ModelAndViewContainer; +import org.springframework.web.servlet.HandlerMapping; + +/** + * Test fixture with {@link MatrixVariableMethodArgumentResolver}. + * + * @author Rossen Stoyanchev + */ +public class MatrixVariablesMapMethodArgumentResolverTests { + + private MatrixVariableMapMethodArgumentResolver resolver; + + private MethodParameter paramString; + private MethodParameter paramMap; + private MethodParameter paramMultivalueMap; + private MethodParameter paramMapForPathVar; + private MethodParameter paramMapWithName; + + private ModelAndViewContainer mavContainer; + + private ServletWebRequest webRequest; + + private MockHttpServletRequest request; + + + @Before + public void setUp() throws Exception { + this.resolver = new MatrixVariableMapMethodArgumentResolver(); + + Method method = getClass().getMethod("handle", String.class, + Map.class, MultiValueMap.class, MultiValueMap.class, Map.class); + + this.paramString = new MethodParameter(method, 0); + this.paramMap = new MethodParameter(method, 1); + this.paramMultivalueMap = new MethodParameter(method, 2); + this.paramMapForPathVar = new MethodParameter(method, 3); + this.paramMapWithName = new MethodParameter(method, 4); + + this.mavContainer = new ModelAndViewContainer(); + this.request = new MockHttpServletRequest(); + this.webRequest = new ServletWebRequest(request, new MockHttpServletResponse()); + + Map<String, MultiValueMap<String, String>> params = new LinkedHashMap<String, MultiValueMap<String, String>>(); + this.request.setAttribute(HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE, params); + } + + @Test + public void supportsParameter() { + assertFalse(resolver.supportsParameter(paramString)); + assertTrue(resolver.supportsParameter(paramMap)); + assertTrue(resolver.supportsParameter(paramMultivalueMap)); + assertTrue(resolver.supportsParameter(paramMapForPathVar)); + assertFalse(resolver.supportsParameter(paramMapWithName)); + } + + @Test + public void resolveArgument() throws Exception { + + MultiValueMap<String, String> params = getMatrixVariables("cars"); + params.add("colors", "red"); + params.add("colors", "green"); + params.add("colors", "blue"); + params.add("year", "2012"); + + @SuppressWarnings("unchecked") + Map<String, String> map = (Map<String, String>) this.resolver.resolveArgument( + this.paramMap, this.mavContainer, this.webRequest, null); + + assertEquals(Arrays.asList("red", "green", "blue"), map.get("colors")); + + @SuppressWarnings("unchecked") + MultiValueMap<String, String> multivalueMap = (MultiValueMap<String, String>) this.resolver.resolveArgument( + this.paramMultivalueMap, this.mavContainer, this.webRequest, null); + + assertEquals(Arrays.asList("red", "green", "blue"), multivalueMap.get("colors")); + } + + @Test + public void resolveArgumentPathVariable() throws Exception { + + MultiValueMap<String, String> params1 = getMatrixVariables("cars"); + params1.add("colors", "red"); + params1.add("colors", "purple"); + + MultiValueMap<String, String> params2 = getMatrixVariables("planes"); + params2.add("colors", "yellow"); + params2.add("colors", "orange"); + + @SuppressWarnings("unchecked") + Map<String, String> mapForPathVar = (Map<String, String>) this.resolver.resolveArgument( + this.paramMapForPathVar, this.mavContainer, this.webRequest, null); + + assertEquals(Arrays.asList("red", "purple"), mapForPathVar.get("colors")); + + @SuppressWarnings("unchecked") + Map<String, String> mapAll = (Map<String, String>) this.resolver.resolveArgument( + this.paramMap, this.mavContainer, this.webRequest, null); + + assertEquals(Arrays.asList("red", "purple", "yellow", "orange"), mapAll.get("colors")); + } + + @Test + public void resolveArgumentNoParams() throws Exception { + + @SuppressWarnings("unchecked") + Map<String, String> map = (Map<String, String>) this.resolver.resolveArgument( + this.paramMap, this.mavContainer, this.webRequest, null); + + assertEquals(Collections.emptyMap(), map); + } + + @Test + public void resolveArgumentNoMatch() throws Exception { + + MultiValueMap<String, String> params2 = getMatrixVariables("planes"); + params2.add("colors", "yellow"); + params2.add("colors", "orange"); + + @SuppressWarnings("unchecked") + Map<String, String> map = (Map<String, String>) this.resolver.resolveArgument( + this.paramMapForPathVar, this.mavContainer, this.webRequest, null); + + assertEquals(Collections.emptyMap(), map); + } + + + @SuppressWarnings("unchecked") + private MultiValueMap<String, String> getMatrixVariables(String pathVarName) { + + Map<String, MultiValueMap<String, String>> matrixVariables = + (Map<String, MultiValueMap<String, String>>) this.request.getAttribute( + HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE); + + MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>(); + matrixVariables.put(pathVarName, params); + + return params; + } + + + public void handle( + String stringArg, + @MatrixVariable Map<String, String> map, + @MatrixVariable MultiValueMap<String, String> multivalueMap, + @MatrixVariable(pathVar="cars") MultiValueMap<String, String> mapForPathVar, + @MatrixVariable("name") Map<String, String> mapWithName) { + } + +} \ No newline at end of file
true
Other
spring-projects
spring-framework
2201dd8c45051230ad1a5a0e895cb5951edbfb74.json
Add support for matrix variables A new @MatrixVariable annotation allows injecting matrix variables into @RequestMapping methods. The matrix variables may appear in any path segment and should be wrapped in a URI template for request mapping purposes to ensure request matching is not affected by the order or the presence/absence of such variables. The @MatrixVariable annotation has an optional "pathVar" attribute that can be used to refer to the URI template where a matrix variable is located. Previously, ";" (semicolon) delimited content was removed from the path used for request mapping purposes. To preserve backwards compatibility that continues to be the case (except for the MVC namespace and Java config) and may be changed by setting the "removeSemicolonContent" property of RequestMappingHandlerMapping to "false". Applications using the MVC namespace and Java config do not need to do anything further to extract and use matrix variables. Issue: SPR-5499, SPR-7818
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/MatrixVariablesMethodArgumentResolverTests.java
@@ -0,0 +1,159 @@ +/* + * Copyright 2002-2011 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.web.servlet.mvc.method.annotation; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.core.LocalVariableTableParameterNameDiscoverer; +import org.springframework.core.MethodParameter; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.bind.ServletRequestBindingException; +import org.springframework.web.bind.annotation.MatrixVariable; +import org.springframework.web.context.request.ServletWebRequest; +import org.springframework.web.method.support.ModelAndViewContainer; +import org.springframework.web.servlet.HandlerMapping; + +/** + * Test fixture with {@link MatrixVariableMethodArgumentResolver}. + * + * @author Rossen Stoyanchev + */ +public class MatrixVariablesMethodArgumentResolverTests { + + private MatrixVariableMethodArgumentResolver resolver; + + private MethodParameter paramString; + private MethodParameter paramColors; + private MethodParameter paramYear; + + private ModelAndViewContainer mavContainer; + + private ServletWebRequest webRequest; + + private MockHttpServletRequest request; + + + @Before + public void setUp() throws Exception { + this.resolver = new MatrixVariableMethodArgumentResolver(); + + Method method = getClass().getMethod("handle", String.class, List.class, int.class); + this.paramString = new MethodParameter(method, 0); + this.paramColors = new MethodParameter(method, 1); + this.paramYear = new MethodParameter(method, 2); + + this.paramColors.initParameterNameDiscovery(new LocalVariableTableParameterNameDiscoverer()); + + this.mavContainer = new ModelAndViewContainer(); + this.request = new MockHttpServletRequest(); + this.webRequest = new ServletWebRequest(request, new MockHttpServletResponse()); + + Map<String, MultiValueMap<String, String>> params = new LinkedHashMap<String, MultiValueMap<String, String>>(); + this.request.setAttribute(HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE, params); + } + + @Test + public void supportsParameter() { + assertFalse(resolver.supportsParameter(paramString)); + assertTrue(resolver.supportsParameter(paramColors)); + assertTrue(resolver.supportsParameter(paramYear)); + } + + @Test + public void resolveArgument() throws Exception { + + MultiValueMap<String, String> params = getMatrixVariables("cars"); + params.add("colors", "red"); + params.add("colors", "green"); + params.add("colors", "blue"); + + assertEquals(Arrays.asList("red", "green", "blue"), + this.resolver.resolveArgument(this.paramColors, this.mavContainer, this.webRequest, null)); + } + + @Test + public void resolveArgumentPathVariable() throws Exception { + + getMatrixVariables("cars").add("year", "2006"); + getMatrixVariables("bikes").add("year", "2005"); + + assertEquals("2006", this.resolver.resolveArgument(this.paramYear, this.mavContainer, this.webRequest, null)); + } + + @Test + public void resolveArgumentDefaultValue() throws Exception { + assertEquals("2013", resolver.resolveArgument(this.paramYear, this.mavContainer, this.webRequest, null)); + } + + @Test(expected=ServletRequestBindingException.class) + public void resolveArgumentMultipleMatches() throws Exception { + + getMatrixVariables("var1").add("colors", "red"); + getMatrixVariables("var2").add("colors", "green"); + + this.resolver.resolveArgument(this.paramColors, this.mavContainer, this.webRequest, null); + } + + @Test(expected=ServletRequestBindingException.class) + public void resolveArgumentRequired() throws Exception { + resolver.resolveArgument(this.paramColors, this.mavContainer, this.webRequest, null); + } + + @Test + public void resolveArgumentNoMatch() throws Exception { + + MultiValueMap<String, String> params = getMatrixVariables("cars"); + params.add("anotherYear", "2012"); + + assertEquals("2013", this.resolver.resolveArgument(this.paramYear, this.mavContainer, this.webRequest, null)); + } + + + @SuppressWarnings("unchecked") + private MultiValueMap<String, String> getMatrixVariables(String pathVarName) { + + Map<String, MultiValueMap<String, String>> matrixVariables = + (Map<String, MultiValueMap<String, String>>) this.request.getAttribute( + HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE); + + MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>(); + matrixVariables.put(pathVarName, params); + + return params; + } + + + public void handle( + String stringArg, + @MatrixVariable List<String> colors, + @MatrixVariable(value="year", pathVar="cars", required=false, defaultValue="2013") int preferredYear) { + } + +} \ No newline at end of file
true
Other
spring-projects
spring-framework
2201dd8c45051230ad1a5a0e895cb5951edbfb74.json
Add support for matrix variables A new @MatrixVariable annotation allows injecting matrix variables into @RequestMapping methods. The matrix variables may appear in any path segment and should be wrapped in a URI template for request mapping purposes to ensure request matching is not affected by the order or the presence/absence of such variables. The @MatrixVariable annotation has an optional "pathVar" attribute that can be used to refer to the URI template where a matrix variable is located. Previously, ";" (semicolon) delimited content was removed from the path used for request mapping purposes. To preserve backwards compatibility that continues to be the case (except for the MVC namespace and Java config) and may be changed by setting the "removeSemicolonContent" property of RequestMappingHandlerMapping to "false". Applications using the MVC namespace and Java config do not need to do anything further to extract and use matrix variables. Issue: SPR-5499, SPR-7818
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/UriTemplateServletAnnotationControllerHandlerMethodTests.java
@@ -22,9 +22,11 @@ import java.io.IOException; import java.io.Writer; import java.text.SimpleDateFormat; +import java.util.Arrays; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; +import java.util.List; import java.util.Locale; import java.util.Map; @@ -38,8 +40,10 @@ import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.stereotype.Controller; +import org.springframework.util.MultiValueMap; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.MatrixVariable; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @@ -52,22 +56,22 @@ import org.springframework.web.servlet.view.AbstractView; /** - * The origin of this test class is {@link UriTemplateServletAnnotationControllerTests}. - * + * The origin of this test class is {@link UriTemplateServletAnnotationControllerTests}. + * * Tests in this class run against the {@link HandlerMethod} infrastructure: * <ul> - * <li>RequestMappingHandlerMapping - * <li>RequestMappingHandlerAdapter + * <li>RequestMappingHandlerMapping + * <li>RequestMappingHandlerAdapter * <li>ExceptionHandlerExceptionResolver * </ul> - * + * * <p>Rather than against the existing infrastructure: * <ul> * <li>DefaultAnnotationHandlerMapping * <li>AnnotationMethodHandlerAdapter * <li>AnnotationMethodHandlerExceptionResolver - * </ul> - * + * </ul> + * * @author Rossen Stoyanchev * @since 3.1 */ @@ -80,17 +84,18 @@ public void simple() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/42"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("test-42", response.getContentAsString()); + assertEquals("test-42-7", response.getContentAsString()); } @Test public void multiple() throws Exception { initServletWithControllers(MultipleUriTemplateController.class); - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/42/bookings/21-other"); + MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/42;q=24/bookings/21-other;q=12"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("test-42-21-other", response.getContentAsString()); + assertEquals(200, response.getStatus()); + assertEquals("test-42-q24-21-other-q12", response.getContentAsString()); } @Test @@ -99,8 +104,8 @@ public void pathVarsInModel() throws Exception { pathVars.put("hotel", "42"); pathVars.put("booking", 21); pathVars.put("other", "other"); - - WebApplicationContext wac = + + WebApplicationContext wac = initServlet(new ApplicationContextInitializer<GenericWebApplicationContext>() { public void initialize(GenericWebApplicationContext context) { RootBeanDefinition beanDef = new RootBeanDefinition(ModelValidatingViewResolver.class); @@ -109,9 +114,9 @@ public void initialize(GenericWebApplicationContext context) { } }, ViewRenderingController.class); - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/42/bookings/21-other"); + MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/42;q=1,2/bookings/21-other;q=3;r=R"); getServlet().service(request, new MockHttpServletResponse()); - + ModelValidatingViewResolver resolver = wac.getBean(ModelValidatingViewResolver.class); assertEquals(3, resolver.validatedAttrCount); } @@ -166,10 +171,10 @@ public void relative() throws Exception { public void extension() throws Exception { initServletWithControllers(SimpleUriTemplateController.class); - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/42.xml"); + MockHttpServletRequest request = new MockHttpServletRequest("GET", "/42;jsessionid=c0o7fszeb1;q=24.xml"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("test-42", response.getContentAsString()); + assertEquals("test-42-24", response.getContentAsString()); } @@ -287,10 +292,11 @@ public void multiPaths() throws Exception { public void customRegex() throws Exception { initServletWithControllers(CustomRegexController.class); - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/42"); + MockHttpServletRequest request = new MockHttpServletRequest("GET", "/42;q=1;q=2"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("test-42", response.getContentAsString()); + assertEquals(200, response.getStatus()); + assertEquals("test-42-;q=1;q=2-[1, 2]", response.getContentAsString()); } /* @@ -343,7 +349,7 @@ public void variableNamesWithUrlExtension() throws Exception { @Test public void doIt() throws Exception { initServletWithControllers(Spr6978Controller.class); - + MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo/100"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); @@ -375,9 +381,11 @@ public void doIt() throws Exception { public static class SimpleUriTemplateController { @RequestMapping("/{root}") - public void handle(@PathVariable("root") int root, Writer writer) throws IOException { + public void handle(@PathVariable("root") int root, @MatrixVariable(required=false, defaultValue="7") int q, + Writer writer) throws IOException { + assertEquals("Invalid path variable value", 42, root); - writer.write("test-" + root); + writer.write("test-" + root + "-" + q); } } @@ -389,10 +397,12 @@ public static class MultipleUriTemplateController { public void handle(@PathVariable("hotel") String hotel, @PathVariable int booking, @PathVariable String other, + @MatrixVariable(value="q", pathVar="hotel") int qHotel, + @MatrixVariable(value="q", pathVar="other") int qOther, Writer writer) throws IOException { assertEquals("Invalid path variable value", "42", hotel); assertEquals("Invalid path variable value", 21, booking); - writer.write("test-" + hotel + "-" + booking + "-" + other); + writer.write("test-" + hotel + "-q" + qHotel + "-" + booking + "-" + other + "-q" + qOther); } } @@ -401,9 +411,13 @@ public void handle(@PathVariable("hotel") String hotel, public static class ViewRenderingController { @RequestMapping("/hotels/{hotel}/bookings/{booking}-{other}") - public void handle(@PathVariable("hotel") String hotel, @PathVariable int booking, @PathVariable String other) { + public void handle(@PathVariable("hotel") String hotel, @PathVariable int booking, + @PathVariable String other, @MatrixVariable MultiValueMap<String, String> params) { + assertEquals("Invalid path variable value", "42", hotel); assertEquals("Invalid path variable value", 21, booking); + assertEquals(Arrays.asList("1", "2", "3"), params.get("q")); + assertEquals("R", params.getFirst("r")); } } @@ -499,12 +513,13 @@ public void handleHotel(@PathVariable String hotel, Writer writer) throws IOExce @Controller public static class CustomRegexController { - @RequestMapping("/{root:\\d+}") - public void handle(@PathVariable("root") int root, Writer writer) throws IOException { + @RequestMapping("/{root:\\d+}{params}") + public void handle(@PathVariable("root") int root, @PathVariable("params") String paramString, + @MatrixVariable List<Integer> q, Writer writer) throws IOException { + assertEquals("Invalid path variable value", 42, root); - writer.write("test-" + root); + writer.write("test-" + root + "-" + paramString + "-" + q); } - } @Controller @@ -515,7 +530,6 @@ public void testLatLong(@PathVariable Double latitude, @PathVariable Double long throws IOException { writer.write("latitude-" + latitude + "-longitude-" + longitude); } - } @@ -650,9 +664,9 @@ public void publish(@PathVariable final String type, @PathVariable final long id public static class ModelValidatingViewResolver implements ViewResolver { private final Map<String, Object> attrsToValidate; - + int validatedAttrCount; - + public ModelValidatingViewResolver(Map<String, Object> attrsToValidate) { this.attrsToValidate = attrsToValidate; } @@ -674,14 +688,14 @@ protected void renderMergedOutputModel(Map<String, Object> model, HttpServletReq }; } } - -// @Ignore("ControllerClassNameHandlerMapping") + +// @Ignore("ControllerClassNameHandlerMapping") // public void controllerClassName() throws Exception { // @Ignore("useDefaultSuffixPattern property not supported") // public void doubles() throws Exception { // @Ignore("useDefaultSuffixPattern property not supported") // public void noDefaultSuffixPattern() throws Exception { - + }
true
Other
spring-projects
spring-framework
2201dd8c45051230ad1a5a0e895cb5951edbfb74.json
Add support for matrix variables A new @MatrixVariable annotation allows injecting matrix variables into @RequestMapping methods. The matrix variables may appear in any path segment and should be wrapped in a URI template for request mapping purposes to ensure request matching is not affected by the order or the presence/absence of such variables. The @MatrixVariable annotation has an optional "pathVar" attribute that can be used to refer to the URI template where a matrix variable is located. Previously, ";" (semicolon) delimited content was removed from the path used for request mapping purposes. To preserve backwards compatibility that continues to be the case (except for the MVC namespace and Java config) and may be changed by setting the "removeSemicolonContent" property of RequestMappingHandlerMapping to "false". Applications using the MVC namespace and Java config do not need to do anything further to extract and use matrix variables. Issue: SPR-5499, SPR-7818
spring-webmvc/src/test/java/org/springframework/web/servlet/view/DefaultRequestToViewNameTranslatorTests.java
@@ -84,6 +84,12 @@ public void testGetViewNameWithNoExtension() { assertViewName(VIEW_NAME); } + @Test + public void testGetViewNameWithSemicolonContent() { + request.setRequestURI(CONTEXT_PATH + VIEW_NAME + ";a=A;b=B"); + assertViewName(VIEW_NAME); + } + @Test public void testGetViewNameWithPrefix() { final String prefix = "fiona_";
true
Other
spring-projects
spring-framework
2201dd8c45051230ad1a5a0e895cb5951edbfb74.json
Add support for matrix variables A new @MatrixVariable annotation allows injecting matrix variables into @RequestMapping methods. The matrix variables may appear in any path segment and should be wrapped in a URI template for request mapping purposes to ensure request matching is not affected by the order or the presence/absence of such variables. The @MatrixVariable annotation has an optional "pathVar" attribute that can be used to refer to the URI template where a matrix variable is located. Previously, ";" (semicolon) delimited content was removed from the path used for request mapping purposes. To preserve backwards compatibility that continues to be the case (except for the MVC namespace and Java config) and may be changed by setting the "removeSemicolonContent" property of RequestMappingHandlerMapping to "false". Applications using the MVC namespace and Java config do not need to do anything further to extract and use matrix variables. Issue: SPR-5499, SPR-7818
src/reference/docbook/mvc.xml
@@ -1054,6 +1054,93 @@ public class RelativePathUriTemplateController { <filename>/owners/*/pets/{petId}</filename>).</para> </section> + <section id="mvc-ann-matrix-variables"> + <title>Matrix Variables</title> + + <para>The URI specification + <ulink url="http://tools.ietf.org/html/rfc3986#section-3.3">RFC 3986</ulink> + defines the possibility of including name-value pairs within path segments. + There is no specific term used in the spec. + The general "URI path parameters" could be applied although the more unique + <ulink url="http://www.w3.org/DesignIssues/MatrixURIs.html">"Matrix URIs"</ulink>, + originating from an old post by Tim Berners-Lee, is also frequently used + and fairly well known. Within Spring MVC these are referred to + as matrix variables.</para> + + <para>Matrix variables can appear in any path segment, each matrix variable + separated with a ";" (semicolon). + For example: <code>"/cars;color=red;year=2012"</code>. + Multiple values may be either "," (comma) separated + <code>"color=red,green,blue"</code> or the variable name may be repeated + <code>"color=red;color=green;color=blue"</code>.</para> + + <para>If a URL is expected to contain matrix variables, the request mapping + pattern must represent them with a URI template. + This ensures the request can be matched correctly regardless of whether + matrix variables are present or not and in what order they are + provided.</para> + + <para>Below is an example of extracting the matrix variable "q":</para> + + <programlisting language="java">// GET /pets/42;q=11;r=22 + +@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET) +public void findPet(@PathVariable String petId, @MatrixVariable int q) { + + // petId == 42 + // q == 11 + +}</programlisting> + + <para>Since all path segments may contain matrix variables, in some cases + you need to be more specific to identify where the variable is expected to be:</para> + + <programlisting language="java">// GET /owners/42;q=11/pets/21;q=22 + +@RequestMapping(value = "/owners/{ownerId}/pets/{petId}", method = RequestMethod.GET) +public void findPet( + @MatrixVariable(value="q", pathVar="ownerId") int q1, + @MatrixVariable(value="q", pathVar="petId") int q2) { + + // q1 == 11 + // q2 == 22 + +}</programlisting> + + <para>A matrix variable may be defined as optional and a default value specified:</para> + + <programlisting language="java">// GET /pets/42 + +@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET) + public void findPet(@MatrixVariable(required=true, defaultValue="1") int q) { + + // q == 1 + + }</programlisting> + + <para>All matrix variables may be obtained in a Map:</para> + + <programlisting language="java">// GET /owners/42;q=11;r=12/pets/21;q=22;s=23 + +@RequestMapping(value = "/owners/{ownerId}/pets/{petId}", method = RequestMethod.GET) + public void findPet( + @MatrixVariable Map&lt;String, String&gt; matrixVars, + @MatrixVariable(pathVar="petId"") Map&lt;String, String&gt; petMatrixVars) { + + // matrixVars: ["q" : [11,22], "r" : 12, "s" : 23] + // petMatrixVars: ["q" : 11, "s" : 23] + + }</programlisting> + + <para>Note that to enable the use of matrix variables, you must set the + <classname>removeSemicolonContent</classname> property of + <classname>RequestMappingHandlerMapping</classname> to <code>false</code>. + By default it is set to <code>true</code> with the exception of the + MVC namespace and the MVC Java config both of which automatically enable + the use of matrix variables.</para> + + </section> + <section id="mvc-ann-requestmapping-consumes"> <title>Consumable Media Types</title> @@ -1254,6 +1341,12 @@ public class RelativePathUriTemplateController { linkend="mvc-ann-requestmapping-uri-templates" />.</para> </listitem> + <listitem> + <para><classname>@MatrixVariable</classname> annotated parameters + for access to name-value pairs located in URI path segments. + See <xref linkend="mvc-ann-matrix-variables" />.</para> + </listitem> + <listitem> <para><classname>@RequestParam</classname> annotated parameters for access to specific Servlet request parameters. Parameter
true
Other
spring-projects
spring-framework
2201dd8c45051230ad1a5a0e895cb5951edbfb74.json
Add support for matrix variables A new @MatrixVariable annotation allows injecting matrix variables into @RequestMapping methods. The matrix variables may appear in any path segment and should be wrapped in a URI template for request mapping purposes to ensure request matching is not affected by the order or the presence/absence of such variables. The @MatrixVariable annotation has an optional "pathVar" attribute that can be used to refer to the URI template where a matrix variable is located. Previously, ";" (semicolon) delimited content was removed from the path used for request mapping purposes. To preserve backwards compatibility that continues to be the case (except for the MVC namespace and Java config) and may be changed by setting the "removeSemicolonContent" property of RequestMappingHandlerMapping to "false". Applications using the MVC namespace and Java config do not need to do anything further to extract and use matrix variables. Issue: SPR-5499, SPR-7818
src/reference/docbook/new-in-3.2.xml
@@ -80,6 +80,14 @@ </section> + <section id="new-in-3.2-matrix-variables"> + <title>Matrix variables</title> + + <para>A new <interfacename>@MatrixVariable</interfacename> annotation + adds support for extracting matrix variables from the request URI. + For more details see <xref linkend="mvc-ann-matrix-variables"/>.</para> + </section> + <section id="new-in-3.2-webmvc-exception-handler-support"> <title>New <classname>ResponseEntityExceptionHandler</classname> class</title>
true
Other
spring-projects
spring-framework
ca017a488056701a07673b872e8faa40667cd32e.json
Introduce strategy for BeanInfo creation Before this commit, the CachedIntrospectionResults was hard-coded to create ExtendedBeanInfos for bean classes. The ExtendedBeanInfo support the JavaBeans property contract only. This commit introduces the BeanInfoFactory, a strategy for creating BeanInfos. Through this strategy, it is possible to support beans that do not necessarily implement the JavaBeans contract (i.e. have a different getter or setter style). BeanInfoFactories are are instantiated by the CachedIntrospectionResults, which looks for 'META-INF/spring.beanInfoFactories' files on the class path. These files contain one or more BeanInfoFactory class names. When a BeanInfo is to be created, the CachedIntrospectionResults will iterate through the factories, asking it to create a BeanInfo for the given bean class. If none of the factories support it, an ExtendedBeanInfo is created as a default. This commit also contains a change to Property, allowing BeanWrapperImpl to specify the property name at construction time (as opposed to using Property#resolveName(), which supports the JavaBeans contract only). Issue: SPR-9677
spring-beans/src/main/java/org/springframework/beans/BeanInfoFactory.java
@@ -0,0 +1,47 @@ +/* + * Copyright 2002-2012 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.beans; + +import java.beans.BeanInfo; +import java.beans.IntrospectionException; + +/** + * Strategy for creating {@link BeanInfo} instances. + * + * @author Arjen Poutsma + * @since 3.2 + */ +public interface BeanInfoFactory { + + /** + * Indicates whether a bean with the given class is supported by this factory. + * + * @param beanClass the bean class + * @return {@code true} if supported; {@code false} otherwise + */ + boolean supports(Class<?> beanClass); + + /** + * Returns the bean info for the given class. + * + * @param beanClass the bean class + * @return the bean info + * @throws IntrospectionException in case of exceptions + */ + BeanInfo getBeanInfo(Class<?> beanClass) throws IntrospectionException; + +}
true
Other
spring-projects
spring-framework
ca017a488056701a07673b872e8faa40667cd32e.json
Introduce strategy for BeanInfo creation Before this commit, the CachedIntrospectionResults was hard-coded to create ExtendedBeanInfos for bean classes. The ExtendedBeanInfo support the JavaBeans property contract only. This commit introduces the BeanInfoFactory, a strategy for creating BeanInfos. Through this strategy, it is possible to support beans that do not necessarily implement the JavaBeans contract (i.e. have a different getter or setter style). BeanInfoFactories are are instantiated by the CachedIntrospectionResults, which looks for 'META-INF/spring.beanInfoFactories' files on the class path. These files contain one or more BeanInfoFactory class names. When a BeanInfo is to be created, the CachedIntrospectionResults will iterate through the factories, asking it to create a BeanInfo for the given bean class. If none of the factories support it, an ExtendedBeanInfo is created as a default. This commit also contains a change to Property, allowing BeanWrapperImpl to specify the property name at construction time (as opposed to using Property#resolveName(), which supports the JavaBeans contract only). Issue: SPR-9677
spring-beans/src/main/java/org/springframework/beans/BeanWrapperImpl.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2012 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. @@ -518,7 +518,7 @@ private Object convertForProperty(String propertyName, Object oldValue, Object n private Property property(PropertyDescriptor pd) { GenericTypeAwarePropertyDescriptor typeAware = (GenericTypeAwarePropertyDescriptor) pd; - return new Property(typeAware.getBeanClass(), typeAware.getReadMethod(), typeAware.getWriteMethod()); + return new Property(typeAware.getBeanClass(), typeAware.getReadMethod(), typeAware.getWriteMethod(), typeAware.getName()); }
true
Other
spring-projects
spring-framework
ca017a488056701a07673b872e8faa40667cd32e.json
Introduce strategy for BeanInfo creation Before this commit, the CachedIntrospectionResults was hard-coded to create ExtendedBeanInfos for bean classes. The ExtendedBeanInfo support the JavaBeans property contract only. This commit introduces the BeanInfoFactory, a strategy for creating BeanInfos. Through this strategy, it is possible to support beans that do not necessarily implement the JavaBeans contract (i.e. have a different getter or setter style). BeanInfoFactories are are instantiated by the CachedIntrospectionResults, which looks for 'META-INF/spring.beanInfoFactories' files on the class path. These files contain one or more BeanInfoFactory class names. When a BeanInfo is to be created, the CachedIntrospectionResults will iterate through the factories, asking it to create a BeanInfo for the given bean class. If none of the factories support it, an ExtendedBeanInfo is created as a default. This commit also contains a change to Property, allowing BeanWrapperImpl to specify the property name at construction time (as opposed to using Property#resolveName(), which supports the JavaBeans contract only). Issue: SPR-9677
spring-beans/src/main/java/org/springframework/beans/CachedIntrospectionResults.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2012 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. @@ -20,19 +20,25 @@ import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; +import java.io.IOException; import java.lang.ref.Reference; import java.lang.ref.WeakReference; +import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; +import java.util.Properties; import java.util.Set; import java.util.WeakHashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.springframework.core.annotation.AnnotationAwareOrderComparator; +import org.springframework.core.io.support.PropertiesLoaderUtils; import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; @@ -58,6 +64,12 @@ */ public class CachedIntrospectionResults { + /** + * The location to look for the bean info mapping files. Can be present in multiple JAR files. + */ + public static final String BEAN_INFO_FACTORIES_LOCATION = "META-INF/spring.beanInfoFactories"; + + private static final Log logger = LogFactory.getLog(CachedIntrospectionResults.class); /** @@ -73,6 +85,11 @@ public class CachedIntrospectionResults { */ static final Map<Class, Object> classCache = Collections.synchronizedMap(new WeakHashMap<Class, Object>()); + /** Stores the BeanInfoFactory instances */ + private static List<BeanInfoFactory> beanInfoFactories; + + private static final Object beanInfoFactoriesMutex = new Object(); + /** * Accept the given ClassLoader as cache-safe, even if its classes would @@ -221,7 +238,20 @@ private CachedIntrospectionResults(Class beanClass, boolean cacheFullMetadata) t if (logger.isTraceEnabled()) { logger.trace("Getting BeanInfo for class [" + beanClass.getName() + "]"); } - this.beanInfo = new ExtendedBeanInfo(Introspector.getBeanInfo(beanClass)); + + BeanInfo beanInfo = null; + List<BeanInfoFactory> beanInfoFactories = getBeanInfoFactories(beanClass.getClassLoader()); + for (BeanInfoFactory beanInfoFactory : beanInfoFactories) { + if (beanInfoFactory.supports(beanClass)) { + beanInfo = beanInfoFactory.getBeanInfo(beanClass); + break; + } + } + if (beanInfo == null) { + // If none of the factories supported the class, use the default + beanInfo = new ExtendedBeanInfo(Introspector.getBeanInfo(beanClass)); + } + this.beanInfo = beanInfo; // Immediately remove class from Introspector cache, to allow for proper // garbage collection on class loader shutdown - we cache it here anyway, @@ -305,4 +335,61 @@ private PropertyDescriptor buildGenericTypeAwarePropertyDescriptor(Class beanCla } } + private static List<BeanInfoFactory> getBeanInfoFactories(ClassLoader classLoader) { + if (beanInfoFactories == null) { + synchronized (beanInfoFactoriesMutex) { + if (beanInfoFactories == null) { + try { + Properties properties = + PropertiesLoaderUtils.loadAllProperties( + BEAN_INFO_FACTORIES_LOCATION, classLoader); + + if (logger.isDebugEnabled()) { + logger.debug("Loaded BeanInfoFactories: " + properties.keySet()); + } + + List<BeanInfoFactory> factories = new ArrayList<BeanInfoFactory>(properties.size()); + + for (Object key : properties.keySet()) { + if (key instanceof String) { + String className = (String) key; + BeanInfoFactory factory = instantiateBeanInfoFactory(className, classLoader); + factories.add(factory); + } + } + + Collections.sort(factories, new AnnotationAwareOrderComparator()); + + beanInfoFactories = Collections.synchronizedList(factories); + } + catch (IOException ex) { + throw new IllegalStateException( + "Unable to load BeanInfoFactories from location [" + BEAN_INFO_FACTORIES_LOCATION + "]", ex); + } + } + } + } + return beanInfoFactories; + } + + private static BeanInfoFactory instantiateBeanInfoFactory(String className, + ClassLoader classLoader) { + try { + Class<?> factoryClass = ClassUtils.forName(className, classLoader); + if (!BeanInfoFactory.class.isAssignableFrom(factoryClass)) { + throw new FatalBeanException( + "Class [" + className + "] does not implement the [" + + BeanInfoFactory.class.getName() + "] interface"); + } + return (BeanInfoFactory) BeanUtils.instantiate(factoryClass); + } + catch (ClassNotFoundException ex) { + throw new FatalBeanException( + "BeanInfoFactory class [" + className + "] not found", ex); + } + catch (LinkageError err) { + throw new FatalBeanException("Invalid BeanInfoFactory class [" + className + + "]: problem with handler class file or dependent class", err); + } + } }
true
Other
spring-projects
spring-framework
ca017a488056701a07673b872e8faa40667cd32e.json
Introduce strategy for BeanInfo creation Before this commit, the CachedIntrospectionResults was hard-coded to create ExtendedBeanInfos for bean classes. The ExtendedBeanInfo support the JavaBeans property contract only. This commit introduces the BeanInfoFactory, a strategy for creating BeanInfos. Through this strategy, it is possible to support beans that do not necessarily implement the JavaBeans contract (i.e. have a different getter or setter style). BeanInfoFactories are are instantiated by the CachedIntrospectionResults, which looks for 'META-INF/spring.beanInfoFactories' files on the class path. These files contain one or more BeanInfoFactory class names. When a BeanInfo is to be created, the CachedIntrospectionResults will iterate through the factories, asking it to create a BeanInfo for the given bean class. If none of the factories support it, an ExtendedBeanInfo is created as a default. This commit also contains a change to Property, allowing BeanWrapperImpl to specify the property name at construction time (as opposed to using Property#resolveName(), which supports the JavaBeans contract only). Issue: SPR-9677
spring-beans/src/test/java/org/springframework/beans/CachedIntrospectionResultsTests.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2008 the original author or authors. + * Copyright 2002-2012 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. @@ -16,21 +16,24 @@ package org.springframework.beans; -import static org.junit.Assert.*; +import java.beans.BeanInfo; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import org.junit.Test; -import org.springframework.core.OverridingClassLoader; - import test.beans.TestBean; +import org.springframework.core.OverridingClassLoader; + /** * @author Juergen Hoeller * @author Chris Beams + * @author Arjen Poutsma */ public final class CachedIntrospectionResultsTests { @Test - public void testAcceptClassLoader() throws Exception { + public void acceptClassLoader() throws Exception { BeanWrapper bw = new BeanWrapperImpl(TestBean.class); assertTrue(bw.isWritableProperty("name")); assertTrue(bw.isWritableProperty("age")); @@ -50,4 +53,12 @@ public void testAcceptClassLoader() throws Exception { assertTrue(CachedIntrospectionResults.classCache.containsKey(TestBean.class)); } + @Test + public void customBeanInfoFactory() throws Exception { + CachedIntrospectionResults results = CachedIntrospectionResults.forClass(CachedIntrospectionResultsTests.class); + BeanInfo beanInfo = results.getBeanInfo(); + + assertTrue("Invalid BeanInfo instance", beanInfo instanceof DummyBeanInfoFactory.DummyBeanInfo); + } + }
true
Other
spring-projects
spring-framework
ca017a488056701a07673b872e8faa40667cd32e.json
Introduce strategy for BeanInfo creation Before this commit, the CachedIntrospectionResults was hard-coded to create ExtendedBeanInfos for bean classes. The ExtendedBeanInfo support the JavaBeans property contract only. This commit introduces the BeanInfoFactory, a strategy for creating BeanInfos. Through this strategy, it is possible to support beans that do not necessarily implement the JavaBeans contract (i.e. have a different getter or setter style). BeanInfoFactories are are instantiated by the CachedIntrospectionResults, which looks for 'META-INF/spring.beanInfoFactories' files on the class path. These files contain one or more BeanInfoFactory class names. When a BeanInfo is to be created, the CachedIntrospectionResults will iterate through the factories, asking it to create a BeanInfo for the given bean class. If none of the factories support it, an ExtendedBeanInfo is created as a default. This commit also contains a change to Property, allowing BeanWrapperImpl to specify the property name at construction time (as opposed to using Property#resolveName(), which supports the JavaBeans contract only). Issue: SPR-9677
spring-beans/src/test/java/org/springframework/beans/DummyBeanInfoFactory.java
@@ -0,0 +1,41 @@ +/* + * Copyright 2002-2012 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.beans; + +import java.beans.BeanInfo; +import java.beans.PropertyDescriptor; +import java.beans.SimpleBeanInfo; + +public class DummyBeanInfoFactory implements BeanInfoFactory { + + public boolean supports(Class<?> beanClass) { + return CachedIntrospectionResultsTests.class.equals(beanClass); + } + + public BeanInfo getBeanInfo(Class<?> beanClass) { + return new DummyBeanInfo(); + } + + public static class DummyBeanInfo extends SimpleBeanInfo { + + @Override + public PropertyDescriptor[] getPropertyDescriptors() { + return new PropertyDescriptor[0]; + } + } + +}
true
Other
spring-projects
spring-framework
ca017a488056701a07673b872e8faa40667cd32e.json
Introduce strategy for BeanInfo creation Before this commit, the CachedIntrospectionResults was hard-coded to create ExtendedBeanInfos for bean classes. The ExtendedBeanInfo support the JavaBeans property contract only. This commit introduces the BeanInfoFactory, a strategy for creating BeanInfos. Through this strategy, it is possible to support beans that do not necessarily implement the JavaBeans contract (i.e. have a different getter or setter style). BeanInfoFactories are are instantiated by the CachedIntrospectionResults, which looks for 'META-INF/spring.beanInfoFactories' files on the class path. These files contain one or more BeanInfoFactory class names. When a BeanInfo is to be created, the CachedIntrospectionResults will iterate through the factories, asking it to create a BeanInfo for the given bean class. If none of the factories support it, an ExtendedBeanInfo is created as a default. This commit also contains a change to Property, allowing BeanWrapperImpl to specify the property name at construction time (as opposed to using Property#resolveName(), which supports the JavaBeans contract only). Issue: SPR-9677
spring-beans/src/test/resources/META-INF/spring.beanInfoFactories
@@ -0,0 +1,3 @@ +# Dummy bean info factories file, used by CachedIntrospectionResultsTests + +org.springframework.beans.DummyBeanInfoFactory \ No newline at end of file
true
Other
spring-projects
spring-framework
ca017a488056701a07673b872e8faa40667cd32e.json
Introduce strategy for BeanInfo creation Before this commit, the CachedIntrospectionResults was hard-coded to create ExtendedBeanInfos for bean classes. The ExtendedBeanInfo support the JavaBeans property contract only. This commit introduces the BeanInfoFactory, a strategy for creating BeanInfos. Through this strategy, it is possible to support beans that do not necessarily implement the JavaBeans contract (i.e. have a different getter or setter style). BeanInfoFactories are are instantiated by the CachedIntrospectionResults, which looks for 'META-INF/spring.beanInfoFactories' files on the class path. These files contain one or more BeanInfoFactory class names. When a BeanInfo is to be created, the CachedIntrospectionResults will iterate through the factories, asking it to create a BeanInfo for the given bean class. If none of the factories support it, an ExtendedBeanInfo is created as a default. This commit also contains a change to Property, allowing BeanWrapperImpl to specify the property name at construction time (as opposed to using Property#resolveName(), which supports the JavaBeans contract only). Issue: SPR-9677
spring-core/src/main/java/org/springframework/core/convert/Property.java
@@ -57,11 +57,20 @@ public final class Property { public Property(Class<?> objectType, Method readMethod, Method writeMethod) { + this(objectType, readMethod, writeMethod, null); + } + + public Property(Class<?> objectType, Method readMethod, Method writeMethod, String name) { this.objectType = objectType; this.readMethod = readMethod; this.writeMethod = writeMethod; this.methodParameter = resolveMethodParameter(); - this.name = resolveName(); + if (name != null) { + this.name = name; + } + else { + this.name = resolveName(); + } this.annotations = resolveAnnotations(); }
true
Other
spring-projects
spring-framework
c9b7b132fb0370f51169929b704862b71183b49a.json
Support generic types in @RequestBody arguments This change makes it possible to declare an @RequestBody argument with a generic type (e.g. List<Foo>). If a GenericHttpMessageConverter implementation supports the method argument, then the request will be converted to the apropiate target type. The new GenericHttpMessageConverter is implemented by the MappingJacksonHttpMessageConverter and also by a new Jaxb2CollectionHttpMessageConverter that can read read a generic Collection where the generic type is a JAXB type annotated with @XmlRootElement or @XmlType. Issue: SPR-9570
spring-web/src/main/java/org/springframework/web/client/HttpMessageConverterExtractor.java
@@ -42,6 +42,8 @@ private final Type responseType; + private final Class<T> responseClass; + private final List<HttpMessageConverter<?>> messageConverters; private final Log logger; @@ -64,10 +66,12 @@ public HttpMessageConverterExtractor(Type responseType, List<HttpMessageConverte this(responseType, messageConverters, LogFactory.getLog(HttpMessageConverterExtractor.class)); } + @SuppressWarnings("unchecked") HttpMessageConverterExtractor(Type responseType, List<HttpMessageConverter<?>> messageConverters, Log logger) { Assert.notNull(responseType, "'responseType' must not be null"); Assert.notEmpty(messageConverters, "'messageConverters' must not be empty"); this.responseType = responseType; + this.responseClass = (responseType instanceof Class) ? (Class<T>) responseType : null; this.messageConverters = messageConverters; this.logger = logger; } @@ -79,28 +83,24 @@ public T extractData(ClientHttpResponse response) throws IOException { } MediaType contentType = getContentType(response); - Class<T> responseClass = null; - if (this.responseType instanceof Class) { - responseClass = (Class) this.responseType; - } for (HttpMessageConverter messageConverter : this.messageConverters) { - if (responseClass != null) { - if (messageConverter.canRead(responseClass, contentType)) { + if (messageConverter instanceof GenericHttpMessageConverter) { + GenericHttpMessageConverter genericMessageConverter = (GenericHttpMessageConverter) messageConverter; + if (genericMessageConverter.canRead(this.responseType, contentType)) { if (logger.isDebugEnabled()) { - logger.debug("Reading [" + responseClass.getName() + "] as \"" + + logger.debug("Reading [" + this.responseType + "] as \"" + contentType + "\" using [" + messageConverter + "]"); } - return (T) messageConverter.read(responseClass, response); + return (T) genericMessageConverter.read(this.responseType, response); } } - else if (messageConverter instanceof GenericHttpMessageConverter) { - GenericHttpMessageConverter genericMessageConverter = (GenericHttpMessageConverter) messageConverter; - if (genericMessageConverter.canRead(this.responseType, contentType)) { + if (this.responseClass != null) { + if (messageConverter.canRead(this.responseClass, contentType)) { if (logger.isDebugEnabled()) { - logger.debug("Reading [" + this.responseType + "] as \"" + + logger.debug("Reading [" + this.responseClass.getName() + "] as \"" + contentType + "\" using [" + messageConverter + "]"); } - return (T) genericMessageConverter.read(this.responseType, response); + return (T) messageConverter.read(this.responseClass, response); } } }
true
Other
spring-projects
spring-framework
c9b7b132fb0370f51169929b704862b71183b49a.json
Support generic types in @RequestBody arguments This change makes it possible to declare an @RequestBody argument with a generic type (e.g. List<Foo>). If a GenericHttpMessageConverter implementation supports the method argument, then the request will be converted to the apropiate target type. The new GenericHttpMessageConverter is implemented by the MappingJacksonHttpMessageConverter and also by a new Jaxb2CollectionHttpMessageConverter that can read read a generic Collection where the generic type is a JAXB type annotated with @XmlRootElement or @XmlType. Issue: SPR-9570
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodArgumentResolver.java
@@ -17,6 +17,7 @@ package org.springframework.web.servlet.mvc.method.annotation; import java.io.IOException; +import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashSet; @@ -30,6 +31,7 @@ import org.springframework.core.MethodParameter; import org.springframework.http.HttpInputMessage; import org.springframework.http.MediaType; +import org.springframework.http.converter.GenericHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.util.Assert; @@ -85,8 +87,8 @@ private static List<MediaType> getAllSupportedMediaTypes(List<HttpMessageConvert * @throws IOException if the reading from the request fails * @throws HttpMediaTypeNotSupportedException if no suitable message converter is found */ - protected <T> Object readWithMessageConverters(NativeWebRequest webRequest, MethodParameter methodParam, Class<T> paramType) throws IOException, - HttpMediaTypeNotSupportedException { + protected <T> Object readWithMessageConverters(NativeWebRequest webRequest, + MethodParameter methodParam, Type paramType) throws IOException, HttpMediaTypeNotSupportedException { HttpInputMessage inputMessage = createInputMessage(webRequest); return readWithMessageConverters(inputMessage, methodParam, paramType); @@ -106,20 +108,34 @@ protected <T> Object readWithMessageConverters(NativeWebRequest webRequest, Meth */ @SuppressWarnings("unchecked") protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage, MethodParameter methodParam, - Class<T> paramType) throws IOException, HttpMediaTypeNotSupportedException { + Type paramType) throws IOException, HttpMediaTypeNotSupportedException { MediaType contentType = inputMessage.getHeaders().getContentType(); if (contentType == null) { contentType = MediaType.APPLICATION_OCTET_STREAM; } + Class<T> paramClass = (paramType instanceof Class) ? (Class) paramType : null; + for (HttpMessageConverter<?> messageConverter : this.messageConverters) { - if (messageConverter.canRead(paramType, contentType)) { - if (logger.isDebugEnabled()) { - logger.debug("Reading [" + paramType.getName() + "] as \"" + contentType + "\" using [" + - messageConverter + "]"); + if (messageConverter instanceof GenericHttpMessageConverter) { + GenericHttpMessageConverter genericMessageConverter = (GenericHttpMessageConverter) messageConverter; + if (genericMessageConverter.canRead(paramType, contentType)) { + if (logger.isDebugEnabled()) { + logger.debug("Reading [" + paramType + "] as \"" + + contentType + "\" using [" + messageConverter + "]"); + } + return (T) genericMessageConverter.read(paramType, inputMessage); + } + } + if (paramClass != null) { + if (messageConverter.canRead(paramClass, contentType)) { + if (logger.isDebugEnabled()) { + logger.debug("Reading [" + paramClass.getName() + "] as \"" + contentType + "\" using [" + + messageConverter + "]"); + } + return ((HttpMessageConverter<T>) messageConverter).read(paramClass, inputMessage); } - return ((HttpMessageConverter<T>) messageConverter).read(paramType, inputMessage); } }
true
Other
spring-projects
spring-framework
c9b7b132fb0370f51169929b704862b71183b49a.json
Support generic types in @RequestBody arguments This change makes it possible to declare an @RequestBody argument with a generic type (e.g. List<Foo>). If a GenericHttpMessageConverter implementation supports the method argument, then the request will be converted to the apropiate target type. The new GenericHttpMessageConverter is implemented by the MappingJacksonHttpMessageConverter and also by a new Jaxb2CollectionHttpMessageConverter that can read read a generic Collection where the generic type is a JAXB type annotated with @XmlRootElement or @XmlType. Issue: SPR-9570
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessor.java
@@ -79,13 +79,13 @@ public Object resolveArgument( throws IOException, HttpMediaTypeNotSupportedException { HttpInputMessage inputMessage = createInputMessage(webRequest); - Class<?> paramType = getHttpEntityType(parameter); + Type paramType = getHttpEntityType(parameter); Object body = readWithMessageConverters(webRequest, parameter, paramType); return new HttpEntity<Object>(body, inputMessage.getHeaders()); } - private Class<?> getHttpEntityType(MethodParameter parameter) { + private Type getHttpEntityType(MethodParameter parameter) { Assert.isAssignable(HttpEntity.class, parameter.getParameterType()); ParameterizedType type = (ParameterizedType) parameter.getGenericParameterType(); if (type.getActualTypeArguments().length == 1) { @@ -97,10 +97,12 @@ else if (typeArgument instanceof GenericArrayType) { Type componentType = ((GenericArrayType) typeArgument).getGenericComponentType(); if (componentType instanceof Class) { // Surely, there should be a nicer way to determine the array type - Object array = Array.newInstance((Class<?>) componentType, 0); - return array.getClass(); + return Array.newInstance((Class<?>) componentType, 0).getClass(); } } + else if (typeArgument instanceof ParameterizedType) { + return typeArgument; + } } throw new IllegalArgumentException("HttpEntity parameter (" + parameter.getParameterName() + ") " + "in method " + parameter.getMethod() + "is not parameterized");
true
Other
spring-projects
spring-framework
c9b7b132fb0370f51169929b704862b71183b49a.json
Support generic types in @RequestBody arguments This change makes it possible to declare an @RequestBody argument with a generic type (e.g. List<Foo>). If a GenericHttpMessageConverter implementation supports the method argument, then the request will be converted to the apropiate target type. The new GenericHttpMessageConverter is implemented by the MappingJacksonHttpMessageConverter and also by a new Jaxb2CollectionHttpMessageConverter that can read read a generic Collection where the generic type is a JAXB type annotated with @XmlRootElement or @XmlType. Issue: SPR-9570
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessor.java
@@ -18,6 +18,7 @@ import java.io.IOException; import java.lang.annotation.Annotation; +import java.lang.reflect.Type; import java.util.List; import org.springframework.core.Conventions; @@ -86,7 +87,7 @@ public boolean supportsReturnType(MethodParameter returnType) { public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { - Object argument = readWithMessageConverters(webRequest, parameter, parameter.getParameterType()); + Object argument = readWithMessageConverters(webRequest, parameter, parameter.getGenericParameterType()); String name = Conventions.getVariableNameForParameter(parameter); WebDataBinder binder = binderFactory.createBinder(webRequest, argument, name); @@ -134,7 +135,7 @@ private boolean isBindExceptionRequired(WebDataBinder binder, MethodParameter pa @Override protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage, - MethodParameter methodParam, Class<T> paramType) throws IOException, HttpMediaTypeNotSupportedException { + MethodParameter methodParam, Type paramType) throws IOException, HttpMediaTypeNotSupportedException { if (inputMessage.getBody() != null) { return super.readWithMessageConverters(inputMessage, methodParam, paramType);
true
Other
spring-projects
spring-framework
c9b7b132fb0370f51169929b704862b71183b49a.json
Support generic types in @RequestBody arguments This change makes it possible to declare an @RequestBody argument with a generic type (e.g. List<Foo>). If a GenericHttpMessageConverter implementation supports the method argument, then the request will be converted to the apropiate target type. The new GenericHttpMessageConverter is implemented by the MappingJacksonHttpMessageConverter and also by a new Jaxb2CollectionHttpMessageConverter that can read read a generic Collection where the generic type is a JAXB type annotated with @XmlRootElement or @XmlType. Issue: SPR-9570
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessorMockTests.java
@@ -0,0 +1,305 @@ +/* + * Copyright 2002-2012 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.web.servlet.mvc.method.annotation; +import static org.easymock.EasyMock.capture; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.eq; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.isA; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.reset; +import static org.easymock.EasyMock.verify; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.springframework.web.servlet.HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE; + +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.Collections; + +import org.easymock.Capture; +import org.junit.Before; +import org.junit.Test; +import org.springframework.core.MethodParameter; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpInputMessage; +import org.springframework.http.HttpOutputMessage; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.web.HttpMediaTypeNotAcceptableException; +import org.springframework.web.HttpMediaTypeNotSupportedException; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.context.request.ServletWebRequest; +import org.springframework.web.method.support.ModelAndViewContainer; +import org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor; + +/** + * Test fixture for {@link HttpEntityMethodProcessor} delegating to a mock + * {@link HttpMessageConverter}. + * + * <p>Also see {@link HttpEntityMethodProcessorTests}. + * + * @author Arjen Poutsma + * @author Rossen Stoyanchev + */ +public class HttpEntityMethodProcessorMockTests { + + private HttpEntityMethodProcessor processor; + + private HttpMessageConverter<String> messageConverter; + + private MethodParameter paramHttpEntity; + private MethodParameter paramResponseEntity; + private MethodParameter paramInt; + private MethodParameter returnTypeResponseEntity; + private MethodParameter returnTypeHttpEntity; + private MethodParameter returnTypeInt; + private MethodParameter returnTypeResponseEntityProduces; + + private ModelAndViewContainer mavContainer; + + private ServletWebRequest webRequest; + + private MockHttpServletResponse servletResponse; + + private MockHttpServletRequest servletRequest; + + @SuppressWarnings("unchecked") + @Before + public void setUp() throws Exception { + messageConverter = createMock(HttpMessageConverter.class); + expect(messageConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); + replay(messageConverter); + + processor = new HttpEntityMethodProcessor(Collections.<HttpMessageConverter<?>>singletonList(messageConverter)); + reset(messageConverter); + + + Method handle1 = getClass().getMethod("handle1", HttpEntity.class, ResponseEntity.class, Integer.TYPE); + paramHttpEntity = new MethodParameter(handle1, 0); + paramResponseEntity = new MethodParameter(handle1, 1); + paramInt = new MethodParameter(handle1, 2); + returnTypeResponseEntity = new MethodParameter(handle1, -1); + + returnTypeHttpEntity = new MethodParameter(getClass().getMethod("handle2", HttpEntity.class), -1); + + returnTypeInt = new MethodParameter(getClass().getMethod("handle3"), -1); + + returnTypeResponseEntityProduces = new MethodParameter(getClass().getMethod("handle4"), -1); + + mavContainer = new ModelAndViewContainer(); + + servletRequest = new MockHttpServletRequest(); + servletResponse = new MockHttpServletResponse(); + webRequest = new ServletWebRequest(servletRequest, servletResponse); + } + + @Test + public void supportsParameter() { + assertTrue("HttpEntity parameter not supported", processor.supportsParameter(paramHttpEntity)); + assertFalse("ResponseEntity parameter supported", processor.supportsParameter(paramResponseEntity)); + assertFalse("non-entity parameter supported", processor.supportsParameter(paramInt)); + } + + @Test + public void supportsReturnType() { + assertTrue("ResponseEntity return type not supported", processor.supportsReturnType(returnTypeResponseEntity)); + assertTrue("HttpEntity return type not supported", processor.supportsReturnType(returnTypeHttpEntity)); + assertFalse("non-ResponseBody return type supported", processor.supportsReturnType(returnTypeInt)); + } + + @Test + public void resolveArgument() throws Exception { + MediaType contentType = MediaType.TEXT_PLAIN; + servletRequest.addHeader("Content-Type", contentType.toString()); + + String body = "Foo"; + expect(messageConverter.canRead(String.class, contentType)).andReturn(true); + expect(messageConverter.read(eq(String.class), isA(HttpInputMessage.class))).andReturn(body); + replay(messageConverter); + + Object result = processor.resolveArgument(paramHttpEntity, mavContainer, webRequest, null); + + assertTrue(result instanceof HttpEntity); + assertFalse("The requestHandled flag shouldn't change", mavContainer.isRequestHandled()); + assertEquals("Invalid argument", body, ((HttpEntity<?>) result).getBody()); + verify(messageConverter); + } + + @Test(expected = HttpMediaTypeNotSupportedException.class) + public void resolveArgumentNotReadable() throws Exception { + MediaType contentType = MediaType.TEXT_PLAIN; + servletRequest.addHeader("Content-Type", contentType.toString()); + + expect(messageConverter.getSupportedMediaTypes()).andReturn(Arrays.asList(contentType)); + expect(messageConverter.canRead(String.class, contentType)).andReturn(false); + replay(messageConverter); + + processor.resolveArgument(paramHttpEntity, mavContainer, webRequest, null); + + fail("Expected exception"); + } + + @Test(expected = HttpMediaTypeNotSupportedException.class) + public void resolveArgumentNoContentType() throws Exception { + processor.resolveArgument(paramHttpEntity, mavContainer, webRequest, null); + fail("Expected exception"); + } + + @Test + public void handleReturnValue() throws Exception { + String body = "Foo"; + ResponseEntity<String> returnValue = new ResponseEntity<String>(body, HttpStatus.OK); + + MediaType accepted = MediaType.TEXT_PLAIN; + servletRequest.addHeader("Accept", accepted.toString()); + + expect(messageConverter.canWrite(String.class, null)).andReturn(true); + expect(messageConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); + expect(messageConverter.canWrite(String.class, accepted)).andReturn(true); + messageConverter.write(eq(body), eq(accepted), isA(HttpOutputMessage.class)); + replay(messageConverter); + + processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest); + + assertTrue(mavContainer.isRequestHandled()); + verify(messageConverter); + } + + @Test + public void handleReturnValueProduces() throws Exception { + String body = "Foo"; + ResponseEntity<String> returnValue = new ResponseEntity<String>(body, HttpStatus.OK); + + servletRequest.addHeader("Accept", "text/*"); + servletRequest.setAttribute(PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, Collections.singleton(MediaType.TEXT_HTML)); + + expect(messageConverter.canWrite(String.class, MediaType.TEXT_HTML)).andReturn(true); + messageConverter.write(eq(body), eq(MediaType.TEXT_HTML), isA(HttpOutputMessage.class)); + replay(messageConverter); + + processor.handleReturnValue(returnValue, returnTypeResponseEntityProduces, mavContainer, webRequest); + + assertTrue(mavContainer.isRequestHandled()); + verify(messageConverter); + } + + @Test(expected = HttpMediaTypeNotAcceptableException.class) + public void handleReturnValueNotAcceptable() throws Exception { + String body = "Foo"; + ResponseEntity<String> returnValue = new ResponseEntity<String>(body, HttpStatus.OK); + + MediaType accepted = MediaType.APPLICATION_ATOM_XML; + servletRequest.addHeader("Accept", accepted.toString()); + + expect(messageConverter.canWrite(String.class, null)).andReturn(true); + expect(messageConverter.getSupportedMediaTypes()).andReturn(Arrays.asList(MediaType.TEXT_PLAIN)); + expect(messageConverter.canWrite(String.class, accepted)).andReturn(false); + replay(messageConverter); + + processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest); + + fail("Expected exception"); + } + + @Test(expected = HttpMediaTypeNotAcceptableException.class) + public void handleReturnValueNotAcceptableProduces() throws Exception { + String body = "Foo"; + ResponseEntity<String> returnValue = new ResponseEntity<String>(body, HttpStatus.OK); + + MediaType accepted = MediaType.TEXT_PLAIN; + servletRequest.addHeader("Accept", accepted.toString()); + + expect(messageConverter.canWrite(String.class, null)).andReturn(true); + expect(messageConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); + expect(messageConverter.canWrite(String.class, accepted)).andReturn(false); + replay(messageConverter); + + processor.handleReturnValue(returnValue, returnTypeResponseEntityProduces, mavContainer, webRequest); + + fail("Expected exception"); + } + + // SPR-9142 + + @Test(expected=HttpMediaTypeNotAcceptableException.class) + public void handleReturnValueNotAcceptableParseError() throws Exception { + ResponseEntity<String> returnValue = new ResponseEntity<String>("Body", HttpStatus.ACCEPTED); + servletRequest.addHeader("Accept", "01"); + + processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest); + fail("Expected exception"); + } + + @Test + public void responseHeaderNoBody() throws Exception { + HttpHeaders headers = new HttpHeaders(); + headers.set("headerName", "headerValue"); + ResponseEntity<String> returnValue = new ResponseEntity<String>(headers, HttpStatus.ACCEPTED); + + processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest); + + assertTrue(mavContainer.isRequestHandled()); + assertEquals("headerValue", servletResponse.getHeader("headerName")); + } + + @Test + public void responseHeaderAndBody() throws Exception { + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.set("header", "headerValue"); + ResponseEntity<String> returnValue = new ResponseEntity<String>("body", responseHeaders, HttpStatus.ACCEPTED); + + Capture<HttpOutputMessage> outputMessage = new Capture<HttpOutputMessage>(); + expect(messageConverter.canWrite(String.class, null)).andReturn(true); + expect(messageConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); + expect(messageConverter.canWrite(String.class, MediaType.TEXT_PLAIN)).andReturn(true); + messageConverter.write(eq("body"), eq(MediaType.TEXT_PLAIN), capture(outputMessage)); + replay(messageConverter); + + processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest); + + assertTrue(mavContainer.isRequestHandled()); + assertEquals("headerValue", outputMessage.getValue().getHeaders().get("header").get(0)); + verify(messageConverter); + } + + public ResponseEntity<String> handle1(HttpEntity<String> httpEntity, ResponseEntity<String> responseEntity, int i) { + return responseEntity; + } + + public HttpEntity<?> handle2(HttpEntity<?> entity) { + return entity; + } + + public int handle3() { + return 42; + } + + @RequestMapping(produces = {"text/html", "application/xhtml+xml"}) + public ResponseEntity<String> handle4() { + return null; + } + + +} \ No newline at end of file
true
Other
spring-projects
spring-framework
c9b7b132fb0370f51169929b704862b71183b49a.json
Support generic types in @RequestBody arguments This change makes it possible to declare an @RequestBody argument with a generic type (e.g. List<Foo>). If a GenericHttpMessageConverter implementation supports the method argument, then the request will be converted to the apropiate target type. The new GenericHttpMessageConverter is implemented by the MappingJacksonHttpMessageConverter and also by a new Jaxb2CollectionHttpMessageConverter that can read read a generic Collection where the generic type is a JAXB type annotated with @XmlRootElement or @XmlType. Issue: SPR-9570
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessorTests.java
@@ -15,64 +15,40 @@ */ package org.springframework.web.servlet.mvc.method.annotation; -import static org.easymock.EasyMock.capture; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.eq; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.isA; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.reset; -import static org.easymock.EasyMock.verify; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.springframework.web.servlet.HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE; +import static org.junit.Assert.assertNotNull; import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.Collections; +import java.util.ArrayList; +import java.util.List; -import org.easymock.Capture; import org.junit.Before; import org.junit.Test; import org.springframework.core.MethodParameter; import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpInputMessage; -import org.springframework.http.HttpOutputMessage; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.web.HttpMediaTypeNotAcceptableException; -import org.springframework.web.HttpMediaTypeNotSupportedException; -import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.support.WebDataBinderFactory; +import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.method.support.ModelAndViewContainer; -import org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor; /** - * Test fixture with {@link HttpEntityMethodProcessor} and mock {@link HttpMessageConverter}. + * Test fixture with {@link HttpEntityMethodProcessor} delegating to + * actual {@link HttpMessageConverter} instances. + * + * <p>Also see {@link HttpEntityMethodProcessorMockTests}. * - * @author Arjen Poutsma * @author Rossen Stoyanchev */ public class HttpEntityMethodProcessorTests { - private HttpEntityMethodProcessor processor; - - private HttpMessageConverter<String> messageConverter; - - private MethodParameter paramHttpEntity; - private MethodParameter paramResponseEntity; - private MethodParameter paramInt; - private MethodParameter returnTypeResponseEntity; - private MethodParameter returnTypeHttpEntity; - private MethodParameter returnTypeInt; - private MethodParameter returnTypeResponseEntityProduces; + private MethodParameter paramList; + private MethodParameter paramSimpleBean; private ModelAndViewContainer mavContainer; @@ -82,28 +58,12 @@ public class HttpEntityMethodProcessorTests { private MockHttpServletRequest servletRequest; - @SuppressWarnings("unchecked") @Before public void setUp() throws Exception { - messageConverter = createMock(HttpMessageConverter.class); - expect(messageConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); - replay(messageConverter); - - processor = new HttpEntityMethodProcessor(Collections.<HttpMessageConverter<?>>singletonList(messageConverter)); - reset(messageConverter); - - - Method handle1 = getClass().getMethod("handle1", HttpEntity.class, ResponseEntity.class, Integer.TYPE); - paramHttpEntity = new MethodParameter(handle1, 0); - paramResponseEntity = new MethodParameter(handle1, 1); - paramInt = new MethodParameter(handle1, 2); - returnTypeResponseEntity = new MethodParameter(handle1, -1); - - returnTypeHttpEntity = new MethodParameter(getClass().getMethod("handle2", HttpEntity.class), -1); - returnTypeInt = new MethodParameter(getClass().getMethod("handle3"), -1); - - returnTypeResponseEntityProduces = new MethodParameter(getClass().getMethod("handle4"), -1); + Method method = getClass().getMethod("handle", HttpEntity.class, HttpEntity.class); + paramList = new MethodParameter(method, 0); + paramSimpleBean = new MethodParameter(method, 1); mavContainer = new ModelAndViewContainer(); @@ -112,191 +72,70 @@ public void setUp() throws Exception { webRequest = new ServletWebRequest(servletRequest, servletResponse); } - @Test - public void supportsParameter() { - assertTrue("HttpEntity parameter not supported", processor.supportsParameter(paramHttpEntity)); - assertFalse("ResponseEntity parameter supported", processor.supportsParameter(paramResponseEntity)); - assertFalse("non-entity parameter supported", processor.supportsParameter(paramInt)); - } - - @Test - public void supportsReturnType() { - assertTrue("ResponseEntity return type not supported", processor.supportsReturnType(returnTypeResponseEntity)); - assertTrue("HttpEntity return type not supported", processor.supportsReturnType(returnTypeHttpEntity)); - assertFalse("non-ResponseBody return type supported", processor.supportsReturnType(returnTypeInt)); - } - @Test public void resolveArgument() throws Exception { - MediaType contentType = MediaType.TEXT_PLAIN; - servletRequest.addHeader("Content-Type", contentType.toString()); - - String body = "Foo"; - expect(messageConverter.canRead(String.class, contentType)).andReturn(true); - expect(messageConverter.read(eq(String.class), isA(HttpInputMessage.class))).andReturn(body); - replay(messageConverter); - - Object result = processor.resolveArgument(paramHttpEntity, mavContainer, webRequest, null); - - assertTrue(result instanceof HttpEntity); - assertFalse("The requestHandled flag shouldn't change", mavContainer.isRequestHandled()); - assertEquals("Invalid argument", body, ((HttpEntity<?>) result).getBody()); - verify(messageConverter); - } - - @Test(expected = HttpMediaTypeNotSupportedException.class) - public void resolveArgumentNotReadable() throws Exception { - MediaType contentType = MediaType.TEXT_PLAIN; - servletRequest.addHeader("Content-Type", contentType.toString()); - - expect(messageConverter.getSupportedMediaTypes()).andReturn(Arrays.asList(contentType)); - expect(messageConverter.canRead(String.class, contentType)).andReturn(false); - replay(messageConverter); - - processor.resolveArgument(paramHttpEntity, mavContainer, webRequest, null); - - fail("Expected exception"); - } - - @Test(expected = HttpMediaTypeNotSupportedException.class) - public void resolveArgumentNoContentType() throws Exception { - processor.resolveArgument(paramHttpEntity, mavContainer, webRequest, null); - fail("Expected exception"); - } - - @Test - public void handleReturnValue() throws Exception { - String body = "Foo"; - ResponseEntity<String> returnValue = new ResponseEntity<String>(body, HttpStatus.OK); + String content = "{\"name\" : \"Jad\"}"; + this.servletRequest.setContent(content.getBytes("UTF-8")); + this.servletRequest.setContentType("application/json"); - MediaType accepted = MediaType.TEXT_PLAIN; - servletRequest.addHeader("Accept", accepted.toString()); + List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>(); + converters.add(new MappingJackson2HttpMessageConverter()); + HttpEntityMethodProcessor processor = new HttpEntityMethodProcessor(converters); - expect(messageConverter.canWrite(String.class, null)).andReturn(true); - expect(messageConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); - expect(messageConverter.canWrite(String.class, accepted)).andReturn(true); - messageConverter.write(eq(body), eq(accepted), isA(HttpOutputMessage.class)); - replay(messageConverter); + @SuppressWarnings("unchecked") + HttpEntity<SimpleBean> result = (HttpEntity<SimpleBean>) processor.resolveArgument( + paramSimpleBean, mavContainer, webRequest, new ValidatingBinderFactory()); - processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest); - - assertTrue(mavContainer.isRequestHandled()); - verify(messageConverter); + assertNotNull(result); + assertEquals("Jad", result.getBody().getName()); } @Test - public void handleReturnValueProduces() throws Exception { - String body = "Foo"; - ResponseEntity<String> returnValue = new ResponseEntity<String>(body, HttpStatus.OK); - - servletRequest.addHeader("Accept", "text/*"); - servletRequest.setAttribute(PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, Collections.singleton(MediaType.TEXT_HTML)); + public void resolveGenericArgument() throws Exception { + String content = "[{\"name\" : \"Jad\"}, {\"name\" : \"Robert\"}]"; + this.servletRequest.setContent(content.getBytes("UTF-8")); + this.servletRequest.setContentType("application/json"); - expect(messageConverter.canWrite(String.class, MediaType.TEXT_HTML)).andReturn(true); - messageConverter.write(eq(body), eq(MediaType.TEXT_HTML), isA(HttpOutputMessage.class)); - replay(messageConverter); + List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>(); + converters.add(new MappingJackson2HttpMessageConverter()); + HttpEntityMethodProcessor processor = new HttpEntityMethodProcessor(converters); - processor.handleReturnValue(returnValue, returnTypeResponseEntityProduces, mavContainer, webRequest); + @SuppressWarnings("unchecked") + HttpEntity<List<SimpleBean>> result = (HttpEntity<List<SimpleBean>>) processor.resolveArgument( + paramList, mavContainer, webRequest, new ValidatingBinderFactory()); - assertTrue(mavContainer.isRequestHandled()); - verify(messageConverter); + assertNotNull(result); + assertEquals("Jad", result.getBody().get(0).getName()); + assertEquals("Robert", result.getBody().get(1).getName()); } - @Test(expected = HttpMediaTypeNotAcceptableException.class) - public void handleReturnValueNotAcceptable() throws Exception { - String body = "Foo"; - ResponseEntity<String> returnValue = new ResponseEntity<String>(body, HttpStatus.OK); - - MediaType accepted = MediaType.APPLICATION_ATOM_XML; - servletRequest.addHeader("Accept", accepted.toString()); - - expect(messageConverter.canWrite(String.class, null)).andReturn(true); - expect(messageConverter.getSupportedMediaTypes()).andReturn(Arrays.asList(MediaType.TEXT_PLAIN)); - expect(messageConverter.canWrite(String.class, accepted)).andReturn(false); - replay(messageConverter); - processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest); - - fail("Expected exception"); + public void handle(HttpEntity<List<SimpleBean>> arg1, HttpEntity<SimpleBean> arg2) { } - @Test(expected = HttpMediaTypeNotAcceptableException.class) - public void handleReturnValueNotAcceptableProduces() throws Exception { - String body = "Foo"; - ResponseEntity<String> returnValue = new ResponseEntity<String>(body, HttpStatus.OK); - - MediaType accepted = MediaType.TEXT_PLAIN; - servletRequest.addHeader("Accept", accepted.toString()); - - expect(messageConverter.canWrite(String.class, null)).andReturn(true); - expect(messageConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); - expect(messageConverter.canWrite(String.class, accepted)).andReturn(false); - replay(messageConverter); - processor.handleReturnValue(returnValue, returnTypeResponseEntityProduces, mavContainer, webRequest); + private static class SimpleBean { - fail("Expected exception"); - } - - // SPR-9142 + private String name; - @Test(expected=HttpMediaTypeNotAcceptableException.class) - public void handleReturnValueNotAcceptableParseError() throws Exception { - ResponseEntity<String> returnValue = new ResponseEntity<String>("Body", HttpStatus.ACCEPTED); - servletRequest.addHeader("Accept", "01"); + public String getName() { + return name; + } - processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest); - fail("Expected exception"); + @SuppressWarnings("unused") + public void setName(String name) { + this.name = name; + } } - @Test - public void responseHeaderNoBody() throws Exception { - HttpHeaders headers = new HttpHeaders(); - headers.set("headerName", "headerValue"); - ResponseEntity<String> returnValue = new ResponseEntity<String>(headers, HttpStatus.ACCEPTED); - - processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest); - - assertTrue(mavContainer.isRequestHandled()); - assertEquals("headerValue", servletResponse.getHeader("headerName")); + private final class ValidatingBinderFactory implements WebDataBinderFactory { + public WebDataBinder createBinder(NativeWebRequest webRequest, Object target, String objectName) throws Exception { + LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); + validator.afterPropertiesSet(); + WebDataBinder dataBinder = new WebDataBinder(target, objectName); + dataBinder.setValidator(validator); + return dataBinder; + } } - @Test - public void responseHeaderAndBody() throws Exception { - HttpHeaders responseHeaders = new HttpHeaders(); - responseHeaders.set("header", "headerValue"); - ResponseEntity<String> returnValue = new ResponseEntity<String>("body", responseHeaders, HttpStatus.ACCEPTED); - - Capture<HttpOutputMessage> outputMessage = new Capture<HttpOutputMessage>(); - expect(messageConverter.canWrite(String.class, null)).andReturn(true); - expect(messageConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); - expect(messageConverter.canWrite(String.class, MediaType.TEXT_PLAIN)).andReturn(true); - messageConverter.write(eq("body"), eq(MediaType.TEXT_PLAIN), capture(outputMessage)); - replay(messageConverter); - - processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest); - - assertTrue(mavContainer.isRequestHandled()); - assertEquals("headerValue", outputMessage.getValue().getHeaders().get("header").get(0)); - verify(messageConverter); - } - - public ResponseEntity<String> handle1(HttpEntity<String> httpEntity, ResponseEntity<String> responseEntity, int i) { - return responseEntity; - } - - public HttpEntity<?> handle2(HttpEntity<?> entity) { - return entity; - } - - public int handle3() { - return 42; - } - - @RequestMapping(produces = {"text/html", "application/xhtml+xml"}) - public ResponseEntity<String> handle4() { - return null; - } - - } \ No newline at end of file
true
Other
spring-projects
spring-framework
c9b7b132fb0370f51169929b704862b71183b49a.json
Support generic types in @RequestBody arguments This change makes it possible to declare an @RequestBody argument with a generic type (e.g. List<Foo>). If a GenericHttpMessageConverter implementation supports the method argument, then the request will be converted to the apropiate target type. The new GenericHttpMessageConverter is implemented by the MappingJacksonHttpMessageConverter and also by a new Jaxb2CollectionHttpMessageConverter that can read read a generic Collection where the generic type is a JAXB type annotated with @XmlRootElement or @XmlType. Issue: SPR-9570
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorMockTests.java
@@ -0,0 +1,356 @@ +/* + * Copyright 2002-2012 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.web.servlet.mvc.method.annotation; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.eq; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.isA; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.reset; +import static org.easymock.EasyMock.verify; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import javax.validation.Valid; +import javax.validation.constraints.NotNull; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.core.MethodParameter; +import org.springframework.http.HttpInputMessage; +import org.springframework.http.HttpOutputMessage; +import org.springframework.http.MediaType; +import org.springframework.http.converter.ByteArrayHttpMessageConverter; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.http.converter.StringHttpMessageConverter; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; +import org.springframework.web.HttpMediaTypeNotAcceptableException; +import org.springframework.web.HttpMediaTypeNotSupportedException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.support.WebDataBinderFactory; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.context.request.ServletWebRequest; +import org.springframework.web.method.support.ModelAndViewContainer; +import org.springframework.web.servlet.HandlerMapping; + +/** + * Test fixture for {@link RequestResponseBodyMethodProcessor} delegating to a + * mock HttpMessageConverter. + * + * <p>Also see {@link RequestResponseBodyMethodProcessorTests}. + * + * @author Arjen Poutsma + * @author Rossen Stoyanchev + */ +public class RequestResponseBodyMethodProcessorMockTests { + + private RequestResponseBodyMethodProcessor processor; + + private HttpMessageConverter<String> messageConverter; + + private MethodParameter paramRequestBodyString; + private MethodParameter paramInt; + private MethodParameter paramValidBean; + private MethodParameter paramStringNotRequired; + private MethodParameter returnTypeString; + private MethodParameter returnTypeInt; + private MethodParameter returnTypeStringProduces; + + private ModelAndViewContainer mavContainer; + + private NativeWebRequest webRequest; + + private MockHttpServletRequest servletRequest; + + private MockHttpServletResponse servletResponse; + + @SuppressWarnings("unchecked") + @Before + public void setUp() throws Exception { + messageConverter = createMock(HttpMessageConverter.class); + expect(messageConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); + replay(messageConverter); + + processor = new RequestResponseBodyMethodProcessor(Collections.<HttpMessageConverter<?>>singletonList(messageConverter)); + reset(messageConverter); + + Method methodHandle1 = getClass().getMethod("handle1", String.class, Integer.TYPE); + paramRequestBodyString = new MethodParameter(methodHandle1, 0); + paramInt = new MethodParameter(methodHandle1, 1); + returnTypeString = new MethodParameter(methodHandle1, -1); + returnTypeInt = new MethodParameter(getClass().getMethod("handle2"), -1); + returnTypeStringProduces = new MethodParameter(getClass().getMethod("handle3"), -1); + paramValidBean = new MethodParameter(getClass().getMethod("handle4", SimpleBean.class), 0); + paramStringNotRequired = new MethodParameter(getClass().getMethod("handle5", String.class), 0); + + mavContainer = new ModelAndViewContainer(); + + servletRequest = new MockHttpServletRequest(); + servletResponse = new MockHttpServletResponse(); + webRequest = new ServletWebRequest(servletRequest, servletResponse); + } + + @Test + public void supportsParameter() { + assertTrue("RequestBody parameter not supported", processor.supportsParameter(paramRequestBodyString)); + assertFalse("non-RequestBody parameter supported", processor.supportsParameter(paramInt)); + } + + @Test + public void supportsReturnType() { + assertTrue("ResponseBody return type not supported", processor.supportsReturnType(returnTypeString)); + assertFalse("non-ResponseBody return type supported", processor.supportsReturnType(returnTypeInt)); + } + + @Test + public void resolveArgument() throws Exception { + MediaType contentType = MediaType.TEXT_PLAIN; + servletRequest.addHeader("Content-Type", contentType.toString()); + + String body = "Foo"; + servletRequest.setContent(body.getBytes()); + + expect(messageConverter.canRead(String.class, contentType)).andReturn(true); + expect(messageConverter.read(eq(String.class), isA(HttpInputMessage.class))).andReturn(body); + replay(messageConverter); + + Object result = processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, new ValidatingBinderFactory()); + + assertEquals("Invalid argument", body, result); + assertFalse("The requestHandled flag shouldn't change", mavContainer.isRequestHandled()); + verify(messageConverter); + } + + @Test + public void resolveArgumentNotValid() throws Exception { + try { + testResolveArgumentWithValidation(new SimpleBean(null)); + fail("Expected exception"); + } catch (MethodArgumentNotValidException e) { + assertEquals("simpleBean", e.getBindingResult().getObjectName()); + assertEquals(1, e.getBindingResult().getErrorCount()); + assertNotNull(e.getBindingResult().getFieldError("name")); + } + } + + @Test + public void resolveArgumentValid() throws Exception { + testResolveArgumentWithValidation(new SimpleBean("name")); + } + + private void testResolveArgumentWithValidation(SimpleBean simpleBean) throws IOException, Exception { + MediaType contentType = MediaType.TEXT_PLAIN; + servletRequest.addHeader("Content-Type", contentType.toString()); + servletRequest.setContent(new byte[] {}); + + @SuppressWarnings("unchecked") + HttpMessageConverter<SimpleBean> beanConverter = createMock(HttpMessageConverter.class); + expect(beanConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); + expect(beanConverter.canRead(SimpleBean.class, contentType)).andReturn(true); + expect(beanConverter.read(eq(SimpleBean.class), isA(HttpInputMessage.class))).andReturn(simpleBean); + replay(beanConverter); + + processor = new RequestResponseBodyMethodProcessor(Collections.<HttpMessageConverter<?>>singletonList(beanConverter)); + processor.resolveArgument(paramValidBean, mavContainer, webRequest, new ValidatingBinderFactory()); + + verify(beanConverter); + } + + @Test(expected = HttpMediaTypeNotSupportedException.class) + public void resolveArgumentNotReadable() throws Exception { + MediaType contentType = MediaType.TEXT_PLAIN; + servletRequest.addHeader("Content-Type", contentType.toString()); + servletRequest.setContent(new byte[] {}); + + expect(messageConverter.canRead(String.class, contentType)).andReturn(false); + replay(messageConverter); + + processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null); + } + + @Test(expected = HttpMediaTypeNotSupportedException.class) + public void resolveArgumentNoContentType() throws Exception { + servletRequest.setContent(new byte[] {}); + processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null); + } + + @Test(expected = HttpMessageNotReadableException.class) + public void resolveArgumentRequiredNoContent() throws Exception { + processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null); + } + + @Test + public void resolveArgumentNotRequiredNoContent() throws Exception { + assertNull(processor.resolveArgument(paramStringNotRequired, mavContainer, webRequest, new ValidatingBinderFactory())); + } + + @Test + public void handleReturnValue() throws Exception { + MediaType accepted = MediaType.TEXT_PLAIN; + servletRequest.addHeader("Accept", accepted.toString()); + + String body = "Foo"; + expect(messageConverter.canWrite(String.class, null)).andReturn(true); + expect(messageConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); + expect(messageConverter.canWrite(String.class, accepted)).andReturn(true); + messageConverter.write(eq(body), eq(accepted), isA(HttpOutputMessage.class)); + replay(messageConverter); + + processor.handleReturnValue(body, returnTypeString, mavContainer, webRequest); + + assertTrue("The requestHandled flag wasn't set", mavContainer.isRequestHandled()); + verify(messageConverter); + } + + @Test + public void handleReturnValueProduces() throws Exception { + String body = "Foo"; + + servletRequest.addHeader("Accept", "text/*"); + servletRequest.setAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, Collections.singleton(MediaType.TEXT_HTML)); + + expect(messageConverter.canWrite(String.class, MediaType.TEXT_HTML)).andReturn(true); + messageConverter.write(eq(body), eq(MediaType.TEXT_HTML), isA(HttpOutputMessage.class)); + replay(messageConverter); + + processor.handleReturnValue(body, returnTypeStringProduces, mavContainer, webRequest); + + assertTrue(mavContainer.isRequestHandled()); + verify(messageConverter); + } + + + @Test(expected = HttpMediaTypeNotAcceptableException.class) + public void handleReturnValueNotAcceptable() throws Exception { + MediaType accepted = MediaType.APPLICATION_ATOM_XML; + servletRequest.addHeader("Accept", accepted.toString()); + + expect(messageConverter.canWrite(String.class, null)).andReturn(true); + expect(messageConverter.getSupportedMediaTypes()).andReturn(Arrays.asList(MediaType.TEXT_PLAIN)); + expect(messageConverter.canWrite(String.class, accepted)).andReturn(false); + replay(messageConverter); + + processor.handleReturnValue("Foo", returnTypeString, mavContainer, webRequest); + } + + @Test(expected = HttpMediaTypeNotAcceptableException.class) + public void handleReturnValueNotAcceptableProduces() throws Exception { + MediaType accepted = MediaType.TEXT_PLAIN; + servletRequest.addHeader("Accept", accepted.toString()); + + expect(messageConverter.canWrite(String.class, null)).andReturn(true); + expect(messageConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); + expect(messageConverter.canWrite(String.class, accepted)).andReturn(false); + replay(messageConverter); + + processor.handleReturnValue("Foo", returnTypeStringProduces, mavContainer, webRequest); + } + + // SPR-9160 + + @Test + public void handleReturnValueSortByQuality() throws Exception { + this.servletRequest.addHeader("Accept", "text/plain; q=0.5, application/json"); + + List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>(); + converters.add(new MappingJackson2HttpMessageConverter()); + converters.add(new StringHttpMessageConverter()); + RequestResponseBodyMethodProcessor handler = new RequestResponseBodyMethodProcessor(converters); + + handler.writeWithMessageConverters("Foo", returnTypeStringProduces, webRequest); + + assertEquals("application/json;charset=UTF-8", servletResponse.getHeader("Content-Type")); + } + + @Test + public void handleReturnValueString() throws Exception { + List<HttpMessageConverter<?>>converters = new ArrayList<HttpMessageConverter<?>>(); + converters.add(new ByteArrayHttpMessageConverter()); + converters.add(new StringHttpMessageConverter()); + + processor = new RequestResponseBodyMethodProcessor(converters); + processor.handleReturnValue("Foo", returnTypeString, mavContainer, webRequest); + + assertEquals("text/plain;charset=ISO-8859-1", servletResponse.getHeader("Content-Type")); + assertEquals("Foo", servletResponse.getContentAsString()); + } + + @ResponseBody + public String handle1(@RequestBody String s, int i) { + return s; + } + + public int handle2() { + return 42; + } + + @ResponseBody + public String handle3() { + return null; + } + + public void handle4(@Valid @RequestBody SimpleBean b) { + } + + public void handle5(@RequestBody(required=false) String s) { + } + + private final class ValidatingBinderFactory implements WebDataBinderFactory { + public WebDataBinder createBinder(NativeWebRequest webRequest, Object target, String objectName) throws Exception { + LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); + validator.afterPropertiesSet(); + WebDataBinder dataBinder = new WebDataBinder(target, objectName); + dataBinder.setValidator(validator); + return dataBinder; + } + } + + @SuppressWarnings("unused") + private static class SimpleBean { + + @NotNull + private final String name; + + public SimpleBean(String name) { + this.name = name; + } + + public String getName() { + return name; + } + } + +} \ No newline at end of file
true
Other
spring-projects
spring-framework
c9b7b132fb0370f51169929b704862b71183b49a.json
Support generic types in @RequestBody arguments This change makes it possible to declare an @RequestBody argument with a generic type (e.g. List<Foo>). If a GenericHttpMessageConverter implementation supports the method argument, then the request will be converted to the apropiate target type. The new GenericHttpMessageConverter is implemented by the MappingJacksonHttpMessageConverter and also by a new Jaxb2CollectionHttpMessageConverter that can read read a generic Collection where the generic type is a JAXB type annotated with @XmlRootElement or @XmlType. Issue: SPR-9570
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorTests.java
@@ -16,75 +16,43 @@ package org.springframework.web.servlet.mvc.method.annotation; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.eq; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.isA; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.reset; -import static org.easymock.EasyMock.verify; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; import java.util.List; -import javax.validation.Valid; -import javax.validation.constraints.NotNull; - import org.junit.Before; import org.junit.Test; import org.springframework.core.MethodParameter; -import org.springframework.http.HttpInputMessage; -import org.springframework.http.HttpOutputMessage; -import org.springframework.http.MediaType; import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; -import org.springframework.web.HttpMediaTypeNotAcceptableException; -import org.springframework.web.HttpMediaTypeNotSupportedException; -import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.support.WebDataBinderFactory; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.method.support.ModelAndViewContainer; -import org.springframework.web.servlet.HandlerMapping; /** - * Test fixture with {@link RequestResponseBodyMethodProcessor} and mock {@link HttpMessageConverter}. + * Test fixture for a {@link RequestResponseBodyMethodProcessor} with actual delegation + * to HttpMessageConverter instances. + * + * <p>Also see {@link RequestResponseBodyMethodProcessorMockTests}. * - * @author Arjen Poutsma * @author Rossen Stoyanchev */ public class RequestResponseBodyMethodProcessorTests { - private RequestResponseBodyMethodProcessor processor; - - private HttpMessageConverter<String> messageConverter; - - private MethodParameter paramRequestBodyString; - private MethodParameter paramInt; - private MethodParameter paramValidBean; - private MethodParameter paramStringNotRequired; + private MethodParameter paramGenericList; + private MethodParameter paramSimpleBean; private MethodParameter returnTypeString; - private MethodParameter returnTypeInt; - private MethodParameter returnTypeStringProduces; private ModelAndViewContainer mavContainer; @@ -94,24 +62,13 @@ public class RequestResponseBodyMethodProcessorTests { private MockHttpServletResponse servletResponse; - @SuppressWarnings("unchecked") @Before public void setUp() throws Exception { - messageConverter = createMock(HttpMessageConverter.class); - expect(messageConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); - replay(messageConverter); - - processor = new RequestResponseBodyMethodProcessor(Collections.<HttpMessageConverter<?>>singletonList(messageConverter)); - reset(messageConverter); - - Method handle = getClass().getMethod("handle1", String.class, Integer.TYPE); - paramRequestBodyString = new MethodParameter(handle, 0); - paramInt = new MethodParameter(handle, 1); - returnTypeString = new MethodParameter(handle, -1); - returnTypeInt = new MethodParameter(getClass().getMethod("handle2"), -1); - returnTypeStringProduces = new MethodParameter(getClass().getMethod("handle3"), -1); - paramValidBean = new MethodParameter(getClass().getMethod("handle4", SimpleBean.class), 0); - paramStringNotRequired = new MethodParameter(getClass().getMethod("handle5", String.class), 0); + + Method method = getClass().getMethod("handle", List.class, SimpleBean.class); + paramGenericList = new MethodParameter(method, 0); + paramSimpleBean = new MethodParameter(method, 1); + returnTypeString = new MethodParameter(method, -1); mavContainer = new ModelAndViewContainer(); @@ -120,160 +77,41 @@ public void setUp() throws Exception { webRequest = new ServletWebRequest(servletRequest, servletResponse); } - @Test - public void supportsParameter() { - assertTrue("RequestBody parameter not supported", processor.supportsParameter(paramRequestBodyString)); - assertFalse("non-RequestBody parameter supported", processor.supportsParameter(paramInt)); - } @Test - public void supportsReturnType() { - assertTrue("ResponseBody return type not supported", processor.supportsReturnType(returnTypeString)); - assertFalse("non-ResponseBody return type supported", processor.supportsReturnType(returnTypeInt)); - } - - @Test - public void resolveArgument() throws Exception { - MediaType contentType = MediaType.TEXT_PLAIN; - servletRequest.addHeader("Content-Type", contentType.toString()); + public void resolveGenericArgument() throws Exception { + String content = "[{\"name\" : \"Jad\"}, {\"name\" : \"Robert\"}]"; + this.servletRequest.setContent(content.getBytes("UTF-8")); + this.servletRequest.setContentType("application/json"); - String body = "Foo"; - servletRequest.setContent(body.getBytes()); - - expect(messageConverter.canRead(String.class, contentType)).andReturn(true); - expect(messageConverter.read(eq(String.class), isA(HttpInputMessage.class))).andReturn(body); - replay(messageConverter); - - Object result = processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, new ValidatingBinderFactory()); - - assertEquals("Invalid argument", body, result); - assertFalse("The requestHandled flag shouldn't change", mavContainer.isRequestHandled()); - verify(messageConverter); - } - - @Test - public void resolveArgumentNotValid() throws Exception { - try { - testResolveArgumentWithValidation(new SimpleBean(null)); - fail("Expected exception"); - } catch (MethodArgumentNotValidException e) { - assertEquals("simpleBean", e.getBindingResult().getObjectName()); - assertEquals(1, e.getBindingResult().getErrorCount()); - assertNotNull(e.getBindingResult().getFieldError("name")); - } - } - - @Test - public void resolveArgumentValid() throws Exception { - testResolveArgumentWithValidation(new SimpleBean("name")); - } - - private void testResolveArgumentWithValidation(SimpleBean simpleBean) throws IOException, Exception { - MediaType contentType = MediaType.TEXT_PLAIN; - servletRequest.addHeader("Content-Type", contentType.toString()); - servletRequest.setContent(new byte[] {}); + List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>(); + converters.add(new MappingJackson2HttpMessageConverter()); + RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters); @SuppressWarnings("unchecked") - HttpMessageConverter<SimpleBean> beanConverter = createMock(HttpMessageConverter.class); - expect(beanConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); - expect(beanConverter.canRead(SimpleBean.class, contentType)).andReturn(true); - expect(beanConverter.read(eq(SimpleBean.class), isA(HttpInputMessage.class))).andReturn(simpleBean); - replay(beanConverter); - - processor = new RequestResponseBodyMethodProcessor(Collections.<HttpMessageConverter<?>>singletonList(beanConverter)); - processor.resolveArgument(paramValidBean, mavContainer, webRequest, new ValidatingBinderFactory()); - - verify(beanConverter); - } - - @Test(expected = HttpMediaTypeNotSupportedException.class) - public void resolveArgumentNotReadable() throws Exception { - MediaType contentType = MediaType.TEXT_PLAIN; - servletRequest.addHeader("Content-Type", contentType.toString()); - servletRequest.setContent(new byte[] {}); - - expect(messageConverter.canRead(String.class, contentType)).andReturn(false); - replay(messageConverter); - - processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null); - } - - @Test(expected = HttpMediaTypeNotSupportedException.class) - public void resolveArgumentNoContentType() throws Exception { - servletRequest.setContent(new byte[] {}); - processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null); - } - - @Test(expected = HttpMessageNotReadableException.class) - public void resolveArgumentRequiredNoContent() throws Exception { - processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null); - } + List<SimpleBean> result = (List<SimpleBean>) processor.resolveArgument( + paramGenericList, mavContainer, webRequest, new ValidatingBinderFactory()); - @Test - public void resolveArgumentNotRequiredNoContent() throws Exception { - assertNull(processor.resolveArgument(paramStringNotRequired, mavContainer, webRequest, new ValidatingBinderFactory())); + assertNotNull(result); + assertEquals("Jad", result.get(0).getName()); + assertEquals("Robert", result.get(1).getName()); } @Test - public void handleReturnValue() throws Exception { - MediaType accepted = MediaType.TEXT_PLAIN; - servletRequest.addHeader("Accept", accepted.toString()); - - String body = "Foo"; - expect(messageConverter.canWrite(String.class, null)).andReturn(true); - expect(messageConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); - expect(messageConverter.canWrite(String.class, accepted)).andReturn(true); - messageConverter.write(eq(body), eq(accepted), isA(HttpOutputMessage.class)); - replay(messageConverter); - - processor.handleReturnValue(body, returnTypeString, mavContainer, webRequest); - - assertTrue("The requestHandled flag wasn't set", mavContainer.isRequestHandled()); - verify(messageConverter); - } - - @Test - public void handleReturnValueProduces() throws Exception { - String body = "Foo"; - - servletRequest.addHeader("Accept", "text/*"); - servletRequest.setAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, Collections.singleton(MediaType.TEXT_HTML)); - - expect(messageConverter.canWrite(String.class, MediaType.TEXT_HTML)).andReturn(true); - messageConverter.write(eq(body), eq(MediaType.TEXT_HTML), isA(HttpOutputMessage.class)); - replay(messageConverter); - - processor.handleReturnValue(body, returnTypeStringProduces, mavContainer, webRequest); - - assertTrue(mavContainer.isRequestHandled()); - verify(messageConverter); - } - - - @Test(expected = HttpMediaTypeNotAcceptableException.class) - public void handleReturnValueNotAcceptable() throws Exception { - MediaType accepted = MediaType.APPLICATION_ATOM_XML; - servletRequest.addHeader("Accept", accepted.toString()); - - expect(messageConverter.canWrite(String.class, null)).andReturn(true); - expect(messageConverter.getSupportedMediaTypes()).andReturn(Arrays.asList(MediaType.TEXT_PLAIN)); - expect(messageConverter.canWrite(String.class, accepted)).andReturn(false); - replay(messageConverter); - - processor.handleReturnValue("Foo", returnTypeString, mavContainer, webRequest); - } + public void resolveArgument() throws Exception { + String content = "{\"name\" : \"Jad\"}"; + this.servletRequest.setContent(content.getBytes("UTF-8")); + this.servletRequest.setContentType("application/json"); - @Test(expected = HttpMediaTypeNotAcceptableException.class) - public void handleReturnValueNotAcceptableProduces() throws Exception { - MediaType accepted = MediaType.TEXT_PLAIN; - servletRequest.addHeader("Accept", accepted.toString()); + List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>(); + converters.add(new MappingJackson2HttpMessageConverter()); + RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters); - expect(messageConverter.canWrite(String.class, null)).andReturn(true); - expect(messageConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); - expect(messageConverter.canWrite(String.class, accepted)).andReturn(false); - replay(messageConverter); + SimpleBean result = (SimpleBean) processor.resolveArgument( + paramSimpleBean, mavContainer, webRequest, new ValidatingBinderFactory()); - processor.handleReturnValue("Foo", returnTypeStringProduces, mavContainer, webRequest); + assertNotNull(result); + assertEquals("Jad", result.getName()); } // SPR-9160 @@ -285,9 +123,9 @@ public void handleReturnValueSortByQuality() throws Exception { List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>(); converters.add(new MappingJackson2HttpMessageConverter()); converters.add(new StringHttpMessageConverter()); - RequestResponseBodyMethodProcessor handler = new RequestResponseBodyMethodProcessor(converters); + RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters); - handler.writeWithMessageConverters("Foo", returnTypeStringProduces, webRequest); + processor.writeWithMessageConverters("Foo", returnTypeString, webRequest); assertEquals("application/json;charset=UTF-8", servletResponse.getHeader("Content-Type")); } @@ -298,31 +136,31 @@ public void handleReturnValueString() throws Exception { converters.add(new ByteArrayHttpMessageConverter()); converters.add(new StringHttpMessageConverter()); - processor = new RequestResponseBodyMethodProcessor(converters); + RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters); processor.handleReturnValue("Foo", returnTypeString, mavContainer, webRequest); assertEquals("text/plain;charset=ISO-8859-1", servletResponse.getHeader("Content-Type")); assertEquals("Foo", servletResponse.getContentAsString()); } - @ResponseBody - public String handle1(@RequestBody String s, int i) { - return s; - } - public int handle2() { - return 42; - } - - @ResponseBody - public String handle3() { + public String handle(@RequestBody List<SimpleBean> list, @RequestBody SimpleBean simpleBean) { return null; } - public void handle4(@Valid @RequestBody SimpleBean b) { - } - public void handle5(@RequestBody(required=false) String s) { + private static class SimpleBean { + + private String name; + + public String getName() { + return name; + } + + @SuppressWarnings("unused") + public void setName(String name) { + this.name = name; + } } private final class ValidatingBinderFactory implements WebDataBinderFactory { @@ -335,19 +173,4 @@ public WebDataBinder createBinder(NativeWebRequest webRequest, Object target, St } } - @SuppressWarnings("unused") - private static class SimpleBean { - - @NotNull - private final String name; - - public SimpleBean(String name) { - this.name = name; - } - - public String getName() { - return name; - } - } - } \ No newline at end of file
true
Other
spring-projects
spring-framework
ed3823b045fd19cdb801609eb034c93dd4d75c3f.json
Support generic target types in the RestTemplate This change makes it possible to use the RestTemplate to read an HTTP response into a target generic type object. The RestTemplate has three new exchange(...) methods that accept ParameterizedTypeReference -- a new class that enables capturing and passing generic type info. See the Javadoc of the three new methods in RestOperations for a short example. To support this feature, the HttpMessageConverter is now extended by GenericHttpMessageConverter, which adds a method for reading an HttpInputMessage to a specific generic type. The new interface is implemented by the MappingJacksonHttpMessageConverter and also by a new Jaxb2CollectionHttpMessageConverter that can read read a generic Collection where the generic type is a JAXB type annotated with @XmlRootElement or @XmlType. Issue: SPR-7023
spring-core/src/main/java/org/springframework/core/ParameterizedTypeReference.java
@@ -0,0 +1,99 @@ +/* + * Copyright 2002-2012 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.core; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; + +import org.springframework.util.Assert; + +/** + * The purpose of this class is to enable capturing and passing a generic + * {@link Type}. In order to capture the generic type and retain it at runtime, + * you need to create a sub-class as follows: + * + * <pre class="code"> + * ParameterizedTypeReference&lt;List&lt;String&gt;&gt; typeRef = new ParameterizedTypeReference&lt;List&lt;String&gt;&gt;() {}; + * </pre> + * + * <p>The resulting {@code typeReference} instance can then be used to obtain a + * {@link Type} instance that carries parameterized type information. + * For more information on "super type tokens" see the link to Neal Gafter's blog post. + * + * @author Arjen Poutsma + * @author Rossen Stoyanchev + * @since 3.2 + * + * @see http://gafter.blogspot.nl/2006/12/super-type-tokens.html + */ +public abstract class ParameterizedTypeReference<T> { + + private final Type type; + + protected ParameterizedTypeReference() { + Class<?> parameterizedTypeReferenceSubClass = findParameterizedTypeReferenceSubClass(getClass()); + + Type type = parameterizedTypeReferenceSubClass.getGenericSuperclass(); + Assert.isInstanceOf(ParameterizedType.class, type); + + ParameterizedType parameterizedType = (ParameterizedType) type; + Assert.isTrue(parameterizedType.getActualTypeArguments().length == 1); + + this.type = parameterizedType.getActualTypeArguments()[0]; + } + + private static Class<?> findParameterizedTypeReferenceSubClass(Class<?> child) { + + Class<?> parent = child.getSuperclass(); + + if (Object.class.equals(parent)) { + throw new IllegalStateException("Expected ParameterizedTypeReference superclass"); + } + else if (ParameterizedTypeReference.class.equals(parent)) { + return child; + } + else { + return findParameterizedTypeReferenceSubClass(parent); + } + } + + public Type getType() { + return this.type; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o instanceof ParameterizedTypeReference) { + ParameterizedTypeReference<?> other = (ParameterizedTypeReference<?>) o; + return this.type.equals(other.type); + } + return false; + } + + @Override + public int hashCode() { + return this.type.hashCode(); + } + + @Override + public String toString() { + return "ParameterizedTypeReference<" + this.type + ">"; + } +}
true
Other
spring-projects
spring-framework
ed3823b045fd19cdb801609eb034c93dd4d75c3f.json
Support generic target types in the RestTemplate This change makes it possible to use the RestTemplate to read an HTTP response into a target generic type object. The RestTemplate has three new exchange(...) methods that accept ParameterizedTypeReference -- a new class that enables capturing and passing generic type info. See the Javadoc of the three new methods in RestOperations for a short example. To support this feature, the HttpMessageConverter is now extended by GenericHttpMessageConverter, which adds a method for reading an HttpInputMessage to a specific generic type. The new interface is implemented by the MappingJacksonHttpMessageConverter and also by a new Jaxb2CollectionHttpMessageConverter that can read read a generic Collection where the generic type is a JAXB type annotated with @XmlRootElement or @XmlType. Issue: SPR-7023
spring-core/src/test/java/org/springframework/core/ParameterizedTypeReferenceTest.java
@@ -0,0 +1,61 @@ +/* + * Copyright 2002-2012 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.core; + +import java.lang.reflect.Type; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import org.junit.Test; + +/** + * Test fixture for {@link ParameterizedTypeReference}. + * + * @author Arjen Poutsma + * @author Rossen Stoyanchev + */ +public class ParameterizedTypeReferenceTest { + + @Test + public void map() throws NoSuchMethodException { + Type mapType = getClass().getMethod("mapMethod").getGenericReturnType(); + ParameterizedTypeReference<Map<Object,String>> mapTypeReference = new ParameterizedTypeReference<Map<Object,String>>() {}; + assertEquals(mapType, mapTypeReference.getType()); + } + + @Test + public void list() throws NoSuchMethodException { + Type mapType = getClass().getMethod("listMethod").getGenericReturnType(); + ParameterizedTypeReference<List<String>> mapTypeReference = new ParameterizedTypeReference<List<String>>() {}; + assertEquals(mapType, mapTypeReference.getType()); + } + + @Test + public void string() { + ParameterizedTypeReference<String> typeReference = new ParameterizedTypeReference<String>() {}; + assertEquals(String.class, typeReference.getType()); + } + + public static Map<Object, String> mapMethod() { + return null; + } + + public static List<String> listMethod() { + return null; + } +}
true
Other
spring-projects
spring-framework
ed3823b045fd19cdb801609eb034c93dd4d75c3f.json
Support generic target types in the RestTemplate This change makes it possible to use the RestTemplate to read an HTTP response into a target generic type object. The RestTemplate has three new exchange(...) methods that accept ParameterizedTypeReference -- a new class that enables capturing and passing generic type info. See the Javadoc of the three new methods in RestOperations for a short example. To support this feature, the HttpMessageConverter is now extended by GenericHttpMessageConverter, which adds a method for reading an HttpInputMessage to a specific generic type. The new interface is implemented by the MappingJacksonHttpMessageConverter and also by a new Jaxb2CollectionHttpMessageConverter that can read read a generic Collection where the generic type is a JAXB type annotated with @XmlRootElement or @XmlType. Issue: SPR-7023
spring-web/src/main/java/org/springframework/http/converter/GenericHttpMessageConverter.java
@@ -0,0 +1,60 @@ +/* + * Copyright 2002-2012 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.http.converter; + +import java.io.IOException; +import java.lang.reflect.Type; + +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpInputMessage; +import org.springframework.http.MediaType; + +/** + * A specialization of {@link HttpMessageConverter} that can convert an HTTP + * request into a target object of a specified generic type. + * + * @author Arjen Poutsma + * @since 3.2 + * + * @see ParameterizedTypeReference + */ +public interface GenericHttpMessageConverter<T> extends HttpMessageConverter<T> { + + /** + * Indicates whether the given type can be read by this converter. + * @param type the type to test for readability + * @param mediaType the media type to read, can be {@code null} if not specified. + * Typically the value of a {@code Content-Type} header. + * @return {@code true} if readable; {@code false} otherwise + */ + boolean canRead(Type type, MediaType mediaType); + + /** + * Read an object of the given type form the given input message, and returns it. + * @param clazz the type of object to return. This type must have previously + * been passed to the {@link #canRead canRead} method of this interface, + * which must have returned {@code true}. + * @param type the type of the target object + * @param inputMessage the HTTP input message to read from + * @return the converted object + * @throws IOException in case of I/O errors + * @throws HttpMessageNotReadableException in case of conversion errors + */ + T read(Type type, HttpInputMessage inputMessage) + throws IOException, HttpMessageNotReadableException; + +}
true
Other
spring-projects
spring-framework
ed3823b045fd19cdb801609eb034c93dd4d75c3f.json
Support generic target types in the RestTemplate This change makes it possible to use the RestTemplate to read an HTTP response into a target generic type object. The RestTemplate has three new exchange(...) methods that accept ParameterizedTypeReference -- a new class that enables capturing and passing generic type info. See the Javadoc of the three new methods in RestOperations for a short example. To support this feature, the HttpMessageConverter is now extended by GenericHttpMessageConverter, which adds a method for reading an HttpInputMessage to a specific generic type. The new interface is implemented by the MappingJacksonHttpMessageConverter and also by a new Jaxb2CollectionHttpMessageConverter that can read read a generic Collection where the generic type is a JAXB type annotated with @XmlRootElement or @XmlType. Issue: SPR-7023
spring-web/src/main/java/org/springframework/http/converter/json/MappingJackson2HttpMessageConverter.java
@@ -17,17 +17,10 @@ package org.springframework.http.converter.json; import java.io.IOException; +import java.lang.reflect.Type; import java.nio.charset.Charset; import java.util.List; -import org.springframework.http.HttpInputMessage; -import org.springframework.http.HttpOutputMessage; -import org.springframework.http.MediaType; -import org.springframework.http.converter.AbstractHttpMessageConverter; -import org.springframework.http.converter.HttpMessageNotReadableException; -import org.springframework.http.converter.HttpMessageNotWritableException; -import org.springframework.util.Assert; - import com.fasterxml.jackson.core.JsonEncoding; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; @@ -36,6 +29,15 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; +import org.springframework.http.HttpInputMessage; +import org.springframework.http.HttpOutputMessage; +import org.springframework.http.MediaType; +import org.springframework.http.converter.AbstractHttpMessageConverter; +import org.springframework.http.converter.GenericHttpMessageConverter; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.http.converter.HttpMessageNotWritableException; +import org.springframework.util.Assert; + /** * Implementation of {@link org.springframework.http.converter.HttpMessageConverter HttpMessageConverter} * that can read and write JSON using <a href="http://jackson.codehaus.org/">Jackson 2's</a> {@link ObjectMapper}. @@ -50,7 +52,8 @@ * @since 3.1.2 * @see org.springframework.web.servlet.view.json.MappingJackson2JsonView */ -public class MappingJackson2HttpMessageConverter extends AbstractHttpMessageConverter<Object> { +public class MappingJackson2HttpMessageConverter extends AbstractHttpMessageConverter<Object> + implements GenericHttpMessageConverter<Object> { public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); @@ -63,7 +66,7 @@ public class MappingJackson2HttpMessageConverter extends AbstractHttpMessageConv /** - * Construct a new {@code BindingJacksonHttpMessageConverter}. + * Construct a new {@code MappingJackson2HttpMessageConverter}. */ public MappingJackson2HttpMessageConverter() { super(new MediaType("application", "json", DEFAULT_CHARSET)); @@ -125,7 +128,11 @@ public void setPrettyPrint(boolean prettyPrint) { @Override public boolean canRead(Class<?> clazz, MediaType mediaType) { - JavaType javaType = getJavaType(clazz); + return canRead((Type) clazz, mediaType); + } + + public boolean canRead(Type type, MediaType mediaType) { + JavaType javaType = getJavaType(type); return (this.objectMapper.canDeserialize(javaType) && canRead(mediaType)); } @@ -145,6 +152,17 @@ protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { JavaType javaType = getJavaType(clazz); + return readJavaType(javaType, inputMessage); + } + + public Object read(Type type, HttpInputMessage inputMessage) + throws IOException, HttpMessageNotReadableException { + + JavaType javaType = getJavaType(type); + return readJavaType(javaType, inputMessage); + } + + private Object readJavaType(JavaType javaType, HttpInputMessage inputMessage) { try { return this.objectMapper.readValue(inputMessage.getBody(), javaType); } @@ -153,6 +171,7 @@ protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) } } + @Override protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { @@ -180,24 +199,24 @@ protected void writeInternal(Object object, HttpOutputMessage outputMessage) /** - * Return the Jackson {@link JavaType} for the specified class. + * Return the Jackson {@link JavaType} for the specified type. * <p>The default implementation returns {@link ObjectMapper#constructType(java.lang.reflect.Type)}, * but this can be overridden in subclasses, to allow for custom generic collection handling. * For instance: * <pre class="code"> - * protected JavaType getJavaType(Class&lt;?&gt; clazz) { - * if (List.class.isAssignableFrom(clazz)) { - * return objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, MyBean.class); + * protected JavaType getJavaType(Type type) { + * if (type instanceof Class && List.class.isAssignableFrom((Class)type)) { + * return TypeFactory.collectionType(ArrayList.class, MyBean.class); * } else { - * return super.getJavaType(clazz); + * return super.getJavaType(type); * } * } * </pre> - * @param clazz the class to return the java type for + * @param type the type to return the java type for * @return the java type */ - protected JavaType getJavaType(Class<?> clazz) { - return objectMapper.constructType(clazz); + protected JavaType getJavaType(Type type) { + return this.objectMapper.constructType(type); } /**
true
Other
spring-projects
spring-framework
ed3823b045fd19cdb801609eb034c93dd4d75c3f.json
Support generic target types in the RestTemplate This change makes it possible to use the RestTemplate to read an HTTP response into a target generic type object. The RestTemplate has three new exchange(...) methods that accept ParameterizedTypeReference -- a new class that enables capturing and passing generic type info. See the Javadoc of the three new methods in RestOperations for a short example. To support this feature, the HttpMessageConverter is now extended by GenericHttpMessageConverter, which adds a method for reading an HttpInputMessage to a specific generic type. The new interface is implemented by the MappingJacksonHttpMessageConverter and also by a new Jaxb2CollectionHttpMessageConverter that can read read a generic Collection where the generic type is a JAXB type annotated with @XmlRootElement or @XmlType. Issue: SPR-7023
spring-web/src/main/java/org/springframework/http/converter/json/MappingJacksonHttpMessageConverter.java
@@ -1,11 +1,11 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2012 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 + * 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, @@ -17,26 +17,28 @@ package org.springframework.http.converter.json; import java.io.IOException; +import java.lang.reflect.Type; import java.nio.charset.Charset; import java.util.List; +import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; import org.codehaus.jackson.JsonEncoding; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonProcessingException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; import org.codehaus.jackson.map.type.TypeFactory; import org.codehaus.jackson.type.JavaType; + import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpOutputMessage; import org.springframework.http.MediaType; import org.springframework.http.converter.AbstractHttpMessageConverter; +import org.springframework.http.converter.GenericHttpMessageConverter; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.converter.HttpMessageNotWritableException; import org.springframework.util.Assert; -import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; - /** * Implementation of {@link org.springframework.http.converter.HttpMessageConverter HttpMessageConverter} * that can read and write JSON using <a href="http://jackson.codehaus.org/">Jackson's</a> {@link ObjectMapper}. @@ -50,7 +52,8 @@ * @since 3.0 * @see org.springframework.web.servlet.view.json.MappingJacksonJsonView */ -public class MappingJacksonHttpMessageConverter extends AbstractHttpMessageConverter<Object> { +public class MappingJacksonHttpMessageConverter extends AbstractHttpMessageConverter<Object> + implements GenericHttpMessageConverter<Object> { public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); @@ -63,7 +66,7 @@ public class MappingJacksonHttpMessageConverter extends AbstractHttpMessageConve /** - * Construct a new {@code BindingJacksonHttpMessageConverter}. + * Construct a new {@code MappingJacksonHttpMessageConverter}. */ public MappingJacksonHttpMessageConverter() { super(new MediaType("application", "json", DEFAULT_CHARSET)); @@ -125,7 +128,11 @@ public void setPrettyPrint(boolean prettyPrint) { @Override public boolean canRead(Class<?> clazz, MediaType mediaType) { - JavaType javaType = getJavaType(clazz); + return canRead((Type) clazz, mediaType); + } + + public boolean canRead(Type type, MediaType mediaType) { + JavaType javaType = getJavaType(type); return (this.objectMapper.canDeserialize(javaType) && canRead(mediaType)); } @@ -145,6 +152,17 @@ protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { JavaType javaType = getJavaType(clazz); + return readJavaType(javaType, inputMessage); + } + + public Object read(Type type, HttpInputMessage inputMessage) + throws IOException, HttpMessageNotReadableException { + + JavaType javaType = getJavaType(type); + return readJavaType(javaType, inputMessage); + } + + private Object readJavaType(JavaType javaType, HttpInputMessage inputMessage) { try { return this.objectMapper.readValue(inputMessage.getBody(), javaType); } @@ -180,24 +198,24 @@ protected void writeInternal(Object object, HttpOutputMessage outputMessage) /** - * Return the Jackson {@link JavaType} for the specified class. + * Return the Jackson {@link JavaType} for the specified type. * <p>The default implementation returns {@link TypeFactory#type(java.lang.reflect.Type)}, * but this can be overridden in subclasses, to allow for custom generic collection handling. * For instance: * <pre class="code"> - * protected JavaType getJavaType(Class&lt;?&gt; clazz) { - * if (List.class.isAssignableFrom(clazz)) { + * protected JavaType getJavaType(Type type) { + * if (type instanceof Class && List.class.isAssignableFrom((Class)type)) { * return TypeFactory.collectionType(ArrayList.class, MyBean.class); * } else { - * return super.getJavaType(clazz); + * return super.getJavaType(type); * } * } * </pre> - * @param clazz the class to return the java type for + * @param type the type to return the java type for * @return the java type */ - protected JavaType getJavaType(Class<?> clazz) { - return TypeFactory.type(clazz); + protected JavaType getJavaType(Type type) { + return TypeFactory.type(type); } /**
true
Other
spring-projects
spring-framework
ed3823b045fd19cdb801609eb034c93dd4d75c3f.json
Support generic target types in the RestTemplate This change makes it possible to use the RestTemplate to read an HTTP response into a target generic type object. The RestTemplate has three new exchange(...) methods that accept ParameterizedTypeReference -- a new class that enables capturing and passing generic type info. See the Javadoc of the three new methods in RestOperations for a short example. To support this feature, the HttpMessageConverter is now extended by GenericHttpMessageConverter, which adds a method for reading an HttpInputMessage to a specific generic type. The new interface is implemented by the MappingJacksonHttpMessageConverter and also by a new Jaxb2CollectionHttpMessageConverter that can read read a generic Collection where the generic type is a JAXB type annotated with @XmlRootElement or @XmlType. Issue: SPR-7023
spring-web/src/main/java/org/springframework/http/converter/xml/Jaxb2CollectionHttpMessageConverter.java
@@ -0,0 +1,228 @@ +/* + * Copyright 2002-2012 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.http.converter.xml; + +import java.io.IOException; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.SortedSet; +import java.util.TreeSet; + +import javax.xml.bind.JAXBException; +import javax.xml.bind.UnmarshalException; +import javax.xml.bind.Unmarshaller; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.transform.Result; +import javax.xml.transform.Source; + +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpInputMessage; +import org.springframework.http.MediaType; +import org.springframework.http.converter.GenericHttpMessageConverter; +import org.springframework.http.converter.HttpMessageConversionException; +import org.springframework.http.converter.HttpMessageNotReadableException; + +/** + * An {@code HttpMessageConverter} that can read XML collections using JAXB2. + * + * <p>This converter can read {@linkplain Collection collections} that contain classes + * annotated with {@link XmlRootElement} and {@link XmlType}. Note that this converter + * does not support writing. + * + * @author Arjen Poutsma + * @since 3.2 + */ +public class Jaxb2CollectionHttpMessageConverter<T extends Collection> + extends AbstractJaxb2HttpMessageConverter<T> implements GenericHttpMessageConverter<T> { + + private final XMLInputFactory inputFactory = createXmlInputFactory(); + + /** + * Always returns {@code false} since Jaxb2CollectionHttpMessageConverter + * required generic type information in order to read a Collection. + */ + @Override + public boolean canRead(Class<?> clazz, MediaType mediaType) { + return false; + } + + /** + * {@inheritDoc} + * <p>Jaxb2CollectionHttpMessageConverter can read a generic + * {@link Collection} where the generic type is a JAXB type annotated with + * {@link XmlRootElement} or {@link XmlType}. + */ + public boolean canRead(Type type, MediaType mediaType) { + if (!(type instanceof ParameterizedType)) { + return false; + } + ParameterizedType parameterizedType = (ParameterizedType) type; + if (!(parameterizedType.getRawType() instanceof Class)) { + return false; + } + Class<?> rawType = (Class<?>) parameterizedType.getRawType(); + if (!(Collection.class.isAssignableFrom(rawType))) { + return false; + } + if (parameterizedType.getActualTypeArguments().length != 1) { + return false; + } + Type typeArgument = parameterizedType.getActualTypeArguments()[0]; + if (!(typeArgument instanceof Class)) { + return false; + } + Class<?> typeArgumentClass = (Class<?>) typeArgument; + return (typeArgumentClass.isAnnotationPresent(XmlRootElement.class) || + typeArgumentClass.isAnnotationPresent(XmlType.class)) && canRead(mediaType); + } + + /** + * Always returns {@code false} since Jaxb2CollectionHttpMessageConverter + * does not convert collections to XML. + */ + @Override + public boolean canWrite(Class<?> clazz, MediaType mediaType) { + return false; + } + + @Override + protected boolean supports(Class<?> clazz) { + // should not be called, since we override canRead/Write + throw new UnsupportedOperationException(); + } + + @Override + protected T readFromSource(Class<? extends T> clazz, HttpHeaders headers, Source source) throws IOException { + // should not be called, since we return false for canRead(Class) + throw new UnsupportedOperationException(); + } + + public T read(Type type, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { + ParameterizedType parameterizedType = (ParameterizedType) type; + T result = createCollection((Class<?>) parameterizedType.getRawType()); + Class<?> elementClass = (Class<?>) parameterizedType.getActualTypeArguments()[0]; + + try { + Unmarshaller unmarshaller = createUnmarshaller(elementClass); + XMLStreamReader streamReader = this.inputFactory.createXMLStreamReader(inputMessage.getBody()); + int event = moveToFirstChildOfRootElement(streamReader); + + while (event != XMLStreamReader.END_DOCUMENT) { + if (elementClass.isAnnotationPresent(XmlRootElement.class)) { + result.add(unmarshaller.unmarshal(streamReader)); + } + else if (elementClass.isAnnotationPresent(XmlType.class)) { + result.add(unmarshaller.unmarshal(streamReader, elementClass).getValue()); + } + else { + // should not happen, since we check in canRead(Type) + throw new HttpMessageConversionException("Could not unmarshal to [" + elementClass + "]"); + } + event = moveToNextElement(streamReader); + } + return result; + } + catch (UnmarshalException ex) { + throw new HttpMessageNotReadableException("Could not unmarshal to [" + elementClass + "]: " + ex.getMessage(), ex); + } + catch (JAXBException ex) { + throw new HttpMessageConversionException("Could not instantiate JAXBContext: " + ex.getMessage(), ex); + } + catch (XMLStreamException ex) { + throw new HttpMessageConversionException(ex.getMessage(), ex); + } + } + + /** + * Create a Collection of the given type, with the given initial capacity + * (if supported by the Collection type). + * + * @param collectionClass the type of Collection to instantiate + * @return the created Collection instance + */ + @SuppressWarnings("unchecked") + protected T createCollection(Class<?> collectionClass) { + if (!collectionClass.isInterface()) { + try { + return (T) collectionClass.newInstance(); + } + catch (Exception ex) { + throw new IllegalArgumentException( + "Could not instantiate collection class [" + + collectionClass.getName() + "]: " + ex.getMessage()); + } + } + else if (List.class.equals(collectionClass)) { + return (T) new ArrayList(); + } + else if (SortedSet.class.equals(collectionClass)) { + return (T) new TreeSet(); + } + else { + return (T) new LinkedHashSet(); + } + } + + private int moveToFirstChildOfRootElement(XMLStreamReader streamReader) throws XMLStreamException { + // root + int event = streamReader.next(); + while (event != XMLStreamReader.START_ELEMENT) { + event = streamReader.next(); + } + + // first child + event = streamReader.next(); + while ((event != XMLStreamReader.START_ELEMENT) && (event != XMLStreamReader.END_DOCUMENT)) { + event = streamReader.next(); + } + return event; + } + + private int moveToNextElement(XMLStreamReader streamReader) throws XMLStreamException { + int event = streamReader.getEventType(); + while (event != XMLStreamReader.START_ELEMENT && event != XMLStreamReader.END_DOCUMENT) { + event = streamReader.next(); + } + return event; + } + + @Override + protected void writeToResult(T t, HttpHeaders headers, Result result) throws IOException { + throw new UnsupportedOperationException(); + } + + /** + * Create a {@code XMLInputFactory} that this converter will use to create {@link + * javax.xml.stream.XMLStreamReader} and {@link javax.xml.stream.XMLEventReader} objects. + * <p/> Can be overridden in subclasses, adding further initialization of the factory. + * The resulting factory is cached, so this method will only be called once. + * + * @return the created factory + */ + protected XMLInputFactory createXmlInputFactory() { + return XMLInputFactory.newInstance(); + } + +}
true
Other
spring-projects
spring-framework
ed3823b045fd19cdb801609eb034c93dd4d75c3f.json
Support generic target types in the RestTemplate This change makes it possible to use the RestTemplate to read an HTTP response into a target generic type object. The RestTemplate has three new exchange(...) methods that accept ParameterizedTypeReference -- a new class that enables capturing and passing generic type info. See the Javadoc of the three new methods in RestOperations for a short example. To support this feature, the HttpMessageConverter is now extended by GenericHttpMessageConverter, which adds a method for reading an HttpInputMessage to a specific generic type. The new interface is implemented by the MappingJacksonHttpMessageConverter and also by a new Jaxb2CollectionHttpMessageConverter that can read read a generic Collection where the generic type is a JAXB type annotated with @XmlRootElement or @XmlType. Issue: SPR-7023
spring-web/src/main/java/org/springframework/web/client/HttpMessageConverterExtractor.java
@@ -17,6 +17,7 @@ package org.springframework.web.client; import java.io.IOException; +import java.lang.reflect.Type; import java.util.List; import org.apache.commons.logging.Log; @@ -25,34 +26,45 @@ import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.client.ClientHttpResponse; +import org.springframework.http.converter.GenericHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.util.Assert; /** - * Response extractor that uses the given {@linkplain HttpMessageConverter entity converters} to convert the response - * into a type <code>T</code>. + * Response extractor that uses the given {@linkplain HttpMessageConverter entity + * converters} to convert the response into a type <code>T</code>. * * @author Arjen Poutsma * @see RestTemplate * @since 3.0 */ public class HttpMessageConverterExtractor<T> implements ResponseExtractor<T> { - private final Class<T> responseType; + private final Type responseType; private final List<HttpMessageConverter<?>> messageConverters; private final Log logger; /** - * Creates a new instance of the {@code HttpMessageConverterExtractor} with the given response type and message - * converters. The given converters must support the response type. + * Creates a new instance of the {@code HttpMessageConverterExtractor} with the given + * response type and message converters. The given converters must support the response + * type. */ public HttpMessageConverterExtractor(Class<T> responseType, List<HttpMessageConverter<?>> messageConverters) { + this((Type) responseType, messageConverters); + } + + /** + * Creates a new instance of the {@code HttpMessageConverterExtractor} with the given + * response type and message converters. The given converters must support the response + * type. + */ + public HttpMessageConverterExtractor(Type responseType, List<HttpMessageConverter<?>> messageConverters) { this(responseType, messageConverters, LogFactory.getLog(HttpMessageConverterExtractor.class)); } - HttpMessageConverterExtractor(Class<T> responseType, List<HttpMessageConverter<?>> messageConverters, Log logger) { + HttpMessageConverterExtractor(Type responseType, List<HttpMessageConverter<?>> messageConverters, Log logger) { Assert.notNull(responseType, "'responseType' must not be null"); Assert.notEmpty(messageConverters, "'messageConverters' must not be empty"); this.responseType = responseType; @@ -65,39 +77,62 @@ public T extractData(ClientHttpResponse response) throws IOException { if (!hasMessageBody(response)) { return null; } + MediaType contentType = getContentType(response); + + Class<T> responseClass = null; + if (this.responseType instanceof Class) { + responseClass = (Class) this.responseType; + } + for (HttpMessageConverter messageConverter : this.messageConverters) { + if (responseClass != null) { + if (messageConverter.canRead(responseClass, contentType)) { + if (logger.isDebugEnabled()) { + logger.debug("Reading [" + responseClass.getName() + "] as \"" + + contentType + "\" using [" + messageConverter + "]"); + } + return (T) messageConverter.read(responseClass, response); + } + } + else if (messageConverter instanceof GenericHttpMessageConverter) { + GenericHttpMessageConverter genericMessageConverter = (GenericHttpMessageConverter) messageConverter; + if (genericMessageConverter.canRead(this.responseType, contentType)) { + if (logger.isDebugEnabled()) { + logger.debug("Reading [" + this.responseType + "] as \"" + + contentType + "\" using [" + messageConverter + "]"); + } + return (T) genericMessageConverter.read(this.responseType, response); + } + } + } + throw new RestClientException( + "Could not extract response: no suitable HttpMessageConverter found for response type [" + + this.responseType + "] and content type [" + contentType + "]"); + } + + private MediaType getContentType(ClientHttpResponse response) { MediaType contentType = response.getHeaders().getContentType(); if (contentType == null) { if (logger.isTraceEnabled()) { logger.trace("No Content-Type header found, defaulting to application/octet-stream"); } contentType = MediaType.APPLICATION_OCTET_STREAM; } - for (HttpMessageConverter messageConverter : messageConverters) { - if (messageConverter.canRead(responseType, contentType)) { - if (logger.isDebugEnabled()) { - logger.debug("Reading [" + responseType.getName() + "] as \"" + contentType - +"\" using [" + messageConverter + "]"); - } - return (T) messageConverter.read(this.responseType, response); - } - } - throw new RestClientException( - "Could not extract response: no suitable HttpMessageConverter found for response type [" + - this.responseType.getName() + "] and content type [" + contentType + "]"); + return contentType; } /** - * Indicates whether the given response has a message body. - * <p>Default implementation returns {@code false} for a response status of {@code 204} or {@code 304}, or a - * {@code Content-Length} of {@code 0}. + * Indicates whether the given response has a message body. <p>Default implementation + * returns {@code false} for a response status of {@code 204} or {@code 304}, or a {@code + * Content-Length} of {@code 0}. * * @param response the response to check for a message body * @return {@code true} if the response has a body, {@code false} otherwise * @throws IOException in case of I/O errors */ protected boolean hasMessageBody(ClientHttpResponse response) throws IOException { HttpStatus responseStatus = response.getStatusCode(); - if (responseStatus == HttpStatus.NO_CONTENT || responseStatus == HttpStatus.NOT_MODIFIED) { + if (responseStatus == HttpStatus.NO_CONTENT || + responseStatus == HttpStatus.NOT_MODIFIED) { return false; } long contentLength = response.getHeaders().getContentLength();
true
Other
spring-projects
spring-framework
ed3823b045fd19cdb801609eb034c93dd4d75c3f.json
Support generic target types in the RestTemplate This change makes it possible to use the RestTemplate to read an HTTP response into a target generic type object. The RestTemplate has three new exchange(...) methods that accept ParameterizedTypeReference -- a new class that enables capturing and passing generic type info. See the Javadoc of the three new methods in RestOperations for a short example. To support this feature, the HttpMessageConverter is now extended by GenericHttpMessageConverter, which adds a method for reading an HttpInputMessage to a specific generic type. The new interface is implemented by the MappingJacksonHttpMessageConverter and also by a new Jaxb2CollectionHttpMessageConverter that can read read a generic Collection where the generic type is a JAXB type annotated with @XmlRootElement or @XmlType. Issue: SPR-7023
spring-web/src/main/java/org/springframework/web/client/RestOperations.java
@@ -1,11 +1,11 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2012 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 + * 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, @@ -20,6 +20,7 @@ import java.util.Map; import java.util.Set; +import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; @@ -396,6 +397,69 @@ <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requ <T> ResponseEntity<T> exchange(URI url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType) throws RestClientException; + /** + * Execute the HTTP method to the given URI template, writing the given + * request entity to the request, and returns the response as {@link ResponseEntity}. + * The given {@link ParameterizedTypeReference} is used to pass generic type information: + * + * <pre class="code"> + * ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt; myBean = new ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt;() {}; + * ResponseEntity&lt;List&lt;MyBean&gt;&gt; response = template.exchange(&quot;http://example.com&quot;,HttpMethod.GET, null, myBean); + * </pre> + * + * @param url the URL + * @param method the HTTP method (GET, POST, etc) + * @param requestEntity the entity (headers and/or body) to write to the + * request, may be {@code null} + * @param responseType the type of the return value + * @param uriVariables the variables to expand in the template + * @return the response as entity + * @since 3.2.0 + */ + <T> ResponseEntity<T> exchange(String url,HttpMethod method, HttpEntity<?> requestEntity, + ParameterizedTypeReference<T> responseType, Object... uriVariables) throws RestClientException; + + /** + * Execute the HTTP method to the given URI template, writing the given + * request entity to the request, and returns the response as {@link ResponseEntity}. + * The given {@link ParameterizedTypeReference} is used to pass generic type information: + * + * <pre class="code"> + * ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt; myBean = new ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt;() {}; + * ResponseEntity&lt;List&lt;MyBean&gt;&gt; response = template.exchange(&quot;http://example.com&quot;,HttpMethod.GET, null, myBean); + * </pre> + * + * @param url the URL + * @param method the HTTP method (GET, POST, etc) + * @param requestEntity the entity (headers and/or body) to write to the request, may be {@code null} + * @param responseType the type of the return value + * @param uriVariables the variables to expand in the template + * @return the response as entity + * @since 3.2.0 + */ + <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, + ParameterizedTypeReference<T> responseType, Map<String, ?> uriVariables) throws RestClientException; + + /** + * Execute the HTTP method to the given URI template, writing the given + * request entity to the request, and returns the response as {@link ResponseEntity}. + * The given {@link ParameterizedTypeReference} is used to pass generic type information: + * + * <pre class="code"> + * ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt; myBean = new ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt;() {}; + * ResponseEntity&lt;List&lt;MyBean&gt;&gt; response = template.exchange(&quot;http://example.com&quot;,HttpMethod.GET, null, myBean); + * </pre> + * + * @param url the URL + * @param method the HTTP method (GET, POST, etc) + * @param requestEntity the entity (headers and/or body) to write to the request, may be {@code null} + * @param responseType the type of the return value + * @return the response as entity + * @since 3.2.0 + */ + <T> ResponseEntity<T> exchange(URI url, HttpMethod method, HttpEntity<?> requestEntity, + ParameterizedTypeReference<T> responseType) throws RestClientException; + // general execution /**
true
Other
spring-projects
spring-framework
ed3823b045fd19cdb801609eb034c93dd4d75c3f.json
Support generic target types in the RestTemplate This change makes it possible to use the RestTemplate to read an HTTP response into a target generic type object. The RestTemplate has three new exchange(...) methods that accept ParameterizedTypeReference -- a new class that enables capturing and passing generic type info. See the Javadoc of the three new methods in RestOperations for a short example. To support this feature, the HttpMessageConverter is now extended by GenericHttpMessageConverter, which adds a method for reading an HttpInputMessage to a specific generic type. The new interface is implemented by the MappingJacksonHttpMessageConverter and also by a new Jaxb2CollectionHttpMessageConverter that can read read a generic Collection where the generic type is a JAXB type annotated with @XmlRootElement or @XmlType. Issue: SPR-7023
spring-web/src/main/java/org/springframework/web/client/RestTemplate.java
@@ -5,7 +5,7 @@ * 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 + * 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, @@ -18,13 +18,15 @@ import java.io.IOException; import java.io.UnsupportedEncodingException; +import java.lang.reflect.Type; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; +import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; @@ -35,6 +37,7 @@ import org.springframework.http.client.ClientHttpResponse; import org.springframework.http.client.support.InterceptingHttpAccessor; import org.springframework.http.converter.ByteArrayHttpMessageConverter; +import org.springframework.http.converter.GenericHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.ResourceHttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; @@ -384,25 +387,55 @@ public Set<HttpMethod> optionsForAllow(URI url) throws RestClientException { public <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables) throws RestClientException { + HttpEntityRequestCallback requestCallback = new HttpEntityRequestCallback(requestEntity, responseType); ResponseEntityResponseExtractor<T> responseExtractor = new ResponseEntityResponseExtractor<T>(responseType); return execute(url, method, requestCallback, responseExtractor, uriVariables); } public <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Map<String, ?> uriVariables) throws RestClientException { + HttpEntityRequestCallback requestCallback = new HttpEntityRequestCallback(requestEntity, responseType); ResponseEntityResponseExtractor<T> responseExtractor = new ResponseEntityResponseExtractor<T>(responseType); return execute(url, method, requestCallback, responseExtractor, uriVariables); } public <T> ResponseEntity<T> exchange(URI url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType) throws RestClientException { + HttpEntityRequestCallback requestCallback = new HttpEntityRequestCallback(requestEntity, responseType); ResponseEntityResponseExtractor<T> responseExtractor = new ResponseEntityResponseExtractor<T>(responseType); return execute(url, method, requestCallback, responseExtractor); } + public <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, + ParameterizedTypeReference<T> responseType, Object... uriVariables) throws RestClientException { + + Type type = responseType.getType(); + HttpEntityRequestCallback requestCallback = new HttpEntityRequestCallback(requestEntity, type); + ResponseEntityResponseExtractor<T> responseExtractor = new ResponseEntityResponseExtractor<T>(type); + return execute(url, method, requestCallback, responseExtractor, uriVariables); + } + + public <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, + ParameterizedTypeReference<T> responseType, Map<String, ?> uriVariables) throws RestClientException { + + Type type = responseType.getType(); + HttpEntityRequestCallback requestCallback = new HttpEntityRequestCallback(requestEntity, type); + ResponseEntityResponseExtractor<T> responseExtractor = new ResponseEntityResponseExtractor<T>(type); + return execute(url, method, requestCallback, responseExtractor, uriVariables); + } + + public <T> ResponseEntity<T> exchange(URI url, HttpMethod method, HttpEntity<?> requestEntity, + ParameterizedTypeReference<T> responseType) throws RestClientException { + + Type type = responseType.getType(); + HttpEntityRequestCallback requestCallback = new HttpEntityRequestCallback(requestEntity, type); + ResponseEntityResponseExtractor<T> responseExtractor = new ResponseEntityResponseExtractor<T>(type); + return execute(url, method, requestCallback, responseExtractor); + } + // general execution public <T> T execute(String url, HttpMethod method, RequestCallback requestCallback, @@ -504,37 +537,62 @@ private void handleResponseError(HttpMethod method, URI url, ClientHttpResponse */ private class AcceptHeaderRequestCallback implements RequestCallback { - private final Class<?> responseType; + private final Type responseType; - private AcceptHeaderRequestCallback(Class<?> responseType) { + private AcceptHeaderRequestCallback(Type responseType) { this.responseType = responseType; } @SuppressWarnings("unchecked") public void doWithRequest(ClientHttpRequest request) throws IOException { if (responseType != null) { + Class<?> responseClass = null; + if (responseType instanceof Class) { + responseClass = (Class) responseType; + } + List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>(); for (HttpMessageConverter<?> messageConverter : getMessageConverters()) { - if (messageConverter.canRead(responseType, null)) { - List<MediaType> supportedMediaTypes = messageConverter.getSupportedMediaTypes(); - for (MediaType supportedMediaType : supportedMediaTypes) { - if (supportedMediaType.getCharSet() != null) { - supportedMediaType = - new MediaType(supportedMediaType.getType(), supportedMediaType.getSubtype()); - } - allSupportedMediaTypes.add(supportedMediaType); + if (responseClass != null) { + if (messageConverter.canRead(responseClass, null)) { + allSupportedMediaTypes + .addAll(getSupportedMediaTypes(messageConverter)); } } + else if (messageConverter instanceof GenericHttpMessageConverter) { + + GenericHttpMessageConverter genericMessageConverter = + (GenericHttpMessageConverter) messageConverter; + if (genericMessageConverter.canRead(responseType, null)) { + allSupportedMediaTypes + .addAll(getSupportedMediaTypes(messageConverter)); + } + } + } if (!allSupportedMediaTypes.isEmpty()) { MediaType.sortBySpecificity(allSupportedMediaTypes); if (logger.isDebugEnabled()) { - logger.debug("Setting request Accept header to " + allSupportedMediaTypes); + logger.debug("Setting request Accept header to " + + allSupportedMediaTypes); } request.getHeaders().setAccept(allSupportedMediaTypes); } } } + + private List<MediaType> getSupportedMediaTypes(HttpMessageConverter<?> messageConverter) { + List<MediaType> supportedMediaTypes = messageConverter.getSupportedMediaTypes(); + List<MediaType> result = new ArrayList<MediaType>(supportedMediaTypes.size()); + for (MediaType supportedMediaType : supportedMediaTypes) { + if (supportedMediaType.getCharSet() != null) { + supportedMediaType = + new MediaType(supportedMediaType.getType(), supportedMediaType.getSubtype()); + } + result.add(supportedMediaType); + } + return result; + } } @@ -550,7 +608,7 @@ private HttpEntityRequestCallback(Object requestBody) { } @SuppressWarnings("unchecked") - private HttpEntityRequestCallback(Object requestBody, Class<?> responseType) { + private HttpEntityRequestCallback(Object requestBody, Type responseType) { super(responseType); if (requestBody instanceof HttpEntity) { this.requestEntity = (HttpEntity) requestBody; @@ -618,7 +676,7 @@ public void doWithRequest(ClientHttpRequest httpRequest) throws IOException { private final HttpMessageConverterExtractor<T> delegate; - public ResponseEntityResponseExtractor(Class<T> responseType) { + public ResponseEntityResponseExtractor(Type responseType) { if (responseType != null && !Void.class.equals(responseType)) { this.delegate = new HttpMessageConverterExtractor<T>(responseType, getMessageConverters(), logger); } else {
true
Other
spring-projects
spring-framework
ed3823b045fd19cdb801609eb034c93dd4d75c3f.json
Support generic target types in the RestTemplate This change makes it possible to use the RestTemplate to read an HTTP response into a target generic type object. The RestTemplate has three new exchange(...) methods that accept ParameterizedTypeReference -- a new class that enables capturing and passing generic type info. See the Javadoc of the three new methods in RestOperations for a short example. To support this feature, the HttpMessageConverter is now extended by GenericHttpMessageConverter, which adds a method for reading an HttpInputMessage to a specific generic type. The new interface is implemented by the MappingJacksonHttpMessageConverter and also by a new Jaxb2CollectionHttpMessageConverter that can read read a generic Collection where the generic type is a JAXB type annotated with @XmlRootElement or @XmlType. Issue: SPR-7023
spring-web/src/test/java/org/springframework/http/converter/json/MappingJackson2HttpMessageConverterTests.java
@@ -16,23 +16,22 @@ package org.springframework.http.converter.json; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.io.IOException; +import java.lang.reflect.Type; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; +import com.fasterxml.jackson.databind.JavaType; +import com.fasterxml.jackson.databind.ObjectMapper; +import static org.junit.Assert.*; import org.junit.Test; + +import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.MediaType; import org.springframework.http.MockHttpInputMessage; import org.springframework.http.MockHttpOutputMessage; -import com.fasterxml.jackson.databind.JavaType; -import com.fasterxml.jackson.databind.ObjectMapper; - /** * Jackson 2.x converter tests. * @@ -52,12 +51,12 @@ public void readGenerics() throws IOException { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter() { @Override - protected JavaType getJavaType(Class<?> clazz) { - if (List.class.isAssignableFrom(clazz)) { + protected JavaType getJavaType(Type type) { + if (type instanceof Class && List.class.isAssignableFrom((Class)type)) { return new ObjectMapper().getTypeFactory().constructCollectionType(ArrayList.class, MyBean.class); } else { - return super.getJavaType(clazz); + return super.getJavaType(type); } } }; @@ -77,6 +76,29 @@ protected JavaType getJavaType(Class<?> clazz) { assertArrayEquals(new byte[]{0x1, 0x2}, result.getBytes()); } + @Test + @SuppressWarnings("unchecked") + public void readParameterizedType() throws IOException { + ParameterizedTypeReference<List<MyBean>> beansList = new ParameterizedTypeReference<List<MyBean>>() {}; + + String body = + "[{\"bytes\":\"AQI=\",\"array\":[\"Foo\",\"Bar\"],\"number\":42,\"string\":\"Foo\",\"bool\":true,\"fraction\":42.0}]"; + MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8")); + inputMessage.getHeaders().setContentType(new MediaType("application", "json")); + + MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); + List<MyBean> results = (List<MyBean>) converter.read(beansList.getType(), inputMessage); + assertEquals(1, results.size()); + MyBean result = results.get(0); + assertEquals("Foo", result.getString()); + assertEquals(42, result.getNumber()); + assertEquals(42F, result.getFraction(), 0F); + assertArrayEquals(new String[]{"Foo", "Bar"}, result.getArray()); + assertTrue(result.isBool()); + assertArrayEquals(new byte[]{0x1, 0x2}, result.getBytes()); + } + + @Test public void prettyPrint() throws Exception { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
true
Other
spring-projects
spring-framework
ed3823b045fd19cdb801609eb034c93dd4d75c3f.json
Support generic target types in the RestTemplate This change makes it possible to use the RestTemplate to read an HTTP response into a target generic type object. The RestTemplate has three new exchange(...) methods that accept ParameterizedTypeReference -- a new class that enables capturing and passing generic type info. See the Javadoc of the three new methods in RestOperations for a short example. To support this feature, the HttpMessageConverter is now extended by GenericHttpMessageConverter, which adds a method for reading an HttpInputMessage to a specific generic type. The new interface is implemented by the MappingJacksonHttpMessageConverter and also by a new Jaxb2CollectionHttpMessageConverter that can read read a generic Collection where the generic type is a JAXB type annotated with @XmlRootElement or @XmlType. Issue: SPR-7023
spring-web/src/test/java/org/springframework/http/converter/json/MappingJacksonHttpMessageConverterTests.java
@@ -16,18 +16,18 @@ package org.springframework.http.converter.json; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.io.IOException; +import java.lang.reflect.Type; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import org.codehaus.jackson.map.type.TypeFactory; import org.codehaus.jackson.type.JavaType; +import static org.junit.Assert.*; import org.junit.Test; + +import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.MediaType; import org.springframework.http.MockHttpInputMessage; import org.springframework.http.MockHttpOutputMessage; @@ -49,12 +49,12 @@ protected MappingJacksonHttpMessageConverter createConverter() { public void readGenerics() throws IOException { MappingJacksonHttpMessageConverter converter = new MappingJacksonHttpMessageConverter() { @Override - protected JavaType getJavaType(Class<?> clazz) { - if (List.class.isAssignableFrom(clazz)) { + protected JavaType getJavaType(Type type) { + if (type instanceof Class && List.class.isAssignableFrom((Class)type)) { return TypeFactory.collectionType(ArrayList.class, MyBean.class); } else { - return super.getJavaType(clazz); + return super.getJavaType(type); } } }; @@ -74,6 +74,28 @@ protected JavaType getJavaType(Class<?> clazz) { assertArrayEquals(new byte[]{0x1, 0x2}, result.getBytes()); } + @Test + @SuppressWarnings("unchecked") + public void readParameterizedType() throws IOException { + ParameterizedTypeReference<List<MyBean>> beansList = new ParameterizedTypeReference<List<MyBean>>() {}; + + String body = + "[{\"bytes\":\"AQI=\",\"array\":[\"Foo\",\"Bar\"],\"number\":42,\"string\":\"Foo\",\"bool\":true,\"fraction\":42.0}]"; + MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8")); + inputMessage.getHeaders().setContentType(new MediaType("application", "json")); + + MappingJacksonHttpMessageConverter converter = new MappingJacksonHttpMessageConverter(); + List<MyBean> results = (List<MyBean>) converter.read(beansList.getType(), inputMessage); + assertEquals(1, results.size()); + MyBean result = results.get(0); + assertEquals("Foo", result.getString()); + assertEquals(42, result.getNumber()); + assertEquals(42F, result.getFraction(), 0F); + assertArrayEquals(new String[]{"Foo", "Bar"}, result.getArray()); + assertTrue(result.isBool()); + assertArrayEquals(new byte[]{0x1, 0x2}, result.getBytes()); + } + @Test public void prettyPrint() throws Exception { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
true
Other
spring-projects
spring-framework
ed3823b045fd19cdb801609eb034c93dd4d75c3f.json
Support generic target types in the RestTemplate This change makes it possible to use the RestTemplate to read an HTTP response into a target generic type object. The RestTemplate has three new exchange(...) methods that accept ParameterizedTypeReference -- a new class that enables capturing and passing generic type info. See the Javadoc of the three new methods in RestOperations for a short example. To support this feature, the HttpMessageConverter is now extended by GenericHttpMessageConverter, which adds a method for reading an HttpInputMessage to a specific generic type. The new interface is implemented by the MappingJacksonHttpMessageConverter and also by a new Jaxb2CollectionHttpMessageConverter that can read read a generic Collection where the generic type is a JAXB type annotated with @XmlRootElement or @XmlType. Issue: SPR-7023
spring-web/src/test/java/org/springframework/http/converter/xml/Jaxb2CollectionHttpMessageConverterTests.java
@@ -0,0 +1,189 @@ +/* + * Copyright 2002-2012 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.http.converter.xml; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.lang.reflect.Type; +import java.util.Collection; +import java.util.List; +import java.util.Set; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.MockHttpInputMessage; + +/** + * Test fixture for {@link Jaxb2CollectionHttpMessageConverter}. + * + * @author Arjen Poutsma + */ +public class Jaxb2CollectionHttpMessageConverterTests { + + private Jaxb2CollectionHttpMessageConverter<?> converter; + + private Type rootElementListType; + + private Type rootElementSetType; + + private Type typeListType; + + private Type typeSetType; + + + @Before + public void setUp() { + converter = new Jaxb2CollectionHttpMessageConverter<Collection<Object>>(); + rootElementListType = new ParameterizedTypeReference<List<RootElement>>() {}.getType(); + rootElementSetType = new ParameterizedTypeReference<Set<RootElement>>() {}.getType(); + typeListType = new ParameterizedTypeReference<List<TestType>>() {}.getType(); + typeSetType = new ParameterizedTypeReference<Set<TestType>>() {}.getType(); + } + + @Test + public void canRead() throws Exception { + assertTrue(converter.canRead(rootElementListType, null)); + assertTrue(converter.canRead(rootElementSetType, null)); + assertTrue(converter.canRead(typeSetType, null)); + } + + @Test + @SuppressWarnings("unchecked") + public void readXmlRootElementList() throws Exception { + String content = "<list><rootElement><type s=\"1\"/></rootElement><rootElement><type s=\"2\"/></rootElement></list>"; + MockHttpInputMessage inputMessage = new MockHttpInputMessage(content.getBytes("UTF-8")); + + List<RootElement> result = (List<RootElement>) converter.read(rootElementListType, inputMessage); + + assertEquals("Invalid result", 2, result.size()); + assertEquals("Invalid result", "1", result.get(0).type.s); + assertEquals("Invalid result", "2", result.get(1).type.s); + } + + @Test + @SuppressWarnings("unchecked") + public void readXmlRootElementSet() throws Exception { + String content = "<set><rootElement><type s=\"1\"/></rootElement><rootElement><type s=\"2\"/></rootElement></set>"; + MockHttpInputMessage inputMessage = new MockHttpInputMessage(content.getBytes("UTF-8")); + + Set<RootElement> result = (Set<RootElement>) converter.read(rootElementSetType, inputMessage); + + assertEquals("Invalid result", 2, result.size()); + assertTrue("Invalid result", result.contains(new RootElement("1"))); + assertTrue("Invalid result", result.contains(new RootElement("2"))); + } + + @Test + @SuppressWarnings("unchecked") + public void readXmlTypeList() throws Exception { + String content = "<list><foo s=\"1\"/><bar s=\"2\"/></list>"; + MockHttpInputMessage inputMessage = new MockHttpInputMessage(content.getBytes("UTF-8")); + + List<TestType> result = (List<TestType>) converter.read(typeListType, inputMessage); + + assertEquals("Invalid result", 2, result.size()); + assertEquals("Invalid result", "1", result.get(0).s); + assertEquals("Invalid result", "2", result.get(1).s); + } + + @Test + @SuppressWarnings("unchecked") + public void readXmlTypeSet() throws Exception { + String content = "<set><foo s=\"1\"/><bar s=\"2\"/></set>"; + MockHttpInputMessage inputMessage = new MockHttpInputMessage(content.getBytes("UTF-8")); + + Set<TestType> result = (Set<TestType>) converter.read(typeSetType, inputMessage); + + assertEquals("Invalid result", 2, result.size()); + assertTrue("Invalid result", result.contains(new TestType("1"))); + assertTrue("Invalid result", result.contains(new TestType("2"))); + } + + + @XmlRootElement + public static class RootElement { + + public RootElement() { + } + + public RootElement(String s) { + this.type = new TestType(s); + } + + @XmlElement + public TestType type = new TestType(); + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o instanceof RootElement) { + RootElement other = (RootElement) o; + return this.type.equals(other.type); + } + return false; + } + + @Override + public int hashCode() { + return type.hashCode(); + } + } + + @XmlType + public static class TestType { + + public TestType() { + } + + public TestType(String s) { + this.s = s; + } + + @XmlAttribute + public String s = "Hello World"; + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o instanceof TestType) { + TestType other = (TestType) o; + return this.s.equals(other.s); + } + return false; + } + + @Override + public int hashCode() { + return s.hashCode(); + } + + + + } + +}
true
Other
spring-projects
spring-framework
ed3823b045fd19cdb801609eb034c93dd4d75c3f.json
Support generic target types in the RestTemplate This change makes it possible to use the RestTemplate to read an HTTP response into a target generic type object. The RestTemplate has three new exchange(...) methods that accept ParameterizedTypeReference -- a new class that enables capturing and passing generic type info. See the Javadoc of the three new methods in RestOperations for a short example. To support this feature, the HttpMessageConverter is now extended by GenericHttpMessageConverter, which adds a method for reading an HttpInputMessage to a specific generic type. The new interface is implemented by the MappingJacksonHttpMessageConverter and also by a new Jaxb2CollectionHttpMessageConverter that can read read a generic Collection where the generic type is a JAXB type annotated with @XmlRootElement or @XmlType. Issue: SPR-7023
spring-web/src/test/java/org/springframework/web/client/HttpMessageConverterExtractorTests.java
@@ -0,0 +1,196 @@ +/* + * Copyright 2002-2012 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.web.client; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.http.converter.GenericHttpMessageConverter; +import org.springframework.http.converter.HttpMessageConverter; + +/** + * Test fixture for {@link HttpMessageConverter}. + * + * @author Arjen Poutsma + */ +public class HttpMessageConverterExtractorTests { + + private HttpMessageConverterExtractor extractor; + + private ClientHttpResponse response; + + @Before + public void createMocks() { + response = createMock(ClientHttpResponse.class); + } + + @Test + public void noContent() throws IOException { + HttpMessageConverter<?> converter = createMock(HttpMessageConverter.class); + + extractor = new HttpMessageConverterExtractor<String>(String.class, createConverterList(converter)); + + expect(response.getStatusCode()).andReturn(HttpStatus.NO_CONTENT); + + replay(response, converter); + Object result = extractor.extractData(response); + + assertNull(result); + verify(response, converter); + } + + @Test + public void notModified() throws IOException { + HttpMessageConverter<?> converter = createMock(HttpMessageConverter.class); + + extractor = new HttpMessageConverterExtractor<String>(String.class, createConverterList(converter)); + + expect(response.getStatusCode()).andReturn(HttpStatus.NOT_MODIFIED); + + replay(response, converter); + Object result = extractor.extractData(response); + + assertNull(result); + verify(response, converter); + } + + @Test + public void zeroContentLength() throws IOException { + HttpMessageConverter<?> converter = createMock(HttpMessageConverter.class); + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.setContentLength(0); + + extractor = new HttpMessageConverterExtractor<String>(String.class, createConverterList(converter)); + + expect(response.getStatusCode()).andReturn(HttpStatus.OK); + expect(response.getHeaders()).andReturn(responseHeaders); + + replay(response, converter); + Object result = extractor.extractData(response); + + assertNull(result); + verify(response, converter); + } + + @Test + @SuppressWarnings("unchecked") + public void normal() throws IOException { + HttpMessageConverter<String> converter = createMock(HttpMessageConverter.class); + List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>(); + converters.add(converter); + + HttpHeaders responseHeaders = new HttpHeaders(); + MediaType contentType = MediaType.TEXT_PLAIN; + responseHeaders.setContentType(contentType); + String expected = "Foo"; + + extractor = new HttpMessageConverterExtractor<String>(String.class, converters); + + expect(response.getStatusCode()).andReturn(HttpStatus.OK); + expect(response.getHeaders()).andReturn(responseHeaders).times(2); + expect(converter.canRead(String.class, contentType)).andReturn(true); + expect(converter.read(String.class, response)).andReturn(expected); + + replay(response, converter); + Object result = extractor.extractData(response); + + assertEquals(expected, result); + verify(response, converter); + } + + @Test + @SuppressWarnings("unchecked") + public void cannotRead() throws IOException { + HttpMessageConverter<String> converter = createMock(HttpMessageConverter.class); + List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>(); + converters.add(converter); + + HttpHeaders responseHeaders = new HttpHeaders(); + MediaType contentType = MediaType.TEXT_PLAIN; + responseHeaders.setContentType(contentType); + + extractor = new HttpMessageConverterExtractor<String>(String.class, converters); + + expect(response.getStatusCode()).andReturn(HttpStatus.OK); + expect(response.getHeaders()).andReturn(responseHeaders).times(2); + expect(converter.canRead(String.class, contentType)).andReturn(false); + + replay(response, converter); + try { + extractor.extractData(response); + fail("RestClientException expected"); + } + catch (RestClientException expected) { + // expected + } + + verify(response, converter); + } + + @Test + @SuppressWarnings("unchecked") + public void generics() throws IOException { + GenericHttpMessageConverter<String> converter = createMock(GenericHttpMessageConverter.class); + List<HttpMessageConverter<?>> converters = createConverterList(converter); + + HttpHeaders responseHeaders = new HttpHeaders(); + MediaType contentType = MediaType.TEXT_PLAIN; + responseHeaders.setContentType(contentType); + String expected = "Foo"; + + ParameterizedTypeReference<List<String>> reference = new ParameterizedTypeReference<List<String>>() {}; + Type type = reference.getType(); + + extractor = new HttpMessageConverterExtractor<List<String>>(type, converters); + + expect(response.getStatusCode()).andReturn(HttpStatus.OK); + expect(response.getHeaders()).andReturn(responseHeaders).times(2); + expect(converter.canRead(type, contentType)).andReturn(true); + expect(converter.read(type, response)).andReturn(expected); + + replay(response, converter); + Object result = extractor.extractData(response); + + assertEquals(expected, result); + verify(response, converter); + } + + private List<HttpMessageConverter<?>> createConverterList(HttpMessageConverter converter) { + List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>(1); + converters.add(converter); + return converters; + } + + +}
true
Other
spring-projects
spring-framework
ed3823b045fd19cdb801609eb034c93dd4d75c3f.json
Support generic target types in the RestTemplate This change makes it possible to use the RestTemplate to read an HTTP response into a target generic type object. The RestTemplate has three new exchange(...) methods that accept ParameterizedTypeReference -- a new class that enables capturing and passing generic type info. See the Javadoc of the three new methods in RestOperations for a short example. To support this feature, the HttpMessageConverter is now extended by GenericHttpMessageConverter, which adds a method for reading an HttpInputMessage to a specific generic type. The new interface is implemented by the MappingJacksonHttpMessageConverter and also by a new Jaxb2CollectionHttpMessageConverter that can read read a generic Collection where the generic type is a JAXB type annotated with @XmlRootElement or @XmlType. Issue: SPR-7023
spring-web/src/test/java/org/springframework/web/client/RestTemplateTests.java
@@ -1,11 +1,11 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2012 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 + * 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, @@ -21,12 +21,16 @@ import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Set; +import static org.easymock.EasyMock.*; +import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; +import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; @@ -36,11 +40,9 @@ import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.ClientHttpResponse; +import org.springframework.http.converter.GenericHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; -import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; - /** @author Arjen Poutsma */ @SuppressWarnings("unchecked") public class RestTemplateTests { @@ -600,9 +602,8 @@ public void ioException() throws Exception { @Test public void exchange() throws Exception { - MediaType textPlain = new MediaType("text", "plain"); expect(converter.canRead(Integer.class, null)).andReturn(true); - expect(converter.getSupportedMediaTypes()).andReturn(Collections.singletonList(textPlain)); + expect(converter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).andReturn(this.request); HttpHeaders requestHeaders = new HttpHeaders(); expect(this.request.getHeaders()).andReturn(requestHeaders).times(2); @@ -612,12 +613,12 @@ public void exchange() throws Exception { expect(this.request.execute()).andReturn(response); expect(errorHandler.hasError(response)).andReturn(false); HttpHeaders responseHeaders = new HttpHeaders(); - responseHeaders.setContentType(textPlain); + responseHeaders.setContentType(MediaType.TEXT_PLAIN); responseHeaders.setContentLength(10); expect(response.getStatusCode()).andReturn(HttpStatus.OK); expect(response.getHeaders()).andReturn(responseHeaders).times(3); Integer expected = 42; - expect(converter.canRead(Integer.class, textPlain)).andReturn(true); + expect(converter.canRead(Integer.class, MediaType.TEXT_PLAIN)).andReturn(true); expect(converter.read(Integer.class, response)).andReturn(expected); expect(response.getStatusCode()).andReturn(HttpStatus.OK); response.close(); @@ -629,14 +630,56 @@ public void exchange() throws Exception { HttpEntity<String> requestEntity = new HttpEntity<String>(body, entityHeaders); ResponseEntity<Integer> result = template.exchange("http://example.com", HttpMethod.POST, requestEntity, Integer.class); assertEquals("Invalid POST result", expected, result.getBody()); - assertEquals("Invalid Content-Type", textPlain, result.getHeaders().getContentType()); - assertEquals("Invalid Accept header", textPlain.toString(), requestHeaders.getFirst("Accept")); + assertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType()); + assertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept")); assertEquals("Invalid custom header", "MyValue", requestHeaders.getFirst("MyHeader")); assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode()); verifyMocks(); } + @Test + public void exchangeParameterizedType() throws Exception { + GenericHttpMessageConverter converter = createMock(GenericHttpMessageConverter.class); + template.setMessageConverters(Collections.<HttpMessageConverter<?>>singletonList(converter)); + + ParameterizedTypeReference<List<Integer>> intList = new ParameterizedTypeReference<List<Integer>>() {}; + expect(converter.canRead(intList.getType(), null)).andReturn(true); + expect(converter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); + expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).andReturn(this.request); + HttpHeaders requestHeaders = new HttpHeaders(); + expect(this.request.getHeaders()).andReturn(requestHeaders).times(2); + expect(converter.canWrite(String.class, null)).andReturn(true); + String requestBody = "Hello World"; + converter.write(requestBody, null, this.request); + expect(this.request.execute()).andReturn(response); + expect(errorHandler.hasError(response)).andReturn(false); + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.setContentType(MediaType.TEXT_PLAIN); + responseHeaders.setContentLength(10); + expect(response.getStatusCode()).andReturn(HttpStatus.OK); + expect(response.getHeaders()).andReturn(responseHeaders).times(3); + List<Integer> expected = Collections.singletonList(42); + expect(converter.canRead(intList.getType(), MediaType.TEXT_PLAIN)).andReturn(true); + expect(converter.read(intList.getType(), response)).andReturn(expected); + expect(response.getStatusCode()).andReturn(HttpStatus.OK); + response.close(); + + replay(requestFactory, request, response, errorHandler, converter); + + HttpHeaders entityHeaders = new HttpHeaders(); + entityHeaders.set("MyHeader", "MyValue"); + HttpEntity<String> requestEntity = new HttpEntity<String>(requestBody, entityHeaders); + ResponseEntity<List<Integer>> result = template.exchange("http://example.com", HttpMethod.POST, requestEntity, intList); + assertEquals("Invalid POST result", expected, result.getBody()); + assertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType()); + assertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept")); + assertEquals("Invalid custom header", "MyValue", requestHeaders.getFirst("MyHeader")); + assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode()); + + verify(requestFactory, request, response, errorHandler, converter); + } + private void replayMocks() { replay(requestFactory, request, response, errorHandler, converter);
true
Other
spring-projects
spring-framework
2965df6bee12638e3e1a1208c382679fe3d46751.json
Update Javadoc of UriComponentsBuilder Issue: SPR-9474
spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java
@@ -143,7 +143,19 @@ public static UriComponentsBuilder fromUri(URI uri) { /** * Returns a builder that is initialized with the given URI string. * - * @param uri the URI string to initialize with + * <p><strong>Note:</strong> The presence of reserved characters can prevent + * correct parsing of the URI string. For example if a query parameter + * contains {@code '='} or {@code '&'} characters, the query string cannot + * be parsed unambiguously. Such values should be substituted for URI + * variables to enable correct parsing: + * + * <pre> + * String uriString = &quot;/hotels/42?filter={value}&quot;; + * UriComponentsBuilder.fromUriString(uriString).buildAndExpand(&quot;hot&amp;cold&quot;); + * </pre> + * + * @param uri + * the URI string to initialize with * @return the new {@code UriComponentsBuilder} */ public static UriComponentsBuilder fromUriString(String uri) { @@ -173,6 +185,17 @@ public static UriComponentsBuilder fromUriString(String uri) { /** * Creates a new {@code UriComponents} object from the string HTTP URL. * + * <p><strong>Note:</strong> The presence of reserved characters can prevent + * correct parsing of the URI string. For example if a query parameter + * contains {@code '='} or {@code '&'} characters, the query string cannot + * be parsed unambiguously. Such values should be substituted for URI + * variables to enable correct parsing: + * + * <pre> + * String uriString = &quot;/hotels/42?filter={value}&quot;; + * UriComponentsBuilder.fromUriString(uriString).buildAndExpand(&quot;hot&amp;cold&quot;); + * </pre> + * * @param httpUrl the source URI * @return the URI components of the URI */ @@ -213,9 +236,11 @@ public UriComponents build() { } /** - * Builds a {@code UriComponents} instance from the various components contained in this builder. + * Builds a {@code UriComponents} instance from the various components + * contained in this builder. * - * @param encoded whether all the components set in this builder are encoded ({@code true}) or not ({@code false}). + * @param encoded whether all the components set in this builder are + * encoded ({@code true}) or not ({@code false}). * @return the URI components */ public UriComponents build(boolean encoded) { @@ -283,10 +308,11 @@ public UriComponentsBuilder uri(URI uri) { } /** - * Sets the URI scheme. The given scheme may contain URI template variables, and may also be {@code null} to clear the - * scheme of this builder. + * Sets the URI scheme. The given scheme may contain URI template variables, + * and may also be {@code null} to clear the scheme of this builder. * - * @param scheme the URI scheme + * @param scheme + * the URI scheme * @return this UriComponentsBuilder */ public UriComponentsBuilder scheme(String scheme) { @@ -295,10 +321,12 @@ public UriComponentsBuilder scheme(String scheme) { } /** - * Sets the URI user info. The given user info may contain URI template variables, and may also be {@code null} to - * clear the user info of this builder. + * Sets the URI user info. The given user info may contain URI template + * variables, and may also be {@code null} to clear the user info of this + * builder. * - * @param userInfo the URI user info + * @param userInfo + * the URI user info * @return this UriComponentsBuilder */ public UriComponentsBuilder userInfo(String userInfo) { @@ -307,10 +335,11 @@ public UriComponentsBuilder userInfo(String userInfo) { } /** - * Sets the URI host. The given host may contain URI template variables, and may also be {@code null} to clear the host - * of this builder. + * Sets the URI host. The given host may contain URI template variables, and + * may also be {@code null} to clear the host of this builder. * - * @param host the URI host + * @param host + * the URI host * @return this UriComponentsBuilder */ public UriComponentsBuilder host(String host) { @@ -331,9 +360,11 @@ public UriComponentsBuilder port(int port) { } /** - * Appends the given path to the existing path of this builder. The given path may contain URI template variables. + * Appends the given path to the existing path of this builder. The given + * path may contain URI template variables. * - * @param path the URI path + * @param path + * the URI path * @return this UriComponentsBuilder */ public UriComponentsBuilder path(String path) { @@ -372,7 +403,19 @@ public UriComponentsBuilder pathSegment(String... pathSegments) throws IllegalAr } /** - * Appends the given query to the existing query of this builder. The given query may contain URI template variables. + * Appends the given query to the existing query of this builder. + * The given query may contain URI template variables. + * + * <p><strong>Note:</strong> The presence of reserved characters can prevent + * correct parsing of the URI string. For example if a query parameter + * contains {@code '='} or {@code '&'} characters, the query string cannot + * be parsed unambiguously. Such values should be substituted for URI + * variables to enable correct parsing: + * + * <pre> + * String uriString = &quot;/hotels/42?filter={value}&quot;; + * UriComponentsBuilder.fromUriString(uriString).buildAndExpand(&quot;hot&amp;cold&quot;); + * </pre> * * @param query the query string * @return this UriComponentsBuilder @@ -405,12 +448,15 @@ public UriComponentsBuilder replaceQuery(String query) { } /** - * Appends the given query parameter to the existing query parameters. The given name or any of the values may contain - * URI template variables. If no values are given, the resulting URI will contain the query parameter name only (i.e. - * {@code ?foo} instead of {@code ?foo=bar}. + * Appends the given query parameter to the existing query parameters. The + * given name or any of the values may contain URI template variables. If no + * values are given, the resulting URI will contain the query parameter name + * only (i.e. {@code ?foo} instead of {@code ?foo=bar}. * - * @param name the query parameter name - * @param values the query parameter values + * @param name + * the query parameter name + * @param values + * the query parameter values * @return this UriComponentsBuilder */ public UriComponentsBuilder queryParam(String name, Object... values) { @@ -428,11 +474,14 @@ public UriComponentsBuilder queryParam(String name, Object... values) { } /** - * Sets the query parameter values overriding all existing query values for the same parameter. - * If no values are given, the query parameter is removed. + * Sets the query parameter values overriding all existing query values for + * the same parameter. If no values are given, the query parameter is + * removed. * - * @param name the query parameter name - * @param values the query parameter values + * @param name + * the query parameter name + * @param values + * the query parameter values * @return this UriComponentsBuilder */ public UriComponentsBuilder replaceQueryParam(String name, Object... values) { @@ -445,10 +494,12 @@ public UriComponentsBuilder replaceQueryParam(String name, Object... values) { } /** - * Sets the URI fragment. The given fragment may contain URI template variables, and may also be {@code null} to clear - * the fragment of this builder. + * Sets the URI fragment. The given fragment may contain URI template + * variables, and may also be {@code null} to clear the fragment of this + * builder. * - * @param fragment the URI fragment + * @param fragment + * the URI fragment * @return this UriComponentsBuilder */ public UriComponentsBuilder fragment(String fragment) {
false
Other
spring-projects
spring-framework
b3f0b6e2d664bf232e3468acac2eba0e39dab4ab.json
Fix links in MVC chapter Issue: SPR-9344
src/reference/docbook/mvc.xml
@@ -868,9 +868,9 @@ public class ClinicController { <classname>RequestMappingHandlerAdapter</classname> respectively. They are recommended for use and even required to take advantage of new features in Spring MVC 3.1 and going forward. The new support - classes are enabled by default by the MVC namespace and MVC Java - config (<classname>@EnableWebMvc</classname>) but must be configured - explicitly if using neither. This section describes a few + classes are enabled by default by the MVC namespace and the MVC Java + config but must be configured explicitly if using neither. + This section describes a few important differences between the old and the new support classes. </para> @@ -1181,7 +1181,7 @@ public class RelativePathUriTemplateController { They are recommended for use and even required to take advantage of new features in Spring MVC 3.1 and going forward. The new support classes are enabled by default from the MVC namespace and - with use of the MVC Java config (<code>@EnableWebMvc</code>) but must be + with use of the MVC Java config but must be configured explicitly if using neither. </para></note> @@ -1550,16 +1550,20 @@ public void handle(@RequestBody String body, Writer writer) throws IOException { <para>For more information on these converters, see <link linkend="rest-message-conversion">Message Converters</link>. Also note - that if using the MVC namespace, a wider range of message converters - are registered by default. See <xref - linkend="mvc-annotation-driven" /> for more information.</para> + that if using the MVC namespace or the MVC Java config, a wider + range of message converters are registered by default. + See <link linkend="mvc-config-enable">Enabling the MVC Java Config or + the MVC XML Namespace</link> for more information.</para> <para>If you intend to read and write XML, you will need to configure the <classname>MarshallingHttpMessageConverter</classname> with a specific <interfacename>Marshaller</interfacename> and an <interfacename>Unmarshaller</interfacename> implementation from the - <classname>org.springframework.oxm</classname> package. For - example:</para> + <classname>org.springframework.oxm</classname> package. The example + below shows how to do that directly in your configuration but if + your application is configured through the MVC namespace or the + MVC Java config see <link linkend="mvc-config-enable">Enabling + the MVC Java Config or the MVC XML Namespace</link> instead.</para> <programlisting language="xml">&lt;bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"&gt; &lt;property name="messageConverters"&gt; @@ -1584,7 +1588,7 @@ public void handle(@RequestBody String body, Writer writer) throws IOException { <para>An <classname>@RequestBody</classname> method parameter can be annotated with <classname>@Valid</classname>, in which case it will be validated using the configured <classname>Validator</classname> - instance. When using the MVC namespace or Java config, a JSR-303 validator + instance. When using the MVC namespace or the MVC Java config, a JSR-303 validator is configured automatically assuming a JSR-303 implementation is available on the classpath.</para> <para>Just like with <classname>@ModelAttribute</classname> parameters, @@ -1596,9 +1600,10 @@ public void handle(@RequestBody String body, Writer writer) throws IOException { a <literal>400</literal> error back to the client.</para> <note> - <para>Also see <xref linkend="mvc-annotation-driven" /> for + <para>Also see <link linkend="mvc-config-enable">Enabling the MVC + Java Config or the MVC XML Namespace</link> for information on configuring message converters and a validator - through the MVC namespace.</para> + through the MVC namespace or the MVC Java config.</para> </note> </section> @@ -1951,8 +1956,7 @@ public class EditPetForm { <interfacename>RedirectAttributes</interfacename> or if it doesn't do so no attributes should be passed on to <classname>RedirectView</classname>. Both the MVC namespace and the - MVC Java config (via <interfacename>@EnableWebMvc</interfacename>) - keep this flag set to <literal>false</literal> in order to maintain + MVC Java config keep this flag set to <literal>false</literal> in order to maintain backwards compatibility. However, for new applications we recommend setting it to <literal>true</literal></para> @@ -2435,8 +2439,10 @@ public class TimeBasedAccessInterceptor extends HandlerInterceptorAdapter { <para>In the example above, the configured interceptor will apply to all requests handled with annotated controller methods. If you want to narrow down the URL paths to which an interceptor applies, you can use - the MVC namespace to do that. See <xref - linkend="mvc-annotation-driven" />.</para> + the MVC namespace or the MVC Java config, or declare bean instances + of type <classname>MappedInterceptor</classname> to do that. See <link + linkend="mvc-config-enable">Enabling the MVC Java Config or the MVC + XML Namespace</link>.</para> </tip> </section> </section> @@ -3684,8 +3690,8 @@ public String onSubmit(<emphasis role="bold">@RequestPart("meta-data") MetaData methods from any controller. The <interfacename>@ControllerAdvice</interfacename> annotation is a component annotation, which can be used with classpath scanning. It is - automatically enabled when using the MVC namespace and Java config, or - otherwise depending on whether the + automatically enabled when using the MVC namespace and the MVC Java config, + or otherwise depending on whether the <classname>ExceptionHandlerExceptionResolver</classname> is configured or not. Below is an example of a controller-local <interfacename>@ExceptionHandler</interfacename> method:</para> @@ -3742,7 +3748,7 @@ public class SimpleController { <para>The <classname>DefaultHandlerExceptionResolver</classname> translates Spring MVC exceptions to specific error status codes. It is registered - by default with the MVC namespace, the MVC Java config. and also by the + by default with the MVC namespace, the MVC Java config, and also by the the <classname>DispatcherServlet</classname> (i.e. when not using the MVC namespace or Java config). Listed below are some of the exceptions handled by this resolver and the corresponding status codes: @@ -4319,7 +4325,7 @@ public class ErrorController { </para> <section id="mvc-config-enable"> - <title>Enabling MVC Java Config or the MVC XML Namespace</title> + <title>Enabling the MVC Java Config or the MVC XML Namespace</title> <para>To enable MVC Java config add the annotation <interfacename>@EnableWebMvc</interfacename> to one of your
false
Other
spring-projects
spring-framework
888835445c4f0bfb49055167d19b2c6cb25d7b45.json
Update error message in DispatcherServlet Issue: SPR-8338
spring-webmvc/src/main/java/org/springframework/web/servlet/DispatcherServlet.java
@@ -1126,7 +1126,7 @@ protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletExcepti } } throw new ServletException("No adapter for handler [" + handler + - "]: Does your handler implement a supported interface like Controller?"); + "]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler"); } /**
false
Other
spring-projects
spring-framework
af1561634c0b039c7dd16d526e831e09b8b11045.json
Allow Errors after @RequestBody and @RequestPart An @RequestBody or an @RequestPart argument can now be followed by an Errors/BindingResult argument making it possible to handle validation errors (as a result of an @Valid annotation) locally within the @RequestMapping method. Issue: SPR-7114
spring-web/src/main/java/org/springframework/web/bind/annotation/RequestMapping.java
@@ -100,9 +100,8 @@ * converted to the declared method argument type using * {@linkplain org.springframework.http.converter.HttpMessageConverter message * converters}. Such parameters may optionally be annotated with {@code @Valid} - * but do not support access to validation results through a - * {@link org.springframework.validation.Errors} / - * {@link org.springframework.validation.BindingResult} argument. + * and also support access to validation results through an + * {@link org.springframework.validation.Errors} argument. * Instead a {@link org.springframework.web.servlet.mvc.method.annotation.MethodArgumentNotValidException} * exception is raised. * <li>{@link RequestPart @RequestPart} annotated parameters @@ -112,9 +111,8 @@ * converted to the declared method argument type using * {@linkplain org.springframework.http.converter.HttpMessageConverter message * converters}. Such parameters may optionally be annotated with {@code @Valid} - * but do not support access to validation results through a - * {@link org.springframework.validation.Errors} / - * {@link org.springframework.validation.BindingResult} argument. + * and support access to validation results through a + * {@link org.springframework.validation.Errors} argument. * Instead a {@link org.springframework.web.servlet.mvc.method.annotation.MethodArgumentNotValidException} * exception is raised. * <li>{@link org.springframework.http.HttpEntity HttpEntity&lt;?&gt;} parameters
true
Other
spring-projects
spring-framework
af1561634c0b039c7dd16d526e831e09b8b11045.json
Allow Errors after @RequestBody and @RequestPart An @RequestBody or an @RequestPart argument can now be followed by an Errors/BindingResult argument making it possible to handle validation errors (as a result of an @Valid annotation) locally within the @RequestMapping method. Issue: SPR-7114
spring-web/src/main/java/org/springframework/web/method/annotation/ErrorsMethodArgumentResolver.java
@@ -60,8 +60,8 @@ public Object resolveArgument( } throw new IllegalStateException( - "An Errors/BindingResult argument is expected to be immediately after the model attribute " + - "argument in the controller method signature: " + parameter.getMethod()); + "An Errors/BindingResult argument is expected to be declared immediately after the model attribute, " + + "the @RequestBody or the @RequestPart arguments to which they apply: " + parameter.getMethod()); } }
true
Other
spring-projects
spring-framework
af1561634c0b039c7dd16d526e831e09b8b11045.json
Allow Errors after @RequestBody and @RequestPart An @RequestBody or an @RequestPart argument can now be followed by an Errors/BindingResult argument making it possible to handle validation errors (as a result of an @Valid annotation) locally within the @RequestMapping method. Issue: SPR-7114
spring-web/src/main/java/org/springframework/web/method/annotation/ModelAttributeMethodProcessor.java
@@ -157,16 +157,16 @@ protected void validateIfApplicable(WebDataBinder binder, MethodParameter parame if (annot.annotationType().getSimpleName().startsWith("Valid")) { Object hints = AnnotationUtils.getValue(annot); binder.validate(hints instanceof Object[] ? (Object[]) hints : new Object[] {hints}); + break; } } } /** - * Whether to raise a {@link BindException} on bind or validation errors. - * The default implementation returns {@code true} if the next method - * argument is not of type {@link Errors}. + * Whether to raise a {@link BindException} on validation errors. * @param binder the data binder used to perform data binding * @param parameter the method argument + * @return {@code true} if the next method argument is not of type {@link Errors}. */ protected boolean isBindExceptionRequired(WebDataBinder binder, MethodParameter parameter) { int i = parameter.getParameterIndex();
true
Other
spring-projects
spring-framework
af1561634c0b039c7dd16d526e831e09b8b11045.json
Allow Errors after @RequestBody and @RequestPart An @RequestBody or an @RequestPart argument can now be followed by an Errors/BindingResult argument making it possible to handle validation errors (as a result of an @Valid annotation) locally within the @RequestMapping method. Issue: SPR-7114
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodArgumentResolver.java
@@ -38,8 +38,8 @@ import org.springframework.web.method.support.HandlerMethodArgumentResolver; /** - * A base class for resolving method argument values by reading from the body of a request - * with {@link HttpMessageConverter}s. + * A base class for resolving method argument values by reading from the body of + * a request with {@link HttpMessageConverter}s. * * @author Arjen Poutsma * @author Rossen Stoyanchev @@ -48,9 +48,9 @@ public abstract class AbstractMessageConverterMethodArgumentResolver implements HandlerMethodArgumentResolver { protected final Log logger = LogFactory.getLog(getClass()); - + protected final List<HttpMessageConverter<?>> messageConverters; - + protected final List<MediaType> allSupportedMediaTypes; public AbstractMessageConverterMethodArgumentResolver(List<HttpMessageConverter<?>> messageConverters) { @@ -60,8 +60,8 @@ public AbstractMessageConverterMethodArgumentResolver(List<HttpMessageConverter< } /** - * Returns the media types supported by all provided message converters preserving their ordering and - * further sorting by specificity via {@link MediaType#sortBySpecificity(List)}. + * Return the media types supported by all provided message converters sorted + * by specificity via {@link MediaType#sortBySpecificity(List)}. */ private static List<MediaType> getAllSupportedMediaTypes(List<HttpMessageConverter<?>> messageConverters) { Set<MediaType> allSupportedMediaTypes = new LinkedHashSet<MediaType>(); @@ -72,11 +72,12 @@ private static List<MediaType> getAllSupportedMediaTypes(List<HttpMessageConvert MediaType.sortBySpecificity(result); return Collections.unmodifiableList(result); } - + /** - * Creates the method argument value of the expected parameter type by reading from the given request. - * - * @param <T> the expected type of the argument value to be created + * Creates the method argument value of the expected parameter type by + * reading from the given request. + * + * @param <T> the expected type of the argument value to be created * @param webRequest the current request * @param methodParam the method argument * @param paramType the type of the argument value to be created @@ -86,15 +87,16 @@ private static List<MediaType> getAllSupportedMediaTypes(List<HttpMessageConvert */ protected <T> Object readWithMessageConverters(NativeWebRequest webRequest, MethodParameter methodParam, Class<T> paramType) throws IOException, HttpMediaTypeNotSupportedException { - - HttpInputMessage inputMessage = createInputMessage(webRequest); - return readWithMessageConverters(inputMessage, methodParam, paramType); - } + + HttpInputMessage inputMessage = createInputMessage(webRequest); + return readWithMessageConverters(inputMessage, methodParam, paramType); + } /** - * Creates the method argument value of the expected parameter type by reading from the given HttpInputMessage. - * - * @param <T> the expected type of the argument value to be created + * Creates the method argument value of the expected parameter type by reading + * from the given HttpInputMessage. + * + * @param <T> the expected type of the argument value to be created * @param inputMessage the HTTP input message representing the current request * @param methodParam the method argument * @param paramType the type of the argument value to be created @@ -103,14 +105,14 @@ protected <T> Object readWithMessageConverters(NativeWebRequest webRequest, Meth * @throws HttpMediaTypeNotSupportedException if no suitable message converter is found */ @SuppressWarnings("unchecked") - protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage, MethodParameter methodParam, Class<T> paramType) throws IOException, - HttpMediaTypeNotSupportedException { - + protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage, MethodParameter methodParam, + Class<T> paramType) throws IOException, HttpMediaTypeNotSupportedException { + MediaType contentType = inputMessage.getHeaders().getContentType(); if (contentType == null) { contentType = MediaType.APPLICATION_OCTET_STREAM; } - + for (HttpMessageConverter<?> messageConverter : this.messageConverters) { if (messageConverter.canRead(paramType, contentType)) { if (logger.isDebugEnabled()) { @@ -120,7 +122,7 @@ protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage, Me return ((HttpMessageConverter<T>) messageConverter).read(paramType, inputMessage); } } - + throw new HttpMediaTypeNotSupportedException(contentType, allSupportedMediaTypes); }
true
Other
spring-projects
spring-framework
af1561634c0b039c7dd16d526e831e09b8b11045.json
Allow Errors after @RequestBody and @RequestPart An @RequestBody or an @RequestPart argument can now be followed by an Errors/BindingResult argument making it possible to handle validation errors (as a result of an @Valid annotation) locally within the @RequestMapping method. Issue: SPR-7114
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartMethodArgumentResolver.java
@@ -28,6 +28,7 @@ import org.springframework.http.converter.HttpMessageConverter; import org.springframework.util.Assert; import org.springframework.validation.BindingResult; +import org.springframework.validation.Errors; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.RequestBody; @@ -49,26 +50,26 @@ * Resolves the following method arguments: * <ul> * <li>Annotated with {@code @RequestPart} - * <li>Of type {@link MultipartFile} in conjunction with Spring's + * <li>Of type {@link MultipartFile} in conjunction with Spring's * {@link MultipartResolver} abstraction - * <li>Of type {@code javax.servlet.http.Part} in conjunction with + * <li>Of type {@code javax.servlet.http.Part} in conjunction with * Servlet 3.0 multipart requests * </ul> - * - * <p>When a parameter is annotated with {@code @RequestPart} the content of the - * part is passed through an {@link HttpMessageConverter} to resolve the method - * argument with the 'Content-Type' of the request part in mind. This is + * + * <p>When a parameter is annotated with {@code @RequestPart} the content of the + * part is passed through an {@link HttpMessageConverter} to resolve the method + * argument with the 'Content-Type' of the request part in mind. This is * analogous to what @{@link RequestBody} does to resolve an argument based on * the content of a regular request. - * - * <p>When a parameter is not annotated or the name of the part is not specified, + * + * <p>When a parameter is not annotated or the name of the part is not specified, * it is derived from the name of the method argument. - * - * <p>Automatic validation may be applied if the argument is annotated with - * {@code @javax.validation.Valid}. In case of validation failure, a + * + * <p>Automatic validation may be applied if the argument is annotated with + * {@code @javax.validation.Valid}. In case of validation failure, a * {@link MethodArgumentNotValidException} is raised and a 400 response status * code returned if {@link DefaultHandlerExceptionResolver} is configured. - * + * * @author Rossen Stoyanchev * @since 3.1 */ @@ -111,8 +112,8 @@ public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer m HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class); assertIsMultipartRequest(servletRequest); - - MultipartHttpServletRequest multipartRequest = + + MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(servletRequest, MultipartHttpServletRequest.class); String partName = getPartName(parameter); @@ -133,20 +134,11 @@ else if ("javax.servlet.http.Part".equals(parameter.getParameterType().getName() try { HttpInputMessage inputMessage = new RequestPartServletServerHttpRequest(servletRequest, partName); arg = readWithMessageConverters(inputMessage, parameter, parameter.getParameterType()); + WebDataBinder binder = binderFactory.createBinder(request, arg, partName); if (arg != null) { - Annotation[] annotations = parameter.getParameterAnnotations(); - for (Annotation annot : annotations) { - if (annot.annotationType().getSimpleName().startsWith("Valid")) { - WebDataBinder binder = binderFactory.createBinder(request, arg, partName); - Object hints = AnnotationUtils.getValue(annot); - binder.validate(hints instanceof Object[] ? (Object[]) hints : new Object[] {hints}); - BindingResult bindingResult = binder.getBindingResult(); - if (bindingResult.hasErrors()) { - throw new MethodArgumentNotValidException(parameter, bindingResult); - } - } - } + validate(binder, parameter); } + mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + partName, binder.getBindingResult()); } catch (MissingServletRequestPartException ex) { // handled below @@ -160,7 +152,7 @@ else if ("javax.servlet.http.Part".equals(parameter.getParameterType().getName() if (arg == null && isRequired) { throw new MissingServletRequestPartException(partName); } - + return arg; } @@ -170,7 +162,7 @@ private static void assertIsMultipartRequest(HttpServletRequest request) { throw new MultipartException("The current request is not a multipart request"); } } - + private String getPartName(MethodParameter parameter) { RequestPart annot = parameter.getParameterAnnotation(RequestPart.class); String partName = (annot != null) ? annot.value() : ""; @@ -181,7 +173,7 @@ private String getPartName(MethodParameter parameter) { } return partName; } - + private boolean isMultipartFileCollection(MethodParameter parameter) { Class<?> paramType = parameter.getParameterType(); if (Collection.class.equals(paramType) || List.class.isAssignableFrom(paramType)){ @@ -193,4 +185,35 @@ private boolean isMultipartFileCollection(MethodParameter parameter) { return false; } + private void validate(WebDataBinder binder, MethodParameter parameter) throws MethodArgumentNotValidException { + + Annotation[] annotations = parameter.getParameterAnnotations(); + for (Annotation annot : annotations) { + if (annot.annotationType().getSimpleName().startsWith("Valid")) { + Object hints = AnnotationUtils.getValue(annot); + binder.validate(hints instanceof Object[] ? (Object[]) hints : new Object[] {hints}); + BindingResult bindingResult = binder.getBindingResult(); + if (bindingResult.hasErrors()) { + if (isBindExceptionRequired(binder, parameter)) { + throw new MethodArgumentNotValidException(parameter, bindingResult); + } + } + } + } + } + + /** + * Whether to raise a {@link MethodArgumentNotValidException} on validation errors. + * @param binder the data binder used to perform data binding + * @param parameter the method argument + * @return {@code true} if the next method argument is not of type {@link Errors}. + */ + private boolean isBindExceptionRequired(WebDataBinder binder, MethodParameter parameter) { + int i = parameter.getParameterIndex(); + Class<?>[] paramTypes = parameter.getMethod().getParameterTypes(); + boolean hasBindingResult = (paramTypes.length > (i + 1) && Errors.class.isAssignableFrom(paramTypes[i + 1])); + + return !hasBindingResult; + } + }
true
Other
spring-projects
spring-framework
af1561634c0b039c7dd16d526e831e09b8b11045.json
Allow Errors after @RequestBody and @RequestPart An @RequestBody or an @RequestPart argument can now be followed by an Errors/BindingResult argument making it possible to handle validation errors (as a result of an @Valid annotation) locally within the @RequestMapping method. Issue: SPR-7114
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessor.java
@@ -27,6 +27,7 @@ import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.validation.BindingResult; +import org.springframework.validation.Errors; import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.HttpMediaTypeNotSupportedException; import org.springframework.web.accept.ContentNegotiationManager; @@ -85,33 +86,52 @@ public boolean supportsReturnType(MethodParameter returnType) { public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { - Object arg = readWithMessageConverters(webRequest, parameter, parameter.getParameterType()); - validate(parameter, webRequest, binderFactory, arg); - return arg; - } + Object argument = readWithMessageConverters(webRequest, parameter, parameter.getParameterType()); - private void validate(MethodParameter parameter, NativeWebRequest webRequest, - WebDataBinderFactory binderFactory, Object arg) throws Exception, MethodArgumentNotValidException { + String name = Conventions.getVariableNameForParameter(parameter); + WebDataBinder binder = binderFactory.createBinder(webRequest, argument, name); - if (arg == null) { - return; + if (argument != null) { + validate(binder, parameter); } + + mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult()); + + return argument; + } + + private void validate(WebDataBinder binder, MethodParameter parameter) throws Exception, MethodArgumentNotValidException { + Annotation[] annotations = parameter.getParameterAnnotations(); for (Annotation annot : annotations) { - if (!annot.annotationType().getSimpleName().startsWith("Valid")) { - continue; - } - String name = Conventions.getVariableNameForParameter(parameter); - WebDataBinder binder = binderFactory.createBinder(webRequest, arg, name); - Object hints = AnnotationUtils.getValue(annot); - binder.validate(hints instanceof Object[] ? (Object[]) hints : new Object[] {hints}); - BindingResult bindingResult = binder.getBindingResult(); - if (bindingResult.hasErrors()) { - throw new MethodArgumentNotValidException(parameter, bindingResult); + if (annot.annotationType().getSimpleName().startsWith("Valid")) { + Object hints = AnnotationUtils.getValue(annot); + binder.validate(hints instanceof Object[] ? (Object[]) hints : new Object[] {hints}); + BindingResult bindingResult = binder.getBindingResult(); + if (bindingResult.hasErrors()) { + if (isBindExceptionRequired(binder, parameter)) { + throw new MethodArgumentNotValidException(parameter, bindingResult); + } + } + break; } } } + /** + * Whether to raise a {@link MethodArgumentNotValidException} on validation errors. + * @param binder the data binder used to perform data binding + * @param parameter the method argument + * @return {@code true} if the next method argument is not of type {@link Errors}. + */ + private boolean isBindExceptionRequired(WebDataBinder binder, MethodParameter parameter) { + int i = parameter.getParameterIndex(); + Class<?>[] paramTypes = parameter.getMethod().getParameterTypes(); + boolean hasBindingResult = (paramTypes.length > (i + 1) && Errors.class.isAssignableFrom(paramTypes[i + 1])); + + return !hasBindingResult; + } + @Override protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage, MethodParameter methodParam, Class<T> paramType) throws IOException, HttpMediaTypeNotSupportedException {
true
Other
spring-projects
spring-framework
af1561634c0b039c7dd16d526e831e09b8b11045.json
Allow Errors after @RequestBody and @RequestPart An @RequestBody or an @RequestPart argument can now be followed by an Errors/BindingResult argument making it possible to handle validation errors (as a result of an @Valid annotation) locally within the @RequestMapping method. Issue: SPR-7114
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapterIntegrationTests.java
@@ -89,29 +89,29 @@ /** * A test fixture with a controller with all supported method signature styles - * and arguments. A convenient place to test or confirm a problem with a - * specific argument or return value type. + * and arguments. A convenient place to test or confirm a problem with a + * specific argument or return value type. * * @author Rossen Stoyanchev - * + * * @see HandlerMethodAnnotationDetectionTests * @see ServletAnnotationControllerHandlerMethodTests */ public class RequestMappingHandlerAdapterIntegrationTests { private final Object handler = new Handler(); - + private RequestMappingHandlerAdapter handlerAdapter; - + private MockHttpServletRequest request; - + private MockHttpServletResponse response; @Before public void setup() throws Exception { ConfigurableWebBindingInitializer bindingInitializer = new ConfigurableWebBindingInitializer(); bindingInitializer.setValidator(new StubValidator()); - + List<HandlerMethodArgumentResolver> customResolvers = new ArrayList<HandlerMethodArgumentResolver>(); customResolvers.add(new ServletWebArgumentResolverAdapter(new ColorArgumentResolver())); @@ -127,19 +127,19 @@ public void setup() throws Exception { request = new MockHttpServletRequest(); response = new MockHttpServletResponse(); - + // Expose request to the current thread (for SpEL expressions) RequestContextHolder.setRequestAttributes(new ServletWebRequest(request)); } - + @After public void teardown() { RequestContextHolder.resetRequestAttributes(); } @Test public void handle() throws Exception { - + Class<?>[] parameterTypes = new Class<?>[] { int.class, String.class, String.class, String.class, Map.class, Date.class, Map.class, String.class, String.class, TestBean.class, Errors.class, TestBean.class, Color.class, HttpServletRequest.class, HttpServletResponse.class, User.class, OtherUser.class, @@ -186,7 +186,7 @@ public void handle() throws Exception { assertEquals("paramByConventionValue", map.get("paramByConvention")); assertEquals("/contextPath", model.get("value")); - + TestBean modelAttr = (TestBean) model.get("modelAttr"); assertEquals(25, modelAttr.getAge()); assertEquals("Set by model method [modelAttr]", modelAttr.getName()); @@ -208,13 +208,13 @@ public void handle() throws Exception { assertTrue(model.get("customArg") instanceof Color); assertEquals(User.class, model.get("user").getClass()); assertEquals(OtherUser.class, model.get("otherUser").getClass()); - + assertEquals(new URI("http://localhost/contextPath/main/path"), model.get("url")); } - + @Test public void handleRequestBody() throws Exception { - + Class<?>[] parameterTypes = new Class<?>[] { byte[].class }; request.addHeader("Content-Type", "text/plain; charset=utf-8"); @@ -229,6 +229,23 @@ public void handleRequestBody() throws Exception { assertEquals(HttpStatus.ACCEPTED.value(), response.getStatus()); } + @Test + public void handleAndValidateRequestBody() throws Exception { + + Class<?>[] parameterTypes = new Class<?>[] { TestBean.class, Errors.class }; + + request.addHeader("Content-Type", "text/plain; charset=utf-8"); + request.setContent("Hello Server".getBytes("UTF-8")); + + HandlerMethod handlerMethod = handlerMethod("handleAndValidateRequestBody", parameterTypes); + + ModelAndView mav = handlerAdapter.handle(request, response, handlerMethod); + + assertNull(mav); + assertEquals("Error count [1]", new String(response.getContentAsByteArray(), "UTF-8")); + assertEquals(HttpStatus.ACCEPTED.value(), response.getStatus()); + } + @Test public void handleHttpEntity() throws Exception { @@ -254,19 +271,31 @@ public void handleRequestPart() throws Exception { HandlerMethod handlerMethod = handlerMethod("handleRequestPart", String.class, Model.class); ModelAndView mav = handlerAdapter.handle(multipartRequest, response, handlerMethod); - + assertNotNull(mav); assertEquals("content", mav.getModelMap().get("requestPart")); } - + + @Test + public void handleAndValidateRequestPart() throws Exception { + MockMultipartHttpServletRequest multipartRequest = new MockMultipartHttpServletRequest(); + multipartRequest.addFile(new MockMultipartFile("requestPart", "", "text/plain", "content".getBytes("UTF-8"))); + + HandlerMethod handlerMethod = handlerMethod("handleAndValidateRequestPart", String.class, Errors.class, Model.class); + ModelAndView mav = handlerAdapter.handle(multipartRequest, response, handlerMethod); + + assertNotNull(mav); + assertEquals(1, mav.getModelMap().get("error count")); + } + @Test public void handleAndCompleteSession() throws Exception { HandlerMethod handlerMethod = handlerMethod("handleAndCompleteSession", SessionStatus.class); handlerAdapter.handle(request, response, handlerMethod); assertFalse(request.getSession().getAttributeNames().hasMoreElements()); } - + private HandlerMethod handlerMethod(String methodName, Class<?>... paramTypes) throws Exception { Method method = handler.getClass().getDeclaredMethod(methodName, paramTypes); return new InvocableHandlerMethod(handler, method); @@ -277,7 +306,7 @@ private HandlerMethod handlerMethod(String methodName, Class<?>... paramTypes) t private static class Handler { @InitBinder("dateParam") - public void initBinder(WebDataBinder dataBinder, @RequestParam("datePattern") String datePattern) { + public void initBinder(WebDataBinder dataBinder, @RequestParam("datePattern") String datePattern) { SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern); dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); } @@ -291,7 +320,7 @@ public void model(Model model) { modelAttr = new TestBean(); modelAttr.setName("Set by model method [modelAttrByConvention]"); model.addAttribute(modelAttr); - + model.addAttribute(new OtherUser()); } @@ -322,31 +351,43 @@ public String handle( .addAttribute("paramByConvention", paramByConvention).addAttribute("value", value) .addAttribute("customArg", customArg).addAttribute(user) .addAttribute("url", builder.path("/path").build().toUri()); - + assertNotNull(request); assertNotNull(response); return "viewName"; } - + @ResponseStatus(value=HttpStatus.ACCEPTED) @ResponseBody public String handleRequestBody(@RequestBody byte[] bytes) throws Exception { String requestBody = new String(bytes, "UTF-8"); return "Handled requestBody=[" + requestBody + "]"; } + @ResponseStatus(value=HttpStatus.ACCEPTED) + @ResponseBody + public String handleAndValidateRequestBody(@Valid TestBean modelAttr, Errors errors) throws Exception { + return "Error count [" + errors.getErrorCount() + "]"; + } + public ResponseEntity<String> handleHttpEntity(HttpEntity<byte[]> httpEntity) throws Exception { HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set("header", "headerValue"); String responseBody = "Handled requestBody=[" + new String(httpEntity.getBody(), "UTF-8") + "]"; return new ResponseEntity<String>(responseBody, responseHeaders, HttpStatus.ACCEPTED); } - + public void handleRequestPart(@RequestPart String requestPart, Model model) { model.addAttribute("requestPart", requestPart); } - + + public void handleAndValidateRequestPart(@RequestPart @Valid String requestPart, + Errors errors, Model model) throws Exception { + + model.addAttribute("error count", errors.getErrorCount()); + } + public void handleAndCompleteSession(SessionStatus sessionStatus) { sessionStatus.setComplete(); } @@ -367,7 +408,7 @@ public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest return new Color(0); } } - + private static class User implements Principal { public String getName() { return "user";
true
Other
spring-projects
spring-framework
af1561634c0b039c7dd16d526e831e09b8b11045.json
Allow Errors after @RequestBody and @RequestPart An @RequestBody or an @RequestPart argument can now be followed by an Errors/BindingResult argument making it possible to handle validation errors (as a result of an @Valid annotation) locally within the @RequestMapping method. Issue: SPR-7114
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorTests.java
@@ -144,7 +144,7 @@ public void resolveArgument() throws Exception { expect(messageConverter.read(eq(String.class), isA(HttpInputMessage.class))).andReturn(body); replay(messageConverter); - Object result = processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null); + Object result = processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, new ValidatingBinderFactory()); assertEquals("Invalid argument", body, result); assertFalse("The requestHandled flag shouldn't change", mavContainer.isRequestHandled()); @@ -211,7 +211,7 @@ public void resolveArgumentRequiredNoContent() throws Exception { @Test public void resolveArgumentNotRequiredNoContent() throws Exception { - assertNull(processor.resolveArgument(paramStringNotRequired, mavContainer, webRequest, null)); + assertNull(processor.resolveArgument(paramStringNotRequired, mavContainer, webRequest, new ValidatingBinderFactory())); } @Test
true
Other
spring-projects
spring-framework
af1561634c0b039c7dd16d526e831e09b8b11045.json
Allow Errors after @RequestBody and @RequestPart An @RequestBody or an @RequestPart argument can now be followed by an Errors/BindingResult argument making it possible to handle validation errors (as a result of an @Valid annotation) locally within the @RequestMapping method. Issue: SPR-7114
src/reference/docbook/mvc.xml
@@ -1584,13 +1584,13 @@ public void handle(@RequestBody String body, Writer writer) throws IOException { <para>An <classname>@RequestBody</classname> method parameter can be annotated with <classname>@Valid</classname>, in which case it will be validated using the configured <classname>Validator</classname> - instance. When using the MVC namespace a JSR-303 validator is - configured automatically assuming a JSR-303 implementation is + instance. When using the MVC namespace or Java config, a JSR-303 validator + is configured automatically assuming a JSR-303 implementation is available on the classpath.</para> - <para>Unlike <classname>@ModelAttribute</classname> parameters, for which - a <classname>BindingResult</classname> can be used to examine the errors, - <classname>@RequestBody</classname> validation errors always result in a - <classname>MethodArgumentNotValidException</classname> being raised. + <para>Just like with <classname>@ModelAttribute</classname> parameters, + an <classname>Errors</classname> argument can be used to examine the errors. + If such an argument is not declared, a + <classname>MethodArgumentNotValidException</classname> will be raised. The exception is handled in the <classname>DefaultHandlerExceptionResolver</classname>, which sends a <literal>400</literal> error back to the client.</para>
true
Other
spring-projects
spring-framework
1cf4a2facd4fa0784fd10a767114011a79164abd.json
Add ExceptionHandlerSupport class The new class is functionally equivalent to the DefaultHandlerExceptionResolver (i.e. it translates Spring MVC exceptions to various status codes) but uses an @ExceptionHandler returning a ResponseEntity<Object>, which means it can be customized to write error content to the body of the response. Issue: SPR-9290
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerSupport.java
@@ -0,0 +1,397 @@ +/* + * Copyright 2002-2012 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.web.servlet.mvc.method.annotation; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.beans.ConversionNotSupportedException; +import org.springframework.beans.TypeMismatchException; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.http.converter.HttpMessageNotWritableException; +import org.springframework.util.CollectionUtils; +import org.springframework.validation.BindException; +import org.springframework.web.HttpMediaTypeNotAcceptableException; +import org.springframework.web.HttpMediaTypeNotSupportedException; +import org.springframework.web.HttpRequestMethodNotSupportedException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.MissingServletRequestParameterException; +import org.springframework.web.bind.ServletRequestBindingException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.multipart.support.MissingServletRequestPartException; +import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException; + +/** + * A convenient base for classes with {@link ExceptionHandler} methods providing + * infrastructure to handle standard Spring MVC exceptions. The functionality is + * equivalent to that of the {@link DefaultHandlerExceptionResolver} except it + * can be customized to write error content to the body of the response. If there + * is no need to write error content, use {@code DefaultHandlerExceptionResolver} + * instead. + * + * <p>It is expected the sub-classes will be annotated with + * {@link ControllerAdvice @ControllerAdvice} and that + * {@link ExceptionHandlerExceptionResolver} is configured to ensure this class + * applies to exceptions from any {@link RequestMapping @RequestMapping} method. + * + * @author Rossen Stoyanchev + * @since 3.2 + * + * @see org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver + */ +public abstract class ExceptionHandlerSupport { + + protected final Log logger = LogFactory.getLog(getClass()); + + /** + * Log category to use when no mapped handler is found for a request. + * @see #pageNotFoundLogger + */ + public static final String PAGE_NOT_FOUND_LOG_CATEGORY = "org.springframework.web.servlet.PageNotFound"; + + /** + * Additional logger to use when no mapped handler is found for a request. + * @see #PAGE_NOT_FOUND_LOG_CATEGORY + */ + protected static final Log pageNotFoundLogger = LogFactory.getLog(PAGE_NOT_FOUND_LOG_CATEGORY); + + + /** + * Provides handling for standard Spring MVC exceptions. + * @param ex the target exception + * @param request the current request + */ + @ExceptionHandler(value={ + NoSuchRequestHandlingMethodException.class, + HttpRequestMethodNotSupportedException.class, + HttpMediaTypeNotSupportedException.class, + HttpMediaTypeNotAcceptableException.class, + MissingServletRequestParameterException.class, + ServletRequestBindingException.class, + ConversionNotSupportedException.class, + TypeMismatchException.class, + HttpMessageNotReadableException.class, + HttpMessageNotWritableException.class, + MethodArgumentNotValidException.class, + MissingServletRequestPartException.class, + BindException.class + }) + public final ResponseEntity<Object> handleException(Exception ex, WebRequest request) { + + HttpHeaders headers = new HttpHeaders(); + + HttpStatus status; + Object body; + + if (ex instanceof NoSuchRequestHandlingMethodException) { + status = HttpStatus.NOT_FOUND; + body = handleNoSuchRequestHandlingMethod((NoSuchRequestHandlingMethodException) ex, headers, status, request); + } + else if (ex instanceof HttpRequestMethodNotSupportedException) { + status = HttpStatus.METHOD_NOT_ALLOWED; + body = handleHttpRequestMethodNotSupported((HttpRequestMethodNotSupportedException) ex, headers, status, request); + } + else if (ex instanceof HttpMediaTypeNotSupportedException) { + status = HttpStatus.UNSUPPORTED_MEDIA_TYPE; + body = handleHttpMediaTypeNotSupported((HttpMediaTypeNotSupportedException) ex, headers, status, request); + } + else if (ex instanceof HttpMediaTypeNotAcceptableException) { + status = HttpStatus.NOT_ACCEPTABLE; + body = handleHttpMediaTypeNotAcceptable((HttpMediaTypeNotAcceptableException) ex, headers, status, request); + } + else if (ex instanceof MissingServletRequestParameterException) { + status = HttpStatus.BAD_REQUEST; + body = handleMissingServletRequestParameter((MissingServletRequestParameterException) ex, headers, status, request); + } + else if (ex instanceof ServletRequestBindingException) { + status = HttpStatus.BAD_REQUEST; + body = handleServletRequestBindingException((ServletRequestBindingException) ex, headers, status, request); + } + else if (ex instanceof ConversionNotSupportedException) { + status = HttpStatus.INTERNAL_SERVER_ERROR; + body = handleConversionNotSupported((ConversionNotSupportedException) ex, headers, status, request); + } + else if (ex instanceof TypeMismatchException) { + status = HttpStatus.BAD_REQUEST; + body = handleTypeMismatch((TypeMismatchException) ex, headers, status, request); + } + else if (ex instanceof HttpMessageNotReadableException) { + status = HttpStatus.BAD_REQUEST; + body = handleHttpMessageNotReadable((HttpMessageNotReadableException) ex, headers, status, request); + } + else if (ex instanceof HttpMessageNotWritableException) { + status = HttpStatus.INTERNAL_SERVER_ERROR; + body = handleHttpMessageNotWritable((HttpMessageNotWritableException) ex, headers, status, request); + } + else if (ex instanceof MethodArgumentNotValidException) { + status = HttpStatus.BAD_REQUEST; + body = handleMethodArgumentNotValid((MethodArgumentNotValidException) ex, headers, status, request); + } + else if (ex instanceof MissingServletRequestPartException) { + status = HttpStatus.BAD_REQUEST; + body = handleMissingServletRequestPart((MissingServletRequestPartException) ex, headers, status, request); + } + else if (ex instanceof BindException) { + status = HttpStatus.BAD_REQUEST; + body = handleBindException((BindException) ex, headers, status, request); + } + else { + logger.warn("Unknown exception type: " + ex.getClass().getName()); + status = HttpStatus.INTERNAL_SERVER_ERROR; + body = handleExceptionInternal(ex, headers, status, request); + } + + return new ResponseEntity<Object>(body, headers, status); + } + + /** + * A single place to customize the response body of all Exception types. + * This method returns {@code null} by default. + * @param ex the exception + * @param headers the headers to be written to the response + * @param status the selected response status + * @param request the current request + */ + protected Object handleExceptionInternal(Exception ex, HttpHeaders headers, HttpStatus status, WebRequest request) { + return null; + } + + /** + * Customize the response for NoSuchRequestHandlingMethodException. + * This method logs a warning and delegates to + * {@link #handleExceptionInternal(Exception, HttpHeaders, HttpStatus, WebRequest)}. + * @param ex the exception + * @param headers the headers to be written to the response + * @param status the selected response status + * @param request the current request + * @return an Object or {@code null} + */ + protected Object handleNoSuchRequestHandlingMethod(NoSuchRequestHandlingMethodException ex, + HttpHeaders headers, HttpStatus status, WebRequest request) { + + pageNotFoundLogger.warn(ex.getMessage()); + + return handleExceptionInternal(ex, headers, status, request); + } + + /** + * Customize the response for HttpRequestMethodNotSupportedException. + * This method logs a warning, sets the "Allow" header, and delegates to + * {@link #handleExceptionInternal(Exception, HttpHeaders, HttpStatus, WebRequest)}. + * @param ex the exception + * @param headers the headers to be written to the response + * @param status the selected response status + * @param request the current request + * @return an Object or {@code null} + */ + protected Object handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex, + HttpHeaders headers, HttpStatus status, WebRequest request) { + + pageNotFoundLogger.warn(ex.getMessage()); + + Set<HttpMethod> mediaTypes = new HashSet<HttpMethod>(); + for (String value : ex.getSupportedMethods()) { + mediaTypes.add(HttpMethod.valueOf(value)); + } + if (!mediaTypes.isEmpty()) { + headers.setAllow(mediaTypes); + } + + return handleExceptionInternal(ex, headers, status, request); + } + + /** + * Customize the response for HttpMediaTypeNotSupportedException. + * This method sets the "Accept" header and delegates to + * {@link #handleExceptionInternal(Exception, HttpHeaders, HttpStatus, WebRequest)}. + * @param ex the exception + * @param headers the headers to be written to the response + * @param status the selected response status + * @param request the current request + * @return an Object or {@code null} + */ + protected Object handleHttpMediaTypeNotSupported(HttpMediaTypeNotSupportedException ex, + HttpHeaders headers, HttpStatus status, WebRequest request) { + + List<MediaType> mediaTypes = ex.getSupportedMediaTypes(); + if (!CollectionUtils.isEmpty(mediaTypes)) { + headers.setAccept(mediaTypes); + } + return handleExceptionInternal(ex, headers, status, request); + } + + /** + * Customize the response for HttpMediaTypeNotAcceptableException. + * This method delegates to {@link #handleExceptionInternal(Exception, HttpHeaders, HttpStatus, WebRequest)}. + * @param ex the exception + * @param headers the headers to be written to the response + * @param status the selected response status + * @param request the current request + * @return an Object or {@code null} + */ + protected Object handleHttpMediaTypeNotAcceptable(HttpMediaTypeNotAcceptableException ex, + HttpHeaders headers, HttpStatus status, WebRequest request) { + + return handleExceptionInternal(ex, headers, status, request); + } + + /** + * Customize the response for MissingServletRequestParameterException. + * This method delegates to {@link #handleExceptionInternal(Exception, HttpHeaders, HttpStatus, WebRequest)}. + * @param ex the exception + * @param headers the headers to be written to the response + * @param status the selected response status + * @param request the current request + * @return an Object or {@code null} + */ + protected Object handleMissingServletRequestParameter(MissingServletRequestParameterException ex, + HttpHeaders headers, HttpStatus status, WebRequest request) { + + return handleExceptionInternal(ex, headers, status, request); + } + + /** + * Customize the response for ServletRequestBindingException. + * This method delegates to {@link #handleExceptionInternal(Exception, HttpHeaders, HttpStatus, WebRequest)}. + * @param ex the exception + * @param headers the headers to be written to the response + * @param status the selected response status + * @param request the current request + * @return an Object or {@code null} + */ + protected Object handleServletRequestBindingException(ServletRequestBindingException ex, + HttpHeaders headers, HttpStatus status, WebRequest request) { + + return handleExceptionInternal(ex, headers, status, request); + } + + /** + * Customize the response for ConversionNotSupportedException. + * This method delegates to {@link #handleExceptionInternal(Exception, HttpHeaders, HttpStatus, WebRequest)}. + * @param ex the exception + * @param headers the headers to be written to the response + * @param status the selected response status + * @param request the current request + * @return an Object or {@code null} + */ + protected Object handleConversionNotSupported(ConversionNotSupportedException ex, + HttpHeaders headers, HttpStatus status, WebRequest request) { + + return handleExceptionInternal(ex, headers, status, request); + } + + /** + * Customize the response for TypeMismatchException. + * This method delegates to {@link #handleExceptionInternal(Exception, HttpHeaders, HttpStatus, WebRequest)}. + * @param ex the exception + * @param headers the headers to be written to the response + * @param status the selected response status + * @param request the current request + * @return an Object or {@code null} + */ + protected Object handleTypeMismatch(TypeMismatchException ex, HttpHeaders headers, + HttpStatus status, WebRequest request) { + + return handleExceptionInternal(ex, headers, status, request); + } + + /** + * Customize the response for HttpMessageNotReadableException. + * This method delegates to {@link #handleExceptionInternal(Exception, HttpHeaders, HttpStatus, WebRequest)}. + * @param ex the exception + * @param headers the headers to be written to the response + * @param status the selected response status + * @param request the current request + * @return an Object or {@code null} + */ + protected Object handleHttpMessageNotReadable(HttpMessageNotReadableException ex, + HttpHeaders headers, HttpStatus status, WebRequest request) { + + return handleExceptionInternal(ex, headers, status, request); + } + + /** + * Customize the response for HttpMessageNotWritableException. + * This method delegates to {@link #handleExceptionInternal(Exception, HttpHeaders, HttpStatus, WebRequest)}. + * @param ex the exception + * @param headers the headers to be written to the response + * @param status the selected response status + * @param request the current request + * @return an Object or {@code null} + */ + protected Object handleHttpMessageNotWritable(HttpMessageNotWritableException ex, + HttpHeaders headers, HttpStatus status, WebRequest request) { + + return handleExceptionInternal(ex, headers, status, request); + } + + /** + * Customize the response for MethodArgumentNotValidException. + * This method delegates to {@link #handleExceptionInternal(Exception, HttpHeaders, HttpStatus, WebRequest)}. + * @param ex the exception + * @param headers the headers to be written to the response + * @param status the selected response status + * @param request the current request + * @return an Object or {@code null} + */ + protected Object handleMethodArgumentNotValid(MethodArgumentNotValidException ex, + HttpHeaders headers, HttpStatus status, WebRequest request) { + + return handleExceptionInternal(ex, headers, status, request); + } + + /** + * Customize the response for MissingServletRequestPartException. + * This method delegates to {@link #handleExceptionInternal(Exception, HttpHeaders, HttpStatus, WebRequest)}. + * @param ex the exception + * @param headers the headers to be written to the response + * @param status the selected response status + * @param request the current request + * @return an Object or {@code null} + */ + protected Object handleMissingServletRequestPart(MissingServletRequestPartException ex, + HttpHeaders headers, HttpStatus status, WebRequest request) { + + return handleExceptionInternal(ex, headers, status, request); + } + + /** + * Customize the response for BindException. + * This method delegates to {@link #handleExceptionInternal(Exception, HttpHeaders, HttpStatus, WebRequest)}. + * @param ex the exception + * @param headers the headers to be written to the response + * @param status the selected response status + * @param request the current request + * @return an Object or {@code null} + */ + protected Object handleBindException(BindException ex, HttpHeaders headers, + HttpStatus status, WebRequest request) { + + return handleExceptionInternal(ex, headers, status, request); + } + +}
true
Other
spring-projects
spring-framework
1cf4a2facd4fa0784fd10a767114011a79164abd.json
Add ExceptionHandlerSupport class The new class is functionally equivalent to the DefaultHandlerExceptionResolver (i.e. it translates Spring MVC exceptions to various status codes) but uses an @ExceptionHandler returning a ResponseEntity<Object>, which means it can be customized to write error content to the body of the response. Issue: SPR-9290
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/support/DefaultHandlerExceptionResolver.java
@@ -59,6 +59,8 @@ * @author Arjen Poutsma * @author Rossen Stoyanchev * @since 3.0 + * + * @see org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerSupport * @see #handleNoSuchRequestHandlingMethod * @see #handleHttpRequestMethodNotSupported * @see #handleHttpMediaTypeNotSupported
true
Other
spring-projects
spring-framework
1cf4a2facd4fa0784fd10a767114011a79164abd.json
Add ExceptionHandlerSupport class The new class is functionally equivalent to the DefaultHandlerExceptionResolver (i.e. it translates Spring MVC exceptions to various status codes) but uses an @ExceptionHandler returning a ResponseEntity<Object>, which means it can be customized to write error content to the body of the response. Issue: SPR-9290
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerSupportTests.java
@@ -0,0 +1,233 @@ +/* + * Copyright 2002-2012 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.web.servlet.mvc.method.annotation; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.UnsupportedEncodingException; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.EnumSet; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.beans.ConversionNotSupportedException; +import org.springframework.beans.TypeMismatchException; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.http.converter.HttpMessageNotWritableException; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.validation.BindException; +import org.springframework.web.HttpMediaTypeNotAcceptableException; +import org.springframework.web.HttpMediaTypeNotSupportedException; +import org.springframework.web.HttpRequestMethodNotSupportedException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.MissingServletRequestParameterException; +import org.springframework.web.bind.ServletRequestBindingException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.context.request.ServletWebRequest; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.context.support.StaticWebApplicationContext; +import org.springframework.web.multipart.support.MissingServletRequestPartException; +import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException; +import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver; + +/** + * Test fixture for {@link ExceptionHandlerSupport}. + * + * @author Rossen Stoyanchev + */ +public class ExceptionHandlerSupportTests { + + private ExceptionHandlerSupport exceptionHandlerSupport; + + private DefaultHandlerExceptionResolver defaultExceptionResolver; + + private WebRequest request; + + private HttpServletRequest servletRequest; + + private MockHttpServletResponse servletResponse; + + + @Before + public void setup() { + this.servletRequest = new MockHttpServletRequest(); + this.servletResponse = new MockHttpServletResponse(); + this.request = new ServletWebRequest(this.servletRequest, this.servletResponse); + + this.exceptionHandlerSupport = new ApplicationExceptionHandler(); + this.defaultExceptionResolver = new DefaultHandlerExceptionResolver(); + } + + @Test + public void supportsAllDefaultHandlerExceptionResolverExceptionTypes() throws Exception { + + Method annotMethod = ExceptionHandlerSupport.class.getMethod("handleException", Exception.class, WebRequest.class); + ExceptionHandler annot = annotMethod.getAnnotation(ExceptionHandler.class); + List<Class<? extends Throwable>> supportedTypes = Arrays.asList(annot.value()); + + for (Method method : DefaultHandlerExceptionResolver.class.getDeclaredMethods()) { + Class<?>[] paramTypes = method.getParameterTypes(); + if (method.getName().startsWith("handle") && (paramTypes.length == 4)) { + String name = paramTypes[0].getSimpleName(); + assertTrue("@ExceptionHandler is missing " + name, supportedTypes.contains(paramTypes[0])); + } + } + } + + @Test + public void noSuchRequestHandlingMethod() { + Exception ex = new NoSuchRequestHandlingMethodException("GET", TestController.class); + testException(ex); + } + + @Test + public void httpRequestMethodNotSupported() { + List<String> supported = Arrays.asList("POST", "DELETE"); + Exception ex = new HttpRequestMethodNotSupportedException("GET", supported); + + ResponseEntity<Object> responseEntity = testException(ex); + assertEquals(EnumSet.of(HttpMethod.POST, HttpMethod.DELETE), responseEntity.getHeaders().getAllow()); + + } + + @Test + public void handleHttpMediaTypeNotSupported() { + List<MediaType> acceptable = Arrays.asList(MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_XML); + Exception ex = new HttpMediaTypeNotSupportedException(MediaType.APPLICATION_JSON, acceptable); + + ResponseEntity<Object> responseEntity = testException(ex); + assertEquals(acceptable, responseEntity.getHeaders().getAccept()); + } + + @Test + public void httpMediaTypeNotAcceptable() { + Exception ex = new HttpMediaTypeNotAcceptableException(""); + testException(ex); + } + + @Test + public void missingServletRequestParameter() { + Exception ex = new MissingServletRequestParameterException("param", "type"); + testException(ex); + } + + @Test + public void servletRequestBindingException() { + Exception ex = new ServletRequestBindingException("message"); + testException(ex); + } + + @Test + public void conversionNotSupported() { + Exception ex = new ConversionNotSupportedException(new Object(), Object.class, null); + testException(ex); + } + + @Test + public void typeMismatch() { + Exception ex = new TypeMismatchException("foo", String.class); + testException(ex); + } + + @Test + public void httpMessageNotReadable() { + Exception ex = new HttpMessageNotReadableException("message"); + testException(ex); + } + + @Test + public void httpMessageNotWritable() { + Exception ex = new HttpMessageNotWritableException(""); + testException(ex); + } + + @Test + public void methodArgumentNotValid() { + Exception ex = new MethodArgumentNotValidException(null, null); + testException(ex); + } + + @Test + public void missingServletRequestPart() { + Exception ex = new MissingServletRequestPartException("partName"); + testException(ex); + } + + @Test + public void bindException() { + Exception ex = new BindException(new Object(), "name"); + testException(ex); + } + + @Test + public void controllerAdvice() throws Exception { + StaticWebApplicationContext cxt = new StaticWebApplicationContext(); + cxt.registerSingleton("exceptionHandler", ApplicationExceptionHandler.class); + cxt.refresh(); + + ExceptionHandlerExceptionResolver resolver = new ExceptionHandlerExceptionResolver(); + resolver.setApplicationContext(cxt); + resolver.afterPropertiesSet(); + + ServletRequestBindingException ex = new ServletRequestBindingException("message"); + resolver.resolveException(this.servletRequest, this.servletResponse, null, ex); + + assertEquals(400, this.servletResponse.getStatus()); + assertEquals("error content", this.servletResponse.getContentAsString()); + assertEquals("someHeaderValue", this.servletResponse.getHeader("someHeader")); + } + + + private ResponseEntity<Object> testException(Exception ex) { + ResponseEntity<Object> responseEntity = this.exceptionHandlerSupport.handleException(ex, this.request); + this.defaultExceptionResolver.resolveException(this.servletRequest, this.servletResponse, null, ex); + + assertEquals(this.servletResponse.getStatus(), responseEntity.getStatusCode().value()); + + return responseEntity; + } + + + private static class TestController { + } + + @ControllerAdvice + private static class ApplicationExceptionHandler extends ExceptionHandlerSupport { + + @Override + protected Object handleServletRequestBindingException(ServletRequestBindingException ex, + HttpHeaders headers, HttpStatus status, WebRequest request) { + + headers.set("someHeader", "someHeaderValue"); + return "error content"; + } + + + } + +}
true
Other
spring-projects
spring-framework
1cf4a2facd4fa0784fd10a767114011a79164abd.json
Add ExceptionHandlerSupport class The new class is functionally equivalent to the DefaultHandlerExceptionResolver (i.e. it translates Spring MVC exceptions to various status codes) but uses an @ExceptionHandler returning a ResponseEntity<Object>, which means it can be customized to write error content to the body of the response. Issue: SPR-9290
src/reference/docbook/mvc.xml
@@ -3646,49 +3646,65 @@ public String onSubmit(<emphasis role="bold">@RequestPart("meta-data") MetaData is only a matter of implementing the <literal>resolveException(Exception, Handler)</literal> method and returning a <classname>ModelAndView</classname>, you may also use the provided - <classname>SimpleMappingExceptionResolver</classname>. This resolver + <classname>SimpleMappingExceptionResolver</classname> or create + <interfacename>@ExceptionHandler</interfacename> methods. + The <classname>SimpleMappingExceptionResolver</classname> enables you to take the class name of any exception that might be thrown and map it to a view name. This is functionally equivalent to the exception mapping feature from the Servlet API, but it is also possible to implement more finely grained mappings of exceptions from different - handlers.</para> + handlers. The <interfacename>@ExceptionHandler</interfacename> annotation on + the other hand can be used on methods that should be invoked to handle an + exception. Such methods may be defined locally within an + <interfacename>@Controller</interfacename> or may apply globally to all + <interfacename>@RequestMapping</interfacename> methods when defined within + an <interfacename>@ControllerAdvice</interfacename> class. + The following sections explain this in more detail.</para> </section> <section id="mvc-ann-exceptionhandler"> <title><interfacename>@ExceptionHandler</interfacename></title> <para>The <interfacename>HandlerExceptionResolver</interfacename> interface and the <classname>SimpleMappingExceptionResolver</classname> implementations - allow you to map Exceptions to specific views along with some Java logic - before forwarding to those views. However, in some cases, especially when - working with programmatic clients (Ajax or non-browser) it is more - convenient to set the status and optionally write error information to the - response body.</para> - - <para>For that you can use <interfacename>@ExceptionHandler</interfacename> - methods. When present within a controller such methods apply to exceptions - raised by that contoroller or any of its sub-classes. - Or you can also declare <interfacename>@ExceptionHandler</interfacename> - methods in an <interfacename>@ControllerAdvice</interfacename>-annotated - class and such methods apply to any controller. - The <interfacename>@ControllerAdvice</interfacename> annotation is - a component annotation allowing implementation classes to be autodetected - through classpath scanning. - </para> + allow you to map Exceptions to specific views declaratively along with some + optional Java logic before forwarding to those views. However, in some cases, + especially when relying on <interfacename>@ResponseBody</interfacename> methods + rather than on view resolution, it may be more convenient to directly set the + status of the response and optionally write error content to the body of the + response.</para> - <para>Here is an example with a controller-level + <para>You can do that with <interfacename>@ExceptionHandler</interfacename> + methods. When declared within a controller such methods apply to exceptions + raised by <interfacename>@RequestMapping</interfacename> methods of that + contoroller (or any of its sub-classes). You can also declare an + <interfacename>@ExceptionHandler</interfacename> method within an + <interfacename>@ControllerAdvice</interfacename> class in which case it + handles exceptions from <interfacename>@RequestMapping</interfacename> + methods from any controller. + The <interfacename>@ControllerAdvice</interfacename> annotation is + a component annotation, which can be used with classpath scanning. It is + automatically enabled when using the MVC namespace and Java config, or + otherwise depending on whether the + <classname>ExceptionHandlerExceptionResolver</classname> is configured or not. + Below is an example of a controller-local <interfacename>@ExceptionHandler</interfacename> method:</para> <programlisting language="java">@Controller public class SimpleController { - // other controller method omitted + + // @RequestMapping methods omitted ... + @ExceptionHandler(IOException.class) - public ResponseEntity handleIOException(IOException ex) { + public ResponseEntity&lt;String&gt; handleIOException(IOException ex) { + // prepare responseEntity + return responseEntity; } + }</programlisting> <para>The <classname>@ExceptionHandler</classname> value can be set to @@ -3711,30 +3727,25 @@ public class SimpleController { <interfacename>@ResponseBody</interfacename> to have the method return value converted with message converters and written to the response stream.</para> - <note><para>To better understand how <interfacename>@ExceptionHandler</interfacename> - methods work, consider that in Spring MVC there is only one abstraction - for handling exceptions and that's the - <interfacename>HandlerExceptionResolver</interfacename>. There is a special - implementation of that interface, - the <classname>ExceptionHandlerExceptionResolver</classname>, which detects - and invokes <interfacename>@ExceptionHandler</interfacename> methods.</para></note> </section> <section id="mvc-ann-rest-spring-mvc-exceptions"> - <title>Handling of Spring MVC Exceptions</title> - - <para>Spring MVC may raise a number of exceptions while processing a request. - A <classname>SimpleMappingExceptionResolver</classname> can be used to easily - map any exception to a default error view or to more specific error views if - desired. However when responding to programmatic clients you may prefer to - translate specific exceptions to the appropriate status that indicates a - client error (4xx) or a server error (5xx).</para> - - <para>For this reason Spring MVC provides the - <classname>DefaultHandlerExceptionResolver</classname>, which translates specific - Spring MVC exceptions by setting a specific response status code. By default, - this resolver is registered by the <classname>DispatcherServlet</classname>. - The following table describes some of the exceptions it handles: + <title>Handling Standard Spring MVC Exceptions</title> + + <para>Spring MVC may raise a number of exceptions while processing + a request. The <classname>SimpleMappingExceptionResolver</classname> can easily + map any exception to a default error view as needed. + However, when working with clients that interpret responses in an automated + way you will want to set specific status code on the response. Depending on + the exception raised the status code may indicate a client error (4xx) or a + server error (5xx).</para> + + <para>The <classname>DefaultHandlerExceptionResolver</classname> translates + Spring MVC exceptions to specific error status codes. It is registered + by default with the MVC namespace, the MVC Java config. and also by the + the <classname>DispatcherServlet</classname> (i.e. when not using the MVC + namespace or Java config). Listed below are some of the exceptions handled + by this resolver and the corresponding status codes: <informaltable> <tgroup cols="2"> <thead> @@ -3822,38 +3833,19 @@ public class SimpleController { </informaltable> </para> - <note><para>If you explicitly register one or more - <interfacename>HandlerExceptionResolver</interfacename> instances in your configuration - then the defaults registered by the <classname>DispatcherServlet</classname> are - cancelled. This is standard behavior with regards to - <classname>DispatcherServlet</classname> defaults. - See <xref linkend="mvc-servlet-special-bean-types"/> for more details.</para></note> - - <para>If building a REST API, then it's very likely you will want to - write some additional information about the error to the body of the response - consistent with the API's error handling throughout. This includes the handling of - Spring MVC exceptions, for which the <classname>DefaultHandlerExceptionResolver</classname> - only sets the status code and doesn't assume how or what content should be written - to the body.</para> - - <para>Instead you can create an <interfacename>@ControllerAdvice</interfacename> - class that handles each of the exceptions handled by the - <classname>DefaultHandlerExceptionResolver</classname> while also writing - developer-friendly API error information to the response body consistent with - the rest of all API error handling of the application. For example:</para> - - <programlisting language="java">@ControllerAdvice -public class ApplicationExceptionResolver { - - @ExceptionHandler - public ResponseEntity handleMediaTypeNotAcceptable(HttpMediaTypeNotAcceptableException ex) { - MyApiError error = ... ; - return new ResponseEntity(error, HttpStatus.SC_NOT_ACCEPTABLE); - } - - // more @ExceptionHandler methods ... - -}</programlisting> + <para>The <classname>DefaultHandlerExceptionResolver</classname> works + transparently by setting the status of the response. However, it stops short + of writing any error content to the body of the response while your + application may need to add developer-friendly content to every error + response for example when providing a REST API.</para> + + <para>To achieve this extend <classname>ExceptionHandlerSupport</classname>, + a convenient base class with an <interfacename>@ExceptionHandler</interfacename> + method that handles standard Spring MVC exceptions just as the + <classname>DefaultHandlerExceptionResolver</classname> does but also + allowing you to prepare error content for the body of the response. + See the Javadoc of <classname>ExceptionHandlerSupport</classname> + for more details.</para> </section> <section id="mvc-ann-annotated-exceptions"> @@ -3869,6 +3861,59 @@ public class ApplicationExceptionResolver { </section> + <section id="mvc-ann-customer-servlet-container-error-page"> + <title>Customizing the Default Servlet Container Error Page</title> + + <para>When the status of the response is set to an error status code + and the body of the response is empty, Servlet containers commonly render + an HTML formatted error page. + To customize the default error page of the container, you can + declare an <code>&lt;error-page&gt;</code> element in + <filename>web.xml</filename>. Up until Servlet 3, that element had to + be mapped to a specific status code or exception type. Starting with + Servlet 3 an error page does not need to be mapped, which effectively + means the specified location customizes the default Servlet container + error page.</para> + + <programlisting language="xml">&lt;error-page&gt; + &lt;location&gt;/error&lt;/location&gt; +&lt;/error-page&gt; +</programlisting> + + <para>Note that the actual location for the error page can be a + JSP page or some other URL within the container including one handled + through an <interfacename>@Controller</interfacename> method:</para> + + <para>When writing error information, the status code and the error message + set on the <interfacename>HttpServletResponse</interfacename> can be + accessed through request attributes in a controller:</para> + +<programlisting language="java">@Controller +public class ErrorController { + + @RequestMapping(value="/error", produces="application/json") + @ResponseBody + public Map&lt;String, Object&gt; handle(HttpServletRequest request) { + + Map&lt;String, Object&gt; map = new HashMap&lt;String, Object&gt;(); + map.put("status", request.getAttribute("javax.servlet.error.status_code")); + map.put("reason", request.getAttribute("javax.servlet.error.message")); + + return map; + } + +}</programlisting> + + <para>or in a JSP:</para> + + <programlisting language="xml">&lt;%@ page contentType="application/json" pageEncoding="UTF-8"%&gt; +{ + status:&lt;%=request.getAttribute("javax.servlet.error.status_code") %&gt;, + reason:&lt;%=request.getAttribute("javax.servlet.error.message") %&gt; +}</programlisting> + + </section> + </section> <section id="mvc-coc">
true
Other
spring-projects
spring-framework
9c8c967caa4062670ac0660db97feee43bf54500.json
Add async options to MVC namespace and Java config The MVC Java config method to implement is WebMvcConfigurer.configureAsyncSupport(AsyncSupportConfigurer) The MVC namespace element is: <mvc:annotation-driven> <mvc:async-support default-timeout="2500" task-executor="myExecutor" /> </mvc:annotation-driven> Issue: SPR-9694
spring-webmvc/src/main/java/org/springframework/web/servlet/config/AnnotationDrivenBeanDefinitionParser.java
@@ -174,6 +174,8 @@ public BeanDefinition parse(Element element, ParserContext parserContext) { ManagedList<?> messageConverters = getMessageConverters(element, source, parserContext); ManagedList<?> argumentResolvers = getArgumentResolvers(element, source, parserContext); ManagedList<?> returnValueHandlers = getReturnValueHandlers(element, source, parserContext); + String asyncTimeout = getAsyncTimeout(element, source, parserContext); + RuntimeBeanReference asyncExecutor = getAsyncExecutor(element, source, parserContext); RootBeanDefinition handlerAdapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class); handlerAdapterDef.setSource(source); @@ -191,6 +193,12 @@ public BeanDefinition parse(Element element, ParserContext parserContext) { if (returnValueHandlers != null) { handlerAdapterDef.getPropertyValues().add("customReturnValueHandlers", returnValueHandlers); } + if (asyncTimeout != null) { + handlerAdapterDef.getPropertyValues().add("asyncRequestTimeout", asyncTimeout); + } + if (asyncExecutor != null) { + handlerAdapterDef.getPropertyValues().add("taskExecutor", asyncExecutor); + } String handlerAdapterName = parserContext.getReaderContext().registerWithGeneratedName(handlerAdapterDef); RootBeanDefinition csInterceptorDef = new RootBeanDefinition(ConversionServiceExposingInterceptor.class); @@ -318,6 +326,21 @@ private RuntimeBeanReference getMessageCodesResolver(Element element, Object sou } } + private String getAsyncTimeout(Element element, Object source, ParserContext parserContext) { + Element asyncElement = DomUtils.getChildElementByTagName(element, "async-support"); + return (asyncElement != null) ? asyncElement.getAttribute("default-timeout") : null; + } + + private RuntimeBeanReference getAsyncExecutor(Element element, Object source, ParserContext parserContext) { + Element asyncElement = DomUtils.getChildElementByTagName(element, "async-support"); + if (asyncElement != null) { + if (asyncElement.hasAttribute("task-executor")) { + return new RuntimeBeanReference(asyncElement.getAttribute("task-executor")); + } + } + return null; + } + private ManagedList<?> getArgumentResolvers(Element element, Object source, ParserContext parserContext) { Element resolversElement = DomUtils.getChildElementByTagName(element, "argument-resolvers"); if (resolversElement != null) {
true
Other
spring-projects
spring-framework
9c8c967caa4062670ac0660db97feee43bf54500.json
Add async options to MVC namespace and Java config The MVC Java config method to implement is WebMvcConfigurer.configureAsyncSupport(AsyncSupportConfigurer) The MVC namespace element is: <mvc:annotation-driven> <mvc:async-support default-timeout="2500" task-executor="myExecutor" /> </mvc:annotation-driven> Issue: SPR-9694
spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/AsyncSupportConfigurer.java
@@ -0,0 +1,75 @@ +/* + * Copyright 2002-2012 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.web.servlet.config.annotation; + +import java.util.concurrent.Callable; + +import org.springframework.core.task.AsyncTaskExecutor; +import org.springframework.core.task.SimpleAsyncTaskExecutor; +import org.springframework.web.context.request.async.AsyncTask; + +/** + * Helps with configuring a options for asynchronous request processing. + * + * @author Rossen Stoyanchev + * @since 3.2 + */ +public class AsyncSupportConfigurer { + + private AsyncTaskExecutor taskExecutor; + + private Long timeout; + + /** + * Set the default {@link AsyncTaskExecutor} to use when a controller method + * returns a {@link Callable}. Controller methods can override this default on + * a per-request basis by returning an {@link AsyncTask}. + * + * <p>By default a {@link SimpleAsyncTaskExecutor} instance is used and it's + * highly recommended to change that default in production since the simple + * executor does not re-use threads. + * + * @param taskExecutor the task executor instance to use by default + */ + public AsyncSupportConfigurer setTaskExecutor(AsyncTaskExecutor taskExecutor) { + this.taskExecutor = taskExecutor; + return this; + } + + /** + * Specify the amount of time, in milliseconds, before asynchronous request + * handling times out. In Servlet 3, the timeout begins after the main request + * processing thread has exited and ends when the request is dispatched again + * for further processing of the concurrently produced result. + * <p>If this value is not set, the default timeout of the underlying + * implementation is used, e.g. 10 seconds on Tomcat with Servlet 3. + * + * @param timeout the timeout value in milliseconds + */ + public AsyncSupportConfigurer setDefaultTimeout(long timeout) { + this.timeout = timeout; + return this; + } + + protected AsyncTaskExecutor getTaskExecutor() { + return this.taskExecutor; + } + + protected Long getTimeout() { + return this.timeout; + } + +}
true
Other
spring-projects
spring-framework
9c8c967caa4062670ac0660db97feee43bf54500.json
Add async options to MVC namespace and Java config The MVC Java config method to implement is WebMvcConfigurer.configureAsyncSupport(AsyncSupportConfigurer) The MVC namespace element is: <mvc:annotation-driven> <mvc:async-support default-timeout="2500" task-executor="myExecutor" /> </mvc:annotation-driven> Issue: SPR-9694
spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.java
@@ -60,6 +60,11 @@ protected void configureContentNegotiation(ContentNegotiationConfigurer configur this.configurers.configureContentNegotiation(configurer); } + @Override + public void configureAsyncSupport(AsyncSupportConfigurer configurer) { + this.configurers.configureAsyncSupport(configurer); + } + @Override protected void addViewControllers(ViewControllerRegistry registry) { this.configurers.addViewControllers(registry);
true
Other
spring-projects
spring-framework
9c8c967caa4062670ac0660db97feee43bf54500.json
Add async options to MVC namespace and Java config The MVC Java config method to implement is WebMvcConfigurer.configureAsyncSupport(AsyncSupportConfigurer) The MVC namespace element is: <mvc:annotation-driven> <mvc:async-support default-timeout="2500" task-executor="myExecutor" /> </mvc:annotation-driven> Issue: SPR-9694
spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java
@@ -354,6 +354,17 @@ public RequestMappingHandlerAdapter requestMappingHandlerAdapter() { adapter.setWebBindingInitializer(webBindingInitializer); adapter.setCustomArgumentResolvers(argumentResolvers); adapter.setCustomReturnValueHandlers(returnValueHandlers); + + AsyncSupportConfigurer configurer = new AsyncSupportConfigurer(); + configureAsyncSupport(configurer); + + if (configurer.getTaskExecutor() != null) { + adapter.setTaskExecutor(configurer.getTaskExecutor()); + } + if (configurer.getTimeout() != null) { + adapter.setAsyncRequestTimeout(configurer.getTimeout()); + } + return adapter; } @@ -516,6 +527,13 @@ else if (jacksonPresent) { protected void addFormatters(FormatterRegistry registry) { } + /** + * Override this method to configure asynchronous request processing options. + * @see AsyncSupportConfigurer + */ + public void configureAsyncSupport(AsyncSupportConfigurer configurer) { + } + /** * Returns a {@link HttpRequestHandlerAdapter} for processing requests * with {@link HttpRequestHandler}s.
true
Other
spring-projects
spring-framework
9c8c967caa4062670ac0660db97feee43bf54500.json
Add async options to MVC namespace and Java config The MVC Java config method to implement is WebMvcConfigurer.configureAsyncSupport(AsyncSupportConfigurer) The MVC namespace element is: <mvc:annotation-driven> <mvc:async-support default-timeout="2500" task-executor="myExecutor" /> </mvc:annotation-driven> Issue: SPR-9694
spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurer.java
@@ -74,6 +74,11 @@ public interface WebMvcConfigurer { */ void configureContentNegotiation(ContentNegotiationConfigurer configurer); + /** + * Configure asynchronous request handling options. + */ + void configureAsyncSupport(AsyncSupportConfigurer configurer); + /** * Add resolvers to support custom controller method argument types. * <p>This does not override the built-in support for resolving handler
true
Other
spring-projects
spring-framework
9c8c967caa4062670ac0660db97feee43bf54500.json
Add async options to MVC namespace and Java config The MVC Java config method to implement is WebMvcConfigurer.configureAsyncSupport(AsyncSupportConfigurer) The MVC namespace element is: <mvc:annotation-driven> <mvc:async-support default-timeout="2500" task-executor="myExecutor" /> </mvc:annotation-driven> Issue: SPR-9694
spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurerAdapter.java
@@ -64,6 +64,13 @@ public Validator getValidator() { public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { } + /** + * {@inheritDoc} + * <p>This implementation is empty. + */ + public void configureAsyncSupport(AsyncSupportConfigurer configurer) { + } + /** * {@inheritDoc} * <p>This implementation is empty.
true
Other
spring-projects
spring-framework
9c8c967caa4062670ac0660db97feee43bf54500.json
Add async options to MVC namespace and Java config The MVC Java config method to implement is WebMvcConfigurer.configureAsyncSupport(AsyncSupportConfigurer) The MVC namespace element is: <mvc:annotation-driven> <mvc:async-support default-timeout="2500" task-executor="myExecutor" /> </mvc:annotation-driven> Issue: SPR-9694
spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurerComposite.java
@@ -55,6 +55,12 @@ public void configureContentNegotiation(ContentNegotiationConfigurer configurer) } } + public void configureAsyncSupport(AsyncSupportConfigurer configurer) { + for (WebMvcConfigurer delegate : this.delegates) { + delegate.configureAsyncSupport(configurer); + } + } + public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { for (WebMvcConfigurer delegate : this.delegates) { delegate.configureMessageConverters(converters);
true
Other
spring-projects
spring-framework
9c8c967caa4062670ac0660db97feee43bf54500.json
Add async options to MVC namespace and Java config The MVC Java config method to implement is WebMvcConfigurer.configureAsyncSupport(AsyncSupportConfigurer) The MVC namespace element is: <mvc:annotation-driven> <mvc:async-support default-timeout="2500" task-executor="myExecutor" /> </mvc:annotation-driven> Issue: SPR-9694
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapter.java
@@ -24,6 +24,7 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Set; +import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import javax.servlet.http.HttpServletRequest; @@ -62,6 +63,7 @@ import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.context.request.WebRequest; +import org.springframework.web.context.request.async.AsyncTask; import org.springframework.web.context.request.async.AsyncWebRequest; import org.springframework.web.context.request.async.AsyncWebUtils; import org.springframework.web.context.request.async.WebAsyncManager; @@ -400,26 +402,28 @@ public void setIgnoreDefaultModelOnRedirect(boolean ignoreDefaultModelOnRedirect } /** - * Set the AsyncTaskExecutor to use when a controller method returns a - * {@code Callable}. - * <p>The default instance type is a {@link SimpleAsyncTaskExecutor}. - * It's recommended to change that default in production as the simple - * executor does not re-use threads. + * Set the default {@link AsyncTaskExecutor} to use when a controller method + * return a {@link Callable}. Controller methods can override this default on + * a per-request basis by returning an {@link AsyncTask}. + * <p>By default a {@link SimpleAsyncTaskExecutor} instance is used. + * It's recommended to change that default in production as the simple executor + * does not re-use threads. */ - public void setAsyncTaskExecutor(AsyncTaskExecutor taskExecutor) { + public void setTaskExecutor(AsyncTaskExecutor taskExecutor) { this.taskExecutor = taskExecutor; } /** - * Set the timeout for asynchronous request processing in milliseconds. - * When the timeout begins depends on the underlying async technology. - * With the Servlet 3 async support the timeout begins after the main - * processing thread has exited and has been returned to the container pool. - * <p>If a value is not provided, the default timeout of the underlying - * async technology is used (10 seconds on Tomcat with Servlet 3 async). + * Specify the amount of time, in milliseconds, before concurrent handling + * should time out. In Servlet 3, the timeout begins after the main request + * processing thread has exited and ends when the request is dispatched again + * for further processing of the concurrently produced result. + * <p>If this value is not set, the default timeout of the underlying + * implementation is used, e.g. 10 seconds on Tomcat with Servlet 3. + * @param timeout the timeout value in milliseconds */ - public void setAsyncRequestTimeout(long asyncRequestTimeout) { - this.asyncRequestTimeout = asyncRequestTimeout; + public void setAsyncRequestTimeout(long timeout) { + this.asyncRequestTimeout = timeout; } /**
true
Other
spring-projects
spring-framework
9c8c967caa4062670ac0660db97feee43bf54500.json
Add async options to MVC namespace and Java config The MVC Java config method to implement is WebMvcConfigurer.configureAsyncSupport(AsyncSupportConfigurer) The MVC namespace element is: <mvc:annotation-driven> <mvc:async-support default-timeout="2500" task-executor="myExecutor" /> </mvc:annotation-driven> Issue: SPR-9694
spring-webmvc/src/main/resources/org/springframework/web/servlet/config/spring-mvc-3.2.xsd
@@ -90,6 +90,38 @@ </xsd:sequence> </xsd:complexType> </xsd:element> + <xsd:element name="async-support" minOccurs="0"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Configure options for asynchronous request processing. + ]]></xsd:documentation> + </xsd:annotation> + <xsd:complexType> + <xsd:attribute name="task-executor" type="xsd:string"> + <xsd:annotation> + <xsd:documentation source="java:org.springframework.core.task.AsyncTaskExecutor"><![CDATA[ + The bean name of a default AsyncTaskExecutor to use when a controller method returns a {@link Callable}. + Controller methods can override this default on a per-request basis by returning an AsyncTask. + By default a SimpleAsyncTaskExecutor is used which does not re-use threads and is not recommended for production. + ]]></xsd:documentation> + <xsd:appinfo> + <tool:annotation kind="ref"> + <tool:expected-type type="java:org.springframework.core.task.AsyncTaskExecutor" /> + </tool:annotation> + </xsd:appinfo> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="default-timeout" type="xsd:long"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Specify the amount of time, in milliseconds, before asynchronous request handling times out. + In Servlet 3, the timeout begins after the main request processing thread has exited and ends when the request is dispatched again for further processing of the concurrently produced result. + If this value is not set, the default timeout of the underlying implementation is used, e.g. 10 seconds on Tomcat with Servlet 3. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + </xsd:complexType> + </xsd:element> </xsd:all> <xsd:attribute name="conversion-service" type="xsd:string"> <xsd:annotation>
true
Other
spring-projects
spring-framework
9c8c967caa4062670ac0660db97feee43bf54500.json
Add async options to MVC namespace and Java config The MVC Java config method to implement is WebMvcConfigurer.configureAsyncSupport(AsyncSupportConfigurer) The MVC namespace element is: <mvc:annotation-driven> <mvc:async-support default-timeout="2500" task-executor="myExecutor" /> </mvc:annotation-driven> Issue: SPR-9694
spring-webmvc/src/test/java/org/springframework/web/servlet/config/MvcNamespaceTests.java
@@ -45,6 +45,7 @@ import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockRequestDispatcher; import org.springframework.mock.web.MockServletContext; +import org.springframework.scheduling.concurrent.ConcurrentTaskExecutor; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.validation.Errors; @@ -451,7 +452,7 @@ public void testViewControllersDefaultConfig() { } @Test - public void testCustomContentNegotiationManager() throws Exception { + public void testContentNegotiationManager() throws Exception { loadBeanDefinitions("mvc-config-content-negotiation-manager.xml", 12); RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class); @@ -462,6 +463,16 @@ public void testCustomContentNegotiationManager() throws Exception { assertEquals(Arrays.asList(MediaType.valueOf("application/rss+xml")), manager.resolveMediaTypes(webRequest)); } + @Test + public void testAsyncSupportOptions() throws Exception { + loadBeanDefinitions("mvc-config-async-support.xml", 13); + + RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class); + assertNotNull(adapter); + assertEquals(ConcurrentTaskExecutor.class, new DirectFieldAccessor(adapter).getPropertyValue("taskExecutor").getClass()); + assertEquals(2500L, new DirectFieldAccessor(adapter).getPropertyValue("asyncRequestTimeout")); + } + private void loadBeanDefinitions(String fileName, int expectedBeanCount) { XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext);
true